commit
stringlengths
40
40
old_file
stringlengths
6
181
new_file
stringlengths
6
181
old_contents
stringlengths
448
7.17k
new_contents
stringlengths
449
7.17k
subject
stringlengths
0
450
message
stringlengths
6
4.92k
lang
stringclasses
1 value
license
stringclasses
12 values
repos
stringlengths
9
33.9k
032868e3731039fe2a43155aa99b30cd8534e33d
lua/settings/init.lua
lua/settings/init.lua
local api = vim.api local sys = require('sys') local nvim = require('nvim') local parent = require('sys').data local mkdir = require('nvim').fn.mkdir local isdirectory = require('nvim').fn.isdirectory local function isempty(s) return s == nil or s == '' end local dirpaths = { backup = 'backupdir', swap = 'directory', undo = 'undodir', cache = '', sessions = '', } for dirname,dir_setting in pairs(dirpaths) do if not isdirectory(parent .. '/' .. dirname) then mkdir(parent .. '/' .. dirname, 'p') end if not isempty(dir_setting) then nvim.option[dir_setting] = parent .. '/' .. dirname end end nvim.g.lua_complete_omni = 1 nvim.g.tex_flavor = 'latex' nvim.g.c_syntax_for_h = 1 nvim.g.terminal_scrollback_buffer_size = 100000 nvim.option.shada = "!,/1000,'1000,<1000,:1000,s10000,h" nvim.option.scrollback = -1 nvim.option.softtabstop = -1 nvim.option.shiftwidth = 4 nvim.option.tabstop = 4 nvim.option.updatetime = 1000 nvim.option.sidescrolloff = 5 nvim.option.scrolloff = 1 nvim.option.undolevels = 10000 nvim.option.inccommand = 'split' nvim.option.winaltkeys = 'no' nvim.option.virtualedit = 'block' nvim.option.formatoptions = 'tcqrolnj' nvim.option.backupcopy = 'yes' nvim.option.complete = '.,w,b,u,t' nvim.option.completeopt = 'menuone,preview' nvim.option.tags = '.git/tags,./tags;,tags' nvim.option.display = 'lastline,msgsep' nvim.option.fileformats = 'unix,dos' nvim.option.wildmenu = true nvim.option.wildmode = 'full' nvim.option.showbreak = '↪\\' nvim.option.listchars = 'tab:▸ ,trail:•,extends:❯,precedes:❮' nvim.option.sessionoptions = 'buffers,curdir,folds,globals,localoptions,options,resize,tabpages,winpos,winsize' nvim.option.cpoptions = 'aAceFs_B' if sys.name == 'windows' then nvim.option.sessionoptions = nvim.option.sessionoptions .. ',slash,unix' end nvim.option.lazyredraw = true nvim.option.showmatch = true nvim.option.splitright = true nvim.option.splitbelow = true nvim.option.backup = true nvim.option.undofile = true nvim.option.termguicolors = true nvim.option.infercase = true nvim.option.ignorecase = true nvim.option.smartindent = true nvim.option.copyindent = true nvim.option.expandtab = true nvim.option.joinspaces = false nvim.option.showmode = false nvim.option.visualbell = true nvim.option.shiftround = true nvim.option.hidden = true nvim.option.autowrite = true nvim.option.autowriteall = true if nvim.g.gonvim_running ~= nil then nvim.option.showmode = false nvim.option.ruler = false else nvim.option.titlestring = '%t (%f)' nvim.option.title = true end if nvim.has_version('0.3.3') then nvim.option.diffopt = 'internal,filler,vertical,iwhiteall,iwhiteeol,indent-heuristic,algorithm:patience' else nvim.option.diffopt = 'filler,vertical,iwhite' end -- Windows options nvim.wo.foldmethod = 'syntax' nvim.wo.signcolumn = 'auto' nvim.wo.colorcolumn = '80' nvim.wo.breakindent = true nvim.wo.relativenumber = true nvim.wo.number = true nvim.wo.list = true nvim.wo.wrap = false nvim.wo.foldenable = false nvim.wo.numberwidth = 1 nvim.wo.foldlevel = 99 nvim.wo.foldcolumn = 0 local wildignores = { '*.spl', '*.aux', '*.out', '*.o', '*.pyc', '*.gz', '*.pdf', '*.sw', '*.swp', '*.swap', '*.com', '*.exe', '*.so', '*/cache/*', '*/__pycache__/*', } local no_backup = { '.git/*', '.svn/*', '.xml', '*.log', '*.bin', '*.7z', '*.dmg', '*.gz', '*.iso', '*.jar', '*.rar', '*.tar', '*.zip', 'TAGS', 'tags', 'GTAGS', 'COMMIT_EDITMSG', } nvim.option.wildignore = table.concat(wildignores, ',') nvim.option.backupskip = table.concat(no_backup, ',') .. ',' .. table.concat(wildignores, ',') if nvim.env.SSH_CONNECTION == nil then nvim.option.mouse = 'a' nvim.option.clipboard = 'unnamedplus,unnamed' else nvim.option.mouse = '' end
local api = vim.api local sys = require('sys') local nvim = require('nvim') local parent = require('sys').data local mkdir = require('nvim').fn.mkdir local isdirectory = require('nvim').fn.isdirectory local function isempty(s) return s == nil or s == '' end local dirpaths = { backup = 'backupdir', swap = 'directory', undo = 'undodir', cache = '', sessions = '', } for dirname,dir_setting in pairs(dirpaths) do if not isdirectory(parent .. '/' .. dirname) then mkdir(parent .. '/' .. dirname, 'p') end if not isempty(dir_setting) then nvim.option[dir_setting] = parent .. '/' .. dirname end end nvim.g.lua_complete_omni = 1 nvim.g.c_syntax_for_h = 1 nvim.g.terminal_scrollback_buffer_size = 100000 nvim.option.shada = "!,/1000,'1000,<1000,:1000,s10000,h" nvim.option.scrollback = -1 nvim.option.softtabstop = -1 nvim.option.shiftwidth = 4 nvim.option.tabstop = 4 nvim.option.updatetime = 1000 nvim.option.sidescrolloff = 5 nvim.option.scrolloff = 1 nvim.option.undolevels = 10000 nvim.option.inccommand = 'split' nvim.option.winaltkeys = 'no' nvim.option.virtualedit = 'block' nvim.option.formatoptions = 'tcqrolnj' nvim.option.backupcopy = 'yes' nvim.option.complete = '.,w,b,u,t' nvim.option.completeopt = 'menuone,preview' nvim.option.tags = '.git/tags,./tags;,tags' nvim.option.display = 'lastline,msgsep' nvim.option.fileformats = 'unix,dos' nvim.option.wildmenu = true nvim.option.wildmode = 'full' nvim.option.showbreak = '↪\\' nvim.option.listchars = 'tab:▸ ,trail:•,extends:❯,precedes:❮' nvim.option.sessionoptions = 'buffers,curdir,folds,globals,localoptions,options,resize,tabpages,winpos,winsize' nvim.option.cpoptions = 'aAceFs_B' if sys.name == 'windows' then nvim.option.sessionoptions = nvim.option.sessionoptions .. ',slash,unix' end nvim.option.lazyredraw = true nvim.option.showmatch = true nvim.option.splitright = true nvim.option.splitbelow = true nvim.option.backup = true nvim.option.undofile = true nvim.option.termguicolors = true nvim.option.infercase = true nvim.option.ignorecase = true nvim.option.smartindent = true nvim.option.copyindent = true nvim.option.expandtab = true nvim.option.joinspaces = false nvim.option.showmode = false nvim.option.visualbell = true nvim.option.shiftround = true nvim.option.hidden = true nvim.option.autowrite = true nvim.option.autowriteall = true if nvim.g.gonvim_running ~= nil then nvim.option.showmode = false nvim.option.ruler = false else nvim.option.titlestring = '%t (%f)' nvim.option.title = true end if nvim.has_version('0.3.3') then nvim.option.diffopt = 'internal,filler,vertical,iwhiteall,iwhiteeol,indent-heuristic,algorithm:patience' else nvim.option.diffopt = 'filler,vertical,iwhite' end -- Windows options nvim.ex.set('breakindent') nvim.ex.set('relativenumber') nvim.ex.set('number') nvim.ex.set('list') nvim.ex.set('nowrap') nvim.ex.set('nofoldenable') nvim.ex.set('colorcolumn=80') nvim.ex.set('foldmethod=syntax') nvim.ex.set('signcolumn=auto') nvim.ex.set('numberwidth=1') nvim.ex.set('foldlevel=99') nvim.ex.set('foldcolumn=0') nvim.ex.set('fileencoding=utf-8') local wildignores = { '*.spl', '*.aux', '*.out', '*.o', '*.pyc', '*.gz', '*.pdf', '*.sw', '*.swp', '*.swap', '*.com', '*.exe', '*.so', '*/cache/*', '*/__pycache__/*', } local no_backup = { '.git/*', '.svn/*', '.xml', '*.log', '*.bin', '*.7z', '*.dmg', '*.gz', '*.iso', '*.jar', '*.rar', '*.tar', '*.zip', 'TAGS', 'tags', 'GTAGS', 'COMMIT_EDITMSG', } nvim.option.wildignore = table.concat(wildignores, ',') nvim.option.backupskip = table.concat(no_backup, ',') .. ',' .. table.concat(wildignores, ',') if nvim.env.SSH_CONNECTION == nil then nvim.option.mouse = 'a' nvim.option.clipboard = 'unnamedplus,unnamed' else nvim.option.mouse = '' end
fix: Change settings cmd
fix: Change settings cmd Use ex.set instead of wo.<NAME> to set window settings
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
9524973c0d6a0f8644782c7f8db85d9f5d1f7785
gumbo/dom/HTMLCollection.lua
gumbo/dom/HTMLCollection.lua
local util = require "gumbo.dom.util" local assertString = util.assertString local type, ipairs = type, ipairs local _ENV = nil local HTMLCollection = {} function HTMLCollection:__index(k) local field = HTMLCollection[k] if field then return field elseif type(k) == "string" then return self:namedItem(k) end end function HTMLCollection:item(index) return self[index] end function HTMLCollection:namedItem(name) assertString(name) if name ~= "" then for i, element in ipairs(self) do if element.id == name or element:getAttribute("name") == name then return element end end end end return HTMLCollection
local util = require "gumbo.dom.util" local assertString = util.assertString local type, ipairs = type, ipairs local _ENV = nil local HTMLCollection = {} function HTMLCollection:__index(k) local field = HTMLCollection[k] if field then return field elseif type(k) == "string" then return self:namedItem(k) end end function HTMLCollection:item(index) return self[index] end function HTMLCollection:namedItem(key) assertString(key) if key == "" then return nil end for _, element in ipairs(self) do if element:getAttribute("id") == key then return element elseif element.namespaceURI == "http://www.w3.org/1999/xhtml" and element:getAttribute("name") == key then return element end end end return HTMLCollection
Fix HTMLCollection.namedItem to properly follow the DOM spec
Fix HTMLCollection.namedItem to properly follow the DOM spec
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
9081796dc38fb1217a44d282cc67898ac9114b86
lexers/perl.lua
lexers/perl.lua
-- Copyright 2006-2015 Mitchell mitchell.att.foicica.com. See LICENSE. -- Perl LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local M = {_NAME = 'perl'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '#' * l.nonnewline_esc^0 local block_comment = l.starts_line('=') * l.alpha * (l.any - l.newline * '=cut')^0 * (l.newline * '=cut')^-1 local comment = token(l.COMMENT, block_comment + line_comment) local delimiter_matches = {['('] = ')', ['['] = ']', ['{'] = '}', ['<'] = '>'} local literal_delimitted = P(function(input, index) -- for single delimiter sets local delimiter = input:sub(index, index) if not delimiter:find('%w') then -- only non alpha-numerics local match_pos, patt if delimiter_matches[delimiter] then -- Handle nested delimiter/matches in strings. local s, e = delimiter, delimiter_matches[delimiter] patt = l.delimited_range(s..e, false, false, true) else patt = l.delimited_range(delimiter) end match_pos = lpeg.match(patt, input, index) return match_pos or #input + 1 end end) local literal_delimitted2 = P(function(input, index) -- for 2 delimiter sets local delimiter = input:sub(index, index) if not delimiter:find('%w') then -- only non alpha-numerics local match_pos, patt if delimiter_matches[delimiter] then -- Handle nested delimiter/matches in strings. local s, e = delimiter, delimiter_matches[delimiter] patt = l.delimited_range(s..e, false, false, true) else patt = l.delimited_range(delimiter) end first_match_pos = lpeg.match(patt, input, index) final_match_pos = lpeg.match(patt, input, first_match_pos - 1) if not final_match_pos then -- using (), [], {}, or <> notation final_match_pos = lpeg.match(l.space^0 * patt, input, first_match_pos) end return final_match_pos or #input + 1 end end) -- Strings. local sq_str = l.delimited_range("'") local dq_str = l.delimited_range('"') local cmd_str = l.delimited_range('`') local heredoc = '<<' * P(function(input, index) local s, e, delimiter = input:find('([%a_][%w_]*)[\n\r\f;]+', index) if s == index and delimiter then local end_heredoc = '[\n\r\f]+' local _, e = input:find(end_heredoc..delimiter, e) return e and e + 1 or #input + 1 end end) local lit_str = 'q' * P('q')^-1 * literal_delimitted local lit_array = 'qw' * literal_delimitted local lit_cmd = 'qx' * literal_delimitted local lit_match = 'm' * literal_delimitted * S('cgimosx')^0 local lit_sub = 's' * literal_delimitted2 * S('ecgimosx')^0 local lit_tr = (P('tr') + 'y') * literal_delimitted2 * S('cds')^0 local regex_str = l.last_char_includes('-<>+*!~\\=%&|^?:;([{') * l.delimited_range('/', true) * S('imosx')^0 local lit_regex = 'qr' * literal_delimitted * S('imosx')^0 local string = token(l.STRING, sq_str + dq_str + cmd_str + heredoc + lit_str + lit_array + lit_cmd + lit_match + lit_sub + lit_tr) + token(l.REGEX, regex_str + lit_regex) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Keywords. local keyword = token(l.KEYWORD, word_match{ 'STDIN', 'STDOUT', 'STDERR', 'BEGIN', 'END', 'CHECK', 'INIT', 'require', 'use', 'break', 'continue', 'do', 'each', 'else', 'elsif', 'foreach', 'for', 'if', 'last', 'local', 'my', 'next', 'our', 'package', 'return', 'sub', 'unless', 'until', 'while', '__FILE__', '__LINE__', '__PACKAGE__', 'and', 'or', 'not', 'eq', 'ne', 'lt', 'gt', 'le', 'ge' }) -- Functions. local func = token(l.FUNCTION, word_match({ 'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller', 'chdir', 'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'closedir', 'close', 'connect', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined', 'delete', 'die', 'dump', 'each', 'endgrent', 'endhostent', 'endnetent', 'endprotoent', 'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists', 'exit', 'exp', 'fcntl', 'fileno', 'flock', 'fork', 'format', 'formline', 'getc', 'getgrent', 'getgrgid', 'getgrnam', 'gethostbyaddr', 'gethostbyname', 'gethostent', 'getlogin', 'getnetbyaddr', 'getnetbyname', 'getnetent', 'getpeername', 'getpgrp', 'getppid', 'getpriority', 'getprotobyname', 'getprotobynumber', 'getprotoent', 'getpwent', 'getpwnam', 'getpwuid', 'getservbyname', 'getservbyport', 'getservent', 'getsockname', 'getsockopt', 'glob', 'gmtime', 'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl', 'join', 'keys', 'kill', 'lcfirst', 'lc', 'length', 'link', 'listen', 'localtime', 'log', 'lstat', 'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv', 'msgsnd', 'new', 'oct', 'opendir', 'open', 'ord', 'pack', 'pipe', 'pop', 'pos', 'printf', 'print', 'prototype', 'push', 'quotemeta', 'rand', 'readdir', 'read', 'readlink', 'recv', 'redo', 'ref', 'rename', 'reset', 'reverse', 'rewinddir', 'rindex', 'rmdir', 'scalar', 'seekdir', 'seek', 'select', 'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent', 'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent', 'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown', 'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf', 'sqrt', 'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysread', 'sysseek', 'system', 'syswrite', 'telldir', 'tell', 'tied', 'tie', 'time', 'times', 'truncate', 'ucfirst', 'uc', 'umask', 'undef', 'unlink', 'unpack', 'unshift', 'untie', 'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray', 'warn', 'write' }, '2')) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Variables. local special_var = '$' * ('^' * S('ADEFHILMOPSTWX')^-1 + S('\\"[]\'&`+*.,;=%~?@<>(|/!-') + ':' * (l.any - ':') + P('$') * -l.word + l.digit^1) local plain_var = ('$#' + S('$@%')) * P('$')^0 * l.word + '$#' local variable = token(l.VARIABLE, special_var + plain_var) -- Operators. local operator = token(l.OPERATOR, S('-<>+*!~\\=/%&|^.?:;()[]{}')) -- Markers. local marker = token(l.COMMENT, word_match{'__DATA__', '__END__'} * l.any^0) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'marker', marker}, {'function', func}, {'string', string}, {'identifier', identifier}, {'comment', comment}, {'number', number}, {'variable', variable}, {'operator', operator}, } M._foldsymbols = { _patterns = {'[%[%]{}]', '#'}, [l.OPERATOR] = {['['] = 1, [']'] = -1, ['{'] = 1, ['}'] = -1}, [l.COMMENT] = {['#'] = l.fold_line_comments('#')} } return M
-- Copyright 2006-2015 Mitchell mitchell.att.foicica.com. See LICENSE. -- Perl LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local M = {_NAME = 'perl'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '#' * l.nonnewline_esc^0 local block_comment = l.starts_line('=') * l.alpha * (l.any - l.newline * '=cut')^0 * (l.newline * '=cut')^-1 local comment = token(l.COMMENT, block_comment + line_comment) local delimiter_matches = {['('] = ')', ['['] = ']', ['{'] = '}', ['<'] = '>'} local literal_delimitted = P(function(input, index) -- for single delimiter sets local delimiter = input:sub(index, index) if not delimiter:find('%w') then -- only non alpha-numerics local match_pos, patt if delimiter_matches[delimiter] then -- Handle nested delimiter/matches in strings. local s, e = delimiter, delimiter_matches[delimiter] patt = l.delimited_range(s..e, false, false, true) else patt = l.delimited_range(delimiter) end match_pos = lpeg.match(patt, input, index) return match_pos or #input + 1 end end) local literal_delimitted2 = P(function(input, index) -- for 2 delimiter sets local delimiter = input:sub(index, index) -- Only consider non-alpha-numerics and non-spaces as delimiters. The -- non-spaces are used to ignore operators like "-s". if not delimiter:find('[%w ]') then local match_pos, patt if delimiter_matches[delimiter] then -- Handle nested delimiter/matches in strings. local s, e = delimiter, delimiter_matches[delimiter] patt = l.delimited_range(s..e, false, false, true) else patt = l.delimited_range(delimiter) end first_match_pos = lpeg.match(patt, input, index) final_match_pos = lpeg.match(patt, input, first_match_pos - 1) if not final_match_pos then -- using (), [], {}, or <> notation final_match_pos = lpeg.match(l.space^0 * patt, input, first_match_pos) end return final_match_pos or #input + 1 end end) -- Strings. local sq_str = l.delimited_range("'") local dq_str = l.delimited_range('"') local cmd_str = l.delimited_range('`') local heredoc = '<<' * P(function(input, index) local s, e, delimiter = input:find('([%a_][%w_]*)[\n\r\f;]+', index) if s == index and delimiter then local end_heredoc = '[\n\r\f]+' local _, e = input:find(end_heredoc..delimiter, e) return e and e + 1 or #input + 1 end end) local lit_str = 'q' * P('q')^-1 * literal_delimitted local lit_array = 'qw' * literal_delimitted local lit_cmd = 'qx' * literal_delimitted local lit_tr = (P('tr') + 'y') * literal_delimitted2 * S('cds')^0 local regex_str = l.last_char_includes('-<>+*!~\\=%&|^?:;([{') * l.delimited_range('/', true) * S('imosx')^0 local lit_regex = 'qr' * literal_delimitted * S('imosx')^0 local lit_match = 'm' * literal_delimitted * S('cgimosx')^0 local lit_sub = 's' * literal_delimitted2 * S('ecgimosx')^0 local string = token(l.STRING, sq_str + dq_str + cmd_str + heredoc + lit_str + lit_array + lit_cmd + lit_tr) + token(l.REGEX, regex_str + lit_regex + lit_match + lit_sub) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Keywords. local keyword = token(l.KEYWORD, word_match{ 'STDIN', 'STDOUT', 'STDERR', 'BEGIN', 'END', 'CHECK', 'INIT', 'require', 'use', 'break', 'continue', 'do', 'each', 'else', 'elsif', 'foreach', 'for', 'if', 'last', 'local', 'my', 'next', 'our', 'package', 'return', 'sub', 'unless', 'until', 'while', '__FILE__', '__LINE__', '__PACKAGE__', 'and', 'or', 'not', 'eq', 'ne', 'lt', 'gt', 'le', 'ge' }) -- Functions. local func = token(l.FUNCTION, word_match({ 'abs', 'accept', 'alarm', 'atan2', 'bind', 'binmode', 'bless', 'caller', 'chdir', 'chmod', 'chomp', 'chop', 'chown', 'chr', 'chroot', 'closedir', 'close', 'connect', 'cos', 'crypt', 'dbmclose', 'dbmopen', 'defined', 'delete', 'die', 'dump', 'each', 'endgrent', 'endhostent', 'endnetent', 'endprotoent', 'endpwent', 'endservent', 'eof', 'eval', 'exec', 'exists', 'exit', 'exp', 'fcntl', 'fileno', 'flock', 'fork', 'format', 'formline', 'getc', 'getgrent', 'getgrgid', 'getgrnam', 'gethostbyaddr', 'gethostbyname', 'gethostent', 'getlogin', 'getnetbyaddr', 'getnetbyname', 'getnetent', 'getpeername', 'getpgrp', 'getppid', 'getpriority', 'getprotobyname', 'getprotobynumber', 'getprotoent', 'getpwent', 'getpwnam', 'getpwuid', 'getservbyname', 'getservbyport', 'getservent', 'getsockname', 'getsockopt', 'glob', 'gmtime', 'goto', 'grep', 'hex', 'import', 'index', 'int', 'ioctl', 'join', 'keys', 'kill', 'lcfirst', 'lc', 'length', 'link', 'listen', 'localtime', 'log', 'lstat', 'map', 'mkdir', 'msgctl', 'msgget', 'msgrcv', 'msgsnd', 'new', 'oct', 'opendir', 'open', 'ord', 'pack', 'pipe', 'pop', 'pos', 'printf', 'print', 'prototype', 'push', 'quotemeta', 'rand', 'readdir', 'read', 'readlink', 'recv', 'redo', 'ref', 'rename', 'reset', 'reverse', 'rewinddir', 'rindex', 'rmdir', 'scalar', 'seekdir', 'seek', 'select', 'semctl', 'semget', 'semop', 'send', 'setgrent', 'sethostent', 'setnetent', 'setpgrp', 'setpriority', 'setprotoent', 'setpwent', 'setservent', 'setsockopt', 'shift', 'shmctl', 'shmget', 'shmread', 'shmwrite', 'shutdown', 'sin', 'sleep', 'socket', 'socketpair', 'sort', 'splice', 'split', 'sprintf', 'sqrt', 'srand', 'stat', 'study', 'substr', 'symlink', 'syscall', 'sysread', 'sysseek', 'system', 'syswrite', 'telldir', 'tell', 'tied', 'tie', 'time', 'times', 'truncate', 'ucfirst', 'uc', 'umask', 'undef', 'unlink', 'unpack', 'unshift', 'untie', 'utime', 'values', 'vec', 'wait', 'waitpid', 'wantarray', 'warn', 'write' }, '2')) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Variables. local special_var = '$' * ('^' * S('ADEFHILMOPSTWX')^-1 + S('\\"[]\'&`+*.,;=%~?@<>(|/!-') + ':' * (l.any - ':') + P('$') * -l.word + l.digit^1) local plain_var = ('$#' + S('$@%')) * P('$')^0 * l.word + '$#' local variable = token(l.VARIABLE, special_var + plain_var) -- Operators. local operator = token(l.OPERATOR, S('-<>+*!~\\=/%&|^.?:;()[]{}')) -- Markers. local marker = token(l.COMMENT, word_match{'__DATA__', '__END__'} * l.any^0) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'marker', marker}, {'function', func}, {'string', string}, {'identifier', identifier}, {'comment', comment}, {'number', number}, {'variable', variable}, {'operator', operator}, } M._foldsymbols = { _patterns = {'[%[%]{}]', '#'}, [l.OPERATOR] = {['['] = 1, [']'] = -1, ['{'] = 1, ['}'] = -1}, [l.COMMENT] = {['#'] = l.fold_line_comments('#')} } return M
More Perl lexer fixes related to regexes; lexers/perl.lua
More Perl lexer fixes related to regexes; lexers/perl.lua
Lua
mit
rgieseke/scintillua
136ee4f6196bcb4b8d7ceec68beb79cd7735d629
lua/entities/gmod_wire_expression2/core/cl_files.lua
lua/entities/gmod_wire_expression2/core/cl_files.lua
--[[ File Extension By: Dan (McLovin) ]]-- local cv_max_transfer_size = CreateConVar( "wire_expression2_file_max_size", "100", { FCVAR_REPLICATED, FCVAR_ARCHIVE } ) //in kb local upload_buffer = {} local download_buffer = {} local upload_chunk_size = 20000 //Our overhead is pretty small so lets send it in moderate sized pieces, no need to max out the buffer local allowed_directories = { //prefix with >(allowed directory)/file.txt for files outside of e2files/ directory ["e2shared"] = "expression2/e2shared", ["cpushared"] = "cpuchip/e2shared", ["gpushared"] = "gpuchip/e2shared", ["dupeshared"] = "adv_duplicator/e2shared" } for _,dir in pairs( allowed_directories ) do if not file.IsDir( dir, "DATA" ) then file.CreateDir( dir ) end end local function process_filepath( filepath ) if string.find( filepath, "..", 1, true ) then return "e2files/", "noname.txt" end local fullpath = "" if string.Left( filepath, 1 ) == ">" then local diresc = string.find( filepath, "/" ) if diresc then local extdir = string.sub( filepath, 2, diresc - 1 ) local dir = (allowed_directories[extdir] or "e2files") .. "/" fullpath = dir .. string.sub( filepath, diresc + 1, string.len( filepath ) ) else fullpath = "e2files/" .. filepath end else fullpath = "e2files/" .. filepath end return string.GetPathFromFilename( fullpath ) or "e2files/", string.GetFileFromFilename( fullpath ) or "noname.txt" end /* --- File Read --- */ local function upload_callback() if !upload_buffer or !upload_buffer.data then return end local chunk_size = math.Clamp( string.len( upload_buffer.data ), 0, upload_chunk_size ) net.Start("wire_expression2_file_chunk") net.WriteString(string.Left( upload_buffer.data, chunk_size )) net.SendToServer() upload_buffer.data = string.sub( upload_buffer.data, chunk_size + 1, string.len( upload_buffer.data ) ) if upload_buffer.chunk >= upload_buffer.chunks then net.Start("wire_expression2_file_finish") net.SendToServer() timer.Remove( "wire_expression2_file_upload" ) return end upload_buffer.chunk = upload_buffer.chunk + 1 end net.Receive("wire_expression2_request_file_sp", function(netlen) local fpath,fname = process_filepath(net.ReadString()) RunConsoleCommand("wire_expression2_file_singleplayer", fpath .. fname) end) net.Receive("wire_expression2_request_file", function(netlen) local fpath,fname = process_filepath(net.ReadString()) local fullpath = fpath .. fname if file.Exists( fullpath,"DATA" ) and file.Size( fullpath, "DATA" ) <= (cv_max_transfer_size:GetInt() * 1024) then local filedata = file.Read( fullpath,"DATA" ) or "" local encoded = E2Lib.encode( filedata ) upload_buffer = { chunk = 1, chunks = math.ceil( string.len( encoded ) / upload_chunk_size ), data = encoded } net.Start("wire_expression2_file_begin") net.WriteUInt(string.len(filedata), 32) net.SendToServer() timer.Create( "wire_expression2_file_upload", 1/60, upload_buffer.chunks, upload_callback ) else net.Start("wire_expression2_file_begin") net.WriteUInt(0, 32) // 404 file not found, send len of 0 net.SendToServer() end end ) /* --- File Write --- */ net.Receive("wire_expression2_file_download_begin", function( netlen ) local fpath,fname = process_filepath( net.ReadString() ) if string.GetExtensionFromFilename( string.lower(fname) ) != "txt" then return end download_buffer = { name = fpath .. fname, data = "" } end ) net.Receive("wire_expression2_file_download_chunk", function( netlen ) if not download_buffer.name then return end download_buffer.data = (download_buffer.data or "") .. net.ReadString() end ) net.Receive("wire_expresison2_file_download_finish", function( netlen ) if not download_buffer.name then return end if net.ReadBit() ~= 0 then file.Append( download_buffer.name, download_buffer.data ) else file.Write( download_buffer.name, download_buffer.data ) end end ) /* --- File List --- */ net.Receive( "wire_expression2_request_list", function( netlen ) local dir = process_filepath(net.ReadString()) net.Start("wire_expression2_file_list") local files, folders = file.Find( dir .. "*","DATA" ) net.WriteUInt(#files + #folders, 16) for _,fop in pairs(files) do if string.GetExtensionFromFilename( fop ) == "txt" then net.WriteString(E2Lib.encode( fop )) end end for _,fop in pairs(folders) do net.WriteString(E2Lib.encode( fop.."/" )) end net.SendToServer() end )
--[[ File Extension By: Dan (McLovin) ]]-- local cv_max_transfer_size = CreateConVar( "wire_expression2_file_max_size", "100", { FCVAR_REPLICATED, FCVAR_ARCHIVE } ) //in kb local upload_buffer = {} local download_buffer = {} local upload_chunk_size = 20000 //Our overhead is pretty small so lets send it in moderate sized pieces, no need to max out the buffer local allowed_directories = { //prefix with >(allowed directory)/file.txt for files outside of e2files/ directory ["e2files"] = "e2files", ["e2shared"] = "expression2/e2shared", ["cpushared"] = "cpuchip/e2shared", ["gpushared"] = "gpuchip/e2shared", ["dupeshared"] = "adv_duplicator/e2shared" } for _,dir in pairs( allowed_directories ) do if not file.IsDir( dir, "DATA" ) then file.CreateDir( dir ) end end local function process_filepath( filepath ) if string.find( filepath, "..", 1, true ) then return "e2files/", "noname.txt" end local fullpath = "" if string.Left( filepath, 1 ) == ">" then local diresc = string.find( filepath, "/" ) if diresc then local extdir = string.sub( filepath, 2, diresc - 1 ) local dir = (allowed_directories[extdir] or "e2files") .. "/" fullpath = dir .. string.sub( filepath, diresc + 1, string.len( filepath ) ) else fullpath = "e2files/" .. filepath end else fullpath = "e2files/" .. filepath end return string.GetPathFromFilename( fullpath ) or "e2files/", string.GetFileFromFilename( fullpath ) or "noname.txt" end /* --- File Read --- */ local function upload_callback() if !upload_buffer or !upload_buffer.data then return end local chunk_size = math.Clamp( string.len( upload_buffer.data ), 0, upload_chunk_size ) net.Start("wire_expression2_file_chunk") net.WriteString(string.Left( upload_buffer.data, chunk_size )) net.SendToServer() upload_buffer.data = string.sub( upload_buffer.data, chunk_size + 1, string.len( upload_buffer.data ) ) if upload_buffer.chunk >= upload_buffer.chunks then net.Start("wire_expression2_file_finish") net.SendToServer() timer.Remove( "wire_expression2_file_upload" ) return end upload_buffer.chunk = upload_buffer.chunk + 1 end net.Receive("wire_expression2_request_file_sp", function(netlen) local fpath,fname = process_filepath(net.ReadString()) RunConsoleCommand("wire_expression2_file_singleplayer", fpath .. fname) end) net.Receive("wire_expression2_request_file", function(netlen) local fpath,fname = process_filepath(net.ReadString()) local fullpath = fpath .. fname if file.Exists( fullpath,"DATA" ) and file.Size( fullpath, "DATA" ) <= (cv_max_transfer_size:GetInt() * 1024) then local filedata = file.Read( fullpath,"DATA" ) or "" local encoded = E2Lib.encode( filedata ) upload_buffer = { chunk = 1, chunks = math.ceil( string.len( encoded ) / upload_chunk_size ), data = encoded } net.Start("wire_expression2_file_begin") net.WriteUInt(string.len(filedata), 32) net.SendToServer() timer.Create( "wire_expression2_file_upload", 1/60, upload_buffer.chunks, upload_callback ) else net.Start("wire_expression2_file_begin") net.WriteUInt(0, 32) // 404 file not found, send len of 0 net.SendToServer() end end ) /* --- File Write --- */ net.Receive("wire_expression2_file_download_begin", function( netlen ) local fpath,fname = process_filepath( net.ReadString() ) if string.GetExtensionFromFilename( string.lower(fname) ) != "txt" then return end if not file.Exists(fpath, "DATA") then file.CreateDir(fpath) end download_buffer = { name = fpath .. fname, data = "" } end ) net.Receive("wire_expression2_file_download_chunk", function( netlen ) if not download_buffer.name then return end download_buffer.data = (download_buffer.data or "") .. net.ReadString() end ) net.Receive("wire_expresison2_file_download_finish", function( netlen ) if not download_buffer.name then return end if net.ReadBit() ~= 0 then file.Append( download_buffer.name, download_buffer.data ) else file.Write( download_buffer.name, download_buffer.data ) end end ) /* --- File List --- */ net.Receive( "wire_expression2_request_list", function( netlen ) local dir = process_filepath(net.ReadString()) net.Start("wire_expression2_file_list") local files, folders = file.Find( dir .. "*","DATA" ) net.WriteUInt(#files + #folders, 16) for _,fop in pairs(files) do if string.GetExtensionFromFilename( fop ) == "txt" then net.WriteString(E2Lib.encode( fop )) end end for _,fop in pairs(folders) do net.WriteString(E2Lib.encode( fop.."/" )) end net.SendToServer() end )
E2 File Writing: Fixed failing if directory didn't exist Fixes #321, probably
E2 File Writing: Fixed failing if directory didn't exist Fixes #321, probably
Lua
apache-2.0
sammyt291/wire,garrysmodlua/wire,Grocel/wire,rafradek/wire,bigdogmat/wire,thegrb93/wire,immibis/wiremod,mms92/wire,Python1320/wire,dvdvideo1234/wire,wiremod/wire,plinkopenguin/wiremod,CaptainPRICE/wire,NezzKryptic/Wire,mitterdoo/wire,notcake/wire
2f5c5e1eca480f4382c2b951f6ce58ca8dafbd79
twitpic.lua
twitpic.lua
local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local ishtml = urlpos["link_expect_html"] local parenturl = parent["url"] -- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"? local html = nil -- Skip redirect from mysite.verizon.net and members.bellatlantic.net if item_type == "image" then if string.match(url, "cloudfront%.net") then return true elseif string.match(url, "twimg%.com") then return true elseif string.match(url, "amazonaws%.com") then return true elseif string.match(url, "advertise%.twitpic%.com") then return false elseif string.match(url, "/[^:]+:[^/]+/") then return false elseif string.match(url, '/[^"]+"[^/]+/') then return false elseif not string.match(url, "twitpic%.com") and ishtml ~= 1 then return true elseif string.match(url, item_value) then return true else return false end elseif item_type == "user" then if string.match(url, "cloudfront%.net") then return true elseif string.match(url, "twimg%.com") then return true elseif string.match(url, "amazonaws%.com") then return true elseif string.match(url, "advertise%.twitpic%.com") then return false elseif not string.match(url, "twitpic%.com") and ishtml ~= 1 then return true elseif string.match(url, item_value) then return true else return false end elseif item_type == "tag" then if string.match(url, "cloudfront%.net") then return true elseif string.match(url, "twimg%.com") then return true elseif string.match(url, "amazonaws%.com") then return true elseif string.match(url, "advertise%.twitpic%.com") then return false -- Check if we are on the last page of a tag elseif string.match(url, "twitpic%.com/tag/[^%?]+%?page=[0-9]+") then if not html then html = read_file(file) end if not string.match(url, '<div class="user%-photo%-content right">') then return false else return true end elseif not string.match(url, "twitpic%.com") and ishtml ~= 1 then return true elseif string.match(url, item_value) then return true else return false end else return verdict end end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r") io.stdout:flush() if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then if string.match(url["host"], "twitpic%.com") or string.match(url["host"], "cloudfront%.net") or string.match(url["host"], "twimg%.com") or string.match(url["host"], "amazonaws%.com") then io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.NOTHING else return wget.actions.CONTINUE end else io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.NOTHING else return wget.actions.CONTINUE end end elseif status_code == 0 then return wget.actions.ABORT end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(1000, 2000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local ishtml = urlpos["link_expect_html"] local parenturl = parent["url"] -- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"? local html = nil -- Skip redirect from mysite.verizon.net and members.bellatlantic.net if item_type == "image" then if string.match(url, "cloudfront%.net") then return verdict elseif string.match(url, "twimg%.com") then return verdict elseif string.match(url, "amazonaws%.com") then return verdict elseif string.match(url, "advertise%.twitpic%.com") then return false elseif string.match(url, "/[^:]+:[^/]+/") then return false elseif string.match(url, '/[^"]+"[^/]+/') then return false elseif not string.match(url, "twitpic%.com") and ishtml ~= 1 then return verdict elseif not string.match(url, item_value) then return false else return false end elseif item_type == "user" then if string.match(url, "cloudfront%.net") then return true elseif string.match(url, "twimg%.com") then return true elseif string.match(url, "amazonaws%.com") then return true elseif string.match(url, "advertise%.twitpic%.com") then return false elseif not string.match(url, "twitpic%.com") and ishtml ~= 1 then return true elseif string.match(url, item_value) then return true else return false end elseif item_type == "tag" then if string.match(url, "cloudfront%.net") then return true elseif string.match(url, "twimg%.com") then return true elseif string.match(url, "amazonaws%.com") then return true elseif string.match(url, "advertise%.twitpic%.com") then return false -- Check if we are on the last page of a tag elseif string.match(url, "twitpic%.com/tag/[^%?]+%?page=[0-9]+") then if not html then html = read_file(file) end if not string.match(url, '<div class="user%-photo%-content right">') then return false else return true end elseif not string.match(url, "twitpic%.com") and ishtml ~= 1 then return true elseif string.match(url, item_value) then return true else return false end else return verdict end end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r") io.stdout:flush() if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then if string.match(url["host"], "twitpic%.com") or string.match(url["host"], "cloudfront%.net") or string.match(url["host"], "twimg%.com") or string.match(url["host"], "amazonaws%.com") then io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.NOTHING else return wget.actions.CONTINUE end else io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.NOTHING else return wget.actions.CONTINUE end end elseif status_code == 0 then return wget.actions.ABORT end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(1000, 2000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
twitpic.lua: fixes for what needs to download
twitpic.lua: fixes for what needs to download
Lua
unlicense
ArchiveTeam/twitpic-grab,ArchiveTeam/twitpic-grab,ArchiveTeam/twitpic-grab
963567a9902898e6f195837bac26859cd639036c
testserver/item/id_314_ash.lua
testserver/item/id_314_ash.lua
require("base.common") module("item.id_314_ash", package.seeall) -- UPDATE common SET com_script='item.id_314_ash' WHERE com_itemid = 314; function LookAtItem(User,Item) -- Mummy -> 101 -- Skeleton -> 111 -- Demonskeleton -> 171 -- Skulls -> 211 -- Ghostskeleton -> 231 if ( Item.quality == 101) then -- Mummie if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Grnliche Asche"); else world:itemInform(User,Item,"greenish ash"); end elseif ( Item.quality == 111 ) then -- Skeleton if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Reine weie Asche"); else world:itemInform(User,Item,"pure white ash"); end elseif ( Item.quality == 171 ) then -- Demonskeleton if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Rtliche Asche"); else world:itemInform(User,Item,"reddish ash"); end elseif ( Item.quality == 211 ) then --Skulls if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Silbrige Asche"); else world:itemInform(User,Item,"silverish ash"); end elseif ( Item.quality == 231 ) then --Ghostskeleton if (User:getPlayerLanguage() == 0) then world:itemInform(User,Item,"Bluliche Asche"); else world:itemInform(User,Item,"blueish ash"); end else User:inform( teleportLookAt( User, Item ) ); end end
require("base.common") module("item.id_314_ash", package.seeall) -- UPDATE common SET com_script='item.id_314_ash' WHERE com_itemid = 314; function LookAtItem(User,Item) -- Mummy -> 101 -- Skeleton -> 111 -- Demonskeleton -> 171 -- Skulls -> 211 -- Ghostskeleton -> 231 if ( Item.quality == 101) then -- Mummie base.lookat.SetSpecialName(Item, "Grnliche Asche", "Greenish ash") elseif ( Item.quality == 111 ) then -- Skeleton base.lookat.SetSpecialName(Item, "Reine weie Asche", "Pure white ash"); elseif ( Item.quality == 171 ) then -- Demonskeleton base.lookat.SetSpecialName(Item, "Rtliche Asche", "Reddish ash"); elseif ( Item.quality == 211 ) then --Skulls base.lookat.SetSpecialName(Item, "Silbrige Asche", "Silverish ash"); elseif ( Item.quality == 231 ) then --Ghostskeleton base.lookat.SetSpecialName(Item, ,"Bluliche Asche", "Blueish ash"); else return; end world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE)); end
lookat fix
lookat fix
Lua
agpl-3.0
KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content
98d234b5fb7f51a1c85153165d2bbcd2982d618b
aspects/nvim/files/.config/nvim/lua/wincent/ftplugin/lua/includeexpr.lua
aspects/nvim/files/.config/nvim/lua/wincent/ftplugin/lua/includeexpr.lua
local fmt = string.format -- Look at first line of `package.config` for directory separator. -- See: http://www.lua.org/manual/5.2/manual.html#pdf-package.config local separator = string.match(package.config, '^[^\n]') -- Search for lua traditional include paths. -- This mimics how require internally works. local function include_paths(fname, ext) ext = ext or "lua" local paths = string.gsub(package.path, "%?", fname) for path in string.gmatch(paths, '[^%;]+') do if vim.fn.filereadable(path) == 1 then return path end end end -- Search for nvim lua include paths local function include_rtpaths(fname, ext) ext = ext or "lua" local rtpaths = vim.api.nvim_list_runtime_paths() local modfile, initfile = fmt("%s.%s", fname, ext), fmt("init.%s", ext) for _, path in ipairs(rtpaths) do -- Look on runtime path for 'lua/*.lua' files local path1 = table.concat({ path, ext, modfile }, separator) if vim.fn.filereadable(path1) == 1 then return path1 end -- Look on runtime path for 'lua/*/init.lua' files local path2 = table.concat({ path, ext, fname, initfile }, separator) if vim.fn.filereadable(path2) == 1 then return path2 end end end -- Global function that searches the path for the required file local function find_required_path(module) -- Properly change '.' to separator (probably '/' on *nix and '\' on Windows) local fname = vim.fn.substitute(module, '\\.', separator, 'g') local f ---- First search for lua modules f = include_paths(fname, "lua") if f then return f end -- This part is just for nvim modules f = include_rtpaths(fname, "lua") if f then return f end ---- Now search for Fennel modules f = include_paths(fname, "fnl") if f then return f end -- This part is just for nvim modules f = include_rtpaths(fname, "fnl") if f then return f end end return find_required_path
local fmt = string.format -- Look at first line of `package.config` for directory separator. -- See: http://www.lua.org/manual/5.2/manual.html#pdf-package.config local separator = string.match(package.config, '^[^\n]') -- Search for lua traditional include paths. -- This mimics how require internally works. local function include_paths(fname) local paths = string.gsub(package.path, "%?", fname) for path in string.gmatch(paths, '[^%;]+') do if vim.fn.filereadable(path) == 1 then return path end end end -- Search for nvim lua include paths local function include_rtpaths(fname, ext) ext = ext or "lua" local rtpaths = vim.api.nvim_list_runtime_paths() local modfile, initfile = fmt("%s.%s", fname, ext), fmt("init.%s", ext) for _, path in ipairs(rtpaths) do -- Look on runtime path for 'lua/*.lua' files local path1 = table.concat({ path, ext, modfile }, separator) if vim.fn.filereadable(path1) == 1 then return path1 end -- Look on runtime path for 'lua/*/init.lua' files local path2 = table.concat({ path, ext, fname, initfile }, separator) if vim.fn.filereadable(path2) == 1 then return path2 end end end -- Global function that searches the path for the required file local function find_required_path(module) -- Properly change '.' to separator (probably '/' on *nix and '\' on Windows) local fname = vim.fn.substitute(module, '\\.', separator, 'g') local f ---- First search for lua modules f = include_paths(fname) if f then return f end -- This part is just for nvim modules f = include_rtpaths(fname, "lua") if f then return f end -- This part is just for nvim modules f = include_rtpaths(fname, "fnl") if f then return f end end return find_required_path
refactor(nvim): remove unused parameter from `include_paths()`
refactor(nvim): remove unused parameter from `include_paths()` `ext` is not used, so the call to `include_paths()` with "fnl" as the second parameter isn't doing anything. Now, `package.path` is going to look something like this (but all on one line, separated by ";"): ./?.lua /usr/local/share/luajit-2.1.0-beta3/?.lua /usr/local/share/lua/5.1/?.lua /usr/local/share/lua/5.1/?/init.lua /usr/local/share/lua/5.1/?.lua /usr/local/share/lua/5.1/?/init.lua It is possible to configure Lua's `require()` to automatically compile ".fnl" files on demand: - https://fennel-lang.org/api#use-luas-built-in-require-function but I don't know whether there is any expectation that you should be able to add "?.fnl" entries to your `package.path` or not. I presume you probably can't, and that what's actually expected is that a ".lua" file gets compiled at the same location. As such, we'd actually expect our code here to check for ".fnl" files first, because the user probably would rather see the source files than the compiled ones. That's something to figure out if I ever become a Fennel user, or one tells me about it. In the meantime, there's dead code to kill, so I'm going to remove it rather than blindly "fixing" it to support a use case I'm not even familiar with.
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
5d79939d8721fd2042be4103c8389e2582b7177e
src_trunk/resources/social-system/s_friends.lua
src_trunk/resources/social-system/s_friends.lua
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// ----------------------[KEY BINDS]-------------------- function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do setElementData(arrayPlayer, "friends.visible", 0, false) if not(isKeyBound(arrayPlayer, "o", "down", toggleFriends)) then bindKey(arrayPlayer, "o", "down", toggleFriends) end end end function bindKeysOnJoin() bindKey(source, "o", "down", toggleFriends) setElementData(source, "friends.visible", 0, false) end addEventHandler("onResourceStart", getResourceRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) function toggleFriends(source) local logged = getElementData(source, "gameaccountloggedin") if (logged==1) then local visible = getElementData(source, "friends.visible") if (visible==0) then -- not already showing local accid = tonumber(getElementData(source, "gameaccountid")) local result = mysql_query(handler, "SELECT friends, friendsmessage FROM accounts WHERE id='" .. accid .. "' LIMIT 1") if (result) then local sfriends = mysql_result(result, 1, 1) local fmessage = mysql_result(result, 1, 2) if (tostring(sfriends)==tostring(mysql_null())) then sfriends = "" end if (tostring(fmessage)==tostring(mysql_null())) then fmessage = "" end local friends = { } local count = 1 for i=1, 100 do local fid = gettok(sfriends, i, 59) if (fid) then local fresult = mysql_query(handler, "SELECT username, friendsmessage, yearday, year, country, os FROM accounts WHERE id='" .. fid .. "' LIMIT 1") local aresult = mysql_query(handler, "SELECT id FROM achievements WHERE account='" .. fid .. "'") local numachievements = mysql_num_rows(aresult) mysql_free_result(aresult) --outputDebugString(mysql_result(fresult, 1, 1)) if (mysql_result(fresult, 1, 1)~=nil) then -- we should make it auto delete in future... friends[count] = { } friends[count][1] = tonumber(fid) -- USER ID friends[count][2] = mysql_result(fresult, 1, 1) -- USERNAME friends[count][3] = mysql_result(fresult, 1, 2) -- MESSAGE friends[count][4] = mysql_result(fresult, 1, 5) -- COUNTRY friends[count][7] = tostring(mysql_result(fresult, 1, 6)) -- OPERATING SYSTEM friends[count][8] = tostring(numachievements) -- NUM ACHIEVEMENTS -- Last online local time = getRealTime() local days = time.monthday local months = (time.month+1) local years = (1900+time.year) local yearday = time.yearday local fyearday = tonumber(mysql_result(fresult, 1, 3)) -- YEAR DAY local fyear = tonumber(mysql_result(fresult, 1, 4)) -- YEAR local found, player = false for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do if (tonumber(getElementData(value, "gameaccountid"))==friends[count][1]) then found = true player = value end end if (found) then friends[count][5] = "Online" friends[count][6] = getPlayerName(player) elseif (years~=fyear) then friends[count][5] = "Last Seen: Last Year" elseif (yearday==fyearday) then friends[count][5] = "Last Seen: Today" else local diff = yearday - fyearday friends[count][5] = "Last Seen: " .. tostring(diff) .. " days ago." end count = count + 1 end mysql_free_result(fresult) else break end end mysql_free_result(result) setElementData(source, "friends.visible", 1) triggerClientEvent(source, "showFriendsList", source, friends) else outputChatBox("Error 600000 - Could not retrieve friends list.", source, 255, 0, 0) end end end end addEvent("sendFriends", false) addEventHandler("sendFriends", getRootElement(), toggleFriends) function updateFriendsMessage(message) local safemessage = mysql_escape_string(handler, tostring(message)) local accid = getElementData(source, "gameaccountid") local query = mysql_query(handler, "UPDATE accounts SET friendsmessage='" .. safemessage .. "' WHERE id='" .. accid .. "'") if (query) then setElementData(source, "friends.visible", 0, false) setElementData(source, "friends.message", tostring(safemessage)) mysql_free_result(query) toggleFriends(source) else outputChatBox("Error updating friends message - ensure you used no special characters!", source, 255, 0, 0) end end addEvent("updateFriendsMessage", true) addEventHandler("updateFriendsMessage", getRootElement(), updateFriendsMessage) function removeFriend(id, username, dontShowFriends) local accid = tonumber(getElementData(source, "gameaccountid")) local result = mysql_query(handler, "SELECT friends, friendsmessage FROM accounts WHERE id='" .. accid .. "' LIMIT 1") if (result) then local sfriends = mysql_result(result, 1, 1) local fmessage = mysql_result(result, 1, 2) local friendstring = "" local count = 1 for i=1, 100 do local fid = gettok(sfriends, i, 59) if (fid) then if not (tonumber(fid)==id) then friendstring = friendstring .. fid .. ";" end end end local query = mysql_query(handler, "UPDATE accounts SET friends='" .. friendstring .. "' WHERE id='" .. accid .. "'") mysql_free_result(query) mysql_free_result(result) outputChatBox("You removed '" .. username .. "' from your friends list.", source, 255, 194, 14) setElementData(source, "friends.visible", 0, false) if (dontShowFriends==false) then toggleFriends(source) end end end addEvent("removeFriend", true) addEventHandler("removeFriend", getRootElement(), removeFriend)
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// ----------------------[KEY BINDS]-------------------- function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do setElementData(arrayPlayer, "friends.visible", 0, false) if not(isKeyBound(arrayPlayer, "o", "down", toggleFriends)) then bindKey(arrayPlayer, "o", "down", toggleFriends) end end end function bindKeysOnJoin() bindKey(source, "o", "down", toggleFriends) setElementData(source, "friends.visible", 0, false) end addEventHandler("onResourceStart", getResourceRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) function toggleFriends(source) local logged = getElementData(source, "gameaccountloggedin") if (logged==1) then local visible = getElementData(source, "friends.visible") if (visible==0) then -- not already showing local accid = tonumber(getElementData(source, "gameaccountid")) local result = mysql_query(handler, "SELECT friends, friendsmessage FROM accounts WHERE id='" .. accid .. "' LIMIT 1") if (result) then local sfriends = mysql_result(result, 1, 1) local fmessage = mysql_result(result, 1, 2) if (tostring(sfriends)==tostring(mysql_null())) then sfriends = "" end if (tostring(fmessage)==tostring(mysql_null())) then fmessage = "" end local friends = { } local count = 1 for i=1, 100 do local fid = gettok(sfriends, i, 59) if (fid) then local fresult = mysql_query(handler, "SELECT username, friendsmessage, yearday, year, country, os FROM accounts WHERE id='" .. fid .. "' LIMIT 1") local aresult = mysql_query(handler, "SELECT id FROM achievements WHERE account='" .. fid .. "'") local numachievements = mysql_num_rows(aresult) mysql_free_result(aresult) --outputDebugString(mysql_result(fresult, 1, 1)) if (mysql_result(fresult, 1, 1)~=nil) then -- we should make it auto delete in future... friends[count] = { } friends[count][1] = tonumber(fid) -- USER ID friends[count][2] = mysql_result(fresult, 1, 1) -- USERNAME friends[count][3] = mysql_result(fresult, 1, 2) -- MESSAGE friends[count][4] = mysql_result(fresult, 1, 5) -- COUNTRY friends[count][7] = tostring(mysql_result(fresult, 1, 6)) -- OPERATING SYSTEM friends[count][8] = tostring(numachievements) -- NUM ACHIEVEMENTS -- Last online local time = getRealTime() local days = time.monthday local months = (time.month+1) local years = (1900+time.year) local yearday = time.yearday local fyearday = tonumber(mysql_result(fresult, 1, 3)) -- YEAR DAY local fyear = tonumber(mysql_result(fresult, 1, 4)) -- YEAR local found, player = false for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do if (tonumber(getElementData(value, "gameaccountid"))==friends[count][1]) then found = true player = value end end if (found) then friends[count][5] = "Online" friends[count][6] = getPlayerName(player) elseif (years~=fyear) then friends[count][5] = "Last Seen: Last Year" elseif (yearday==fyearday) then friends[count][5] = "Last Seen: Today" else local diff = yearday - fyearday if diff == 1 then friends[count][5] = "Last Seen: Yesterday" else friends[count][5] = "Last Seen: " .. tostring(diff) .. " days ago" end end count = count + 1 end mysql_free_result(fresult) else break end end mysql_free_result(result) setElementData(source, "friends.visible", 1) triggerClientEvent(source, "showFriendsList", source, friends) else outputChatBox("Error 600000 - Could not retrieve friends list.", source, 255, 0, 0) end end end end addEvent("sendFriends", false) addEventHandler("sendFriends", getRootElement(), toggleFriends) function updateFriendsMessage(message) local safemessage = mysql_escape_string(handler, tostring(message)) local accid = getElementData(source, "gameaccountid") local query = mysql_query(handler, "UPDATE accounts SET friendsmessage='" .. safemessage .. "' WHERE id='" .. accid .. "'") if (query) then setElementData(source, "friends.visible", 0, false) setElementData(source, "friends.message", tostring(safemessage)) mysql_free_result(query) toggleFriends(source) else outputChatBox("Error updating friends message - ensure you used no special characters!", source, 255, 0, 0) end end addEvent("updateFriendsMessage", true) addEventHandler("updateFriendsMessage", getRootElement(), updateFriendsMessage) function removeFriend(id, username, dontShowFriends) local accid = tonumber(getElementData(source, "gameaccountid")) local result = mysql_query(handler, "SELECT friends, friendsmessage FROM accounts WHERE id='" .. accid .. "' LIMIT 1") if (result) then local sfriends = mysql_result(result, 1, 1) local fmessage = mysql_result(result, 1, 2) local friendstring = "" local count = 1 for i=1, 100 do local fid = gettok(sfriends, i, 59) if (fid) then if not (tonumber(fid)==id) then friendstring = friendstring .. fid .. ";" end end end local query = mysql_query(handler, "UPDATE accounts SET friends='" .. friendstring .. "' WHERE id='" .. accid .. "'") mysql_free_result(query) mysql_free_result(result) outputChatBox("You removed '" .. username .. "' from your friends list.", source, 255, 194, 14) setElementData(source, "friends.visible", 0, false) if (dontShowFriends==false) then toggleFriends(source) end end end addEvent("removeFriend", true) addEventHandler("removeFriend", getRootElement(), removeFriend)
text fix
text fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1307 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
f595f220958cc54910585cecaac9c95e422b0044
libs/web/luasrc/template.lua
libs/web/luasrc/template.lua
--[[ LuCI - Template Parser Description: A template parser supporting includes, translations, Lua code blocks and more. It can be used either as a compiler or as an interpreter. FileId: $Id$ License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local fs = require"luci.fs" local sys = require "luci.sys" local util = require "luci.util" local table = require "table" local string = require "string" local config = require "luci.config" local coroutine = require "coroutine" local tostring, pairs, loadstring = tostring, pairs, loadstring local setmetatable, loadfile = setmetatable, loadfile local getfenv, setfenv = getfenv, setfenv local assert, type, error = assert, type, error --- LuCI template library. module "luci.template" config.template = config.template or {} viewdir = config.template.viewdir or util.libpath() .. "/view" compiledir = config.template.compiledir or util.libpath() .. "/view" -- Compile modes: -- memory: Always compile, do not save compiled files, ignore precompiled -- file: Compile on demand, save compiled files, update precompiled compiler_mode = config.template.compiler_mode or "memory" -- Define the namespace for template modules context = util.threadlocal() viewns = { include = function(name) Template(name):render(getfenv(2)) end, } --- Manually compile a given template into an executable Lua function -- @param template LuCI template -- @return Lua template function function compile(template) local expr = {} -- Search all <% %> expressions local function expr_add(ws1, skip1, command, skip2, ws2) table.insert(expr, command) return ( #skip1 > 0 and "" or ws1 ) .. "<%" .. tostring(#expr) .. "%>" .. ( #skip2 > 0 and "" or ws2 ) end -- Save all expressiosn to table "expr" template = template:gsub("(%s*)<%%(%-?)(.-)(%-?)%%>(%s*)", expr_add) local function sanitize(s) s = "%q" % s return s:sub(2, #s-1) end -- Escape and sanitize all the template (all non-expressions) template = sanitize(template) -- Template module header/footer declaration local header = 'write("' local footer = '")' template = header .. template .. footer -- Replacements local r_include = '")\ninclude("%s")\nwrite("' local r_i18n = '"..translate("%1","%2").."' local r_i18n2 = '"..translate("%1", "").."' local r_pexec = '"..(%s or "").."' local r_exec = '")\n%s\nwrite("' -- Parse the expressions for k,v in pairs(expr) do local p = v:sub(1, 1) v = v:gsub("%%", "%%%%") local re = nil if p == "+" then re = r_include:format(sanitize(string.sub(v, 2))) elseif p == ":" then if v:find(" ") then re = sanitize(v):gsub(":(.-) (.*)", r_i18n) else re = sanitize(v):gsub(":(.+)", r_i18n2) end elseif p == "=" then re = r_pexec:format(v:sub(2)) elseif p == "#" then re = "" else re = r_exec:format(v) end template = template:gsub("<%%"..tostring(k).."%%>", re) end return loadstring(template) end --- Render a certain template. -- @param name Template name -- @param scope Scope to assign to template (optional) function render(name, scope) return Template(name):render(scope or getfenv(2)) end -- Template class Template = util.class() -- Shared template cache to store templates in to avoid unnecessary reloading Template.cache = setmetatable({}, {__mode = "v"}) -- Constructor - Reads and compiles the template on-demand function Template.__init__(self, name, srcfile, comfile) local function _encode_filename(str) local function __chrenc( chr ) return "%%%02x" % string.byte( chr ) end if type(str) == "string" then str = str:gsub( "([^a-zA-Z0-9$_%-%.%+!*'(),])", __chrenc ) end return str end self.template = self.cache[name] self.name = name -- Create a new namespace for this template self.viewns = {sink=self.sink} -- Copy over from general namespace util.update(self.viewns, viewns) if context.viewns then util.update(self.viewns, context.viewns) end -- If we have a cached template, skip compiling and loading if self.template then return end -- Enforce cache security local cdir = compiledir .. "/" .. sys.process.info("uid") -- Compile and build local sourcefile = srcfile or (viewdir .. "/" .. name .. ".htm") local compiledfile = comfile or (cdir .. "/" .. _encode_filename(name) .. ".lua") local err if compiler_mode == "file" then local tplmt = fs.mtime(sourcefile) local commt = fs.mtime(compiledfile) if not fs.mtime(cdir) then fs.mkdir(cdir, true) fs.chmod(fs.dirname(cdir), "a+rxw") end -- Build if there is no compiled file or if compiled file is outdated if ((commt == nil) and not (tplmt == nil)) or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then local source source, err = fs.readfile(sourcefile) if source then local compiled, err = compile(source) fs.writefile(compiledfile, util.get_bytecode(compiled)) fs.chmod(compiledfile, "a-rwx,u+rw") self.template = compiled end else assert( sys.process.info("uid") == fs.stat(compiledfile, "uid") and fs.stat(compiledfile, "mode") == "rw-------", "Fatal: Cachefile is not sane!" ) self.template, err = loadfile(compiledfile) end elseif compiler_mode == "memory" then local source source, err = fs.readfile(sourcefile) if source then self.template, err = compile(source) end end -- If we have no valid template throw error, otherwise cache the template if not self.template then error(err) else self.cache[name] = self.template end end -- Renders a template function Template.render(self, scope) scope = scope or getfenv(2) -- Save old environment local oldfenv = getfenv(self.template) -- Put our predefined objects in the scope of the template util.resfenv(self.template) util.updfenv(self.template, scope) util.updfenv(self.template, self.viewns) -- Now finally render the thing local stat, err = util.copcall(self.template) if not stat then setfenv(self.template, oldfenv) error("Error in template %s: %s" % {self.name, err}) end -- Reset environment setfenv(self.template, oldfenv) end
--[[ LuCI - Template Parser Description: A template parser supporting includes, translations, Lua code blocks and more. It can be used either as a compiler or as an interpreter. FileId: $Id$ License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local fs = require"luci.fs" local sys = require "luci.sys" local util = require "luci.util" local table = require "table" local string = require "string" local config = require "luci.config" local coroutine = require "coroutine" local tostring, pairs, loadstring = tostring, pairs, loadstring local setmetatable, loadfile = setmetatable, loadfile local getfenv, setfenv = getfenv, setfenv local assert, type, error = assert, type, error --- LuCI template library. module "luci.template" config.template = config.template or {} viewdir = config.template.viewdir or util.libpath() .. "/view" compiledir = config.template.compiledir or util.libpath() .. "/view" -- Compile modes: -- memory: Always compile, do not save compiled files, ignore precompiled -- file: Compile on demand, save compiled files, update precompiled compiler_mode = config.template.compiler_mode or "memory" -- Define the namespace for template modules context = util.threadlocal() viewns = { include = function(name) Template(name):render(getfenv(2)) end, } --- Manually compile a given template into an executable Lua function -- @param template LuCI template -- @return Lua template function function compile(template) local expr = {} -- Search all <% %> expressions local function expr_add(ws1, skip1, command, skip2, ws2) table.insert(expr, command) return ( #skip1 > 0 and "" or ws1 ) .. "<%" .. tostring(#expr) .. "%>" .. ( #skip2 > 0 and "" or ws2 ) end -- Save all expressiosn to table "expr" template = template:gsub("(%s*)<%%(%-?)(.-)(%-?)%%>(%s*)", expr_add) local function sanitize(s) s = "%q" % s return s:sub(2, #s-1) end -- Escape and sanitize all the template (all non-expressions) template = sanitize(template) -- Template module header/footer declaration local header = 'write("' local footer = '")' template = header .. template .. footer -- Replacements local r_include = '")\ninclude("%s")\nwrite("' local r_i18n = '"..translate("%1","%2").."' local r_i18n2 = '"..translate("%1", "").."' local r_pexec = '"..(%s or "").."' local r_exec = '")\n%s\nwrite("' -- Parse the expressions for k,v in pairs(expr) do local p = v:sub(1, 1) v = v:gsub("%%", "%%%%") local re = nil if p == "+" then re = r_include:format(sanitize(string.sub(v, 2))) elseif p == ":" then if v:find(" ") then re = sanitize(v):gsub(":(.-) (.*)", r_i18n) else re = sanitize(v):gsub(":(.+)", r_i18n2) end elseif p == "=" then re = r_pexec:format(v:sub(2)) elseif p == "#" then re = "" else re = r_exec:format(v) end template = template:gsub("<%%"..tostring(k).."%%>", re) end return loadstring(template) end --- Render a certain template. -- @param name Template name -- @param scope Scope to assign to template (optional) function render(name, scope) return Template(name):render(scope or getfenv(2)) end -- Template class Template = util.class() -- Shared template cache to store templates in to avoid unnecessary reloading Template.cache = setmetatable({}, {__mode = "v"}) -- Constructor - Reads and compiles the template on-demand function Template.__init__(self, name) local function _encode_filename(str) local function __chrenc( chr ) return "%%%02x" % string.byte( chr ) end if type(str) == "string" then str = str:gsub( "([^a-zA-Z0-9$_%-%.%+!*'(),])", __chrenc ) end return str end self.template = self.cache[name] self.name = name -- Create a new namespace for this template self.viewns = {sink=self.sink} -- Copy over from general namespace util.update(self.viewns, viewns) if context.viewns then util.update(self.viewns, context.viewns) end -- If we have a cached template, skip compiling and loading if self.template then return end -- Enforce cache security local cdir = compiledir .. "/" .. sys.process.info("uid") -- Compile and build local sourcefile = viewdir .. "/" .. name local compiledfile = cdir .. "/" .. _encode_filename(name) .. ".lua" local err if compiler_mode == "file" then local tplmt = fs.mtime(sourcefile) or fs.mtime(sourcefile .. ".htm") local commt = fs.mtime(compiledfile) if not fs.mtime(cdir) then fs.mkdir(cdir, true) fs.chmod(fs.dirname(cdir), "a+rxw") end assert(tplmt or commt, "No such template: " .. name) -- Build if there is no compiled file or if compiled file is outdated if not commt or (commt and tplmt and commt < tplmt) then local source source, err = fs.readfile(sourcefile) or fs.readfile(sourcefile .. ".htm") if source then local compiled, err = compile(source) fs.writefile(compiledfile, util.get_bytecode(compiled)) fs.chmod(compiledfile, "a-rwx,u+rw") self.template = compiled end else assert( sys.process.info("uid") == fs.stat(compiledfile, "uid") and fs.stat(compiledfile, "mode") == "rw-------", "Fatal: Cachefile is not sane!" ) self.template, err = loadfile(compiledfile) end elseif compiler_mode == "memory" then local source source, err = fs.readfile(sourcefile) or fs.readfile(sourcefile .. ".htm") if source then self.template, err = compile(source) end end -- If we have no valid template throw error, otherwise cache the template if not self.template then error(err) else self.cache[name] = self.template end end -- Renders a template function Template.render(self, scope) scope = scope or getfenv(2) -- Save old environment local oldfenv = getfenv(self.template) -- Put our predefined objects in the scope of the template util.resfenv(self.template) util.updfenv(self.template, scope) util.updfenv(self.template, self.viewns) -- Now finally render the thing local stat, err = util.copcall(self.template) if not stat then setfenv(self.template, oldfenv) error("Error in template %s: %s" % {self.name, err}) end -- Reset environment setfenv(self.template, oldfenv) end
libs/web: Fixed luci.template
libs/web: Fixed luci.template git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@3084 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,stephank/luci,saraedum/luci-packages-old,ch3n2k/luci,ch3n2k/luci,alxhh/piratenluci,vhpham80/luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,projectbismark/luci-bismark,jschmidlapp/luci,gwlim/luci,jschmidlapp/luci,projectbismark/luci-bismark,phi-psi/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,projectbismark/luci-bismark,Flexibity/luci,vhpham80/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,alxhh/piratenluci,ch3n2k/luci,ch3n2k/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,8devices/carambola2-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,freifunk-gluon/luci,vhpham80/luci,projectbismark/luci-bismark,freifunk-gluon/luci,Flexibity/luci,Canaan-Creative/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,phi-psi/luci,vhpham80/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,stephank/luci,saraedum/luci-packages-old,Flexibity/luci,gwlim/luci,Flexibity/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,yeewang/openwrt-luci,gwlim/luci,ch3n2k/luci,Flexibity/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,Flexibity/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,alxhh/piratenluci,eugenesan/openwrt-luci,Canaan-Creative/luci,alxhh/piratenluci,8devices/carambola2-luci,yeewang/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,gwlim/luci,jschmidlapp/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,jschmidlapp/luci,ThingMesh/openwrt-luci,phi-psi/luci,phi-psi/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,stephank/luci,ch3n2k/luci,gwlim/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,stephank/luci,saraedum/luci-packages-old,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,stephank/luci,jschmidlapp/luci,Flexibity/luci,phi-psi/luci,projectbismark/luci-bismark,freifunk-gluon/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,phi-psi/luci,phi-psi/luci,jschmidlapp/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,jschmidlapp/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,jschmidlapp/luci,alxhh/piratenluci,yeewang/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,8devices/carambola2-luci
b96a17a22ebddc07d8cf44ac3a330f451c965409
src_trunk/resources/job-system/s_job_system.lua
src_trunk/resources/job-system/s_job_system.lua
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// chDimension = 125 chInterior = 3 employmentCollision = createColSphere(360.8212890625, 173.62351989746, 1009.109375, 5) exports.pool:allocateElement(employmentCollision) -- /employment at cityhall function employment(thePlayer, matchingDimension) local logged = getElementData(thePlayer, "loggedin") if (logged==1) then if (isElementWithinColShape(thePlayer, employmentCollision)) then triggerClientEvent(thePlayer, "onEmployment", thePlayer) end end end addEventHandler("onColShapeHit", employmentCollision, employment) -- CALL BACKS FROM CLIENT function givePlayerJob(jobID) local charname = getPlayerName(source) setElementData(source, "job", jobID) exports.global:givePlayerAchievement(source, 30) if (jobID==4) then -- CITY MAINTENANCE giveWeapon(source, 41, 2500, true) outputChatBox("Use this paint to paint over tags you find.", source, 255, 194, 14) setElementData(source, "tag", 9) end end addEvent("acceptJob", true) addEventHandler("acceptJob", getRootElement(), givePlayerJob)
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// chDimension = 125 chInterior = 3 employmentCollision = createColSphere(360.8212890625, 173.62351989746, 1009.109375, 5) setElementDimension(employmentCollision, chDimension) exports.pool:allocateElement(employmentCollision) -- /employment at cityhall function employment(thePlayer, matchingDimension) if matchingDimension then local logged = getElementData(thePlayer, "loggedin") if (logged==1) then if (isElementWithinColShape(thePlayer, employmentCollision)) then triggerClientEvent(thePlayer, "onEmployment", thePlayer) end end end end addEventHandler("onColShapeHit", employmentCollision, employment) -- CALL BACKS FROM CLIENT function givePlayerJob(jobID) local charname = getPlayerName(source) setElementData(source, "job", jobID) exports.global:givePlayerAchievement(source, 30) if (jobID==4) then -- CITY MAINTENANCE giveWeapon(source, 41, 2500, true) outputChatBox("Use this paint to paint over tags you find.", source, 255, 194, 14) setElementData(source, "tag", 9) end end addEvent("acceptJob", true) addEventHandler("acceptJob", getRootElement(), givePlayerJob)
fixed employment window showing up in fbi/sa-news-hq
fixed employment window showing up in fbi/sa-news-hq git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@741 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
8e35a6e4ab73a01a019ddd6c87425bcb1c61e2cb
frontend/ui/widget/container/inputcontainer.lua
frontend/ui/widget/container/inputcontainer.lua
local WidgetContainer = require("ui/widget/container/widgetcontainer") local UIManager = require("ui/uimanager") local Screen = require("device").screen local Geom = require("ui/geometry") local Event = require("ui/event") local _ = require("gettext") --[[ an InputContainer is an WidgetContainer that handles input events an example for a key_event is this: PanBy20 = { { "Shift", Input.group.Cursor }, seqtext = "Shift+Cursor", doc = "pan by 20px", event = "Pan", args = 20, is_inactive = true, }, PanNormal = { { Input.group.Cursor }, seqtext = "Cursor", doc = "pan by 10 px", event = "Pan", args = 10, }, Quit = { {"Home"} }, it is suggested to reference configurable sequences from another table and store that table as configuration setting --]] local InputContainer = WidgetContainer:new{ vertical_align = "top", } function InputContainer:_init() -- we need to do deep copy here local new_key_events = {} if self.key_events then for k,v in pairs(self.key_events) do new_key_events[k] = v end end self.key_events = new_key_events local new_ges_events = {} if self.ges_events then for k,v in pairs(self.ges_events) do new_ges_events[k] = v end end self.ges_events = new_ges_events end function InputContainer:paintTo(bb, x, y) if self[1] == nil then return end if not self.dimen then local content_size = self[1]:getSize() self.dimen = Geom:new{w = content_size.w, h = content_size.h} end self.dimen.x = x self.dimen.y = y if self.vertical_align == "center" then local content_size = self[1]:getSize() self[1]:paintTo(bb, x, y + math.floor((self.dimen.h - content_size.h)/2)) else self[1]:paintTo(bb, x, y) end end --[[ the following handler handles keypresses and checks if they lead to a command. if this is the case, we retransmit another event within ourselves --]] function InputContainer:onKeyPress(key) for name, seq in pairs(self.key_events) do if not seq.is_inactive then for _, oneseq in ipairs(seq) do if key:match(oneseq) then local eventname = seq.event or name return self:handleEvent(Event:new(eventname, seq.args, key)) end end end end end function InputContainer:onGesture(ev) for name, gsseq in pairs(self.ges_events) do for _, gs_range in ipairs(gsseq) do if gs_range:match(ev) then local eventname = gsseq.event or name return self:handleEvent(Event:new(eventname, gsseq.args, ev)) end end end end function InputContainer:onInput(input) if self.enter_callback == nil then return end local InputDialog = require("ui/widget/inputdialog") self.input_dialog = InputDialog:new{ title = input.title or "", input = input.input, input_hint = input.hint_func and input.hint_func() or input.hint or "", input_type = input.type or "number", buttons = { { { text = _("Cancel"), callback = function() self:closeInputDialog() end, }, { text = _("OK"), callback = function() input.callback(self.input_dialog:getInputText()) self:closeInputDialog() end, }, }, }, enter_callback = function() input.callback(self.input_dialog:getInputText()) self:closeInputDialog() end, width = Screen:getWidth() * 0.8, height = Screen:getHeight() * 0.2, } self.input_dialog:onShowKeyboard() UIManager:show(self.input_dialog) end function InputContainer:closeInputDialog() self.input_dialog:onClose() UIManager:close(self.input_dialog) end return InputContainer
local WidgetContainer = require("ui/widget/container/widgetcontainer") local UIManager = require("ui/uimanager") local Screen = require("device").screen local Geom = require("ui/geometry") local Event = require("ui/event") local _ = require("gettext") --[[ an InputContainer is an WidgetContainer that handles input events an example for a key_event is this: PanBy20 = { { "Shift", Input.group.Cursor }, seqtext = "Shift+Cursor", doc = "pan by 20px", event = "Pan", args = 20, is_inactive = true, }, PanNormal = { { Input.group.Cursor }, seqtext = "Cursor", doc = "pan by 10 px", event = "Pan", args = 10, }, Quit = { {"Home"} }, it is suggested to reference configurable sequences from another table and store that table as configuration setting --]] local InputContainer = WidgetContainer:new{ vertical_align = "top", } function InputContainer:_init() -- we need to do deep copy here local new_key_events = {} if self.key_events then for k,v in pairs(self.key_events) do new_key_events[k] = v end end self.key_events = new_key_events local new_ges_events = {} if self.ges_events then for k,v in pairs(self.ges_events) do new_ges_events[k] = v end end self.ges_events = new_ges_events end function InputContainer:paintTo(bb, x, y) if self[1] == nil then return end if not self.dimen then local content_size = self[1]:getSize() self.dimen = Geom:new{w = content_size.w, h = content_size.h} end self.dimen.x = x self.dimen.y = y if self.vertical_align == "center" then local content_size = self[1]:getSize() self[1]:paintTo(bb, x, y + math.floor((self.dimen.h - content_size.h)/2)) else self[1]:paintTo(bb, x, y) end end --[[ the following handler handles keypresses and checks if they lead to a command. if this is the case, we retransmit another event within ourselves --]] function InputContainer:onKeyPress(key) for name, seq in pairs(self.key_events) do if not seq.is_inactive then for _, oneseq in ipairs(seq) do if key:match(oneseq) then local eventname = seq.event or name return self:handleEvent(Event:new(eventname, seq.args, key)) end end end end end function InputContainer:onGesture(ev) for name, gsseq in pairs(self.ges_events) do for _, gs_range in ipairs(gsseq) do if gs_range:match(ev) then local eventname = gsseq.event or name return self:handleEvent(Event:new(eventname, gsseq.args, ev)) end end end end function InputContainer:onInput(input) local InputDialog = require("ui/widget/inputdialog") self.input_dialog = InputDialog:new{ title = input.title or "", input = input.input, input_hint = input.hint_func and input.hint_func() or input.hint or "", input_type = input.type or "number", buttons = { { { text = _("Cancel"), callback = function() self:closeInputDialog() end, }, { text = _("OK"), callback = function() input.callback(self.input_dialog:getInputText()) self:closeInputDialog() end, }, }, }, enter_callback = function() input.callback(self.input_dialog:getInputText()) self:closeInputDialog() end, width = Screen:getWidth() * 0.8, height = Screen:getHeight() * 0.2, } self.input_dialog:onShowKeyboard() UIManager:show(self.input_dialog) end function InputContainer:closeInputDialog() self.input_dialog:onClose() UIManager:close(self.input_dialog) end return InputContainer
fix inputcontainer
fix inputcontainer
Lua
agpl-3.0
Frenzie/koreader,koreader/koreader,Markismus/koreader,Hzj-jie/koreader,pazos/koreader,NiLuJe/koreader,NiLuJe/koreader,frankyifei/koreader,chihyang/koreader,mwoz123/koreader,poire-z/koreader,apletnev/koreader,mihailim/koreader,Frenzie/koreader,koreader/koreader,robert00s/koreader,lgeek/koreader,houqp/koreader,NickSavage/koreader,poire-z/koreader
1d55c0df9c05314a0c9218132fda4775535d1f27
home/config/nvim/lua/plugins/nvim-lspconfig.lua
home/config/nvim/lua/plugins/nvim-lspconfig.lua
local wk = require('which-key') local li = require('nvim-lsp-installer') local illum = require('illuminate') local aerial = require('aerial') local lsp = vim.lsp local diag = vim.diagnostic wk.register( { l = { name = 'LSP', a = { '<Cmd>AerialToggle<Cr>', 'Toggle Aerial' } , e = { '<Cmd>lua vim.lsp.buf.code_action()<Cr>', 'Code Actions' }, f = { function() lsp.buf.formatting() end, 'Format' }, i = { function() lsp.buf.implementation() end, 'Implementation' }, k = { function() lsp.buf.hover() end, 'Hover' }, l = { function() diag.open_float() end, 'Show Line Diagnostics' }, q = { function() diag.setloclist() end, 'Set Location List' }, R = { '<Cmd>LspRestart<Cr>', 'Restart LSP' }, m = { function() lsp.buf.rename() end, 'Rename' }, y = { function() lsp.buf.type_definition() end, 'Type Definition' }, -- Telescope lsp maps D = { '<Cmd>Telescope lsp_document_diagnostics<Cr>', 'Diagnostics' }, I = { '<Cmd>Telescope lsp_implementations<Cr>', 'Implementations' }, d = { '<Cmd>Telescope lsp_definitions<Cr>', 'Definitions' }, r = { '<Cmd>Telescope lsp_references<Cr>', 'References' }, s = { '<Cmd>Telescope lsp_document_symbols<Cr>', 'Symbols' }, -- nvim-lsp-installer maps L = { '<Cmd>LspInstallInfo<Cr>', 'nvim-lsp-installer UI' }, }, }, { prefix = '<Leader>', } ) wk.register( { ['[d'] = { function() diag.goto_prev() end, 'Previous Diagnostic' }, [']d'] = { function() diag.goto_next() end, 'Next Diagnostic' }, -- vim-illuminate maps [']i'] = { function() illum.next_reference({ wrap = true }) end, 'Move to next doc highlight' }, ['[i'] = { function() illum.next_reference({ wrap = true, reverse = true }) end, 'Move to prev doc highlight' }, } ) local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) local function disable_formatting(client) client.resolved_capabilities.document_formatting = false client.resolved_capabilities.document_range_formatting = false end local enhance_server_opts = { ['tsserver'] = function(opts, client) -- Prefer prettier formatting over null-ls disable_formatting(client) end, ['jsonls'] = function(opts, client) -- Prefer prettier formatting over null-ls disable_formatting(client) end, } li.on_server_ready(function(server) local opts = { capabilities = capabilities, } opts.on_attach = function(client, bufnr) if enhance_server_opts[server.name] then -- Enhance the default opts with the server-specific ones enhance_server_opts[server.name](opts, client) end -- Automatically format for servers which support it if client.resolved_capabilities.document_formatting then vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()") end -- Attach vim-illuminate illum.on_attach(client) -- Attach aerial.nvim aerial.on_attach(client, bufnr) end -- This setp() function is exactly the same as lspconfig's setup function (:help lspconfig-quickstart) server:setup(opts) vim.cmd([[ do User LspAttachBuffers ]]) end)
local wk = require('which-key') local lspinstaller = require('nvim-lsp-installer') local lspconfig = require('lspconfig') local illum = require('illuminate') local aerial = require('aerial') local lsp = vim.lsp local diag = vim.diagnostic wk.register( { l = { name = 'LSP', a = { '<Cmd>AerialToggle<Cr>', 'Toggle Aerial' } , e = { '<Cmd>lua vim.lsp.buf.code_action()<Cr>', 'Code Actions' }, f = { function() lsp.buf.formatting() end, 'Format' }, i = { function() lsp.buf.implementation() end, 'Implementation' }, k = { function() lsp.buf.hover() end, 'Hover' }, l = { function() diag.open_float() end, 'Show Line Diagnostics' }, q = { function() diag.setloclist() end, 'Set Location List' }, R = { '<Cmd>LspRestart<Cr>', 'Restart LSP' }, m = { function() lsp.buf.rename() end, 'Rename' }, y = { function() lsp.buf.type_definition() end, 'Type Definition' }, -- Telescope lsp maps D = { '<Cmd>Telescope lsp_document_diagnostics<Cr>', 'Diagnostics' }, I = { '<Cmd>Telescope lsp_implementations<Cr>', 'Implementations' }, d = { '<Cmd>Telescope lsp_definitions<Cr>', 'Definitions' }, r = { '<Cmd>Telescope lsp_references<Cr>', 'References' }, s = { '<Cmd>Telescope lsp_document_symbols<Cr>', 'Symbols' }, -- nvim-lsp-installer maps L = { '<Cmd>LspInstallInfo<Cr>', 'nvim-lsp-installer UI' }, }, }, { prefix = '<Leader>', } ) wk.register( { ['[d'] = { function() diag.goto_prev() end, 'Previous Diagnostic' }, [']d'] = { function() diag.goto_next() end, 'Next Diagnostic' }, -- vim-illuminate maps [']i'] = { function() illum.next_reference({ wrap = true }) end, 'Move to next doc highlight' }, ['[i'] = { function() illum.next_reference({ wrap = true, reverse = true }) end, 'Move to prev doc highlight' }, } ) local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) local function disable_formatting(client) client.resolved_capabilities.document_formatting = false client.resolved_capabilities.document_range_formatting = false end local enhance_server_opts = { ['tsserver'] = function(opts, client) -- Prefer prettier formatting over null-ls disable_formatting(client) end, ['jsonls'] = function(opts, client) -- Prefer prettier formatting over null-ls disable_formatting(client) end, } lspinstaller.setup() local servers = { 'tsserver', 'jsonls', 'eslint' } for _, server in ipairs(servers) do lspconfig[server].setup({ capabilities = capabilities, on_attach = function(client, bufnr) if enhance_server_opts[server] then -- Enhance the default opts with the server-specific ones enhance_server_opts[server](opts, client) end -- Automatically format for servers which support it if client.resolved_capabilities.document_formatting then vim.cmd("autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()") end -- Attach vim-illuminate illum.on_attach(client) -- Attach aerial.nvim aerial.on_attach(client, bufnr) end, }) end
nvim: fix nvim-lsp-installer deprecation
nvim: fix nvim-lsp-installer deprecation
Lua
unlicense
knpwrs/dotfiles
0969c5f8f53700877a1a42297ebc3e30d932ebd3
openwrt/package/linkmeter/luasrc/linkmeterd.lua
openwrt/package/linkmeter/luasrc/linkmeterd.lua
#! /usr/bin/env lua local io = require("io") local os = require("os") local rrd = require("rrd") local nixio = require("nixio") nixio.fs = require("nixio.fs") local uci = require("uci") local SERIAL_DEVICE = "/dev/ttyS1" local RRD_FILE = "/tmp/hm.rrd" local JSON_FILE = "/tmp/json" local probeNames = { "Pit", "Food Probe1", "Food Probe2", "Ambient" } function rrdCreate() return rrd.create( RRD_FILE, "--step", "2", "DS:sp:GAUGE:30:0:1000", "DS:t0:GAUGE:30:0:1000", "DS:t1:GAUGE:30:0:1000", "DS:t2:GAUGE:30:0:1000", "DS:t3:GAUGE:30:0:1000", "DS:f:GAUGE:30:-1000:100", "RRA:AVERAGE:0.6:5:360", "RRA:AVERAGE:0.6:30:360", "RRA:AVERAGE:0.6:60:360", "RRA:AVERAGE:0.6:90:480" ) end -- This might look a big hokey but rather than build the string -- and discard it every time, just replace the values to reduce -- the load on the garbage collector local JSON_TEMPLATE = { '{"time":', 0, ',"set":', 0, ',"lid":', 0, ',"fan":{"c":', 0, ',"a":', 0, '},"temps":[{"n":"', 'Pit', '","c":', 0, -- probe1 '},{"n":"', 'Food Probe1', '","c":', 0, -- probe2 '},{"n":"', 'Food Probe2', '","c":', 0, -- probe3 '},{"n":"', 'Ambient', '","c":', 0, -- probe4 '}]}' } local JSON_FROM_CSV = {2, 4, 14, 18, 22, 26, 8, 10, 6 } function jsonWrite(vals) local i,v for i,v in ipairs(vals) do JSON_TEMPLATE[JSON_FROM_CSV[i]] = v end return nixio.fs.writefile(JSON_FILE, table.concat(JSON_TEMPLATE)) end function segSplit(line) local retVal = {} local fieldstart = 1 line = line .. ',' repeat local nexti = line:find(',', fieldstart) retVal[#retVal+1] = line:sub(fieldstart, nexti-1) fieldstart = nexti + 1 until fieldstart > line:len() table.remove(retVal, 1) -- remove the segment name return retVal end function segProbeNames(line) local vals = segSplit(line) if #vals < 4 then return end JSON_TEMPLATE[12] = vals[1] JSON_TEMPLATE[16] = vals[2] JSON_TEMPLATE[20] = vals[3] JSON_TEMPLATE[24] = vals[4] end function segRfUpdate(line) local vals = segSplit(line) local idx = 1 while (idx < #vals) do local nodeId = vals[idx] local signalLevel = vals[idx+1] local lastReceive = vals[idx+2] --nixio.syslog("info", ("RF%s: %d last %s"):format(nodeId, math.floor(signalLevel/2.55), lastReceive)) idx = idx + 3 end end local lastUpdate = os.time() function segStateUpdate(line) local vals = segSplit(line) if #vals == 8 then -- If the time has shifted more than 24 hours since the last update -- the clock has probably just been set from 0 (at boot) to actual -- time. Recreate the rrd to prevent a 40 year long graph local time = os.time() if time - lastUpdate > (24*60*60) then nixio.syslog("notice", "Time jumped forward by "..(time-lastUpdate)..", restarting database") rrdCreate() end lastUpdate = time -- Add the time as the first item table.insert(vals, 1, time) jsonWrite(vals) local lid = tonumber(vals[9]) or 0 -- If the lid value is non-zero, it replaces the fan value if lid ~= 0 then vals[7] = lid end table.remove(vals, 9) -- lid table.remove(vals, 8) -- fan avg rrd.update(RRD_FILE, table.concat(vals, ":")) end end local hm = io.open(SERIAL_DEVICE, "rwb") if hm == nil then die("Can not open serial device") end nixio.umask("0022") -- Create database if not nixio.fs.access(RRD_FILE) then rrdCreate() end -- Create json file if not nixio.fs.access("/www/json") then if not nixio.fs.symlink(JSON_FILE, "/www/json") then print("Can not create JSON file link") end end local segmentMap = { ["$HMSU"] = segStateUpdate, ["$HMPN"] = segProbeNames, ["$HMRF"] = segRfUpdate } -- Request the current probe names hm:write("/set?pn@XX\n") while true do local hmline = hm:read("*l") if hmline == nil then break end local segmentFunc = segmentMap[hmline:sub(1,5)]; if segmentFunc ~= nil then segmentFunc(hmline) end end hm:close() nixio.fs.unlink("/var/run/linkmeterd/pid")
#! /usr/bin/env lua local io = require("io") local os = require("os") local rrd = require("rrd") local nixio = require("nixio") nixio.fs = require("nixio.fs") local uci = require("uci") local SERIAL_DEVICE = "/dev/ttyS1" local RRD_FILE = "/tmp/hm.rrd" local JSON_FILE = "/tmp/json" function rrdCreate() return rrd.create( RRD_FILE, "--step", "2", "DS:sp:GAUGE:30:0:1000", "DS:t0:GAUGE:30:0:1000", "DS:t1:GAUGE:30:0:1000", "DS:t2:GAUGE:30:0:1000", "DS:t3:GAUGE:30:0:1000", "DS:f:GAUGE:30:-1000:100", "RRA:AVERAGE:0.6:5:360", "RRA:AVERAGE:0.6:30:360", "RRA:AVERAGE:0.6:60:360", "RRA:AVERAGE:0.6:90:480" ) end -- This might look a big hokey but rather than build the string -- and discard it every time, just replace the values to reduce -- the load on the garbage collector local JSON_TEMPLATE = { '{"time":', 0, ',"set":', 0, ',"lid":', 0, ',"fan":{"c":', 0, ',"a":', 0, '},"temps":[{"n":"', 'Pit', '","c":', 0, -- probe1 '},{"n":"', 'Food Probe1', '","c":', 0, -- probe2 '},{"n":"', 'Food Probe2', '","c":', 0, -- probe3 '},{"n":"', 'Ambient', '","c":', 0, -- probe4 '}]}' } local JSON_FROM_CSV = {2, 4, 14, 18, 22, 26, 8, 10, 6 } function jsonWrite(vals) local i,v for i,v in ipairs(vals) do JSON_TEMPLATE[JSON_FROM_CSV[i]] = v end return nixio.fs.writefile(JSON_FILE, table.concat(JSON_TEMPLATE)) end function segSplit(line) local retVal = {} local fieldstart = 1 line = line .. ',' repeat local nexti = line:find(',', fieldstart) retVal[#retVal+1] = line:sub(fieldstart, nexti-1) fieldstart = nexti + 1 until fieldstart > line:len() table.remove(retVal, 1) -- remove the segment name return retVal end function segProbeNames(line) local vals = segSplit(line) if #vals < 4 then return end JSON_TEMPLATE[12] = vals[1] JSON_TEMPLATE[16] = vals[2] JSON_TEMPLATE[20] = vals[3] JSON_TEMPLATE[24] = vals[4] end function segRfUpdate(line) local vals = segSplit(line) local idx = 1 while (idx < #vals) do local nodeId = vals[idx] local signalLevel = vals[idx+1] local lastReceive = vals[idx+2] --nixio.syslog("info", ("RF%s: %d last %s"):format(nodeId, math.floor(signalLevel/2.55), lastReceive)) idx = idx + 3 end end local lastUpdate = os.time() function segStateUpdate(line) local vals = segSplit(line) if #vals == 8 then -- If the time has shifted more than 24 hours since the last update -- the clock has probably just been set from 0 (at boot) to actual -- time. Recreate the rrd to prevent a 40 year long graph local time = os.time() if time - lastUpdate > (24*60*60) then nixio.syslog("notice", "Time jumped forward by "..(time-lastUpdate)..", restarting database") rrdCreate() end lastUpdate = time -- Add the time as the first item table.insert(vals, 1, time) jsonWrite(vals) local lid = tonumber(vals[9]) or 0 -- If the lid value is non-zero, it replaces the fan value if lid ~= 0 then vals[7] = lid end table.remove(vals, 9) -- lid table.remove(vals, 8) -- fan avg rrd.update(RRD_FILE, table.concat(vals, ":")) end end local hm = io.open(SERIAL_DEVICE, "r+b") if hm == nil then die("Can not open serial device") end nixio.umask("0022") -- Create database if not nixio.fs.access(RRD_FILE) then rrdCreate() end -- Create json file if not nixio.fs.access("/www/json") then if not nixio.fs.symlink(JSON_FILE, "/www/json") then print("Can not create JSON file link") end end local segmentMap = { ["$HMSU"] = segStateUpdate, ["$HMPN"] = segProbeNames, ["$HMRF"] = segRfUpdate } -- Request the current probe names hm:write("/set?pnXXX\n") while true do local hmline = hm:read("*l") if hmline == nil then break end local segmentFunc = segmentMap[hmline:sub(1,5)]; if segmentFunc ~= nil then segmentFunc(hmline) end end hm:close() nixio.fs.unlink("/var/run/linkmeterd/pid")
[lm] Remove superflous probeName array and fix serial device file mode
[lm] Remove superflous probeName array and fix serial device file mode
Lua
mit
shmick/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter
a5ab54c7beeabc5374ac9f3ec3af7623cc2aca13
src/websocket/server_ev.lua
src/websocket/server_ev.lua
local socket = require'socket' local tools = require'websocket.tools' local frame = require'websocket.frame' local handshake = require'websocket.handshake' local tconcat = table.concat local tinsert = table.insert local ev local loop local clients = {} clients[true] = {} local client = function(sock,protocol) assert(sock) sock:setoption('tcp-nodelay',true) local fd = sock:getfd() local message_io local close_timer local async_send = require'websocket.ev_common'.async_send(sock,loop) local self = {} self.state = 'OPEN' local user_on_error local on_error = function(s,err) clients[protocol][self] = nil if user_on_error then user_on_error(self,err) else print('Websocket server error',err) end end local user_on_close local on_close = function(was_clean,code,reason) clients[protocol][self] = nil if close_timer then close_timer:stop(loop) close_timer = nil end message_io:stop(loop) self.state = 'CLOSED' if user_on_close then user_on_close(self,was_clean,code,reason or '') end sock:shutdown() sock:close() end local handle_sock_err = function(err) if err == 'closed' then if self.state ~= 'CLOSED' then on_close(false,1006,'') end else on_error(err) end end local user_on_message local on_message = function(message,opcode) if opcode == frame.TEXT or opcode == frame.BINARY then if user_on_message then user_on_message(self,message,opcode) end elseif opcode == frame.CLOSE then if self.state ~= 'CLOSING' then self.state = 'CLOSING' local code,reason = frame.decode_close(message) local encoded = frame.encode_close(code) encoded = frame.encode(encoded,frame.CLOSE) async_send(encoded, function() on_close(true,code or 1006,reason) end,handle_sock_err) else on_close(true,code or 1006,reason) end end end self.send = function(_,message,opcode) local encoded = frame.encode(message,opcode or frame.TEXT) async_send(encoded) end self.on_close = function(_,on_close_arg) user_on_close = on_close_arg end self.on_error = function(_,on_error_arg) user_on_error = on_error_arg end self.on_message = function(_,on_message_arg) user_on_message = on_message_arg end self.broadcast = function(_,...) for client in pairs(clients[protocol]) do if client.state == 'OPEN' then client:send(...) end end end self.close = function(_,code,reason,timeout) clients[protocol][self] = nil if not message_io then self:start() end if self.state == 'OPEN' then self.state = 'CLOSING' assert(message_io) timeout = timeout or 3 local encoded = frame.encode_close(code or 1000,reason or '') encoded = frame.encode(encoded,frame.CLOSE) async_send(encoded) close_timer = ev.Timer.new(function() close_timer = nil on_close(false,1006,'timeout') end,timeout) close_timer:start(loop) end end self.start = function() message_io = require'websocket.ev_common'.message_io( sock,loop, on_message, handle_sock_err) end return self end local listen = function(opts) assert(opts and (opts.protocols or opts.default)) ev = require'ev' loop = opts.loop or ev.Loop.default local on_error = function(s,err) print(err) end local protocols = {} if opts.protocols then for protocol in pairs(opts.protocols) do clients[protocol] = {} tinsert(protocols,protocol) end end local self = {} local listener,err = socket.bind(opts.interface or '*',opts.port or 80) assert(listener,err) listener:settimeout(0) local listen_io = ev.IO.new( function() local client_sock = listener:accept() client_sock:settimeout(0) assert(client_sock) local request = {} ev.IO.new( function(loop,read_io) repeat local line,err,part = client_sock:receive('*l') if line then if last then line = last..line last = nil end request[#request+1] = line elseif err ~= 'timeout' then on_error(self,'Websocket Handshake failed due to socket err:'..err) read_io:stop(loop) return else last = part return end until line == '' read_io:stop(loop) local upgrade_request = tconcat(request,'\r\n') local response,protocol = handshake.accept_upgrade(upgrade_request,protocols) if not response then print('Handshake failed, Request:') print(upgrade_request) client_sock:close() return end local index ev.IO.new( function(loop,write_io) local len = #response local sent,err = client_sock:send(response,index) if not sent then write_io:stop(loop) print('Websocket client closed while handshake',err) elseif sent == len then write_io:stop(loop) local handler local new_client local protocol_index if protocol and opts.protocols[protocol] then protocol_index = protocol handler = opts.protocols[protocol] elseif opts.default then -- true is the 'magic' index for the default handler protocol_index = true handler = opts.default else client_sock:close() if on_error then on_error('bad protocol') end return end new_client = client(client_sock,protocol_index) clients[protocol_index][new_client] = true new_client:start(loop) handler(new_client) else assert(sent < len) index = sent end end,client_sock:getfd(),ev.WRITE):start(loop) end,client_sock:getfd(),ev.READ):start(loop) end,listener:getfd(),ev.READ) self.close = function(keep_clients) listen_io:stop(loop) listener:close() listener = nil if not keep_clients then for protocol,clients in pairs(clients) do for client in pairs(clients) do client:close() end end end end listen_io:start(loop) return self end return { listen = listen }
local socket = require'socket' local tools = require'websocket.tools' local frame = require'websocket.frame' local handshake = require'websocket.handshake' local tconcat = table.concat local tinsert = table.insert local ev local loop local clients = {} clients[true] = {} local client = function(sock,protocol) assert(sock) sock:setoption('tcp-nodelay',true) local fd = sock:getfd() local message_io local close_timer local async_send = require'websocket.ev_common'.async_send(sock,loop) local self = {} self.state = 'OPEN' local user_on_error local on_error = function(s,err) clients[protocol][self] = nil if user_on_error then user_on_error(self,err) else print('Websocket server error',err) end end local user_on_close local on_close = function(was_clean,code,reason) clients[protocol][self] = nil if close_timer then close_timer:stop(loop) close_timer = nil end message_io:stop(loop) self.state = 'CLOSED' if user_on_close then user_on_close(self,was_clean,code,reason or '') end sock:shutdown() sock:close() end local handle_sock_err = function(err) if err == 'closed' then if self.state ~= 'CLOSED' then on_close(false,1006,'') end else on_error(err) end end local user_on_message local on_message = function(message,opcode) if opcode == frame.TEXT or opcode == frame.BINARY then if user_on_message then user_on_message(self,message,opcode) end elseif opcode == frame.CLOSE then if self.state ~= 'CLOSING' then self.state = 'CLOSING' local code,reason = frame.decode_close(message) local encoded = frame.encode_close(code) encoded = frame.encode(encoded,frame.CLOSE) async_send(encoded, function() on_close(true,code or 1006,reason) end,handle_sock_err) else on_close(true,code or 1006,reason) end end end self.send = function(_,message,opcode) local encoded = frame.encode(message,opcode or frame.TEXT) async_send(encoded) end self.on_close = function(_,on_close_arg) user_on_close = on_close_arg end self.on_error = function(_,on_error_arg) user_on_error = on_error_arg end self.on_message = function(_,on_message_arg) user_on_message = on_message_arg end self.broadcast = function(_,...) for client in pairs(clients[protocol]) do if client.state == 'OPEN' then client:send(...) end end end self.close = function(_,code,reason,timeout) clients[protocol][self] = nil if not message_io then self:start() end if self.state == 'OPEN' then self.state = 'CLOSING' assert(message_io) timeout = timeout or 3 local encoded = frame.encode_close(code or 1000,reason or '') encoded = frame.encode(encoded,frame.CLOSE) async_send(encoded) close_timer = ev.Timer.new(function() close_timer = nil on_close(false,1006,'timeout') end,timeout) close_timer:start(loop) end end self.start = function() message_io = require'websocket.ev_common'.message_io( sock,loop, on_message, handle_sock_err) end return self end local listen = function(opts) assert(opts and (opts.protocols or opts.default)) ev = require'ev' loop = opts.loop or ev.Loop.default local on_error = function(s,err) print(err) end local protocols = {} if opts.protocols then for protocol in pairs(opts.protocols) do clients[protocol] = {} tinsert(protocols,protocol) end end local self = {} local listener,err = socket.bind(opts.interface or '*',opts.port or 80) assert(listener,err) listener:settimeout(0) local listen_io = ev.IO.new( function() local client_sock = listener:accept() client_sock:settimeout(0) assert(client_sock) local request = {} ev.IO.new( function(loop,read_io) repeat local line,err,part = client_sock:receive('*l') if line then if last then line = last..line last = nil end request[#request+1] = line elseif err ~= 'timeout' then on_error(self,'Websocket Handshake failed due to socket err:'..err) read_io:stop(loop) return else last = part return end until line == '' read_io:stop(loop) local upgrade_request = tconcat(request,'\r\n') local response,protocol = handshake.accept_upgrade(upgrade_request,protocols) if not response then print('Handshake failed, Request:') print(upgrade_request) client_sock:close() return end local index ev.IO.new( function(loop,write_io) local len = #response local sent,err = client_sock:send(response,index) if not sent then write_io:stop(loop) print('Websocket client closed while handshake',err) elseif sent == len then write_io:stop(loop) local handler local new_client local protocol_index if protocol and opts.protocols[protocol] then protocol_index = protocol handler = opts.protocols[protocol] elseif opts.default then -- true is the 'magic' index for the default handler protocol_index = true handler = opts.default else client_sock:close() if on_error then on_error('bad protocol') end return end new_client = client(client_sock,protocol_index) clients[protocol_index][new_client] = true handler(new_client) new_client:start(loop) else assert(sent < len) index = sent end end,client_sock:getfd(),ev.WRITE):start(loop) end,client_sock:getfd(),ev.READ):start(loop) end,listener:getfd(),ev.READ) self.close = function(keep_clients) listen_io:stop(loop) listener:close() listener = nil if not keep_clients then for protocol,clients in pairs(clients) do for client in pairs(clients) do client:close() end end end end listen_io:start(loop) return self end return { listen = listen }
fix start order of handler
fix start order of handler
Lua
mit
lipp/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,lipp/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets
5febf5875297d20bea779aa9207ce4be6f54f412
turttlebot2_v4_turtlebot.lua
turttlebot2_v4_turtlebot.lua
function setVels_cb(msg) -- not sure if a scale factor is must be applied local linVel = msg.linear.x/2 -- in m/s local rotVel = msg.angular.z*wheelAxis/2 -- in rad/s velocityRight = linVel+rotVel velocityLeft = linVel-rotVel if simulationIsKinematic then -- Simulation is kinematic p=sim.boolOr32(sim.getModelProperty(objHandle),sim.modelproperty_not_dynamic) sim.setModelProperty(objHandle,p) dt=sim.getSimulationTimeStep() p=sim.getJointPosition(leftJoint) sim.setJointPosition(leftJoint,p+velocityLeft*dt*2/wheelDiameter) p=sim.getJointPosition(rightJoint) sim.setJointPosition(rightJoint,p+velocityRight*dt*2/wheelDiameter) linMov=dt*(velocityLeft+velocityRight)/2.0 rotMov=dt*math.atan((velocityRight-velocityLeft)/interWheelDistance) position=sim.getObjectPosition(objHandle,sim.handle_parent) orientation=sim.getObjectOrientation(objHandle,sim.handle_parent) xDir={math.cos(orientation[3]),math.sin(orientation[3]),0.0} position[1]=position[1]+xDir[1]*linMov position[2]=position[2]+xDir[2]*linMov orientation[3]=orientation[3]+rotMov sim.setObjectPosition(objHandle,sim.handle_parent,position) sim.setObjectOrientation(objHandle,sim.handle_parent,orientation) else -- Simulation is dynamic p=sim.boolOr32(sim.getModelProperty(objHandle),sim.modelproperty_not_dynamic)-sim.modelproperty_not_dynamic sim.setModelProperty(objHandle,p) velocityRight = linVel + math.Rad2Deg(rotVel) velocityLeft = linVel - math.Rad2Deg(rotVel) sim.setJointTargetVelocity(leftJoint,velocityLeft*2/wheelDiameter) sim.setJointTargetVelocity(rightJoint,velocityRight*2/wheelDiameter) end end if (sim_call_type==sim.childscriptcall_initialization) then objHandle=sim.getObjectAssociatedWithScript(sim.handle_self) modelBaseName = sim.getObjectName(objHandle) leftJoint=sim.getObjectHandle("turtlebot_leftWheelJoint_") rightJoint=sim.getObjectHandle("turtlebot_rightWheelJoint_") simulationIsKinematic=false -- we want a dynamic simulation here! -- Braitenberg weights: brait_left={0,-0.5,-1.25,-1,-0.2} t_frontBumper = sim.getObjectHandle('bumper_front_joint') t_rightBumper = sim.getObjectHandle('bumper_right_joint') t_leftBumper = sim.getObjectHandle('bumper_left_joint') originMatrix = sim.getObjectMatrix(objHandle,-1) invOriginMatrix = simGetInvertedMatrix(originMatrix) ----------------------------- ROS STUFF -------------------------------- -- Odometry pubPose = simROS.advertise(modelBaseName..'/pose','nav_msgs/Odometry') simROS.publisherTreatUInt8ArrayAsString(pubPose) -- Commands subCmdVel = simROS.subscribe(modelBaseName..'/cmd_vel','geometry_msgs/Twist','setVels_cb') end if (sim_call_type == sim.childscriptcall_sensing) then -- Front Bumper front_bumper_pos = sim.getJointPosition(t_frontBumper) if(front_bumper_pos < -0.001) then -- print("F. COLLISION!") front_collision=true bumperCenterState = 1 else -- print("F. No Collision") front_collision=false bumperCenterState = 0 end -- Right Bumper right_bumper_pos = sim.getJointPosition(t_rightBumper) if(right_bumper_pos < -0.001) then -- print("R. COLLISION!") right_collision=true bumperRightState = 1 else --print("R. No Collision") right_collision=false bumperRightState = 0 end -- Left Bumper left_bumper_pos = sim.getJointPosition(t_leftBumper) if(left_bumper_pos < -0.001) then -- print("L. COLLISION!") left_collision=true bumperLeftState = 1 else --print("L. No Collision") left_collision=false bumperLeftState = 0 end -- Odometry local transformNow = sim.getObjectMatrix(objHandle,-1) pose_orientationNow = sim.multiplyMatrices(invOriginMatrix, transformNow) r_quaternion = simGetQuaternionFromMatrix(pose_orientationNow) r_position = {pose_orientationNow[3], pose_orientationNow[7], pose_orientationNow[11]} r_linear_velocity, r_angular_velocity = simGetObjectVelocity(objHandle) -- ROSing ros_pose = {} ros_pose['header'] = {seq=0,stamp=simROS.getTime(), frame_id="/robot"..modelBaseName} cov = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} quaternion_ros = {} quaternion_ros["x"] = r_quaternion[1] quaternion_ros["y"] = r_quaternion[2] quaternion_ros["z"] = r_quaternion[3] quaternion_ros["w"] = r_quaternion[4] position_ros = {} position_ros["x"] = r_position[1] position_ros["y"] = r_position[2] position_ros["z"] = r_position[3] pose_r = {position=position_ros, orientation=quaternion_ros} ros_pose['pose'] = {pose=pose_r, covariance = cov} linear_speed = {} linear_speed["x"] = r_linear_velocity[1] linear_speed["y"] = r_linear_velocity[2] linear_speed["z"] = r_linear_velocity[3] angular_speed = {} angular_speed["x"] = r_angular_velocity[1] angular_speed["y"] = r_angular_velocity[2] angular_speed["z"] = r_angular_velocity[3] ros_pose['twist'] = {twist={linear=linear_speed, angular=angular_speed}, covariance=cov} ros_pose['child_frame_id'] = "kinect" simROS.publish(pubPose, ros_pose) end if (sim_call_type==sim.childscriptcall_cleanup) then -- ROS Shutdown simROS.shutdownPublisher(pubPose) simROS.shutdownSubscriber(subCmdVel) end if (sim_call_type==sim.childscriptcall_actuation) then s=sim.getObjectSizeFactor(objHandle) -- make sure that if we scale the robot during simulation, other values are scaled too! v0=0.4*s wheelDiameter=0.085*s interWheelDistance=0.254*s noDetectionDistance=0.4*s end
function setVels_cb(msg) -- not sure if a scale factor is must be applied local wheelAxis = 0.22 -- check this value local linVel = msg.linear.x/2 -- in m/s local rotVel = msg.angular.z*wheelAxis/2 -- in rad/s velocityRight = linVel+rotVel velocityLeft = linVel-rotVel if simulationIsKinematic then -- Simulation is kinematic p=sim.boolOr32(sim.getModelProperty(objHandle),sim.modelproperty_not_dynamic) sim.setModelProperty(objHandle,p) dt=sim.getSimulationTimeStep() p=sim.getJointPosition(leftJoint) sim.setJointPosition(leftJoint,p+velocityLeft*dt*2/wheelDiameter) p=sim.getJointPosition(rightJoint) sim.setJointPosition(rightJoint,p+velocityRight*dt*2/wheelDiameter) linMov=dt*(velocityLeft+velocityRight)/2.0 rotMov=dt*math.atan((velocityRight-velocityLeft)/interWheelDistance) position=sim.getObjectPosition(objHandle,sim.handle_parent) orientation=sim.getObjectOrientation(objHandle,sim.handle_parent) xDir={math.cos(orientation[3]),math.sin(orientation[3]),0.0} position[1]=position[1]+xDir[1]*linMov position[2]=position[2]+xDir[2]*linMov orientation[3]=orientation[3]+rotMov sim.setObjectPosition(objHandle,sim.handle_parent,position) sim.setObjectOrientation(objHandle,sim.handle_parent,orientation) else -- Simulation is dynamic p=sim.boolOr32(sim.getModelProperty(objHandle),sim.modelproperty_not_dynamic)-sim.modelproperty_not_dynamic sim.setModelProperty(objHandle,p) --velocityRight = linVel + math.Rad2Deg(rotVel) --velocityLeft = linVel - math.Rad2Deg(rotVel) velocityRight = linVel + math.deg(rotVel) velocityLeft = linVel - math.deg(rotVel) sim.setJointTargetVelocity(leftJoint,velocityLeft*2/wheelDiameter) sim.setJointTargetVelocity(rightJoint,velocityRight*2/wheelDiameter) end end if (sim_call_type==sim.childscriptcall_initialization) then objHandle=sim.getObjectAssociatedWithScript(sim.handle_self) modelBaseName = sim.getObjectName(objHandle) leftJoint=sim.getObjectHandle("turtlebot_leftWheelJoint_") rightJoint=sim.getObjectHandle("turtlebot_rightWheelJoint_") simulationIsKinematic=false -- we want a dynamic simulation here! -- Braitenberg weights: brait_left={0,-0.5,-1.25,-1,-0.2} t_frontBumper = sim.getObjectHandle('bumper_front_joint') t_rightBumper = sim.getObjectHandle('bumper_right_joint') t_leftBumper = sim.getObjectHandle('bumper_left_joint') originMatrix = sim.getObjectMatrix(objHandle,-1) invOriginMatrix = simGetInvertedMatrix(originMatrix) ----------------------------- ROS STUFF -------------------------------- -- Bumper pubBumper = simROS.advertise(modelBaseName..'/events/bumper','kobuki_msgs/BumperEvent') --simROS.publisherTreatUInt8ArrayAsString(pubBumper) -- Odometry pubPose = simROS.advertise(modelBaseName..'/pose','nav_msgs/Odometry') simROS.publisherTreatUInt8ArrayAsString(pubPose) -- Commands subCmdVel = simROS.subscribe(modelBaseName..'/cmd_vel','geometry_msgs/Twist','setVels_cb') end if (sim_call_type == sim.childscriptcall_sensing) then local bumper_id = 255 local bumper_pressed = 0 -- Front Bumper front_bumper_pos = sim.getJointPosition(t_frontBumper) if(front_bumper_pos < -0.001) then -- print("F. COLLISION!") front_collision=true bumperCenterState = 1 bumper_id = 1 bumper_pressed = 1 else -- print("F. No Collision") front_collision=false bumperCenterState = 0 end -- Right Bumper right_bumper_pos = sim.getJointPosition(t_rightBumper) if(right_bumper_pos < -0.001) then -- print("R. COLLISION!") right_collision=true bumperRightState = 1 bumper_id = 2 bumper_pressed = 1 else --print("R. No Collision") right_collision=false bumperRightState = 0 end -- Left Bumper left_bumper_pos = sim.getJointPosition(t_leftBumper) if(left_bumper_pos < -0.001) then -- print("L. COLLISION!") left_collision=true bumperLeftState = 1 bumper_id = 1 bumper_pressed = 1 else --print("L. No Collision") left_collision=false bumperLeftState = 0 end -- Bumper ROS message ros_kobuki_bumper_event = {} ros_kobuki_bumper_event["bumper"] = bumper_id ros_kobuki_bumper_event["state"] = bumper_pressed simROS.publish(pubBumper, ros_kobuki_bumper_event) -- Odometry local transformNow = sim.getObjectMatrix(objHandle,-1) pose_orientationNow = sim.multiplyMatrices(invOriginMatrix, transformNow) r_quaternion = simGetQuaternionFromMatrix(pose_orientationNow) r_position = {pose_orientationNow[3], pose_orientationNow[7], pose_orientationNow[11]} r_linear_velocity, r_angular_velocity = simGetObjectVelocity(objHandle) -- ROSing ros_pose = {} ros_pose['header'] = {seq=0,stamp=simROS.getTime(), frame_id="/robot"..modelBaseName} cov = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} quaternion_ros = {} quaternion_ros["x"] = r_quaternion[1] quaternion_ros["y"] = r_quaternion[2] quaternion_ros["z"] = r_quaternion[3] quaternion_ros["w"] = r_quaternion[4] position_ros = {} position_ros["x"] = r_position[1] position_ros["y"] = r_position[2] position_ros["z"] = r_position[3] pose_r = {position=position_ros, orientation=quaternion_ros} ros_pose['pose'] = {pose=pose_r, covariance = cov} linear_speed = {} linear_speed["x"] = r_linear_velocity[1] linear_speed["y"] = r_linear_velocity[2] linear_speed["z"] = r_linear_velocity[3] angular_speed = {} angular_speed["x"] = r_angular_velocity[1] angular_speed["y"] = r_angular_velocity[2] angular_speed["z"] = r_angular_velocity[3] ros_pose['twist'] = {twist={linear=linear_speed, angular=angular_speed}, covariance=cov} ros_pose['child_frame_id'] = "kinect" simROS.publish(pubPose, ros_pose) end if (sim_call_type==sim.childscriptcall_cleanup) then -- ROS Shutdown simROS.shutdownPublisher(pubPose) simROS.shutdownPublisher(pubBumper) simROS.shutdownSubscriber(subCmdVel) end if (sim_call_type==sim.childscriptcall_actuation) then s=sim.getObjectSizeFactor(objHandle) -- make sure that if we scale the robot during simulation, other values are scaled too! v0=0.4*s wheelDiameter=0.085*s interWheelDistance=0.254*s noDetectionDistance=0.4*s end
fixed robot control and now publishing bumper data in kobuki_msgs format
fixed robot control and now publishing bumper data in kobuki_msgs format
Lua
apache-2.0
EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu,EricssonResearch/scott-eu
a5a61c1e391e8ac16aac153aefffd073eda04fe5
cache_table.lua
cache_table.lua
local EMPTY_TABLE = {} local support_types = {["string"] = true, ["number"] = true, ["boolean"] = true} local function _sync_cache(self, obj, field_name) local key = assert(obj[self.key_field_name]) local value = assert(obj[field_name]) assert(support_types[type(value)]) self.cache[field_name] = self.cache[field_name] or {} self.cache[field_name][value] = self.cache[field_name][value] or {} self.cache[field_name][value][key] = true end local function add(self, obj) assert(self.objs[self.key_field_name] == nil, ("duplicate key `%s`"):format(key)) local k = assert(obj[self.key_field_name]) self.objs[k] = obj for field_name in pairs(self.index_field_names) do _sync_cache(self, obj, field_name) end end local function remove(self, key) assert(self.objs[key]) self.objs[key] = nil end local function sync(self, syncobj, ...) local key = assert(syncobj[self.key_field_name]) local obj = assert(self.objs[key], ("duplicate key `%s`"):format(key)) local field_names = {...} assert(#field_names >= 1) for _, field_name in ipairs(field_names) do assert(type(field_name) == "string") obj[field_name] = syncobj[field_name] if self.index_field_names[field_name] then _sync_cache(self, obj, field_name) end end end local function select(self, field_name, value) assert(value ~= nil) assert(self.index_field_names[field_name], ("must specify the field_name `%s` as index field name"):format(field_name)) if not self.cache[field_name] then return next, EMPTY_TABLE, nil end if not self.cache[field_name][value] then return next, EMPTY_TABLE, nil end local obj local result = {} for key in pairs(self.cache[field_name][value]) do obj = self.objs[key] if not obj then self.cache[field_name][value][key] = nil else if obj[field_name] ~= value then self.cache[field_name][value][key] = nil else result[key] = obj end end end return next, result, nil end local function selectkey(self, key) return self.objs[key] end local function selectall(self) return next, self.objs, nil end local function empty(self) return not next(self.objs) end return function(key_field_name, ...) local m = {} m.key_field_name = key_field_name m.index_field_names = {} for _, field_name in ipairs({...}) do m.index_field_names[field_name] = true end m.objs = {} m.cache = {} m.add = add m.remove = remove m.sync = sync m.select = select m.selectkey = selectkey m.selectall = selectall m.empty = empty return m end
local EMPTY_TABLE = {} local support_types = {["string"] = true, ["number"] = true, ["boolean"] = true} local function _sync_cache(self, obj, field_name) local key = assert(obj[self.key_field_name]) local value = assert(obj[field_name]) assert(support_types[type(value)]) self.cache[field_name] = self.cache[field_name] or {} self.cache[field_name][value] = self.cache[field_name][value] or {} self.cache[field_name][value][key] = true end local function add(self, obj) local key = assert(obj[self.key_field_name]) assert(self.objs[key] == nil, ("duplicate key `%s`"):format(key)) self.objs[key] = obj for field_name in pairs(self.index_field_names) do _sync_cache(self, obj, field_name) end end local function remove(self, key) assert(self.objs[key]) self.objs[key] = nil end local function sync(self, syncobj, ...) local key = assert(syncobj[self.key_field_name]) local obj = assert(self.objs[key], ("duplicate key `%s`"):format(key)) local field_names = {...} assert(#field_names >= 1) for _, field_name in ipairs(field_names) do assert(type(field_name) == "string") obj[field_name] = syncobj[field_name] if self.index_field_names[field_name] then _sync_cache(self, obj, field_name) end end end local function select(self, field_name, value) assert(value ~= nil) assert(self.index_field_names[field_name], ("must specify the field_name `%s` as index field name"):format(field_name)) if not self.cache[field_name] then return next, EMPTY_TABLE, nil end if not self.cache[field_name][value] then return next, EMPTY_TABLE, nil end local obj local result = {} for key in pairs(self.cache[field_name][value]) do obj = self.objs[key] if not obj then self.cache[field_name][value][key] = nil else if obj[field_name] ~= value then self.cache[field_name][value][key] = nil else result[key] = obj end end end return next, result, nil end local function selectkey(self, key) return self.objs[key] end local function selectall(self) return next, self.objs, nil end local function empty(self) return not next(self.objs) end return function(key_field_name, ...) local m = {} m.key_field_name = key_field_name m.index_field_names = {} for _, field_name in ipairs({...}) do m.index_field_names[field_name] = true end m.objs = {} m.cache = {} m.add = add m.remove = remove m.sync = sync m.select = select m.selectkey = selectkey m.selectall = selectall m.empty = empty return m end
fix bug
fix bug
Lua
mit
kinbei/lua-misc
5cd32ef7c0f9b432dc193e585d437d49232fb92f
layout-app.lua
layout-app.lua
SILE.scratch.layout = "app" local book = SILE.require("classes/book"); book:defineMaster({ id = "right", firstContentFrame = "content", frames = { content = { left = "2mm", right = "100%pw-2mm", top = "12mm", bottom = "top(footnotes)" }, runningHead = { left = "left(content)", right = "right(content)", top = "top(content)-10mm", bottom = "top(content)-2mm" }, footnotes = { left = "left(content)", right = "right(content)", bottom = "100%ph-2mm", height = "0" }, }}) book:defineMaster({ id = "left", firstContentFrame = "content", frames = {} }) book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }); book:mirrorMaster("right", "left") SILE.call("switch-master-one-page", { id = "right" }) local oldImprintFont = SILE.Commands["imprint:font"] SILE.registerCommand("imprint:font", function (options, content) options.size = options.size or "6.5pt" oldImprintFont(options, content) end) SILE.registerCommand("meta:distribution", function (options, content) SILE.call("font", { weight = 600, style = "Bold" }, { "Yayın: " }) SILE.typesetter:typeset("Bu PDF biçimi, akıl telefon cihazlar için uygun biçimlemiştir ve Fetiye Halk Kilise’nin hazırladığı Kilise Uygulaması içinde ve Via Christus’un internet sitesinde izinle üçretsiz yayılmaktadır.") end) -- Mobile device PDF readers don't need blank even numbered pages ;) SILE.registerCommand("open-double-page", function () SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); SILE.typesetter:leaveHmode(); end) -- Forgo bottom of page layouts for mobile devices SILE.registerCommand("topfill", function (options, content) end) SILE.require("packages/background") SILE.call("background", { color = "#e9d8ba" }) local inkColor = SILE.colorparser("#5a4129") SILE.outputter:pushColor(inkColor)
SILE.scratch.layout = "app" local book = SILE.require("classes/book"); book:defineMaster({ id = "right", firstContentFrame = "content", frames = { content = { left = "2mm", right = "100%pw-2mm", top = "16mm", bottom = "top(footnotes)" }, runningHead = { left = "left(content)", right = "right(content)", top = "top(content)-14mm", bottom = "top(content)-2mm" }, footnotes = { left = "left(content)", right = "right(content)", bottom = "100%ph-2mm", height = "0" }, }}) book:defineMaster({ id = "left", firstContentFrame = "content", frames = {} }) book:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" }); book:mirrorMaster("right", "left") SILE.call("switch-master-one-page", { id = "right" }) SILE.registerCommand("book:right-running-head", function (options, content) SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.settings.set("document.lskip", SILE.nodefactory.zeroGlue) SILE.settings.set("document.rskip", SILE.nodefactory.zeroGlue) SILE.call("book:left-running-head-font", {}, function () SILE.call("center", {}, function() SILE.call("meta:title") end) end) SILE.call("skip", { height = "2pt" }) SILE.call("book:right-running-head-font", {}, SILE.scratch.headers.right) SILE.call("hfill") SILE.call("book:page-number-font", {}, { SILE.formatCounter(SILE.scratch.counters.folio) }) SILE.call("skip", { height = "-4pt" }) SILE.call("fullrule") end) SILE.registerCommand("book:left-running-head", function (options, content) SILE.call("book:right-running-head") end) local oldImprintFont = SILE.Commands["imprint:font"] SILE.registerCommand("imprint:font", function (options, content) options.size = options.size or "6.5pt" oldImprintFont(options, content) end) SILE.registerCommand("meta:distribution", function (options, content) SILE.call("font", { weight = 600, style = "Bold" }, { "Yayın: " }) SILE.typesetter:typeset("Bu PDF biçimi, akıl telefon cihazlar için uygun biçimlemiştir ve Fetiye Halk Kilise’nin hazırladığı Kilise Uygulaması içinde ve Via Christus’un internet sitesinde izinle üçretsiz yayılmaktadır.") end) -- Mobile device PDF readers don't need blank even numbered pages ;) SILE.registerCommand("open-double-page", function () SILE.typesetter:leaveHmode(); SILE.Commands["supereject"](); SILE.typesetter:leaveHmode(); end) -- Forgo bottom of page layouts for mobile devices SILE.registerCommand("topfill", function (options, content) end) SILE.require("packages/background") SILE.call("background", { color = "#e9d8ba" }) local inkColor = SILE.colorparser("#5a4129") SILE.outputter:pushColor(inkColor)
Setup app layout PDFS to have two row header
Setup app layout PDFS to have two row header Fixes #17
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
09f5bab7448b964f953f42215683ff0883a01026
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> 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.fs") m = Map("olsr", "OLSR") s = m:section(NamedSection, "general", "olsr") debug = s:option(ListValue, "DebugLevel") for i=0, 9 do debug:value(i) end ipv = s:option(ListValue, "IpVersion") ipv:value("4", "IPv4") ipv:value("6", "IPv6") noint = s:option(Flag, "AllowNoInt") noint.enabled = "yes" noint.disabled = "no" s:option(Value, "Pollrate") tcr = s:option(ListValue, "TcRedundancy") tcr:value("0", translate("olsr_general_tcredundancy_0")) tcr:value("1", translate("olsr_general_tcredundancy_1")) tcr:value("2", translate("olsr_general_tcredundancy_2")) s:option(Value, "MprCoverage") lql = s:option(ListValue, "LinkQualityLevel") lql:value("0", translate("disable")) lql:value("1", translate("olsr_general_linkqualitylevel_1")) lql:value("2", translate("olsr_general_linkqualitylevel_2")) lqfish = s:option(Flag, "LinkQualityFishEye") s:option(Value, "LinkQualityWinSize") s:option(Value, "LinkQualityDijkstraLimit") hyst = s:option(Flag, "UseHysteresis") hyst.enabled = "yes" hyst.disabled = "no" i = m:section(TypedSection, "Interface", translate("interfaces")) i.anonymous = true i.addremove = true i.dynamic = true network = i:option(ListValue, "Interface", translate("network")) network:value("") luci.model.uci.foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then network:value(section[".name"]) end end) i:option(Value, "HelloInterval") i:option(Value, "HelloValidityTime") i:option(Value, "TcInterval") i:option(Value, "TcValidityTime") i:option(Value, "MidInterval") i:option(Value, "MidValidityTime") i:option(Value, "HnaInterval") i:option(Value, "HnaValidityTime") p = m:section(TypedSection, "LoadPlugin") p.addremove = true p.dynamic = true lib = p:option(ListValue, "Library", translate("library")) lib:value("") for k, v in pairs(luci.fs.dir("/usr/lib")) do if v:sub(1, 6) == "olsrd_" then lib:value(v) end end for i, sect in ipairs({ "Hna4", "Hna6" }) do hna = m:section(TypedSection, sect) hna.addremove = true hna.anonymous = true net = hna:option(Value, "NetAddr") msk = hna:option(Value, "Prefix") end ipc = m:section(NamedSection, "IpcConnect") conns = ipc:option(Value, "MaxConnections") conns.isInteger = true nets = ipc:option(Value, "Net") nets.optional = true hosts = ipc:option(Value, "Host") hosts.optional = true return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> 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.fs") m = Map("olsr", "OLSR") s = m:section(NamedSection, "general", "olsr") debug = s:option(ListValue, "DebugLevel") for i=0, 9 do debug:value(i) end ipv = s:option(ListValue, "IpVersion") ipv:value("4", "IPv4") ipv:value("6", "IPv6") noint = s:option(Flag, "AllowNoInt") noint.enabled = "yes" noint.disabled = "no" s:option(Value, "Pollrate") tcr = s:option(ListValue, "TcRedundancy") tcr:value("0", translate("olsr_general_tcredundancy_0")) tcr:value("1", translate("olsr_general_tcredundancy_1")) tcr:value("2", translate("olsr_general_tcredundancy_2")) s:option(Value, "MprCoverage") lql = s:option(ListValue, "LinkQualityLevel") lql:value("0", translate("disable")) lql:value("1", translate("olsr_general_linkqualitylevel_1")) lql:value("2", translate("olsr_general_linkqualitylevel_2")) lqfish = s:option(Flag, "LinkQualityFishEye") s:option(Value, "LinkQualityWinSize") s:option(Value, "LinkQualityDijkstraLimit") hyst = s:option(Flag, "UseHysteresis") hyst.enabled = "yes" hyst.disabled = "no" i = m:section(TypedSection, "Interface", translate("interfaces")) i.anonymous = true i.addremove = true i.dynamic = true network = i:option(ListValue, "Interface", translate("network")) network:value("") luci.model.uci.foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then if section.type and section.type == "bridge" then network:value("br-"..section[".name"],section[".name"]) else network:value(section[".name"]) end end end) i:option(Value, "HelloInterval") i:option(Value, "HelloValidityTime") i:option(Value, "TcInterval") i:option(Value, "TcValidityTime") i:option(Value, "MidInterval") i:option(Value, "MidValidityTime") i:option(Value, "HnaInterval") i:option(Value, "HnaValidityTime") p = m:section(TypedSection, "LoadPlugin") p.addremove = true p.dynamic = true lib = p:option(ListValue, "Library", translate("library")) lib:value("") for k, v in pairs(luci.fs.dir("/usr/lib")) do if v:sub(1, 6) == "olsrd_" then lib:value(v) end end for i, sect in ipairs({ "Hna4", "Hna6" }) do hna = m:section(TypedSection, sect) hna.addremove = true hna.anonymous = true net = hna:option(Value, "NetAddr") msk = hna:option(Value, "Prefix") end ipc = m:section(NamedSection, "IpcConnect") conns = ipc:option(Value, "MaxConnections") conns.isInteger = true nets = ipc:option(Value, "Net") nets.optional = true hosts = ipc:option(Value, "Host") hosts.optional = true return m
* luci/olsr: fix names of interfaces with type bridge
* luci/olsr: fix names of interfaces with type bridge
Lua
apache-2.0
maxrio/luci981213,kuoruan/lede-luci,marcel-sch/luci,florian-shellfire/luci,tcatm/luci,zhaoxx063/luci,jorgifumi/luci,shangjiyu/luci-with-extra,palmettos/test,joaofvieira/luci,palmettos/test,remakeelectric/luci,obsy/luci,rogerpueyo/luci,deepak78/new-luci,oneru/luci,palmettos/cnLuCI,hnyman/luci,RuiChen1113/luci,Kyklas/luci-proto-hso,joaofvieira/luci,oneru/luci,aa65535/luci,LuttyYang/luci,dwmw2/luci,maxrio/luci981213,Hostle/openwrt-luci-multi-user,cshore-firmware/openwrt-luci,ff94315/luci-1,artynet/luci,Noltari/luci,Sakura-Winkey/LuCI,ollie27/openwrt_luci,fkooman/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,lbthomsen/openwrt-luci,david-xiao/luci,david-xiao/luci,shangjiyu/luci-with-extra,david-xiao/luci,jchuang1977/luci-1,LuttyYang/luci,maxrio/luci981213,remakeelectric/luci,forward619/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,cshore-firmware/openwrt-luci,nmav/luci,urueedi/luci,wongsyrone/luci-1,marcel-sch/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,Kyklas/luci-proto-hso,fkooman/luci,male-puppies/luci,lbthomsen/openwrt-luci,oneru/luci,male-puppies/luci,obsy/luci,sujeet14108/luci,ff94315/luci-1,rogerpueyo/luci,Wedmer/luci,hnyman/luci,maxrio/luci981213,jchuang1977/luci-1,openwrt/luci,Hostle/luci,thesabbir/luci,slayerrensky/luci,openwrt-es/openwrt-luci,artynet/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,Noltari/luci,LuttyYang/luci,kuoruan/luci,male-puppies/luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,harveyhu2012/luci,wongsyrone/luci-1,mumuqz/luci,tcatm/luci,teslamint/luci,joaofvieira/luci,bittorf/luci,schidler/ionic-luci,thesabbir/luci,jchuang1977/luci-1,male-puppies/luci,aa65535/luci,openwrt/luci,kuoruan/lede-luci,wongsyrone/luci-1,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,openwrt/luci,mumuqz/luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,dismantl/luci-0.12,joaofvieira/luci,981213/luci-1,slayerrensky/luci,rogerpueyo/luci,bright-things/ionic-luci,cappiewu/luci,deepak78/new-luci,981213/luci-1,tcatm/luci,RuiChen1113/luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,schidler/ionic-luci,sujeet14108/luci,LuttyYang/luci,Hostle/luci,cshore/luci,remakeelectric/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,fkooman/luci,LuttyYang/luci,forward619/luci,jlopenwrtluci/luci,zhaoxx063/luci,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,harveyhu2012/luci,NeoRaider/luci,slayerrensky/luci,fkooman/luci,Kyklas/luci-proto-hso,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,palmettos/cnLuCI,chris5560/openwrt-luci,RuiChen1113/luci,Wedmer/luci,slayerrensky/luci,bittorf/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,LuttyYang/luci,NeoRaider/luci,florian-shellfire/luci,male-puppies/luci,tobiaswaldvogel/luci,thesabbir/luci,bittorf/luci,male-puppies/luci,daofeng2015/luci,NeoRaider/luci,thess/OpenWrt-luci,tcatm/luci,cappiewu/luci,jlopenwrtluci/luci,teslamint/luci,mumuqz/luci,db260179/openwrt-bpi-r1-luci,aa65535/luci,oyido/luci,obsy/luci,openwrt/luci,thess/OpenWrt-luci,oneru/luci,urueedi/luci,deepak78/new-luci,tcatm/luci,bittorf/luci,bright-things/ionic-luci,openwrt/luci,nwf/openwrt-luci,openwrt/luci,LuttyYang/luci,schidler/ionic-luci,lcf258/openwrtcn,openwrt/luci,urueedi/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,slayerrensky/luci,tobiaswaldvogel/luci,jlopenwrtluci/luci,opentechinstitute/luci,nwf/openwrt-luci,palmettos/cnLuCI,ollie27/openwrt_luci,lcf258/openwrtcn,keyidadi/luci,rogerpueyo/luci,jlopenwrtluci/luci,jorgifumi/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,cshore-firmware/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,palmettos/test,kuoruan/lede-luci,openwrt-es/openwrt-luci,obsy/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,chris5560/openwrt-luci,981213/luci-1,cshore/luci,teslamint/luci,Hostle/luci,david-xiao/luci,urueedi/luci,marcel-sch/luci,lcf258/openwrtcn,palmettos/test,wongsyrone/luci-1,aa65535/luci,RedSnake64/openwrt-luci-packages,teslamint/luci,kuoruan/luci,taiha/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,urueedi/luci,hnyman/luci,MinFu/luci,slayerrensky/luci,urueedi/luci,taiha/luci,hnyman/luci,cshore-firmware/openwrt-luci,taiha/luci,kuoruan/lede-luci,mumuqz/luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,MinFu/luci,daofeng2015/luci,jorgifumi/luci,bittorf/luci,dwmw2/luci,artynet/luci,cshore/luci,thesabbir/luci,kuoruan/luci,Kyklas/luci-proto-hso,palmettos/test,shangjiyu/luci-with-extra,sujeet14108/luci,ollie27/openwrt_luci,Noltari/luci,981213/luci-1,maxrio/luci981213,oyido/luci,teslamint/luci,marcel-sch/luci,openwrt-es/openwrt-luci,dwmw2/luci,Noltari/luci,palmettos/cnLuCI,nwf/openwrt-luci,Sakura-Winkey/LuCI,RedSnake64/openwrt-luci-packages,thesabbir/luci,981213/luci-1,remakeelectric/luci,opentechinstitute/luci,sujeet14108/luci,fkooman/luci,dwmw2/luci,jorgifumi/luci,ollie27/openwrt_luci,cshore/luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,MinFu/luci,Noltari/luci,aa65535/luci,palmettos/test,florian-shellfire/luci,nmav/luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,david-xiao/luci,MinFu/luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,bright-things/ionic-luci,joaofvieira/luci,daofeng2015/luci,taiha/luci,thesabbir/luci,oneru/luci,kuoruan/lede-luci,NeoRaider/luci,fkooman/luci,kuoruan/luci,artynet/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,deepak78/new-luci,schidler/ionic-luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,maxrio/luci981213,chris5560/openwrt-luci,nmav/luci,palmettos/test,harveyhu2012/luci,nmav/luci,cappiewu/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,deepak78/new-luci,opentechinstitute/luci,jorgifumi/luci,mumuqz/luci,nmav/luci,cappiewu/luci,kuoruan/luci,wongsyrone/luci-1,daofeng2015/luci,deepak78/new-luci,fkooman/luci,urueedi/luci,keyidadi/luci,oneru/luci,artynet/luci,jorgifumi/luci,openwrt-es/openwrt-luci,bittorf/luci,thess/OpenWrt-luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,male-puppies/luci,florian-shellfire/luci,taiha/luci,nwf/openwrt-luci,Noltari/luci,schidler/ionic-luci,ollie27/openwrt_luci,artynet/luci,taiha/luci,Hostle/luci,Sakura-Winkey/LuCI,thesabbir/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,thess/OpenWrt-luci,cshore-firmware/openwrt-luci,palmettos/cnLuCI,nwf/openwrt-luci,RuiChen1113/luci,openwrt-es/openwrt-luci,teslamint/luci,remakeelectric/luci,palmettos/cnLuCI,schidler/ionic-luci,aircross/OpenWrt-Firefly-LuCI,oyido/luci,tobiaswaldvogel/luci,opentechinstitute/luci,male-puppies/luci,keyidadi/luci,oneru/luci,keyidadi/luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,nmav/luci,daofeng2015/luci,obsy/luci,nwf/openwrt-luci,obsy/luci,lcf258/openwrtcn,rogerpueyo/luci,zhaoxx063/luci,NeoRaider/luci,NeoRaider/luci,aa65535/luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,MinFu/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,Kyklas/luci-proto-hso,lcf258/openwrtcn,bittorf/luci,artynet/luci,rogerpueyo/luci,joaofvieira/luci,florian-shellfire/luci,deepak78/new-luci,slayerrensky/luci,harveyhu2012/luci,chris5560/openwrt-luci,forward619/luci,db260179/openwrt-bpi-r1-luci,bright-things/ionic-luci,jlopenwrtluci/luci,oyido/luci,maxrio/luci981213,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,fkooman/luci,bright-things/ionic-luci,forward619/luci,ollie27/openwrt_luci,artynet/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/luci,florian-shellfire/luci,tcatm/luci,Sakura-Winkey/LuCI,981213/luci-1,Wedmer/luci,RuiChen1113/luci,jchuang1977/luci-1,palmettos/cnLuCI,oyido/luci,mumuqz/luci,cappiewu/luci,shangjiyu/luci-with-extra,dismantl/luci-0.12,taiha/luci,Noltari/luci,tobiaswaldvogel/luci,Wedmer/luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,MinFu/luci,ReclaimYourPrivacy/cloak-luci,nmav/luci,marcel-sch/luci,forward619/luci,harveyhu2012/luci,joaofvieira/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,bittorf/luci,Hostle/luci,NeoRaider/luci,dwmw2/luci,chris5560/openwrt-luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,aa65535/luci,ff94315/luci-1,dismantl/luci-0.12,cshore/luci,wongsyrone/luci-1,keyidadi/luci,RuiChen1113/luci,artynet/luci,hnyman/luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,lcf258/openwrtcn,ff94315/luci-1,oyido/luci,thesabbir/luci,cappiewu/luci,remakeelectric/luci,bright-things/ionic-luci,obsy/luci,dismantl/luci-0.12,opentechinstitute/luci,Noltari/luci,RuiChen1113/luci,sujeet14108/luci,ff94315/luci-1,RedSnake64/openwrt-luci-packages,kuoruan/luci,dwmw2/luci,openwrt/luci,nmav/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,deepak78/new-luci,david-xiao/luci,schidler/ionic-luci,maxrio/luci981213,marcel-sch/luci,wongsyrone/luci-1,sujeet14108/luci,chris5560/openwrt-luci,tcatm/luci,dismantl/luci-0.12,opentechinstitute/luci,obsy/luci,forward619/luci,teslamint/luci,cshore/luci,joaofvieira/luci,zhaoxx063/luci,daofeng2015/luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,jchuang1977/luci-1,chris5560/openwrt-luci,nwf/openwrt-luci,urueedi/luci,marcel-sch/luci,lbthomsen/openwrt-luci,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,jlopenwrtluci/luci,zhaoxx063/luci,cshore/luci,Hostle/openwrt-luci-multi-user,jorgifumi/luci,kuoruan/lede-luci,thess/OpenWrt-luci,forward619/luci,db260179/openwrt-bpi-r1-luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,taiha/luci,Hostle/luci,cappiewu/luci,cshore/luci,MinFu/luci,lbthomsen/openwrt-luci,oyido/luci,jchuang1977/luci-1,Noltari/luci,keyidadi/luci,jlopenwrtluci/luci,nmav/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,lcf258/openwrtcn,dwmw2/luci,florian-shellfire/luci,opentechinstitute/luci,openwrt-es/openwrt-luci,marcel-sch/luci,bright-things/ionic-luci,remakeelectric/luci,slayerrensky/luci,cappiewu/luci,remakeelectric/luci,tobiaswaldvogel/luci,florian-shellfire/luci,kuoruan/luci,oneru/luci,Sakura-Winkey/LuCI,zhaoxx063/luci,teslamint/luci,cshore-firmware/openwrt-luci,Wedmer/luci,opentechinstitute/luci,981213/luci-1,aa65535/luci,forward619/luci,lcf258/openwrtcn,keyidadi/luci,lbthomsen/openwrt-luci,kuoruan/luci,jorgifumi/luci,nwf/openwrt-luci,MinFu/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,ollie27/openwrt_luci,bright-things/ionic-luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,mumuqz/luci
018adc3153500f84a2f416399c22f6c5f437c661
MCServer/Plugins/ProtectionAreas/CommandState.lua
MCServer/Plugins/ProtectionAreas/CommandState.lua
-- CommandState.lua -- Implements the cCommandState class representing a command state for each VIP player --[[ The command state holds internal info, such as the coords they selected using the wand The command state needs to be held in a per-entity manner, so that we can support multiple logins from the same account (just for the fun of it) The OOP class implementation follows the PiL 16.1 Also, a global table g_CommandStates is the map of PlayerEntityID -> cCommandState --]] cCommandState = { -- Default coords m_Coords1 = {x = 0, z = 0}; -- lclk coords m_Coords2 = {x = 0, z = 0}; -- rclk coords m_LastCoords = 0; -- When Coords1 or Coords2 is set, this gets set to 1 or 2, signifying the last changed set of coords m_HasCoords = 1; -- Set to 0, 1, 2 or 3, based on which set of coords has been set (bitmask) }; g_CommandStates = {}; function cCommandState:new(obj) obj = obj or {}; setmetatable(obj, self); self.__index = self; return obj; end --- Returns the current coord pair as a cCuboid object function cCommandState:GetCurrentCuboid() if (self.m_HasCoords ~= 3) then -- Some of the coords haven't been set yet return nil; end local res = cCuboid( self.m_Coords1.x, self.m_Coords1.y, self.m_Coords1.z, self.m_Coords2.x, self.m_Coords2.y, self.m_Coords2.z ); res:Sort(); return res; end --- Returns the x, z coords that were the set last, -- That is, either m_Coords1 or m_Coords2, based on m_LastCoords member -- Returns nothing if no coords were set yet function cCommandState:GetLastCoords() if (self.m_LastCoords == 0) then -- No coords have been set yet return; elseif (self.m_LastCoords == 1) then return self.m_Coords1.x, self.m_Coords1.z; elseif (self.m_LastCoords == 2) then return self.m_Coords2.x, self.m_Coords2.z; else LOGWARNING(PluginPrefix .. "cCommandState is in an unexpected state, m_LastCoords == " .. self.m_LastCoords); return; end end --- Sets the first set of coords (upon rclk with a wand) function cCommandState:SetCoords1(a_BlockX, a_BlockZ) self.m_Coords1.x = a_BlockX; self.m_Coords1.z = a_BlockZ; self.m_LastCoords = 1; end --- Sets the second set of coords (upon lclk with a wand) function cCommandState:SetCoords2(a_BlockX, a_BlockZ) self.m_Coords2.x = a_BlockX; self.m_Coords2.z = a_BlockZ; self.m_LastCoords = 2; end --- Returns the cCommandState for the specified player; creates one if not existant function GetCommandStateForPlayer(a_Player) local res = g_CommandStates[a_Player:GetUniqueID()]; if (res == nil) then res = cCommandState:new(); g_CommandStates[a_Player:GetUniqueID()] = res; end return res; end;
-- CommandState.lua -- Implements the cCommandState class representing a command state for each VIP player --[[ The command state holds internal info, such as the coords they selected using the wand The command state needs to be held in a per-entity manner, so that we can support multiple logins from the same account (just for the fun of it) The OOP class implementation follows the PiL 16.1 Also, a global table g_CommandStates is the map of PlayerEntityID -> cCommandState --]] cCommandState = { -- Default coords m_Coords1 = {x = 0, z = 0}; -- lclk coords m_Coords2 = {x = 0, z = 0}; -- rclk coords m_LastCoords = 0; -- When Coords1 or Coords2 is set, this gets set to 1 or 2, signifying the last changed set of coords m_HasCoords1 = false; -- Set to true when m_Coords1 has been set by the user m_HasCoords2 = false; -- Set to true when m_Coords2 has been set by the user }; g_CommandStates = {}; function cCommandState:new(obj) obj = obj or {}; setmetatable(obj, self); self.__index = self; return obj; end --- Returns the current coord pair as a cCuboid object function cCommandState:GetCurrentCuboid() if (not(self.m_HasCoords1) or not(self.m_HasCoords2)) then -- Some of the coords haven't been set yet return nil; end local res = cCuboid( self.m_Coords1.x, 0, self.m_Coords1.z, self.m_Coords2.x, 255, self.m_Coords2.z ); res:Sort(); return res; end --- Returns the x, z coords that were the set last, -- That is, either m_Coords1 or m_Coords2, based on m_LastCoords member -- Returns nothing if no coords were set yet function cCommandState:GetLastCoords() if (self.m_LastCoords == 0) then -- No coords have been set yet return; elseif (self.m_LastCoords == 1) then return self.m_Coords1.x, self.m_Coords1.z; elseif (self.m_LastCoords == 2) then return self.m_Coords2.x, self.m_Coords2.z; else LOGWARNING(PluginPrefix .. "cCommandState is in an unexpected state, m_LastCoords == " .. self.m_LastCoords); return; end end --- Sets the first set of coords (upon rclk with a wand) function cCommandState:SetCoords1(a_BlockX, a_BlockZ) self.m_Coords1.x = a_BlockX; self.m_Coords1.z = a_BlockZ; self.m_LastCoords = 1; self.m_HasCoords1 = true; end --- Sets the second set of coords (upon lclk with a wand) function cCommandState:SetCoords2(a_BlockX, a_BlockZ) self.m_Coords2.x = a_BlockX; self.m_Coords2.z = a_BlockZ; self.m_LastCoords = 2; self.m_HasCoords2 = true; end --- Returns the cCommandState for the specified player; creates one if not existant function GetCommandStateForPlayer(a_Player) local res = g_CommandStates[a_Player:GetUniqueID()]; if (res == nil) then res = cCommandState:new(); g_CommandStates[a_Player:GetUniqueID()] = res; end return res; end;
ProtectionAreas: Fixed cCommandState's detection of not-selected
ProtectionAreas: Fixed cCommandState's detection of not-selected git-svn-id: ffe80d23790c2318db4f9b6ad70c6163efa9c8e4@1562 0a769ca7-a7f5-676a-18bf-c427514a06d6
Lua
apache-2.0
mc-server/MCServer,thetaeo/cuberite,electromatter/cuberite,zackp30/cuberite,tonibm19/cuberite,bendl/cuberite,electromatter/cuberite,bendl/cuberite,nevercast/cuberite,HelenaKitty/EbooMC,mc-server/MCServer,Tri125/MCServer,MuhammadWang/MCServer,zackp30/cuberite,MuhammadWang/MCServer,marvinkopf/cuberite,electromatter/cuberite,Altenius/cuberite,linnemannr/MCServer,thetaeo/cuberite,mc-server/MCServer,mmdk95/cuberite,SamOatesPlugins/cuberite,Fighter19/cuberite,mjssw/cuberite,thetaeo/cuberite,Frownigami1/cuberite,nicodinh/cuberite,Howaner/MCServer,Tri125/MCServer,linnemannr/MCServer,nevercast/cuberite,nicodinh/cuberite,tonibm19/cuberite,guijun/MCServer,Fighter19/cuberite,Tri125/MCServer,mjssw/cuberite,MuhammadWang/MCServer,zackp30/cuberite,johnsoch/cuberite,birkett/cuberite,Tri125/MCServer,Haxi52/cuberite,nichwall/cuberite,kevinr/cuberite,electromatter/cuberite,Altenius/cuberite,SamOatesPlugins/cuberite,guijun/MCServer,mjssw/cuberite,birkett/MCServer,ionux/MCServer,Fighter19/cuberite,SamOatesPlugins/cuberite,tonibm19/cuberite,Schwertspize/cuberite,Schwertspize/cuberite,bendl/cuberite,jammet/MCServer,electromatter/cuberite,Haxi52/cuberite,kevinr/cuberite,Altenius/cuberite,jammet/MCServer,kevinr/cuberite,birkett/MCServer,jammet/MCServer,Frownigami1/cuberite,linnemannr/MCServer,Haxi52/cuberite,Haxi52/cuberite,nichwall/cuberite,mc-server/MCServer,SamOatesPlugins/cuberite,Howaner/MCServer,birkett/cuberite,ionux/MCServer,mmdk95/cuberite,Haxi52/cuberite,birkett/MCServer,nounoursheureux/MCServer,Tri125/MCServer,Schwertspize/cuberite,QUSpilPrgm/cuberite,Howaner/MCServer,Schwertspize/cuberite,marvinkopf/cuberite,zackp30/cuberite,guijun/MCServer,bendl/cuberite,zackp30/cuberite,Fighter19/cuberite,HelenaKitty/EbooMC,guijun/MCServer,nounoursheureux/MCServer,nicodinh/cuberite,Fighter19/cuberite,nounoursheureux/MCServer,zackp30/cuberite,johnsoch/cuberite,mmdk95/cuberite,QUSpilPrgm/cuberite,Tri125/MCServer,birkett/MCServer,ionux/MCServer,Howaner/MCServer,nicodinh/cuberite,kevinr/cuberite,mmdk95/cuberite,Haxi52/cuberite,birkett/MCServer,HelenaKitty/EbooMC,marvinkopf/cuberite,birkett/cuberite,mjssw/cuberite,thetaeo/cuberite,nounoursheureux/MCServer,nicodinh/cuberite,Altenius/cuberite,Howaner/MCServer,MuhammadWang/MCServer,nichwall/cuberite,ionux/MCServer,SamOatesPlugins/cuberite,kevinr/cuberite,nevercast/cuberite,mjssw/cuberite,nevercast/cuberite,tonibm19/cuberite,marvinkopf/cuberite,mjssw/cuberite,nevercast/cuberite,marvinkopf/cuberite,birkett/cuberite,mmdk95/cuberite,birkett/cuberite,linnemannr/MCServer,thetaeo/cuberite,Schwertspize/cuberite,QUSpilPrgm/cuberite,birkett/cuberite,Fighter19/cuberite,nichwall/cuberite,johnsoch/cuberite,guijun/MCServer,MuhammadWang/MCServer,Howaner/MCServer,birkett/MCServer,QUSpilPrgm/cuberite,linnemannr/MCServer,Frownigami1/cuberite,jammet/MCServer,HelenaKitty/EbooMC,nichwall/cuberite,bendl/cuberite,tonibm19/cuberite,nevercast/cuberite,ionux/MCServer,thetaeo/cuberite,electromatter/cuberite,jammet/MCServer,nounoursheureux/MCServer,linnemannr/MCServer,marvinkopf/cuberite,ionux/MCServer,mc-server/MCServer,QUSpilPrgm/cuberite,mc-server/MCServer,nichwall/cuberite,QUSpilPrgm/cuberite,johnsoch/cuberite,jammet/MCServer,nounoursheureux/MCServer,johnsoch/cuberite,nicodinh/cuberite,HelenaKitty/EbooMC,mmdk95/cuberite,Frownigami1/cuberite,kevinr/cuberite,Altenius/cuberite,guijun/MCServer,Frownigami1/cuberite,tonibm19/cuberite
e74c0f475b4e750572fc8ef91dee1340f2055a14
src/cosy/parameters-i18n.lua
src/cosy/parameters-i18n.lua
return { ["check:error"] = { en = "some parameters are invalid or missing", }, ["check:no-check"] = { en = "request argument {{{key}}} has not been checked", }, ["check:not-found"] = { en = "parameter {{{key}}} is missing", }, ["check:is-table"] = { en = "{{{key}}} must be a table", }, ["check:is-position"] = { en = "{{{key}}} must contain a country, and city", }, ["check:user:miss"] = { en = "user {{{name}}} does not exist", }, ["check:user:not-user"] = { en = "resource {{{name}}} is not a user", }, ["check:user:not-active"] = { en = "user {{{name}}} is not active", }, ["check:user:not-suspended"] = { en = "user {{{name}}} is not suspended", }, ["check:user:suspended"] = { en = "user {{{name}}} is suspended", }, ["check:project:miss"] = { en = "project {{{name}}} does not exist", }, ["check:is-avatar"] = { en = "a {{{key}}} must be a table with contents and source", }, ["check:is-string"] = { en = "a {{{key}}} must be a string", }, ["check:min-size"] = { en = "a {{{key}}} must contain at least {{{count}}} characters", }, ["check:max-size"] = { en = "a {{{key}}} must contain at most {{{count}}} characters", }, ["check:alphanumeric"] = { en = "a {{{key}}} must contain only alphanumeric characters", }, ["check:email:pattern"] = { en = "email address is not valid", }, ["check:locale:pattern"] = { en = "locale is not valid", }, ["check:tos_digest:pattern"] = { en = "a digest must be a sequence of hexadecimal numbers", }, ["check:tos_digest:incorrect"] = { en = "terms of service digest does not correspond to the terms of service", }, ["check:token:invalid"] = { en = "token is invalid", }, ["check:user"] = { en = "a {{{key}}} must be like username", }, ["check:project"] = { en = "a project must be like username/projectname", }, ["translation:failure"] = { "translation failed: {{{reason}}}", }, ["avatar"] = { en = "avatar file or URL", }, ["description"] = { en = "description", }, ["email"] = { en = "email address", }, ["homepage"] = { en = "homepage URL", }, ["is-private"] = { en = "set as private", }, ["locale"] = { en = "locale for messages", }, ["name"] = { en = "full name", }, ["organization"] = { en = "organization", }, ["password"] = { en = "password", }, ["password:checked"] = { en = "password", }, ["token:authentication"] = { en = "authentication token", }, ["token:validation"] = { en = "validation token", }, ["tos"] = { en = "terms of service", }, ["tos-digest"] = { en = "terms of service digest", }, ["user"] = { en = "user", }, ["user:active"] = { en = "active user", }, ["user:suspended"] = { en = "suspended user", }, ["user:name"] = { en = "username", }, }
return { ["check:error"] = { en = "some parameters are invalid or missing", }, ["check:no-check"] = { en = "in request {{{request}}}, argument {{{key}}} has not been checked", }, ["check:not-found"] = { en = "parameter {{{key}}} is missing", }, ["check:is-table"] = { en = "{{{key}}} must be a table", }, ["check:is-position"] = { en = "{{{key}}} must contain a country, and city", }, ["check:user:miss"] = { en = "user {{{name}}} does not exist", }, ["check:user:not-user"] = { en = "resource {{{name}}} is not a user", }, ["check:user:not-active"] = { en = "user {{{name}}} is not active", }, ["check:user:not-suspended"] = { en = "user {{{name}}} is not suspended", }, ["check:user:suspended"] = { en = "user {{{name}}} is suspended", }, ["check:project:miss"] = { en = "project {{{name}}} does not exist", }, ["check:is-avatar"] = { en = "a {{{key}}} must be a table with contents and source", }, ["check:is-string"] = { en = "a {{{key}}} must be a string", }, ["check:min-size"] = { en = "a {{{key}}} must contain at least {{{count}}} characters", }, ["check:max-size"] = { en = "a {{{key}}} must contain at most {{{count}}} characters", }, ["check:alphanumeric"] = { en = "a {{{key}}} must contain only alphanumeric characters", }, ["check:email:pattern"] = { en = "email address is not valid", }, ["check:locale:pattern"] = { en = "locale is not valid", }, ["check:tos_digest:pattern"] = { en = "a digest must be a sequence of hexadecimal numbers", }, ["check:tos_digest:incorrect"] = { en = "terms of service digest does not correspond to the terms of service", }, ["check:token:invalid"] = { en = "token is invalid", }, ["check:user"] = { en = "a {{{key}}} must be like username", }, ["check:project"] = { en = "a project must be like username/projectname", }, ["translation:failure"] = { "translation failed: {{{reason}}}", }, ["avatar"] = { en = "avatar file or URL", }, ["description"] = { en = "description", }, ["email"] = { en = "email address", }, ["homepage"] = { en = "homepage URL", }, ["is-private"] = { en = "set as private", }, ["locale"] = { en = "locale for messages", }, ["name"] = { en = "full name", }, ["organization"] = { en = "organization", }, ["password"] = { en = "password", }, ["password:checked"] = { en = "password", }, ["position"] = { en = "position", }, ["project"] = { en = "project", }, ["string"] = { en = "string", }, ["string:trimmed"] = { en = "string", }, ["token:authentication"] = { en = "authentication token", }, ["token:validation"] = { en = "validation token", }, ["tos"] = { en = "terms of service", }, ["tos:digest"] = { en = "terms of service digest", }, ["user"] = { en = "user", }, ["user:active"] = { en = "active user", }, ["user:suspended"] = { en = "suspended user", }, ["user:name"] = { en = "username", }, }
Fix translations.
Fix translations.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
0c3a2bb2e362679e7d9f3ce2b0fae819ef3cab70
src/_premake_main.lua
src/_premake_main.lua
-- -- _premake_main.lua -- Script-side entry point for the main program logic. -- Copyright (c) 2002-2015 Jason Perkins and the Premake project -- local shorthelp = "Type 'premake5 --help' for help" local versionhelp = "premake5 (Premake Build Script Generator) %s" -- Load the collection of core scripts, required for everything else to work local modules = dofile("_modules.lua") local manifest = dofile("_manifest.lua") for i = 1, #manifest do dofile(manifest[i]) end -- Create namespaces for myself local p = premake p.main = {} local m = p.main --- -- Add a new module loader that knows how to use the Premake paths like -- PREMAKE_PATH and the --scripts option, and follows the module/module.lua -- naming convention. --- function m.installModuleLoader() table.insert(package.loaders, 2, m.moduleLoader) end function m.moduleLoader(name) local dir = path.getdirectory(name) local base = path.getname(name) if dir ~= "." then dir = dir .. "/" .. base else dir = base end local full = dir .. "/" .. base .. ".lua" local p = os.locate("modules/" .. full) or os.locate(full) or os.locate(name .. ".lua") if not p then -- try to load from the embedded script p = "$/" .. full end local chunk, err = loadfile(p) if not chunk then error(err, 0) end return chunk end --- -- Prepare the script environment; anything that should be done -- before the system script gets a chance to run. --- function m.prepareEnvironment() math.randomseed(os.time()) _PREMAKE_DIR = path.getdirectory(_PREMAKE_COMMAND) premake.path = premake.path .. ";" .. _PREMAKE_DIR .. ";" .. _MAIN_SCRIPT_DIR end --- -- Load the required core modules that are shipped as part of Premake -- and expected to be present at startup. --- function m.preloadModules() for i = 1, #modules do local name = modules[i] local preload = name .. "/_preload.lua" local fn = os.locate("modules/" .. preload) or os.locate(preload) if fn then include(fn) else require(name) end end end --- -- Look for and run the system-wide configuration script; make sure any -- configuration scoping gets cleared before continuing. --- function m.runSystemScript() dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" }) filter {} end --- -- Look for a user project script, and set up the related global -- variables if I can find one. --- function m.locateUserScript() local defaults = { "premake5.lua", "premake4.lua" } for i = 1, #defaults do if os.isfile(defaults[i]) then _MAIN_SCRIPT = defaults[i] break end end if not _MAIN_SCRIPT then _MAIN_SCRIPT = defaults[1] end if _OPTIONS.file then _MAIN_SCRIPT = _OPTIONS.file end _MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT) _MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT) end --- -- Set the action to be performed from the command line arguments. --- function m.prepareAction() -- The "next-gen" actions have now replaced their deprecated counterparts. -- Provide a warning for a little while before I remove them entirely. if _ACTION and _ACTION:endswith("ng") then premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3)) end premake.action.set(_ACTION) end --- -- If there is a project script available, run it to get the -- project information, available options and actions, etc. --- function m.runUserScript() if os.isfile(_MAIN_SCRIPT) then dofile(_MAIN_SCRIPT) end end --- -- Run the interactive prompt, if requested. --- function m.checkInteractive() if _OPTIONS.interactive then debug.prompt() end end --- -- Validate and process the command line options and arguments. --- function m.processCommandLine() -- Process special options if (_OPTIONS["version"]) then printf(versionhelp, _PREMAKE_VERSION) os.exit(0) end if (_OPTIONS["help"]) then premake.showhelp() os.exit(1) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options ok, err = premake.option.validate(_OPTIONS) if not ok then print("Error: " .. err) os.exit(1) end -- If no further action is possible, show a short help message if not _OPTIONS.interactive then if not _ACTION then print(shorthelp) os.exit(1) end local action = premake.action.current() if not action then print("Error: no such action '" .. _ACTION .. "'") os.exit(1) end if p.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then print(string.format("No Premake script (%s) found!", path.getname(_MAIN_SCRIPT))) os.exit(1) end end end --- -- Override point, for logic that should run before baking. --- function m.preBake() if p.action.isConfigurable() then print("Building configurations...") end end --- -- "Bake" the project information, preparing it for use by the action. --- function m.bake() if p.action.isConfigurable() then premake.oven.bake() end end --- -- Override point, for logic that should run after baking but before -- the configurations are validated. --- function m.postBake() end --- -- Sanity check the current project setup. --- function m.validate() if p.action.isConfigurable() then p.container.validate(p.api.rootContainer()) end end --- -- Override point, for logic that should run after validation and -- before the action takes control. --- function m.preAction() local action = premake.action.current() printf("Running action '%s'...", action.trigger) end --- -- Hand over control to the action. --- function m.callAction() local action = premake.action.current() premake.action.call(action.trigger) end --- -- Processing is complete. --- function m.postAction() if p.action.isConfigurable() then print("Done.") end end -- -- Script-side program entry point. -- m.elements = { m.installModuleLoader, m.locateUserScript, m.prepareEnvironment, m.preloadModules, m.runSystemScript, m.prepareAction, m.runUserScript, m.checkInteractive, m.processCommandLine, m.preBake, m.bake, m.postBake, m.validate, m.preAction, m.callAction, m.postAction, } function _premake_main() p.callArray(m.elements) return 0 end
-- -- _premake_main.lua -- Script-side entry point for the main program logic. -- Copyright (c) 2002-2015 Jason Perkins and the Premake project -- local shorthelp = "Type 'premake5 --help' for help" local versionhelp = "premake5 (Premake Build Script Generator) %s" -- Load the collection of core scripts, required for everything else to work local modules = dofile("_modules.lua") local manifest = dofile("_manifest.lua") for i = 1, #manifest do dofile(manifest[i]) end -- Create namespaces for myself local p = premake p.main = {} local m = p.main --- -- Add a new module loader that knows how to use the Premake paths like -- PREMAKE_PATH and the --scripts option, and follows the module/module.lua -- naming convention. --- function m.installModuleLoader() table.insert(package.loaders, 2, m.moduleLoader) end function m.moduleLoader(name) local dir = path.getdirectory(name) local base = path.getname(name) if dir ~= "." then dir = dir .. "/" .. base else dir = base end local full = dir .. "/" .. base .. ".lua" local p = os.locate("modules/" .. full) or os.locate(full) or os.locate(name .. ".lua") if not p then -- try to load from the embedded script p = "$/" .. full end local chunk, err = loadfile(p) return chunk end --- -- Prepare the script environment; anything that should be done -- before the system script gets a chance to run. --- function m.prepareEnvironment() math.randomseed(os.time()) _PREMAKE_DIR = path.getdirectory(_PREMAKE_COMMAND) premake.path = premake.path .. ";" .. _PREMAKE_DIR .. ";" .. _MAIN_SCRIPT_DIR end --- -- Load the required core modules that are shipped as part of Premake -- and expected to be present at startup. --- function m.preloadModules() for i = 1, #modules do local name = modules[i] local preload = name .. "/_preload.lua" local fn = os.locate("modules/" .. preload) or os.locate(preload) if fn then include(fn) else require(name) end end end --- -- Look for and run the system-wide configuration script; make sure any -- configuration scoping gets cleared before continuing. --- function m.runSystemScript() dofileopt(_OPTIONS["systemscript"] or { "premake5-system.lua", "premake-system.lua" }) filter {} end --- -- Look for a user project script, and set up the related global -- variables if I can find one. --- function m.locateUserScript() local defaults = { "premake5.lua", "premake4.lua" } for i = 1, #defaults do if os.isfile(defaults[i]) then _MAIN_SCRIPT = defaults[i] break end end if not _MAIN_SCRIPT then _MAIN_SCRIPT = defaults[1] end if _OPTIONS.file then _MAIN_SCRIPT = _OPTIONS.file end _MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT) _MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT) end --- -- Set the action to be performed from the command line arguments. --- function m.prepareAction() -- The "next-gen" actions have now replaced their deprecated counterparts. -- Provide a warning for a little while before I remove them entirely. if _ACTION and _ACTION:endswith("ng") then premake.warnOnce(_ACTION, "'%s' has been deprecated; use '%s' instead", _ACTION, _ACTION:sub(1, -3)) end premake.action.set(_ACTION) end --- -- If there is a project script available, run it to get the -- project information, available options and actions, etc. --- function m.runUserScript() if os.isfile(_MAIN_SCRIPT) then dofile(_MAIN_SCRIPT) end end --- -- Run the interactive prompt, if requested. --- function m.checkInteractive() if _OPTIONS.interactive then debug.prompt() end end --- -- Validate and process the command line options and arguments. --- function m.processCommandLine() -- Process special options if (_OPTIONS["version"]) then printf(versionhelp, _PREMAKE_VERSION) os.exit(0) end if (_OPTIONS["help"]) then premake.showhelp() os.exit(1) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options ok, err = premake.option.validate(_OPTIONS) if not ok then print("Error: " .. err) os.exit(1) end -- If no further action is possible, show a short help message if not _OPTIONS.interactive then if not _ACTION then print(shorthelp) os.exit(1) end local action = premake.action.current() if not action then print("Error: no such action '" .. _ACTION .. "'") os.exit(1) end if p.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then print(string.format("No Premake script (%s) found!", path.getname(_MAIN_SCRIPT))) os.exit(1) end end end --- -- Override point, for logic that should run before baking. --- function m.preBake() if p.action.isConfigurable() then print("Building configurations...") end end --- -- "Bake" the project information, preparing it for use by the action. --- function m.bake() if p.action.isConfigurable() then premake.oven.bake() end end --- -- Override point, for logic that should run after baking but before -- the configurations are validated. --- function m.postBake() end --- -- Sanity check the current project setup. --- function m.validate() if p.action.isConfigurable() then p.container.validate(p.api.rootContainer()) end end --- -- Override point, for logic that should run after validation and -- before the action takes control. --- function m.preAction() local action = premake.action.current() printf("Running action '%s'...", action.trigger) end --- -- Hand over control to the action. --- function m.callAction() local action = premake.action.current() premake.action.call(action.trigger) end --- -- Processing is complete. --- function m.postAction() if p.action.isConfigurable() then print("Done.") end end -- -- Script-side program entry point. -- m.elements = { m.installModuleLoader, m.locateUserScript, m.prepareEnvironment, m.preloadModules, m.runSystemScript, m.prepareAction, m.runUserScript, m.checkInteractive, m.processCommandLine, m.preBake, m.bake, m.postBake, m.validate, m.preAction, m.callAction, m.postAction, } function _premake_main() p.callArray(m.elements) return 0 end
fixed issue #265
fixed issue #265
Lua
bsd-3-clause
Meoo/premake-core,starkos/premake-core,tritao/premake-core,premake/premake-core,LORgames/premake-core,mendsley/premake-core,LORgames/premake-core,martin-traverse/premake-core,alarouche/premake-core,martin-traverse/premake-core,starkos/premake-core,alarouche/premake-core,xriss/premake-core,tvandijck/premake-core,prapin/premake-core,resetnow/premake-core,resetnow/premake-core,alarouche/premake-core,grbd/premake-core,noresources/premake-core,akaStiX/premake-core,grbd/premake-core,aleksijuvani/premake-core,xriss/premake-core,jstewart-amd/premake-core,akaStiX/premake-core,premake/premake-core,noresources/premake-core,Meoo/premake-core,prapin/premake-core,jstewart-amd/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,CodeAnxiety/premake-core,bravnsgaard/premake-core,noresources/premake-core,akaStiX/premake-core,soundsrc/premake-core,Tiger66639/premake-core,jstewart-amd/premake-core,soundsrc/premake-core,premake/premake-core,Zefiros-Software/premake-core,saberhawk/premake-core,aleksijuvani/premake-core,jstewart-amd/premake-core,resetnow/premake-core,prapin/premake-core,starkos/premake-core,sleepingwit/premake-core,premake/premake-core,Blizzard/premake-core,grbd/premake-core,Tiger66639/premake-core,bravnsgaard/premake-core,CodeAnxiety/premake-core,TurkeyMan/premake-core,tritao/premake-core,starkos/premake-core,lizh06/premake-core,Yhgenomics/premake-core,tvandijck/premake-core,jsfdez/premake-core,dcourtois/premake-core,saberhawk/premake-core,Blizzard/premake-core,tritao/premake-core,mandersan/premake-core,LORgames/premake-core,mandersan/premake-core,bravnsgaard/premake-core,LORgames/premake-core,lizh06/premake-core,noresources/premake-core,saberhawk/premake-core,soundsrc/premake-core,alarouche/premake-core,Meoo/premake-core,TurkeyMan/premake-core,tvandijck/premake-core,felipeprov/premake-core,PlexChat/premake-core,lizh06/premake-core,jsfdez/premake-core,soundsrc/premake-core,jsfdez/premake-core,dcourtois/premake-core,martin-traverse/premake-core,starkos/premake-core,Zefiros-Software/premake-core,kankaristo/premake-core,mendsley/premake-core,mendsley/premake-core,Tiger66639/premake-core,Zefiros-Software/premake-core,PlexChat/premake-core,starkos/premake-core,mandersan/premake-core,Meoo/premake-core,premake/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,mandersan/premake-core,aleksijuvani/premake-core,noresources/premake-core,sleepingwit/premake-core,kankaristo/premake-core,felipeprov/premake-core,xriss/premake-core,sleepingwit/premake-core,Tiger66639/premake-core,grbd/premake-core,xriss/premake-core,Yhgenomics/premake-core,resetnow/premake-core,aleksijuvani/premake-core,sleepingwit/premake-core,dcourtois/premake-core,LORgames/premake-core,dcourtois/premake-core,sleepingwit/premake-core,akaStiX/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,felipeprov/premake-core,felipeprov/premake-core,aleksijuvani/premake-core,Yhgenomics/premake-core,CodeAnxiety/premake-core,starkos/premake-core,mandersan/premake-core,CodeAnxiety/premake-core,premake/premake-core,prapin/premake-core,Blizzard/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,mendsley/premake-core,PlexChat/premake-core,tvandijck/premake-core,resetnow/premake-core,noresources/premake-core,martin-traverse/premake-core,lizh06/premake-core,jstewart-amd/premake-core,kankaristo/premake-core,CodeAnxiety/premake-core,dcourtois/premake-core,premake/premake-core,soundsrc/premake-core,Blizzard/premake-core,dcourtois/premake-core,Blizzard/premake-core,tvandijck/premake-core,tritao/premake-core,noresources/premake-core,Blizzard/premake-core,mendsley/premake-core,saberhawk/premake-core,xriss/premake-core,PlexChat/premake-core,jsfdez/premake-core,Yhgenomics/premake-core,kankaristo/premake-core
8cf9da9a88718fd8271bb4cd4462faa16183b36c
GuemUICastingBarFrame.lua
GuemUICastingBarFrame.lua
local AddonName, AddonTable = ... local LSM = LibStub("LibSharedMedia-3.0") _G[AddonName] = _G[AddonName] or LibStub("AceAddon-3.0"):NewAddon(AddonName) local Addon = _G[AddonName] local assert = assert local type = type local getmetatable = getmetatable local CreateFrame = CreateFrame local UIParent = UIParent function Addon:CreateClass(Class, Name, Parent) Name = Name or nil Parent = Parent or UIParent local obj = CreateFrame(Class, Name, Parent) local base = getmetatable(obj).__index obj.callbacks = {} --Wrapping RegisterUnitEvent method function obj:RegisterUnitEvent(event, unit, callback) assert(type(callback) == "function" , "Usage : obj:RegisterUnitEvent(string event, string unitID, function callback") self.callbacks[event] = callback base.RegisterUnitEvent(self, event, unit) end --Wrapping UnregisterAllEvent method function obj:UnregisterAllEvents() self.callbacks = {} base.UnregisterAllEvents() end --Wrapping UnregisterEvent method function obj:UnregisterEvent(event) assert(type(event) == "string", "Usage : obj:UnregisterEvent(string event)") self.callbacks[event] = nil base.UnregisterEvent(self, event) end --SetScript will call self.callbacks[event] on "OnEvent" fired obj:SetScript("OnEvent", function(self, event, ...) self.callbacks[event](self, event, ...) end) return obj end function Addon:CreateCastingBarFrame(Unit) assert(type(Unit) == "string", "Usage : CreateCastingBarFrame(string Unit)") local f = self:CreateClass("Frame", AddonName..Unit) local s = self:CreateClass("StatusBar", nil, f) f:Hide() f:SetSize(220, 24) f:SetPoint("BOTTOM", 0, 170) local t = f:CreateTexture() t:SetColorTexture(0, 0, 0) t:SetAllPoints(f) s:SetAllPoints(f) s:SetStatusBarTexture("Interface\\AddOns\\"..AddonName.."\\Media\\Solid") s:SetStatusBarColor(0, 0.7, 1.0) s:SetFillStyle("STANDARD") s:SetMinMaxValues(0.0, 1.0) f.fadein = f:CreateAnimationGroup() f.fadein:SetLooping("NONE") local alpha = f.fadein:CreateAnimation("Alpha") alpha:SetDuration(0.2) alpha:SetFromAlpha(0.0) alpha:SetToAlpha(1.0) f.fadeout = f:CreateAnimationGroup() f.fadeout:SetLooping("NONE") local alpha = f.fadeout:CreateAnimation("Alpha") alpha:SetDuration(0.5) alpha:SetFromAlpha(1.0) alpha:SetToAlpha(0.0) f:RegisterUnitEvent("UNIT_SPELLCAST_START", "player", function(self, event, unit, name, ...) self:Show() self.fadeout:Stop() self.fadein:Play() end) f:RegisterUnitEvent("UNIT_SPELLCAST_STOP", "player", function(self, event, unit, name, ...) self.fadeout:Play() end) f:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", "player", function(...) local _, val = s:GetMinMaxValues() s:SetValue(val) end) f.fadeout:SetScript("OnFinished", function(self, ...) f:Hide() end) f:SetScript('OnUpdate', function(self, rate) local _, _, _, _, startTime, endTime = UnitCastingInfo("player") if startTime and endTime then s:SetValue((GetTime()*1000 - startTime) / (endTime-startTime)) end end) return f end
local AddonName, AddonTable = ... local LSM = LibStub("LibSharedMedia-3.0") _G[AddonName] = _G[AddonName] or LibStub("AceAddon-3.0"):NewAddon(AddonName) local Addon = _G[AddonName] local assert = assert local type = type local getmetatable = getmetatable local CreateFrame = CreateFrame local GetSpellInfo = GetSpellInfo local GetTime = GetTime local GetNetStats = GetNetStats local UnitCastingInfo = UnitCastingInfo local UnitChannelInfo = UnitChannelInfo local IsHarmfulSpell = IsHarmfulSpell local IsHelpfulSpell = IsHelpfulSpell local UIParent = UIParent function Addon:CreateClass(Class, Name, Parent) Name = Name or nil Parent = Parent or UIParent local obj = CreateFrame(Class, Name, Parent) local base = getmetatable(obj).__index obj.callbacks = {} --Wrapping RegisterUnitEvent method function obj:RegisterUnitEvent(event, unit, callback) assert(type(callback) == "function" , "Usage : obj:RegisterUnitEvent(string event, string unitID, function callback") self.callbacks[event] = callback base.RegisterUnitEvent(self, event, unit) end --Wrapping UnregisterAllEvent method function obj:UnregisterAllEvents() self.callbacks = {} base.UnregisterAllEvents() end --Wrapping UnregisterEvent method function obj:UnregisterEvent(event) assert(type(event) == "string", "Usage : obj:UnregisterEvent(string event)") self.callbacks[event] = nil base.UnregisterEvent(self, event) end --SetScript will call self.callbacks[event] on "OnEvent" fired obj:SetScript("OnEvent", function(self, event, ...) self.callbacks[event](self, event, ...) end) return obj end function Addon:CreateCastingBarFrame(Unit, Parent) assert(type(Unit) == "string", "Usage : CreateCastingBarFrame(string Unit)") Parent = Parent or UIParent local f = self:CreateClass("Frame", AddonName..Unit, Parent) local s = self:CreateClass("StatusBar", nil, f) --local spark = s:CreateTexture(spark) f:Hide() f:SetSize(220, 24) f:SetPoint("BOTTOM", 0, 170) local t = f:CreateTexture() t:SetColorTexture(0, 0, 0) t:SetAllPoints(f) s:SetAllPoints(f) s:SetStatusBarTexture("Interface\\AddOns\\"..AddonName.."\\Media\\Solid") s:SetStatusBarColor(0, 0.7, 1.0) s:SetFillStyle("STANDARD") s:SetMinMaxValues(0.0, 1.0) f.fadein = f:CreateAnimationGroup() f.fadein:SetLooping("NONE") local alpha = f.fadein:CreateAnimation("Alpha") alpha:SetDuration(0.2) alpha:SetFromAlpha(0.0) alpha:SetToAlpha(1.0) f.fadeout = f:CreateAnimationGroup() f.fadeout:SetLooping("NONE") local alpha = f.fadeout:CreateAnimation("Alpha") alpha:SetDuration(0.5) alpha:SetFromAlpha(1.0) alpha:SetToAlpha(0.0) f.fadeout:SetScript("OnFinished", function(self, ...) f:Hide() end) local c = {} f:RegisterUnitEvent("UNIT_SPELLCAST_START", Unit, function(self, event, unit, ...) c.name, _, c.text, c.texture, c.startTime, c.endTime, _, c.castID, c.notInterruptible = UnitCastingInfo(unit) self:Show() self.fadeout:Stop() self.fadein:Play() end) f:RegisterUnitEvent("UNIT_SPELLCAST_STOP", Unit, function(self, event, unit, name, rank, castid, spellid) self.fadeout:Play() end) f:RegisterUnitEvent("UNIT_SPELLCAST_INTERRUPTED", Unit, function(self, event, unit, name, rank, castid, spellid) local val = s:GetMinMaxValues() c = {} s:SetValue(val) end) f:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", Unit, function(self, event, unit, name, rank, castid, spellid) if(castid == c.castid) then local _, val = s:GetMinMaxValues() s:SetValue(val) end end) f:SetScript('OnUpdate', function(self, rate) if c.startTime and c.endTime then s:SetValue((GetTime()*1000 - c.startTime) / (c.endTime-c.startTime)) end end) return f end
fixed a bug making cast bar inccorectly acting like current casting was successful when an other cast was successful while casting.
fixed a bug making cast bar inccorectly acting like current casting was successful when an other cast was successful while casting.
Lua
unlicense
Guema/gCastBars,Guema/GuemUICastBars
1287a71733033664e509458a893e109bec28837c
tests/correctness_tests.lua
tests/correctness_tests.lua
print('starting memory usage: '..collectgarbage('count')) require('util') local hamt = require('hamt') math.randomseed(42) math.randomseed(666) -- if bounds is 0x2FFFFF, then LuaJIT crashes due to out of memory limitations -- since it causes around 1.8 GB of memory to be used. the limit is probably -- lower on 64 bit Linux due to how MAP_32bit works? local bounds = 0x1FFFFF -- since count() uses fold() which is O(n) checking every step would make it -- O(mn) where m is bounds and n is current size, which is close to O(n^2) -- -- use statistical sampling to check only some of the time to avoid this local count_check_rate = 0.0000 --local file = io.open('data.txt', 'wb') local existing_keys = {} local data = {} for i = 1, bounds do local key for try = 1, 64 do key = tostring(math.random(1, 100000000)) if existing_keys[key] == nil then existing_keys[key] = true break else key = nil end end if key == nil then print('need to increase random int space') assert(false) end local value = math.random() table.insert(data, {key, value}) --file:write(key) --file:write(' ') --file:write(value) --file:write('\n') end --file:close() --file = nil print('memory used to store data: '..collectgarbage('count')) local map = nil local start_time = os.clock() local function h(key) io.write('key: ') io.write(key) io.write(' -> hash: ') io.write(hamt.hash(key)) io.write('\n') end --h("85035710") --h("27815778") --h("14756006") -- add for i = 1, bounds do local datum = data[i] local key = datum[1] local value = datum[2] assert(hamt.get(key, map) == nil) map = hamt.set(key, value, map) -- too slow, causes O(n^2) explosision since count() is O(n) --local count = hamt.count(map) --if i ~= count then --print('key: '..tostring(key)) --print('count: ' .. count) --print(table.show(map)) --assert(false) --end if math.random() < count_check_rate then assert(hamt.count(map) == i) end local fetched_value = hamt.get(key, map) if value ~= fetched_value then print('did not retrieve immediately inserted key value pair') print('key: '..key) print('hash: '..hamt.hash(key)) print('value: '..value) print('fetched_value: '..tostring(fetched_value)) assert(false) end end assert(hamt.count(map) == bounds) table.shuffle(data) for i = 1, bounds do local datum = data[i] local key = datum[1] local value = datum[2] local fetched_value = hamt.get(key, map) if fetched_value ~= value then print('retrieved wrong value for key') print('key: '..key) print('hash: '..hamt.hash(key)) print('value: '..value) print('fetched_value'..fetched_value) assert(false) end end -- remove for i = bounds, 1, -1 do local datum = data[i] local key = datum[1] map = hamt.remove(key, map) -- too slow, causes O(n^2) explosision since count() is O(n) --local count = hamt.count(map) --if (i - 1) ~= count then --print('key: '..tostring(key)) --print('count: ' .. count) --print(table.show(map)) --assert(false) --end if math.random() <= count_check_rate then assert(hamt.count(map) == (i - 1)) end end assert(hamt.count(map) == 0) print(os.clock() - start_time) data = nil existing_keys = nil collectgarbage() print('memory used to store persistent: '..collectgarbage('count')) map = nil hamt = nil collectgarbage() collectgarbage() collectgarbage() print('final memory: '..collectgarbage('count'))
print('starting memory usage: '..collectgarbage('count')) require('tests.util') local hamt = require('hamt') math.randomseed(42) math.randomseed(666) -- if bounds is 0x2FFFFF, then LuaJIT crashes due to out of memory limitations -- since it causes around 1.8 GB of memory to be used. the limit is probably -- lower on 64 bit Linux due to how MAP_32bit works? local bounds = 0x1FFFFF -- since count() uses fold() which is O(n) checking every step would make it -- O(mn) where m is bounds and n is current size, which is close to O(n^2) -- -- use statistical sampling to check only some of the time to avoid this local count_check_rate = 0.0000 --local file = io.open('data.txt', 'wb') local existing_keys = {} local data = {} for i = 1, bounds do local key for try = 1, 64 do key = tostring(math.random(1, 100000000)) if existing_keys[key] == nil then existing_keys[key] = true break else key = nil end end if key == nil then print('need to increase random int space') assert(false) end local value = math.random() table.insert(data, {key, value}) --file:write(key) --file:write(' ') --file:write(value) --file:write('\n') end --file:close() --file = nil print('memory used to store data: '..collectgarbage('count')) local map = nil local start_time = os.clock() local function h(key) io.write('key: ') io.write(key) io.write(' -> hash: ') io.write(hamt.hash(key)) io.write('\n') end --h("85035710") --h("27815778") --h("14756006") -- add for i = 1, bounds do local datum = data[i] local key = datum[1] local value = datum[2] assert(hamt.get(key, map) == nil) map = hamt.set(key, value, map) -- too slow, causes O(n^2) explosision since count() is O(n) --local count = hamt.count(map) --if i ~= count then --print('key: '..tostring(key)) --print('count: ' .. count) --print(table.show(map)) --assert(false) --end if math.random() < count_check_rate then assert(hamt.count(map) == i) end local fetched_value = hamt.get(key, map) if value ~= fetched_value then print('did not retrieve immediately inserted key value pair') print('key: '..key) print('hash: '..hamt.hash(key)) print('value: '..value) print('fetched_value: '..tostring(fetched_value)) assert(false) end end assert(hamt.count(map) == bounds) table.shuffle(data) for i = 1, bounds do local datum = data[i] local key = datum[1] local value = datum[2] local fetched_value = hamt.get(key, map) if fetched_value ~= value then print('retrieved wrong value for key') print('key: '..key) print('hash: '..hamt.hash(key)) print('value: '..value) print('fetched_value'..fetched_value) assert(false) end end -- remove for i = bounds, 1, -1 do local datum = data[i] local key = datum[1] map = hamt.remove(key, map) -- too slow, causes O(n^2) explosision since count() is O(n) --local count = hamt.count(map) --if (i - 1) ~= count then --print('key: '..tostring(key)) --print('count: ' .. count) --print(table.show(map)) --assert(false) --end if math.random() <= count_check_rate then assert(hamt.count(map) == (i - 1)) end end assert(hamt.count(map) == 0) print('benchmark time: ') print(os.clock() - start_time) data = nil existing_keys = nil collectgarbage() print('memory used to store persistent: '..collectgarbage('count')) map = nil hamt = nil collectgarbage() collectgarbage() collectgarbage() print('final memory: '..collectgarbage('count'))
slight fixes to make it work
slight fixes to make it work
Lua
mit
raymond-w-ko/hamt.lua,raymond-w-ko/hamt.lua
c6e1daab09aa812dd9d1f58ed4c3e6a32b653358
Modules/Client/Camera/Effects/ZoomedCamera.lua
Modules/Client/Camera/Effects/ZoomedCamera.lua
--- Allow freedom of movement around a current place, much like the classic script works now. -- Not intended to be use with the current character script -- Intended to be used with a SummedCamera, relative. -- @classmod ZoomedCamera -- @usage -- local Zoom = ZoomedCamera.new() -- Zoom.Zoom = 30 -- Distance from original point -- Zoom.MaxZoom = 100 -- Max distance away -- Zoom.MinZoom = 0.5 -- Min distance away -- Assigning .Zoom will automatically clamp local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local CameraState = require("CameraState") local SummedCamera = require("SummedCamera") local ZoomedCamera = {} ZoomedCamera.ClassName = "ZoomedCamera" ZoomedCamera._MaxZoom = 100 ZoomedCamera._MinZoom = 0.5 ZoomedCamera._Zoom = 10 function ZoomedCamera.new() local self = setmetatable({}, ZoomedCamera) return self end function ZoomedCamera:__add(other) return SummedCamera.new(self, other) end function ZoomedCamera:ZoomIn(Value, Min, Max) if Min or Max then self.Zoom = self.Zoom - math.clamp(Value, Min or -math.huge, Max or math.huge) else self.Zoom = self.Zoom - Value end end function ZoomedCamera:__newindex(Index, Value) if Index == "Zoom" or Index == "TargetZoom" then self._Zoom = math.clamp(Value, self.MinZoom, self.MaxZoom) elseif Index == "MaxZoom" then assert(Value > self.MinZoom, "MaxZoom can't be less than MinZoom") self._MaxZoom = Value self.Zoom = self.Zoom -- Reset the zoom with new constraints. elseif Index == "MinZoom" then assert(Value < self.MaxZoom, "MinZoom can't be greater than MinZoom") self._MinZoom = Value self.Zoom = self.Zoom -- Reset the zoom with new constraints. else rawset(self, Index, Value) end end function ZoomedCamera:__index(Index) if Index == "State" or Index == "CameraState" or Index == "Camera" then local State = CameraState.new() State.Position = Vector3.new(0, 0, self.Zoom) return State elseif Index == "Zoom" or Index == "TargetZoom" then return self._Zoom elseif Index == "MaxZoom" then return self._MaxZoom elseif Index == "MinZoom" then return self._MinZoom else return ZoomedCamera[Index] end end return ZoomedCamera
--- Allow freedom of movement around a current place, much like the classic script works now. -- Not intended to be use with the current character script -- Intended to be used with a SummedCamera, relative. -- @classmod ZoomedCamera -- @usage -- local Zoom = ZoomedCamera.new() -- Zoom.Zoom = 30 -- Distance from original point -- Zoom.MaxZoom = 100 -- max distance away -- Zoom.MinZoom = 0.5 -- min distance away -- Assigning .Zoom will automatically clamp local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local CameraState = require("CameraState") local SummedCamera = require("SummedCamera") local ZoomedCamera = {} ZoomedCamera.ClassName = "ZoomedCamera" ZoomedCamera._MaxZoom = 100 ZoomedCamera._MinZoom = 0.5 ZoomedCamera._zoom = 10 function ZoomedCamera.new() local self = setmetatable({}, ZoomedCamera) return self end function ZoomedCamera:__add(other) return SummedCamera.new(self, other) end function ZoomedCamera:ZoomIn(value, min, max) if min or max then self.Zoom = self.Zoom - math.clamp(value, min or -math.huge, max or math.huge) else self.Zoom = self.Zoom - value end end function ZoomedCamera:__newindex(index, value) if index == "Zoom" or index == "TargetZoom" then self._zoom = math.clamp(value, self.MinZoom, self.MaxZoom) elseif index == "MaxZoom" then assert(value > self.MinZoom, "MaxZoom can't be less than MinZoom") self._MaxZoom = value self.Zoom = self.Zoom -- Reset the zoom with new constraints. elseif index == "MinZoom" then assert(value < self.MaxZoom, "MinZoom can't be greater than MinZoom") self._MinZoom = value self.Zoom = self.Zoom -- Reset the zoom with new constraints. else rawset(self, index, value) end end function ZoomedCamera:__index(index) if index == "State" or index == "CameraState" or index == "Camera" then local State = CameraState.new() State.Position = Vector3.new(0, 0, self.Zoom) return State elseif index == "Zoom" or index == "TargetZoom" then return self._zoom elseif index == "MaxZoom" then return self._MaxZoom elseif index == "MinZoom" then return self._MinZoom else return ZoomedCamera[index] end end return ZoomedCamera
Fix zoomed camera
Fix zoomed camera
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
3f2c966ad561bb07cd459c92f472a33f23047ba3
lib/run.lua
lib/run.lua
local json = require "cjson" local route = require "route" local context = require "context" local ENV = os.getenv('SPACER_ENV') local INTERNAL_TOKEN = require "internal_token" local reject = function (status, body) ngx.status = status ngx.say(json.encode(body)) ngx.exit(ngx.HTTP_OK) end ngx.req.read_body() local tmp = {func_path = nil, params = nil} local R = route(function(func_path) tmp.func_path = func_path return function (params) tmp.params = params end end) local uri = ngx.var.uri -- remove trailing slash if string.sub(uri, -1) == '/' then uri = string.sub(uri, 0, -2) end -- parse request json body local body = ngx.req.get_body_data() local params = {} if body then params = json.decode(body) end -- check if this is an internal request if ngx.req.get_uri_args()["spacer_internal_token"] == INTERNAL_TOKEN then -- if it's an internal request, skip router and call the specified function directly tmp.func_path = ngx.var.uri elseif string.sub(ngx.var.uri, 0, 8) == '/private' then -- also skip router if it's a private path (protected by nginx) tmp.func_path = ngx.var.uri else local ok, errmsg = R:execute( ngx.var.request_method, uri, ngx.req.get_uri_args(), -- all these parameters params) -- into a single "params" table if not ok then reject(404, {["error"] = "not found"}) end end if tmp.func_path == nil then return reject(404, {["error"] = "not found"}) end local ok, func = pcall(require, tmp.func_path) if not ok then -- `func` will be the error message if error occured ngx.log(ngx.ERR, func) local status = nil if string.find(func, "not found") then status = 404 else status = 500 end if ENV == 'production' then func = 'Internal Server Error' end return reject(status, {["error"] = func}) end local ok, ret = pcall(func, tmp.params, context) if not ok then if ret.t == "error" then -- user error ngx.log(ngx.ERR, ret.err) return reject(400, {["error"] = ret.err}) else -- unknown exception ngx.log(ngx.ERR, ret) if ENV == 'production' then ret = 'We\'re sorry, something went wrong' end return reject(500, {["error"] = ret}) end end ngx.say(json.encode({data = ret}))
local json = require "cjson" local route = require "route" local context = require "context" local ENV = os.getenv('SPACER_ENV') local INTERNAL_TOKEN = require "internal_token" local reject = function (status, body) ngx.status = status ngx.say(json.encode(body)) ngx.exit(ngx.HTTP_OK) end ngx.req.read_body() local tmp = {func_path = nil, params = nil} local R = route(function(func_path) return function (params) tmp.func_path = func_path tmp.params = params end end) local uri = ngx.var.uri -- remove trailing slash if string.sub(uri, -1) == '/' then uri = string.sub(uri, 0, -2) end -- parse request json body local body = ngx.req.get_body_data() local params = {} if body then params = json.decode(body) end -- check if this is an internal request if ngx.req.get_uri_args()["spacer_internal_token"] == INTERNAL_TOKEN then -- if it's an internal request, skip router and call the specified function directly tmp.func_path = ngx.var.uri elseif string.sub(ngx.var.uri, 0, 8) == '/private' then -- also skip router if it's a private path (protected by nginx) tmp.func_path = ngx.var.uri else local ok, errmsg = R:execute( ngx.var.request_method, uri, ngx.req.get_uri_args(), -- all these parameters params) -- into a single "params" table if not ok then reject(404, {["error"] = "not found"}) end end if tmp.func_path == nil then return reject(404, {["error"] = "not found"}) end local ok, func = pcall(require, tmp.func_path) if not ok then -- `func` will be the error message if error occured ngx.log(ngx.ERR, func) local status = nil if string.find(func, "not found") then status = 404 else status = 500 end if ENV == 'production' then func = 'Internal Server Error' end return reject(status, {["error"] = func}) end local ok, ret = pcall(func, tmp.params, context) if not ok then if ret.t == "error" then -- user error ngx.log(ngx.ERR, ret.err) return reject(400, {["error"] = ret.err}) else -- unknown exception ngx.log(ngx.ERR, ret) if ENV == 'production' then ret = 'We\'re sorry, something went wrong' end return reject(500, {["error"] = ret}) end end ngx.say(json.encode({data = ret}))
fix routing
fix routing
Lua
mit
poga/spacer,poga/spacer,poga/spacer
6b2e3fb98f7c2b9493e48ea1cf82103f6394390a
lua/gen.lua
lua/gen.lua
local bytecode = require("bytecode") local preHooks = {} local postHooks = {} local ccargs = os.getenv("CCARGS") or "" local mainobj local objs = {} local gen = {} -- check if file exists local function fileExists(file) if file then local f = io.open(file,"r") if f ~= nil then io.close(f) return true else return false end end end -- run hooks array local function callHooks(hooks, ...) for i=1, #hooks do hooks[i](...) end end -- add hook to hooks array local function addHook(hooks, fn) for i = 1, #hooks do if hooks[i] == fn then return false end end table.insert(hooks, fn) return true end -- call through pipe to generate local function generateCodeObject(file) local objfile = file local leavesym = "" local name = file:gsub("%..-$", ""):gsub("/",".") -- First file we add is always main if mainobj == nil then name = "main" mainobj = true end -- Run preprocessors on file callHooks(preHooks, file) -- generate lua object if file:match("%.lua$") then if (not opt.flag("n")) then -- load code to check it for errors local fn, err = loadstring(gen.code[file]) -- die on syntax errors if not fn then msg.fatal(err) end end -- check for leave symbols flag if opt.flag("g") then leavesym = "-g" end objfile = file..".o" msg.info("'"..name.."' = "..file) -- create CC line local f = io.popen(string.format( "%s -q %s --bytecode=%s %s %s", RAVABIN, leavesym, name, "-", objfile),"w") -- write code to generator f:write(gen.code[file]) f:close() msg.done() else msg.info("Adding object "..file) msg.done() end -- add object if name == "main" then mainobj = objfile else table.insert(objs, objfile) end --reclame memory (probably overkill in most cases) gen.code[file] = true return objfile end -- list files in a directory gen.scandir = function(dir) local r = {} for file in io.popen("ls -a '"..dir.."' 2>/dev/null"):lines() do table.insert(r, file) end return r end -- Add PreHooks to filter input gen.addPreHook = function(fn) return addHook(preHooks, fn) end -- Add PostHooks to futher process output gen.addPostHook = function(fn) return addHook(postHooks, fn) end -- Add files to the rava compiler gen.addFile = function(...) local arg = {...} for i=1, #arg do -- normalize filename local file = arg[i]:gsub("^%./",""):gsub("^/","") if gen.code[file] then break elseif not fileExists(file) then msg.warning("Failed to add module: "..file) break elseif file:match("%.lua$") then msg.info("Loading "..file) local f, err = io.open(file,"r") if err then msg.fatal(err) end gen.code[file] = f:read("*all") f:close() msg.done() end generateCodeObject(file) end end -- Add a string to the rava compiler gen.addString = function(name, code) name = name:gsub("^%./",""):gsub("^/","") gen.code[name] = code generateCodeObject(name) end -- Evaluate code to run in realtime gen.eval = function(...) local arg = {...} local chunk = "" for x = 1, #arg do chunk = chunk.."\n"..arg[x] end local fn=loadstring(chunk) fn() end -- Execute external files gen.exec = function(...) local arg = {...} for x = 1, #arg do dofile(arg[x]) end end gen.build = function(name, ...) mainobj = true name = name..".a" --load Lua Code gen.addFile(...) msg.info("Building "..name.." library... ") -- Construct compiler call local ccall = string.format([[ %s -r -static %s \ -o %s ]], os.getenv("LD") or "ld", table.concat(objs, " "), name) -- Call compiler os.execute(ccall) msg.done() -- run PostHooks callHooks(postHooks, name) end -- Compile the rava object state to binary gen.compile = function(name, ...) --load Lua Code gen.addFile(...) msg.info("Compiling Binary... ") local f, err = io.open(name..".a", "w+") local files = require("libs"..".ravastore") f:write(files["rava.a"]) f:close() -- Construct compiler call local ccall = string.format([[ %s -O%s -Wall -Wl,-E \ -x none %s -x none %s \ %s \ -o %s -lm -ldl -flto -lpthread ]], os.getenv("CC") or "gcc", OPLEVEL, name..".a", mainobj, ccargs.." "..table.concat(objs, " "), name) -- Call compiler os.execute(ccall) msg.done() -- run PostHooks callHooks(postHooks, name) end -- Generate an object file from lua files gen.bytecode = bytecode.start -- Generate binary filestore gen.filestore = function(name, store, ...) -- open store local out = io.open(store:gsub("%..+$", "")..".lua", "w+") local files = {...} -- start name out:write("local "..name.." = {}\n") -- loop through files for _, file in pairs(files) do local ins = io.open(file, "r") -- test for failed open if not ins then msg.fatal("Error reading " .. file) end -- add file entry to table out:write(name..'["'..file..'"] = "') -- write all data to store in memory safe way repeat local char = ins:read(1) if char ~= nil then out:write(string.format("\\%i", char:byte())) end until char == nil ins:close() out:write('"\n') end -- add module code out:write('\nmodule(...)\n') out:write('return '..name) out:close() gen.bytecode(store:gsub("%..+$", "")..".lua", store:gsub("%..+$", "")..".o") end -- code repository gen.code = {} module(...) return gen
local bytecode = require("bytecode") local preHooks = {} local postHooks = {} local ccargs = os.getenv("CCARGS") or "" local mainobj local objs = {} local gen = {} -- check if file exists local function fileExists(file) if file then local f = io.open(file,"r") if f ~= nil then io.close(f) return true else return false end end end -- run hooks array local function callHooks(hooks, ...) for i=1, #hooks do hooks[i](...) end end -- add hook to hooks array local function addHook(hooks, fn) for i = 1, #hooks do if hooks[i] == fn then return false end end table.insert(hooks, fn) return true end -- call through pipe to generate local function generateCodeObject(file) local objfile = file local leavesym = "" local name = file:gsub("%..-$", ""):gsub("/",".") -- First file we add is always main if mainobj == nil then name = "main" mainobj = true end -- Run preprocessors on file callHooks(preHooks, file) -- generate lua object if file:match("%.lua$") then if (not opt.flag("n")) then -- load code to check it for errors local fn, err = loadstring(gen.code[file]) -- die on syntax errors if not fn then msg.fatal(err) end end -- check for leave symbols flag if opt.flag("g") then leavesym = "-g" end objfile = file..".o" msg.info("'"..name.."' = "..file) -- create CC line local f = io.popen(string.format( "%s -q %s --bytecode=%s %s %s", RAVABIN, leavesym, name, "-", objfile),"w") -- write code to generator f:write(gen.code[file]) f:close() msg.done() else msg.info("Adding object "..file) msg.done() end -- add object if name == "main" then mainobj = objfile else table.insert(objs, objfile) end --reclame memory (probably overkill in most cases) gen.code[file] = true return objfile end -- list files in a directory gen.scandir = function(dir) local r = {} for file in io.popen("ls -a '"..dir.."' 2>/dev/null"):lines() do table.insert(r, file) end return r end -- Add PreHooks to filter input gen.addPreHook = function(fn) return addHook(preHooks, fn) end -- Add PostHooks to futher process output gen.addPostHook = function(fn) return addHook(postHooks, fn) end -- Add files to the rava compiler gen.addFile = function(...) local arg = {...} for i=1, #arg do -- normalize filename local file = arg[i]:gsub("^%./",""):gsub("^/","") if gen.code[file] then break elseif not fileExists(file) then msg.warning("Failed to add module: "..file) break elseif file:match("%.lua$") then msg.info("Loading "..file) local f, err = io.open(file,"r") if err then msg.fatal(err) end gen.code[file] = f:read("*all") f:close() msg.done() end generateCodeObject(file) end end -- Add a string to the rava compiler gen.addString = function(name, code) name = name:gsub("^%./",""):gsub("^/","") gen.code[name] = code generateCodeObject(name) end -- Evaluate code to run in realtime gen.eval = function(...) local arg = {...} local chunk = "" for x = 1, #arg do chunk = chunk.."\n"..arg[x] end local fn=loadstring(chunk) fn() end -- Execute external files gen.exec = function(...) local arg = {...} for x = 1, #arg do dofile(arg[x]) end end gen.build = function(name, ...) mainobj = true name = name..".a" --load Lua Code gen.addFile(...) msg.info("Building "..name.." library... ") -- Construct compiler call local ccall = string.format([[ %s -r -static %s \ -o %s ]], os.getenv("LD") or "ld", table.concat(objs, " "), name) -- Call compiler os.execute(ccall) msg.done() -- run PostHooks callHooks(postHooks, name) end -- Compile the rava object state to binary gen.compile = function(name, ...) --load Lua Code gen.addFile(...) msg.info("Compiling Binary... ") local f, err = io.open(name..".a", "w+") local files = require("libs"..".ravastore") f:write(files["rava.a"]) f:close() -- Construct compiler call local ccall = string.format([[ %s -O%s -Wall -Wl,-E \ -x none %s -x none %s \ %s \ -o %s -lm -ldl -flto -lpthread ]], os.getenv("CC") or "gcc", OPLEVEL, name..".a", mainobj, ccargs.." "..table.concat(objs, " "), name) -- Call compiler os.execute(ccall) msg.done() -- run PostHooks callHooks(postHooks, name) end -- Generate an object file from lua files gen.bytecode = bytecode.start -- Generate binary filestore gen.filestore = function(name, store, ...) store = store:gsub("%..[^%.]+$", "") -- open store local out = io.open(store..".lua", "w+") local files = {...} -- start name out:write("local "..name.." = {}\n") -- loop through files for _, file in pairs(files) do local ins = io.open(file, "r") -- test for failed open if not ins then msg.fatal("Error reading " .. file) end -- add file entry to table out:write(name..'["'..file..'"] = "') -- write all data to store in memory safe way repeat local char = ins:read(1) if char ~= nil then out:write(string.format("\\%i", char:byte())) end until char == nil ins:close() out:write('"\n') end -- add module code out:write('\nmodule(...)\n') out:write('return '..name) out:close() gen.bytecode(store..".lua", store..".o") end -- code repository gen.code = {} module(...) return gen
fixed gen.filestore
fixed gen.filestore
Lua
mit
frinknet/rava,frinknet/rava,frinknet/rava
3a06a72deaa1a2d1fd3b7bccb2deab7de6b9c91a
tundra.lua
tundra.lua
local macosx = { Env = { CCOPTS = { "-Wall", "-Weverything", "-Werror", "-I.", "-DMACOSX", "-Wno-missing-prototypes", "-Wno-padded", { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, }, OPENCL_COMPILER = "$(OBJECTDIR)$(SEP)wclc$(PROGSUFFIX)", }, } local win32 = { Env = { CPPPATH = { { "external/windows/include" ; Config = "win32-*-*" }, }, LIBPATH = { { "external/windows/lib/x86" ; Config = "win32-*-*" }, }, GENERATE_PDB = "1", CCOPTS = { "/W4", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4996", "/wd4389", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, }, }, } local win64 = { Env = { CPPPATH = { { "external/windows/include" ; Config = "win32-*-*" }, }, GENERATE_PDB = "1", CCOPTS = { "/MT", "/W4", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, }, }, } Build { Units = "units.lua", Passes = { BuildCompiler = { Name="Build Compiler", BuildOrder = 1 }, }, Configs = { Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } }, Config { Name = "win32-msvc", DefaultOnHost = { "windows" }, Inherit = win32, Tools = { "msvc" } }, Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc" } }, }, IdeGenerationHints = { Msvc = { -- Remap config names to MSVC platform names (affects things like header scanning & debugging) PlatformMappings = { ['win64-msvc'] = 'x64', }, -- Remap variant names to MSVC friendly names VariantMappings = { ['release'] = 'Release', ['debug'] = 'Debug', }, }, }, }
local macosx = { Env = { CCOPTS = { "-Wall", "-Weverything", "-Werror", "-I.", "-DMACOSX", "-Wno-missing-prototypes", "-Wno-padded", { "-O0", "-g"; Config = "*-*-debug" }, { "-O3", "-g"; Config = "*-*-release" }, }, OPENCL_COMPILER = "$(OBJECTDIR)$(SEP)wclc$(PROGSUFFIX)", }, } local win32 = { Env = { CPPPATH = { { "external/windows/include" ; Config = "win32-*-*" }, }, LIBPATH = { { "external/windows/lib/x86" ; Config = "win32-*-*" }, }, GENERATE_PDB = "1", CCOPTS = { "/W4", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4996", "/wd4389", "/wd4706", "/wd4204", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, }, OPENCL_COMPILER = "$(OBJECTDIR)$(SEP)wclc$(PROGSUFFIX)", }, } local win64 = { Env = { CPPPATH = { { "external/windows/include" ; Config = "win32-*-*" }, }, GENERATE_PDB = "1", CCOPTS = { "/MT", "/W4", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4152", "/wd4996", "/wd4389", { "/Od"; Config = "*-*-debug" }, { "/O2"; Config = "*-*-release" }, }, OPENCL_COMPILER = "$(OBJECTDIR)$(SEP)wclc$(PROGSUFFIX)", }, } Build { Units = "units.lua", Passes = { BuildCompiler = { Name="Build Compiler", BuildOrder = 1 }, }, Configs = { Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } }, Config { Name = "win32-msvc", DefaultOnHost = { "windows" }, Inherit = win32, Tools = { "msvc" } }, Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { "msvc" } }, }, IdeGenerationHints = { Msvc = { -- Remap config names to MSVC platform names (affects things like header scanning & debugging) PlatformMappings = { ['win64-msvc'] = 'x64', }, -- Remap variant names to MSVC friendly names VariantMappings = { ['release'] = 'Release', ['debug'] = 'Debug', }, }, }, }
Fixed win32 warnings
Fixed win32 warnings
Lua
mit
emoon/sico,emoon/sico
c28f63b9394681dd13ca2bada3a1fa3deb367a4d
xmake/rules/qt/moc/xmake.lua
xmake/rules/qt/moc/xmake.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: moc rule("qt.moc") -- add rule: qt environment add_deps("qt.env") -- set extensions set_extensions(".h", ".hpp") -- before load before_load(function (target) -- get moc local moc = path.join(target:data("qt").bindir, is_host("windows") and "moc.exe" or "moc") assert(moc and os.isexec(moc), "moc not found!") -- save moc target:data_set("qt.moc", moc) end) -- before build file (we need compile it first if exists Q_PRIVATE_SLOT) before_build_file(function (target, sourcefile, opt) -- imports import("moc") import("core.base.option") import("core.theme.theme") import("core.project.config") import("core.tool.compiler") import("core.project.depend") -- get c++ source file for moc -- -- add_files("mainwindow.h") -> moc_MainWindow.cpp -- add_files("mainwindow.cpp", {rules = "qt.moc"}) -> mainwindow.moc, @see https://github.com/xmake-io/xmake/issues/750 -- local basename = path.basename(sourcefile) local filename_moc = "moc_" .. basename .. ".cpp" if sourcefile:endswith(".cpp") then filename_moc = basename .. ".moc" end local sourcefile_moc = path.join(target:autogendir(), "rules", "qt", "moc", filename_moc) -- get object file local objectfile = target:objectfile(sourcefile_moc) -- load compiler local compinst = compiler.load("cxx", {target = target}) -- get compile flags local compflags = compinst:compflags({target = target, sourcefile = sourcefile_moc}) -- add objectfile table.insert(target:objectfiles(), objectfile) -- load dependent info local dependfile = target:dependfile(objectfile) local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {}) -- need build this object? local depvalues = {compinst:program(), compflags} if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectfile), values = depvalues}) then return end -- trace progress info cprintf("${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} ", opt.progress) if option.get("verbose") then cprint("${dim color.build.object}compiling.qt.moc %s", sourcefile) else cprint("${color.build.object}compiling.qt.moc %s", sourcefile) end -- generate c++ source file for moc moc.generate(target, sourcefile, sourcefile_moc) -- we need compile this moc_xxx.cpp file if exists Q_PRIVATE_SLOT, @see https://github.com/xmake-io/xmake/issues/750 dependinfo.files = {} local mocdata = io.readfile(sourcefile) if mocdata and mocdata:find("Q_PRIVATE_SLOT") then -- add includedirs of sourcefile_moc target:add("includedirs", path.directory(sourcefile_moc)) -- remove the object file of sourcefile_moc local objectfiles = target:objectfiles() for idx, objectfile in ipairs(objectfiles) do if objectfile == target:objectfile(sourcefile_moc) then table.remove(objectfiles, idx) break end end else -- trace if option.get("verbose") then print(compinst:compcmd(sourcefile_moc, objectfile, {compflags = compflags})) end -- compile c++ source file for moc assert(compinst:compile(sourcefile_moc, objectfile, {dependinfo = dependinfo, compflags = compflags})) end -- update files and values to the dependent file dependinfo.values = depvalues table.insert(dependinfo.files, sourcefile) depend.save(dependinfo, dependfile) end)
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define rule: moc rule("qt.moc") -- add rule: qt environment add_deps("qt.env") -- set extensions set_extensions(".h", ".hpp") -- before load before_load(function (target) -- get moc local moc = path.join(target:data("qt").bindir, is_host("windows") and "moc.exe" or "moc") assert(moc and os.isexec(moc), "moc not found!") -- save moc target:data_set("qt.moc", moc) end) -- before build file (we need compile it first if exists Q_PRIVATE_SLOT) before_build_file(function (target, sourcefile, opt) -- imports import("moc") import("core.base.option") import("core.theme.theme") import("core.project.config") import("core.tool.compiler") import("core.project.depend") -- get c++ source file for moc -- -- add_files("mainwindow.h") -> moc_MainWindow.cpp -- add_files("mainwindow.cpp", {rules = "qt.moc"}) -> mainwindow.moc, @see https://github.com/xmake-io/xmake/issues/750 -- local basename = path.basename(sourcefile) local filename_moc = "moc_" .. basename .. ".cpp" if sourcefile:endswith(".cpp") then filename_moc = basename .. ".moc" end local sourcefile_moc = path.join(target:autogendir(), "rules", "qt", "moc", filename_moc) -- get object file local objectfile = target:objectfile(sourcefile_moc) -- load compiler local compinst = compiler.load("cxx", {target = target}) -- get compile flags local compflags = compinst:compflags({target = target, sourcefile = sourcefile_moc}) -- add objectfile table.insert(target:objectfiles(), objectfile) -- load dependent info local dependfile = target:dependfile(objectfile) local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {}) -- need build this object? local depvalues = {compinst:program(), compflags} if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectfile), values = depvalues}) then return end -- trace progress info cprintf("${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} ", opt.progress) if option.get("verbose") then cprint("${dim color.build.object}compiling.qt.moc %s", sourcefile) else cprint("${color.build.object}compiling.qt.moc %s", sourcefile) end -- generate c++ source file for moc moc.generate(target, sourcefile, sourcefile_moc) -- we need compile this moc_xxx.cpp file if exists Q_PRIVATE_SLOT, @see https://github.com/xmake-io/xmake/issues/750 dependinfo.files = {} local mocdata = io.readfile(sourcefile) if mocdata and mocdata:find("Q_PRIVATE_SLOT") or sourcefile_moc:endswith(".moc") then -- add includedirs of sourcefile_moc target:add("includedirs", path.directory(sourcefile_moc)) -- remove the object file of sourcefile_moc local objectfiles = target:objectfiles() for idx, objectfile in ipairs(objectfiles) do if objectfile == target:objectfile(sourcefile_moc) then table.remove(objectfiles, idx) break end end else -- trace if option.get("verbose") then print(compinst:compcmd(sourcefile_moc, objectfile, {compflags = compflags})) end -- compile c++ source file for moc assert(compinst:compile(sourcefile_moc, objectfile, {dependinfo = dependinfo, compflags = compflags})) end -- update files and values to the dependent file dependinfo.values = depvalues table.insert(dependinfo.files, sourcefile) depend.save(dependinfo, dependfile) end)
fix: cl.exe warning D9024 :无法识别的源文件类型
fix: cl.exe warning D9024 :无法识别的源文件类型
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
66e54fe90fa3a759a5e33cd018703992da475c63
misc/freeswitch/scripts/common/call_history.lua
misc/freeswitch/scripts/common/call_history.lua
-- Gemeinschaft 5 module: call_history class -- (c) AMOOMA GmbH 2012 -- module(...,package.seeall) function camelize_type(account_type) ACCOUNT_TYPES = { sipaccount = 'SipAccount', conference = 'Conference', faxaccount = 'FaxAccount', callthrough = 'Callthrough', huntgroup = 'HuntGroup', automaticcalldistributor = 'AutomaticCallDistributor', } return ACCOUNT_TYPES[account_type] or account_type; end CallHistory = {} -- Create CallHistory object function CallHistory.new(self, arg) arg = arg or {} object = arg.object or {} setmetatable(object, self); self.__index = self; self.class = 'callhistory'; self.log = arg.log; self.database = arg.database; return object; end function CallHistory.insert_entry(self, call_history) local keys = {} local values = {} call_history.created_at = 'NOW()'; call_history.updated_at = 'NOW()'; for key, value in pairs(call_history) do table.insert(keys, key); table.insert(values, value); end local sql_query = 'INSERT INTO `call_histories` (`' .. table.concat(keys, "`, `") .. '`) VALUES (' .. table.concat(values, ", ") .. ')'; local result = self.database:query(sql_query); if not result then self.log:error('[', call_history.caller_channel_uuid, '] CALL_HISTORY_SAVE - SQL: ', sql_query); end return result; end function CallHistory.insert_event(self, uuid, account_type, account_id, entry_type, event) require 'common.str' local call_history = {} call_history.entry_type = common.str.to_sql(entry_type); call_history.call_historyable_type = common.str.to_sql(camelize_type(account_type)); call_history.call_historyable_id = common.str.to_sql(account_id); call_history.caller_channel_uuid = common.str.to_sql(uuid); call_history.duration = common.str.to_sql(event:getHeader('variable_billsec')); call_history.caller_id_number = common.str.to_sql(event:getHeader('variable_effective_caller_id_number')); call_history.caller_id_name = common.str.to_sql(event:getHeader('variable_effective_caller_id_name')); call_history.callee_id_number = common.str.to_sql(event:getHeader('variable_effective_callee_id_number')); call_history.callee_id_name = common.str.to_sql(event:getHeader('variable_effective_callee_id_name')); call_history.result = common.str.to_sql(event:getHeader('variable_hangup_cause')); call_history.start_stamp = 'FROM_UNIXTIME(' .. math.floor(common.str.to_i(event:getHeader('Caller-Channel-Created-Time')) / 1000000) .. ')'; call_history.auth_account_type = common.str.to_sql(camelize_type(event:getHeader('variable_gs_auth_account_type'))); call_history.auth_account_id = common.str.to_sql(event:getHeader('variable_gs_auth_account_id')); call_history.callee_account_type = common.str.to_sql(camelize_type(event:getHeader('variable_gs_destination_type'))); call_history.callee_account_id = common.str.to_sql(event:getHeader('variable_gs_destination_id')); call_history.destination_number = common.str.to_sql(event:getHeader('variable_gs_destination_number')); call_history.forwarding_service = common.str.to_sql(event:getHeader('variable_gs_forwarding_service')); if not common.str.to_b(event:getHeader('variable_gs_clir')) then call_history.caller_account_type = common.str.to_sql(camelize_type(event:getHeader('variable_gs_caller_account_type') or event:getHeader('variable_gs_account_type'))); call_history.caller_account_id = common.str.to_sql(event:getHeader('variable_gs_caller_account_id') or event:getHeader('variable_gs_account_id')); end if common.str.to_s(event:getHeader('variable_gs_call_service')) == 'pickup' then call_history.forwarding_service = common.str.to_sql('pickup'); end self.log:info('[', uuid,'] CALL_HISTORY_SAVE ', entry_type,' - account: ', account_type, '=', account_id, ', caller: ', call_history.caller_id_number, ' ', call_history.caller_id_name, ', callee: ', call_history.callee_id_number, ' ', call_history.callee_id_name, ', result: ', call_history.result ); return self:insert_entry(call_history); end function CallHistory.insert_forwarded(self, uuid, account_type, account_id, caller, destination, result) require 'common.str' local call_history = {} call_history.entry_type = common.str.to_sql('forwarded'); call_history.call_historyable_type = common.str.to_sql(camelize_type(account_type)); call_history.call_historyable_id = common.str.to_sql(account_id); call_history.caller_channel_uuid = common.str.to_sql(uuid); call_history.duration = common.str.to_sql(caller:to_i('billsec')); call_history.caller_id_number = common.str.to_sql(caller.caller_id_number); call_history.caller_id_name = common.str.to_sql(caller.caller_id_name); call_history.callee_id_number = common.str.to_sql(caller.callee_id_number); call_history.callee_id_name = common.str.to_sql(caller.callee_id_name); call_history.result = common.str.to_sql(result.cause or 'UNSPECIFIED'); call_history.start_stamp = 'FROM_UNIXTIME(' .. math.floor(caller:to_i('created_time') / 1000000) .. ')'; if caller.account and not common.str.to_b(event:getHeader('variable_gs_clir')) then call_history.caller_account_type = common.str.to_sql(camelize_type(caller.account.class)); call_history.caller_account_id = common.str.to_sql(caller.account.id); end if caller.auth_account then call_history.auth_account_type = common.str.to_sql(camelize_type(caller.auth_account.class)); call_history.auth_account_id = common.str.to_sql(caller.auth_account.id); end if destination then call_history.callee_account_type = common.str.to_sql(camelize_type(destination.type)); call_history.callee_account_id = common.str.to_sql(destination.id); call_history.destination_number = common.str.to_sql(destination.number); end call_history.forwarding_service = common.str.to_sql(caller.forwarding_service); self.log:info('CALL_HISTORY_SAVE forwarded - account: ', account_type, '=', account_id, ', service: ', call_history.forwarding_service, ', caller: ', call_history.caller_id_number, ' ', call_history.caller_id_name, ', callee: ', call_history.callee_id_number, ' ', call_history.callee_id_name, ', result: ', call_history.result ); return self:insert_entry(call_history); end
-- Gemeinschaft 5 module: call_history class -- (c) AMOOMA GmbH 2012 -- module(...,package.seeall) function camelize_type(account_type) ACCOUNT_TYPES = { sipaccount = 'SipAccount', conference = 'Conference', faxaccount = 'FaxAccount', callthrough = 'Callthrough', huntgroup = 'HuntGroup', automaticcalldistributor = 'AutomaticCallDistributor', } return ACCOUNT_TYPES[account_type] or account_type; end CallHistory = {} -- Create CallHistory object function CallHistory.new(self, arg) arg = arg or {} object = arg.object or {} setmetatable(object, self); self.__index = self; self.class = 'callhistory'; self.log = arg.log; self.database = arg.database; return object; end function CallHistory.insert_entry(self, call_history) local keys = {} local values = {} call_history.created_at = 'NOW()'; call_history.updated_at = 'NOW()'; for key, value in pairs(call_history) do table.insert(keys, key); table.insert(values, value); end local sql_query = 'INSERT INTO `call_histories` (`' .. table.concat(keys, "`, `") .. '`) VALUES (' .. table.concat(values, ", ") .. ')'; local result = self.database:query(sql_query); if not result then self.log:error('[', call_history.caller_channel_uuid, '] CALL_HISTORY_SAVE - SQL: ', sql_query); end return result; end function CallHistory.insert_event(self, uuid, account_type, account_id, entry_type, event) require 'common.str' local call_history = {} call_history.entry_type = common.str.to_sql(entry_type); call_history.call_historyable_type = common.str.to_sql(camelize_type(account_type)); call_history.call_historyable_id = common.str.to_sql(account_id); call_history.caller_channel_uuid = common.str.to_sql(uuid); call_history.duration = common.str.to_sql(event:getHeader('variable_billsec')); call_history.caller_id_number = common.str.to_sql(event:getHeader('variable_effective_caller_id_number')); call_history.caller_id_name = common.str.to_sql(event:getHeader('variable_effective_caller_id_name')); call_history.callee_id_number = common.str.to_sql(event:getHeader('variable_effective_callee_id_number')); call_history.callee_id_name = common.str.to_sql(event:getHeader('variable_effective_callee_id_name')); call_history.result = common.str.to_sql(event:getHeader('variable_hangup_cause')); call_history.start_stamp = 'FROM_UNIXTIME(' .. math.floor(common.str.to_i(event:getHeader('Caller-Channel-Created-Time')) / 1000000) .. ')'; call_history.auth_account_type = common.str.to_sql(camelize_type(event:getHeader('variable_gs_auth_account_type'))); call_history.auth_account_id = common.str.to_sql(event:getHeader('variable_gs_auth_account_id')); call_history.callee_account_type = common.str.to_sql(camelize_type(event:getHeader('variable_gs_destination_type'))); call_history.callee_account_id = common.str.to_sql(event:getHeader('variable_gs_destination_id')); call_history.destination_number = common.str.to_sql(event:getHeader('variable_gs_destination_number')); call_history.forwarding_service = common.str.to_sql(event:getHeader('variable_gs_forwarding_service')); if not common.str.to_b(event:getHeader('variable_gs_clir')) then call_history.caller_account_type = common.str.to_sql(camelize_type(event:getHeader('variable_gs_caller_account_type') or event:getHeader('variable_gs_account_type'))); call_history.caller_account_id = common.str.to_sql(event:getHeader('variable_gs_caller_account_id') or event:getHeader('variable_gs_account_id')); end if common.str.to_s(event:getHeader('variable_gs_call_service')) == 'pickup' then call_history.forwarding_service = common.str.to_sql('pickup'); end self.log:info('[', uuid,'] CALL_HISTORY_SAVE ', entry_type,' - account: ', account_type, '=', account_id, ', caller: ', call_history.caller_id_number, ' ', call_history.caller_id_name, ', callee: ', call_history.callee_id_number, ' ', call_history.callee_id_name, ', result: ', call_history.result ); return self:insert_entry(call_history); end function CallHistory.insert_forwarded(self, uuid, account_type, account_id, caller, destination, result) require 'common.str' local call_history = {} call_history.entry_type = common.str.to_sql('forwarded'); call_history.call_historyable_type = common.str.to_sql(camelize_type(account_type)); call_history.call_historyable_id = common.str.to_sql(account_id); call_history.caller_channel_uuid = common.str.to_sql(uuid); call_history.duration = common.str.to_sql(caller:to_i('billsec')); call_history.caller_id_number = common.str.to_sql(caller.caller_id_number); call_history.caller_id_name = common.str.to_sql(caller.caller_id_name); call_history.callee_id_number = common.str.to_sql(caller.callee_id_number); call_history.callee_id_name = common.str.to_sql(caller.callee_id_name); call_history.result = common.str.to_sql(result.cause or 'UNSPECIFIED'); call_history.start_stamp = 'FROM_UNIXTIME(' .. math.floor(caller:to_i('created_time') / 1000000) .. ')'; if caller.account and not caller.clir then call_history.caller_account_type = common.str.to_sql(camelize_type(caller.account.class)); call_history.caller_account_id = common.str.to_sql(caller.account.id); end if caller.auth_account then call_history.auth_account_type = common.str.to_sql(camelize_type(caller.auth_account.class)); call_history.auth_account_id = common.str.to_sql(caller.auth_account.id); end if destination then call_history.callee_account_type = common.str.to_sql(camelize_type(destination.type)); call_history.callee_account_id = common.str.to_sql(destination.id); call_history.destination_number = common.str.to_sql(destination.number); end call_history.forwarding_service = common.str.to_sql(caller.forwarding_service); self.log:info('CALL_HISTORY_SAVE forwarded - account: ', account_type, '=', account_id, ', service: ', call_history.forwarding_service, ', caller: ', call_history.caller_id_number, ' ', call_history.caller_id_name, ', callee: ', call_history.callee_id_number, ' ', call_history.callee_id_name, ', result: ', call_history.result ); return self:insert_entry(call_history); end
variable context fixed
variable context fixed
Lua
mit
amooma/GS5,amooma/GS5,amooma/GS5,funkring/gs5,funkring/gs5,funkring/gs5,funkring/gs5,amooma/GS5
436ccb77ecdea5a70bb2d4627965551b6c3858b0
rules/misc.lua
rules/misc.lua
--[[ Copyright (c) 2011-2015, Vsevolod Stakhov <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ]]-- -- This is main lua config file for rspamd local util = require "rspamd_util" local rspamd_regexp = require "rspamd_regexp" local rspamd_logger = require "rspamd_logger" local reconf = config['regexp'] -- Uncategorized rules local subject_re = rspamd_regexp.create('/^(?:(?:Re|Fwd|Fw|Aw|Antwort|Sv):\\s*)+(.+)$/i') -- Local rules local r_bgcolor = '/BGCOLOR=/iP' local r_font_color = '/font color=[\\"\']?\\#FFFFFF[\\"\']?/iP' reconf['R_WHITE_ON_WHITE'] = string.format('(!(%s) & (%s))', r_bgcolor, r_font_color) reconf['R_FLASH_REDIR_IMGSHACK'] = '/^(?:http:\\/\\/)?img\\d{1,5}\\.imageshack\\.us\\/\\S+\\.swf/U' -- Different text parts rspamd_config.R_PARTS_DIFFER = function(task) local distance = task:get_mempool():get_variable('parts_distance', 'int') if distance then local nd = tonumber(distance) if nd < 50 then local score = 1 - util.tanh(nd / 100.0) task:insert_result('R_PARTS_DIFFER', score, tostring(nd) .. '%') end end return false end -- Date issues rspamd_config.MISSING_DATE = function(task) if rspamd_config:get_api_version() >= 5 then if not task:get_header_raw('Date') then return true end end return false end rspamd_config.DATE_IN_FUTURE = function(task) if rspamd_config:get_api_version() >= 5 then local dm = task:get_date{format = 'message'} local dt = task:get_date{format = 'connect'} -- An 2 hour if dm > 0 and dm - dt > 7200 then return true end end return false end rspamd_config.DATE_IN_PAST = function(task) if rspamd_config:get_api_version() >= 5 then local dm = task:get_date{format = 'message', gmt = true} local dt = task:get_date{format = 'connect', gmt = true} -- A day if dm > 0 and dt - dm > 86400 then return true end end return false end rspamd_config.R_SUSPICIOUS_URL = { callback = function(task) local urls = task:get_urls() if urls then for i,u in ipairs(urls) do if u:is_obscured() then return true end end end return false end, score = 6.0, group = 'url', one_shot = true, description = 'Obfusicated or suspicious URL has been found in a message' } rspamd_config.SUBJ_ALL_CAPS = { callback = function(task) local sbj = task:get_header('Subject') if sbj then local stripped_subject = subject_re:search(sbj, false, true) if stripped_subject and stripped_subject[1] and stripped_subject[1][2] then sbj = stripped_subject[1][2] end if util.is_uppercase(sbj) then return true end end return false end, score = 3.0, group = 'headers', description = 'All capital letters in subject' } rspamd_config.BROKEN_HEADERS = { callback = function(task) if task:has_flag('broken_headers') then return true end return false end, score = 1.0, group = 'headers', description = 'Headers structure is likely broken' } rspamd_config.HEADER_RCONFIRM_MISMATCH = { callback = function (task) local header_from = task:get_from('mime')[1] local cread = task:get_header('X-Confirm-Reading-To') local header_cread = nil if cread then local headers_cread = util.parse_mail_address(cread) if headers_cread then header_cread = headers_cread[1] end end if header_from and header_cread then if not string.find(header_from['addr'], header_cread['addr']) then return true end end return false end, score = 2.0, group = 'headers', description = 'Read confirmation address is different to from address' } rspamd_config.HEADER_FORGED_MDN = { callback = function (task) local mdn = task:get_header('Disposition-Notification-To') local header_rp = task:get_from('smtp')[1] -- Parse mail addr local header_mdn = nil if mdn then local headers_mdn = util.parse_mail_address(mdn) if headers_mdn then header_mdn = headers_mdn[1] end end if header_mdn and not header_rp then return true end if header_rp and not header_mdn then return false end if header_mdn['addr'] ~= header_rp['addr'] then return true end return false end, score = 2.0, group = 'headers', description = 'Read confirmation address is different to return path' } local headers_unique = { 'Content-Type', 'Content-Transfer-Encoding', 'Date', 'Message-ID' } rspamd_config.MULTIPLE_UNIQUE_HEADERS = { callback = function (task) local res = 0 local res_tbl = {} for i,hdr in ipairs(headers_unique) do local h = task:get_header_full(hdr) if h and #h > 1 then res = res + 1 table.insert(res_tbl, hdr) end end if res > 0 then return true,res,table.concat(res_tbl, ',') end return false end, score = 5.0, group = 'headers', description = 'Repeated unique headers' }
--[[ Copyright (c) 2011-2015, Vsevolod Stakhov <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ]]-- -- This is main lua config file for rspamd local util = require "rspamd_util" local rspamd_regexp = require "rspamd_regexp" local rspamd_logger = require "rspamd_logger" local reconf = config['regexp'] -- Uncategorized rules local subject_re = rspamd_regexp.create('/^(?:(?:Re|Fwd|Fw|Aw|Antwort|Sv):\\s*)+(.+)$/i') -- Local rules local r_bgcolor = '/BGCOLOR=/iP' local r_font_color = '/font color=[\\"\']?\\#FFFFFF[\\"\']?/iP' reconf['R_WHITE_ON_WHITE'] = string.format('(!(%s) & (%s))', r_bgcolor, r_font_color) reconf['R_FLASH_REDIR_IMGSHACK'] = '/^(?:http:\\/\\/)?img\\d{1,5}\\.imageshack\\.us\\/\\S+\\.swf/U' -- Different text parts rspamd_config.R_PARTS_DIFFER = function(task) local distance = task:get_mempool():get_variable('parts_distance', 'int') if distance then local nd = tonumber(distance) if nd < 50 then local score = 1 - util.tanh(nd / 100.0) task:insert_result('R_PARTS_DIFFER', score, tostring(nd) .. '%') end end return false end -- Date issues rspamd_config.MISSING_DATE = function(task) if rspamd_config:get_api_version() >= 5 then if not task:get_header_raw('Date') then return true end end return false end rspamd_config.DATE_IN_FUTURE = function(task) if rspamd_config:get_api_version() >= 5 then local dm = task:get_date{format = 'message'} local dt = task:get_date{format = 'connect'} -- An 2 hour if dm > 0 and dm - dt > 7200 then return true end end return false end rspamd_config.DATE_IN_PAST = function(task) if rspamd_config:get_api_version() >= 5 then local dm = task:get_date{format = 'message', gmt = true} local dt = task:get_date{format = 'connect', gmt = true} -- A day if dm > 0 and dt - dm > 86400 then return true end end return false end rspamd_config.R_SUSPICIOUS_URL = { callback = function(task) local urls = task:get_urls() if urls then for i,u in ipairs(urls) do if u:is_obscured() then return true end end end return false end, score = 6.0, group = 'url', one_shot = true, description = 'Obfusicated or suspicious URL has been found in a message' } rspamd_config.SUBJ_ALL_CAPS = { callback = function(task) local sbj = task:get_header('Subject') if sbj then local stripped_subject = subject_re:search(sbj, false, true) if stripped_subject and stripped_subject[1] and stripped_subject[1][2] then sbj = stripped_subject[1][2] end if util.is_uppercase(sbj) then return true end end return false end, score = 3.0, group = 'headers', description = 'All capital letters in subject' } rspamd_config.BROKEN_HEADERS = { callback = function(task) if task:has_flag('broken_headers') then return true end return false end, score = 1.0, group = 'headers', description = 'Headers structure is likely broken' } rspamd_config.HEADER_RCONFIRM_MISMATCH = { callback = function (task) local header_from = nil local cread = task:get_header('X-Confirm-Reading-To') if task:has_from('mime') then header_from = task:get_from('mime')[1] end local header_cread = nil if cread then local headers_cread = util.parse_mail_address(cread) if headers_cread then header_cread = headers_cread[1] end end if header_from and header_cread then if not string.find(header_from['addr'], header_cread['addr']) then return true end end return false end, score = 2.0, group = 'headers', description = 'Read confirmation address is different to from address' } rspamd_config.HEADER_FORGED_MDN = { callback = function (task) local mdn = task:get_header('Disposition-Notification-To') local header_rp = nil if task:has_from('smtp') then header_rp = task:get_from('smtp')[1] end -- Parse mail addr local header_mdn = nil if mdn then local headers_mdn = util.parse_mail_address(mdn) if headers_mdn then header_mdn = headers_mdn[1] end end if header_mdn and not header_rp then return true end if header_rp and not header_mdn then return false end if header_mdn['addr'] ~= header_rp['addr'] then return true end return false end, score = 2.0, group = 'headers', description = 'Read confirmation address is different to return path' } local headers_unique = { 'Content-Type', 'Content-Transfer-Encoding', 'Date', 'Message-ID' } rspamd_config.MULTIPLE_UNIQUE_HEADERS = { callback = function (task) local res = 0 local res_tbl = {} for i,hdr in ipairs(headers_unique) do local h = task:get_header_full(hdr) if h and #h > 1 then res = res + 1 table.insert(res_tbl, hdr) end end if res > 0 then return true,res,table.concat(res_tbl, ',') end return false end, score = 5.0, group = 'headers', description = 'Repeated unique headers' }
Fix rules to avoid nil indexing
Fix rules to avoid nil indexing
Lua
apache-2.0
andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd
fcfea044f3b34b5923822a6456986c281bd8f4f7
src/logger.lua
src/logger.lua
local logging = require("logging") local tg_logger = logging.new( function(self, level, msg) bot.sendMessage(config.monitor, ("*[%s]*\n```\n%s\n```"):format(level, msg), "Markdown") return true end ) tg_logger:setLevel(logging.WARN) local logger = logging.new( function(self, level, msg) print(("%s | %-7s | %s"):format( os.date("%Y-%m-%d %H:%M:%S", os.time() + 8 * 3600), level, msg:gsub("%s+", " ") )) tg_logger:log(level, msg) return true end ) logger:setLevel(logging.DEBUG) return logger
local logging = require("logging") local tg_logger = logging.new( function(self, level, msg) if type(bot) == "table" then bot.sendMessage(config.monitor, ("*[%s]*\n```\n%s\n```"):format(level, msg), "Markdown") end return true end ) tg_logger:setLevel(logging.WARN) local logger = logging.new( function(self, level, msg) print(("%s | %-7s | %s"):format( os.date("%Y-%m-%d %H:%M:%S", os.time() + 8 * 3600), level, msg:gsub("%s+", " ") )) tg_logger:log(level, msg) return true end ) logger:setLevel(logging.DEBUG) return logger
fix(logger): indexed nil value
fix(logger): indexed nil value
Lua
apache-2.0
SJoshua/Project-Small-R
ab47240cba9736c8afcfc84cb48cc0cd54abcdde
love2d/pawn.lua
love2d/pawn.lua
require('math') local SPRITE_SIZE = 64 --this assumes rectangular sprites local EPSILON = 0.001 function love.game.newPawn(id, world) local o = {} o.world = world o.zoom = 1 o.x = 2 o.y = 3 o.maxSpeed = 2 o.velX = 0 o.velY = 0 o.name = id o.water = 100 o.temperature = 33 o.temperatureDelta = 1 o.image = love.graphics.newImage("res/gfx/character.png") o.spritesize = 32 o.anim = {0, 0} o.animstates = 2 o.animspeed = 0.1 o.curAnimdt = 0 o.ambientTemperature = 33 o.update = function(dt) if o.temperature <= 22 or o.temperature >= 56 then o.temperatureDelta = - o.temperatureDelta -- simplified temp change end o.temperature = o.temperature + dt * o.temperatureDelta o.water = o.water -0.0005*o.temperature*o.temperature* dt --one per five seconds. TODO: make this dependent on all sorts of other things --update target coordinates --TODO right now these goals are set by mouse clicks --set the velocity according to the goal; just move straight towards it at maximum speed local wantX = o.world.goalX - o.x local wantY = o.world.goalY - o.y local dirX, dirY = love.game.normalize(wantX, wantY) o.velX = dirX * o.maxSpeed o.velY = dirY * o.maxSpeed if (math.abs(o.velX) < EPSILON)then o.velX = 0 end if (math.abs(o.velY) < EPSILON)then o.velY = 0 end -- update position and possibly speed local tmpX= o.x + o.velX* dt local tmpY= o.y + o.velY* dt if tmpY <= 1 or tmpY >= o.world.map.height then o.velY = -o.velY elseif tmpX <= 1 or tmpX >= o.world.map.width then o.velX = -o.velX end o.x = tmpX o.y = tmpY --determine animation frame o.curAnimdt = o.curAnimdt + dt if o.curAnimdt > o.animspeed then o.anim[1] = (o.anim[1] + 1) % o.animstates o.curAnimdt = o.curAnimdt - o.animspeed end --determine facing if math.abs(o.velX) > math.abs(o.velY) then if o.velX < EPSILON then -- left o.anim[2] = 3 elseif o.velX > EPSILON then --right o.anim[2] = 2 end else if o.velY < EPSILON then -- up o.anim[2] = 1 elseif o.velY > EPSILON then --down o.anim[2] = 0 end end end o.draw = function(x, y) love.graphics.setColor(255,255,255) local quad = love.graphics.newQuad(o.anim[1] * o.spritesize, o.anim[2] * o.spritesize, o.spritesize, o.spritesize, o.image:getWidth(), o.image:getHeight()) love.graphics.draw( o.image, quad, (o.x * SPRITE_SIZE + x) * o.zoom, (o.y * SPRITE_SIZE + y) * o.zoom, 0, 2 * o.zoom, 2 * o.zoom) --show the target of this pawn --TODO: only show when this pawn is selected / being followed love.graphics.setColor(255,255,0) love.graphics.rectangle("line", (o.world.goalX*SPRITE_SIZE+x)*o.zoom,(o.world.goalY*SPRITE_SIZE+y)*o.zoom, SPRITE_SIZE*o.zoom,SPRITE_SIZE*o.zoom) end o.setZoom = function(zoom) o.zoom = zoom end return o end
require('math') local SPRITE_SIZE = 64 --this assumes rectangular sprites local EPSILON = 0.001 function love.game.newPawn(id, world) local o = {} o.world = world o.zoom = 1 o.x = 2 o.y = 3 o.maxSpeed = 2 o.velX = 0 o.velY = 0 o.name = id o.water = 100 o.temperature = 33 o.temperatureDelta = 1 o.image = love.graphics.newImage("res/gfx/character.png") o.spritesize = 32 o.anim = {0, 0} o.animstates = 2 o.animspeed = 0.1 o.curAnimdt = 0 o.ambientTemperature = 33 o.update = function(dt) if o.temperature <= 22 or o.temperature >= 56 then o.temperatureDelta = - o.temperatureDelta -- simplified temp change end o.temperature = o.temperature + dt * o.temperatureDelta o.water = o.water -0.0005*o.temperature*o.temperature* dt --one per five seconds. TODO: make this dependent on all sorts of other things --update target coordinates --TODO right now these goals are set by mouse clicks --set the velocity according to the goal; just move straight towards it at maximum speed local wantX = o.world.goalX - o.x local wantY = o.world.goalY - o.y local dirX, dirY = love.game.normalize(wantX, wantY) o.velX = dirX * o.maxSpeed o.velY = dirY * o.maxSpeed if (math.abs(wantX) < EPSILON)then o.velX = 0 o.x = math.floor(o.x+0.5) end if (math.abs(wantY) <EPSILON)then o.velY = 0 o.y = math.floor(o.y+0.5) end -- update position and possibly speed local tmpX= o.x + o.velX* dt local tmpY= o.y + o.velY* dt if tmpY <= 1 or tmpY >= o.world.map.height then o.velY = -o.velY elseif tmpX <= 1 or tmpX >= o.world.map.width then o.velX = -o.velX end o.x = tmpX o.y = tmpY --determine animation frame o.curAnimdt = o.curAnimdt + dt if o.curAnimdt > o.animspeed then o.anim[1] = (o.anim[1] + 1) % o.animstates o.curAnimdt = o.curAnimdt - o.animspeed end --determine facing if math.abs(o.velX) > math.abs(o.velY) then if o.velX < EPSILON then -- left o.anim[2] = 3 elseif o.velX > EPSILON then --right o.anim[2] = 2 end else if o.velY < EPSILON then -- up o.anim[2] = 1 elseif o.velY > EPSILON then --down o.anim[2] = 0 end end end o.draw = function(x, y) love.graphics.setColor(255,255,255) local quad = love.graphics.newQuad(o.anim[1] * o.spritesize, o.anim[2] * o.spritesize, o.spritesize, o.spritesize, o.image:getWidth(), o.image:getHeight()) love.graphics.draw( o.image, quad, (o.x * SPRITE_SIZE + x) * o.zoom, (o.y * SPRITE_SIZE + y) * o.zoom, 0, 2 * o.zoom, 2 * o.zoom) --show the target of this pawn --TODO: only show when this pawn is selected / being followed love.graphics.setColor(255,255,0) love.graphics.rectangle("line", (o.world.goalX*SPRITE_SIZE+x)*o.zoom,(o.world.goalY*SPRITE_SIZE+y)*o.zoom, SPRITE_SIZE*o.zoom,SPRITE_SIZE*o.zoom) end o.setZoom = function(zoom) o.zoom = zoom end return o end
actually fix the dancing
actually fix the dancing
Lua
mit
nczempin/lizard-journey
fda9970002658def48c6398e7b0fbeff79a2e6f3
lib/switchboard_modules/lua_script_debugger/premade_scripts/7_log_voltage_to_file.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/7_log_voltage_to_file.lua
print("Log voltage to file. Voltage measured on AIN1. Store value every 1 second for 10 seconds") --Requires SD Card installed inside the T7 or T7-Pro. --Requires FW 1.0150 or newer. On older firmware the file must exist already on the SD card --Older firmware uses "assert" command: file=assert(io.open(Filename, "w")) --timestamp (real-time-clock) available on T7-Pro only local hardware = MB.R(60010, 1) local passed = 1 if(bit.band(hardware, 8) ~= 8) then print("uSD card not detected") passed = 0 end if(bit.band(hardware, 4) ~= 4) then print("RTC module not detected") passed = 0 end if(passed == 0) then print("This Lua script requires an RTC module and a microSD card, but one or both are not detected. These features are only preinstalled on the T7-Pro. Script Stopping") MB.W(6000, 1, 0)--stop script end local mbRead=MB.R --local functions for faster processing local mbReadArray=MB.RA local Filename = "/log1.csv" local voltage = 0 local count = 0 local delimiter = "," local dateStr = "" local voltageStr = "" local table = {} table[1] = 0 --year table[2] = 0 --month table[3] = 0 --day table[4] = 0 --hour table[5] = 0 --minute table[6] = 0 --second local file = io.open(Filename, "w") --create and open file for write access -- Make sure that the file was opened properly. if file then print("Opened File on uSD Card") else -- If the file was not opened properly we probably have a bad SD card. print("!! Failed to open file on uSD Card !!") end MB.W(48005, 0, 1) --ensure analog is on LJ.IntervalConfig(0, 1000) --set interval to 1000 for 1000ms local checkInterval=LJ.CheckInterval while true do if checkInterval(0) then --interval completed voltage = mbRead(2, 3) --voltage on AIN1, address is 2, type is 3 table, error = mbReadArray(61510, 0, 6) --Read the RTC timestamp, -Pro only print("AIN1: ", voltage, "V") dateStr = string.format("%04d/%02d/%02d %02d:%02d.%02d", table[1], table[2], table[3], table[4], table[5], table[6]) voltageStr = string.format("%.6f", voltage) print(dateStr, "\n") file:write(dateStr, delimiter, voltageStr, "\n") count = count + 1 end if count >= 10 then break end end file:close() print("Done acquiring data. Now read and display file contents. \n") file = io.open(Filename, "r") local line = file:read("*all") file:close() print(line) print("Finished Script") MB.W(6000, 1, 0);
--[[ Name: 7_log_voltage_to_file.lua Desc: This example shows how to log voltage measurements to file Note: Requires an SD Card installed inside the T7 or T7-Pro This example requires firmware 1.0282 (T7) Timestamp (real-time-clock) available on T7-Pro only --]] print("Log voltage to file. Voltage measured on AIN1. Store value every 1 second for 10 seconds") -- Read information about the hardware installed local hardware = MB.readName("HARDWARE_INSTALLED") local passed = 1 -- If the seventh bit is not a 1 then an SD card is not installed if(bit.band(hardware, 8) ~= 8) then print("uSD card not detected") passed = 0 end -- If the fourth bit is not a 1 then there is no RTC installed if(bit.band(hardware, 4) ~= 4) then print("RTC module not detected") passed = 0 end if(passed == 0) then print("This Lua script requires an RTC module and a microSD card, but one or both are not detected. These features are only preinstalled on the T7-Pro. Script Stopping") -- Writing a 0 to LUA_RUN stops the script MB.W("LUA_RUN", 0) end local filename = "/log1.csv" local voltage = 0 local count = 0 local delimiter = "," local strdate = "" local strvoltage = "" local table = {} table[1] = 0 --year table[2] = 0 --month table[3] = 0 --day table[4] = 0 --hour table[5] = 0 --minute table[6] = 0 --second -- Create and open a file for write access local file = io.open(filename, "w") -- Make sure that the file was opened properly. if file then print("Opened File on uSD Card") else -- If the file was not opened properly we probably have a bad SD card. print("!! Failed to open file on uSD Card !!") end -- Make sure analog is on MB.writeName("POWER_AIN", 1) -- Configure an interval of 1000ms LJ.IntervalConfig(0, 1000) while true do -- If an interval is done if LJ.CheckInterval(0) then voltage = MB.readName("AIN1") -- Read the RTC timestamp (T7-Pro only) table, error = MB.RA(61510, 0, 6) print("AIN1:", voltage, "V") strdate = string.format( "%04d/%02d/%02d %02d:%02d.%02d", table[1], table[2], table[3], table[4], table[5], table[6] ) strvoltage = string.format("%.6f", voltage) print(strdate, "\n") file:write(strdate, delimiter, strvoltage, "\n") count = count + 1 end if count >= 10 then break end end file:close() print("Done acquiring data. Now read and display file contents. \n") file = io.open(filename, "r") local line = file:read("*all") file:close() print(line) print("Finished Script") MB.W(6000, 1, 0);
Fixed up the formatting of the voltage logging example
Fixed up the formatting of the voltage logging example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
a8d11cf93a092f861de3d89eb7969531acbc0708
modules/title.lua
modules/title.lua
local iconv = require"iconv" local parse = require"socket.url".parse local patterns = { -- X://Y url "^(%a[%w%.+-]+://%S+)", "%f[%S](%a[%w%.+-]+://%S+)", -- www.X.Y url "^(www%.[%w_-%%]+%.%S+)", "%f[%S](www%.[%w_-%%]+%.%S+)", -- XXX.YYY.ZZZ.WWW:VVVV/UUUUU IPv4 address with port and path "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d:[0-6]?%d?%d?%d?%d/%S+)", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d:[0-6]?%d?%d?%d?%d/%S+)", -- XXX.YYY.ZZZ.WWW/VVVVV IPv4 address with path "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%/%S+)", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%/%S+)", -- XXX.YYY.ZZZ.WWW IPv4 address "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%)%f[%D]", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%)%f[%D]", -- X.Y.Z:WWWW/VVVVV url with port and path "^([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d/%S+)", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d/%S+)", -- X.Y.Z:WWWW url with port (ts server for example) "^([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d)%f[%D]", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d)%f[%D]", -- X.Y.Z/WWWWW url with path -- "^([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", -- X.Y.Z url -- "^([%w_-%%%.]+[%w_-%%]%.(%a%a+))", -- "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+))", } local danbooru = function(path) local path = path['path'] if(path and path:match'/data/([^%.]+)') then local md5 = path:match'/data/([^%.]+)' local xml, s = utils.http('http://danbooru.donmai.us/post/index.xml?tags=md5:'..md5) if(s == 200) then local id = xml:match' id="(%d+)"' local tags = xml:match'tags="([^"]+)' return string.format('http://danbooru.donmai.us/post/show/%s/ - %s', id, tags) end end end local iiHost = { -- do nothing ['eu.wowarmory.com'] = function() end, ['danbooru.donmai.us'] = danbooru, ['miezaru.donmai.us'] = danbooru, ['open.spotify.com'] = function(path) local path = path['path'] if(path and path:match'/(%w+)/(.+)') then local type, id = path:match'/(%w+)/(.+)' return string.format('spotify:%s:%s', type, id) end end, ['s3.amazonaws.com'] = function(path) local path = path['path'] if(path and path:match'/danbooru/([^%.]+)') then local md5 = path:match'/danbooru/([^%.]+)' local xml, s = utils.http('http://danbooru.donmai.us/post/index.xml?tags=md5:'..md5) if(s == 200) then local id = xml:match' id="(%d+)"' local tags = xml:match'tags="([^"]+)' return string.format('http://danbooru.donmai.us/post/show/%s/ - %s', id, tags) end end end, } local kiraiTitle = { ['sexy%-lena%.com'] = true, -- fap fap fap fap ['unsere%-nackte%-pyjamaparty%.net'] = true, ['johnsrevenge%.com'] = true, ['tapuz%.me2you%.co%.il'] = true, ['.-%mybrute.com'] = true, } local renameCharset = { ['x-sjis'] = 'sjis', } local validProtocols = { ['http'] = true, ['https'] = true, } local getTitle = function(url, offset) local path = parse(url) local host = path['host']:gsub('^www%.', '') for k, v in next, kiraiTitle do if(host:match(k)) then return 'Blacklisted domain.' end end if(iiHost[host]) then return iiHost[host](path) end local body, status, headers = utils.http(url) if(body) then local charset = body:lower():match'<meta.-content=["\'].-(charset=.-)["\'].->' if(charset) then charset = charset:match"charset=(.+)$?;?" end if(not charset) then charset = body:match'<%?xml.-encoding=[\'"](.-)[\'"].-%?>' end if(not charset) then local tmp = utils.split(headers['content-type'], ' ') for _, v in pairs(tmp) do if(v:lower():match"charset") then charset = v:lower():match"charset=(.+)$?;?" break end end end local title = body:match"<[tT][iI][tT][lL][eE]>(.-)</[tT][iI][tT][lL][eE]>" if(title) then for _, pattern in ipairs(patterns) do title = title:gsub(pattern, '<snip />') end end if(charset and title and charset:lower() ~= "utf-8") then charset = charset:gsub("\n", ""):gsub("\r", "") charset = renameCharset[charset] or charset local cd, err = iconv.new("utf-8", charset) if(cd) then title = cd:iconv(title) end end if(title and title ~= "" and title ~= '<snip />') then title = utils.decodeHTML(title) title = title:gsub("[%s%s]+", " ") if(#url > 75) then local short = utils.x0(url) if(short ~= url) then title = "Downgraded URL: " ..short.." - "..title end end return title end end end local found = 0 local urls local gsubit = function(url) found = found + 1 local total = 1 for k in pairs(urls) do total = total + 1 end if(not url:match"://") then url = "http://"..url elseif(not validProtocols[url:match'^[^:]+']) then return end if(not urls[url]) then urls[url] = { n = found, m = total, title = getTitle(url), } else urls[url].n = string.format("%s+%d", urls[url].n, found) end end return { ["^:(%S+) PRIVMSG (%S+) :(.+)$"] = function(self, src, dest, msg) if(self:srctonick(src) == self.config.nick or msg:sub(1,1) == '!') then return end urls, found = {}, 0 for key, msg in pairs(utils.split(msg, " ")) do for _, pattern in ipairs(patterns) do msg:gsub(pattern, gsubit) end end if(next(urls)) then local out = {} for url, data in pairs(urls) do if(data.title) then table.insert(out, data.m, string.format("\002[%s]\002 %s", data.n, data.title)) end end if(#out > 0) then self:msg(dest, src, table.concat(out, " ")) end end end, }
local iconv = require"iconv" local parse = require"socket.url".parse local patterns = { -- X://Y url "^(%a[%w%.+-]+://%S+)", "%f[%S](%a[%w%.+-]+://%S+)", -- www.X.Y url "^(www%.[%w_-%%]+%.%S+)", "%f[%S](www%.[%w_-%%]+%.%S+)", -- XXX.YYY.ZZZ.WWW:VVVV/UUUUU IPv4 address with port and path "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d:[0-6]?%d?%d?%d?%d/%S+)", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d:[0-6]?%d?%d?%d?%d/%S+)", -- XXX.YYY.ZZZ.WWW/VVVVV IPv4 address with path "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%/%S+)", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%/%S+)", -- XXX.YYY.ZZZ.WWW IPv4 address "^([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%)%f[%D]", "%f[%S]([0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%.[0-2]?%d?%d%)%f[%D]", -- X.Y.Z:WWWW/VVVVV url with port and path "^([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d/%S+)", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d/%S+)", -- X.Y.Z:WWWW url with port (ts server for example) "^([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d)%f[%D]", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+):[0-6]?%d?%d?%d?%d)%f[%D]", -- X.Y.Z/WWWWW url with path -- "^([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", -- X.Y.Z url -- "^([%w_-%%%.]+[%w_-%%]%.(%a%a+))", -- "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+))", } local danbooru = function(path) local path = path['path'] if(path and path:match'/data/([^%.]+)') then local md5 = path:match'/data/([^%.]+)' local xml, s = utils.http('http://danbooru.donmai.us/post/index.xml?tags=md5:'..md5) if(s == 200) then local id = xml:match' id="(%d+)"' local tags = xml:match'tags="([^"]+)' return string.format('http://danbooru.donmai.us/post/show/%s/ - %s', id, tags) end end end local iiHost = { -- do nothing ['eu.wowarmory.com'] = function() end, ['danbooru.donmai.us'] = danbooru, ['miezaru.donmai.us'] = danbooru, ['open.spotify.com'] = function(path) local path = path['path'] if(path and path:match'/(%w+)/(.+)') then local type, id = path:match'/(%w+)/(.+)' return string.format('spotify:%s:%s', type, id) end end, ['s3.amazonaws.com'] = function(path) local path = path['path'] if(path and path:match'/danbooru/([^%.]+)') then local md5 = path:match'/danbooru/([^%.]+)' local xml, s = utils.http('http://danbooru.donmai.us/post/index.xml?tags=md5:'..md5) if(s == 200) then local id = xml:match' id="(%d+)"' local tags = xml:match'tags="([^"]+)' return string.format('http://danbooru.donmai.us/post/show/%s/ - %s', id, tags) end end end, } local kiraiTitle = { ['sexy%-lena%.com'] = true, -- fap fap fap fap ['unsere%-nackte%-pyjamaparty%.net'] = true, ['johnsrevenge%.com'] = true, ['tapuz%.me2you%.co%.il'] = true, ['.-%mybrute.com'] = true, ['marie%-gets%-deflowered.com'] = true, ['whycindywhy%.com'] = true, } local renameCharset = { ['x-sjis'] = 'sjis', } local validProtocols = { ['http'] = true, ['https'] = true, } local getTitle = function(url, offset) local path = parse(url) local host = path['host']:gsub('^www%.', '') for k, v in next, kiraiTitle do if(host:lower():match(k)) then return 'Blacklisted domain.' end end if(iiHost[host]) then return iiHost[host](path) end local body, status, headers = utils.http(url) if(body) then local charset = body:lower():match'<meta.-content=["\'].-(charset=.-)["\'].->' if(charset) then charset = charset:match"charset=(.+)$?;?" end if(not charset) then charset = body:match'<%?xml.-encoding=[\'"](.-)[\'"].-%?>' end if(not charset) then local tmp = utils.split(headers['content-type'], ' ') for _, v in pairs(tmp) do if(v:lower():match"charset") then charset = v:lower():match"charset=(.+)$?;?" break end end end local title = body:match"<[tT][iI][tT][lL][eE]>(.-)</[tT][iI][tT][lL][eE]>" if(title) then for _, pattern in ipairs(patterns) do title = title:gsub(pattern, '<snip />') end end if(charset and title and charset:lower() ~= "utf-8") then charset = charset:gsub("\n", ""):gsub("\r", "") charset = renameCharset[charset] or charset local cd, err = iconv.new("utf-8", charset) if(cd) then title = cd:iconv(title) end end if(title and title ~= "" and title ~= '<snip />') then title = utils.decodeHTML(title) title = title:gsub("[%s%s]+", " ") if(#url > 75) then local short = utils.x0(url) if(short ~= url) then title = "Downgraded URL: " ..short.." - "..title end end return title end end end local found = 0 local urls local gsubit = function(url) found = found + 1 local total = 1 for k in pairs(urls) do total = total + 1 end if(not url:match"://") then url = "http://"..url elseif(not validProtocols[url:match'^[^:]+']) then return end if(not urls[url]) then urls[url] = { n = found, m = total, title = getTitle(url), } else urls[url].n = string.format("%s+%d", urls[url].n, found) end end return { ["^:(%S+) PRIVMSG (%S+) :(.+)$"] = function(self, src, dest, msg) if(self:srctonick(src) == self.config.nick or msg:sub(1,1) == '!') then return end urls, found = {}, 0 for key, msg in pairs(utils.split(msg, " ")) do for _, pattern in ipairs(patterns) do msg:gsub(pattern, gsubit) end end if(next(urls)) then local out = {} for url, data in pairs(urls) do if(data.title) then table.insert(out, data.m, string.format("\002[%s]\002 %s", data.n, data.title)) end end if(#out > 0) then self:msg(dest, src, table.concat(out, " ")) end end end, }
Minor fixes to title.
Minor fixes to title.
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
9ceee593d9c676aa93a3c206d547ddf5f11f28e5
busted/outputHandlers/TAP.lua
busted/outputHandlers/TAP.lua
local pretty = require 'pl.pretty' local tablex = require 'pl.tablex' return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) local getFullName = function(context) local parent = context.parent local names = { (context.name or context.descriptor) } while parent and (parent.name or parent.descriptor) and parent.descriptor ~= 'file' do table.insert(names, 1, parent.name or parent.descriptor) parent = busted.context.parent(parent) end return table.concat(names, ' ') end handler.suiteEnd = function(name, parent) local total = handler.successesCount + handler.errorsCount + handler.failuresCount print('1..' .. total) local success = 'ok %u - %s' local failure = 'not ' .. success local counter = 0 for i,t in pairs(handler.successes) do counter = counter + 1 print(counter .. ' ' .. handler.format(t).name) end for i,t in pairs(handler.failures) do counter = counter + 1 local message = t.message if message == nil then message = 'Nil error' elseif type(message) ~= 'string' then message = pretty.write(message) end print(counter .. ' ' .. handler.format(t).name) print('# ' .. t.trace.short_src .. ' @ ' .. t.trace.currentline) print('# Failure message: ' .. message:gsub('\n', '\n# ' )) end return nil, true end busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) return handler end
local pretty = require 'pl.pretty' local tablex = require 'pl.tablex' return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) local getFullName = function(context) local parent = context.parent local names = { (context.name or context.descriptor) } while parent and (parent.name or parent.descriptor) and parent.descriptor ~= 'file' do table.insert(names, 1, parent.name or parent.descriptor) parent = busted.context.parent(parent) end return table.concat(names, ' ') end handler.suiteEnd = function(name, parent) local total = handler.successesCount + handler.errorsCount + handler.failuresCount print('1..' .. total) local success = 'ok %u - %s' local failure = 'not ' .. success local counter = 0 for i,t in pairs(handler.successes) do counter = counter + 1 print( success:format( counter, handler.format(t).name )) end for i,t in pairs(handler.failures) do counter = counter + 1 local message = t.message if message == nil then message = 'Nil error' elseif type(message) ~= 'string' then message = pretty.write(message) end print( failure:format( counter, handler.format(t).name )) print('# ' .. t.trace.short_src .. ' @ ' .. t.trace.currentline) print('# Failure message: ' .. message:gsub('\n', '\n# ' )) end return nil, true end busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) return handler end
Fix issue #291 TAP output type is broken in 2.0rc3
Fix issue #291 TAP output type is broken in 2.0rc3 The success and failure format strings were bypassed in commit 88f7850. Now, if the following two tests are run with TAP output, we will get the expected ok/not ok formats. $ bin/busted -o TAP spec/cl_spec.lua 1..1 ok 1 - Tests the busted command-line options $ bin/busted -o TAP spec/cl_two_failures.lua 1..2 not ok 1 - Runs 2 failing tests is failing test 2 (details omitted) not ok 2 - Runs 2 failing tests is failing test 1 (details omitted)
Lua
mit
ryanplusplus/busted,nehz/busted,mpeterv/busted,leafo/busted,xyliuke/busted,istr/busted,o-lim/busted,sobrinho/busted,DorianGray/busted,Olivine-Labs/busted
737e96fb6439c8a6c6b283f081638b09071153f5
defaut/Pretre.lua
defaut/Pretre.lua
Ovale.defaut["PRIEST"] = [[Define(berserking 26297) SpellInfo(berserking duration=10 cd=180 ) SpellAddBuff(berserking berserking=1) Define(devouring_plague 2944) SpellInfo(devouring_plague duration=6 shadoworbs=1 ) SpellAddTargetDebuff(devouring_plague devouring_plague=1) Define(dispersion 47585) SpellInfo(dispersion duration=6 cd=120 ) SpellAddBuff(dispersion dispersion=1) Define(divine_insight_shadow 124430) SpellInfo(divine_insight_shadow duration=12 ) SpellAddBuff(divine_insight_shadow divine_insight_shadow=1) Define(halo_damage 120517) SpellInfo(halo_damage cd=40 ) Define(inner_fire 588) SpellAddBuff(inner_fire inner_fire=1) Define(inner_will 73413) SpellAddBuff(inner_will inner_will=1) Define(mind_blast 8092) SpellInfo(mind_blast shadoworbs=-1 cd=8 test) Define(mind_flay 15407) SpellInfo(mind_flay duration=3 canStopChannelling=1 ) SpellAddTargetDebuff(mind_flay mind_flay=1) Define(mind_sear 48045) SpellInfo(mind_sear duration=5 canStopChannelling=1 ) SpellAddBuff(mind_sear mind_sear=1) Define(mind_spike 73510) Define(power_word_fortitude 21562) SpellInfo(power_word_fortitude duration=3600 ) SpellAddBuff(power_word_fortitude power_word_fortitude=1) Define(shadow_word_death 32379) SpellInfo(shadow_word_death cd=8 ) Define(shadow_word_pain 589) SpellInfo(shadow_word_pain duration=18 ) SpellAddTargetDebuff(shadow_word_pain shadow_word_pain=1) Define(shadowfiend 34433) SpellInfo(shadowfiend duration=12 cd=180 ) Define(shadowform 15473) SpellInfo(shadowform cd=1.5 ) SpellAddBuff(shadowform shadowform=1) Define(surge_of_darkness 87160) SpellInfo(surge_of_darkness duration=10 ) SpellAddBuff(surge_of_darkness surge_of_darkness=1) Define(vampiric_touch 34914) SpellInfo(vampiric_touch duration=15 ) SpellAddTargetDebuff(vampiric_touch vampiric_touch=1) AddIcon mastery=3 help=main { if not InCombat() { if not BuffPresent(stamina) Spell(power_word_fortitude) if BuffExpires(inner_fire) and BuffExpires(inner_will) Spell(inner_fire) Spell(shadowform) } Spell(shadowform) if ShadowOrbs() ==3 and {SpellCooldown(mind_blast) <2 or target.HealthPercent() <20 } Spell(devouring_plague) if SpellCooldown(mind_blast) Spell(mind_blast) if {not target.DebuffPresent(shadow_word_pain) or target.DebuffRemains(shadow_word_pain) <TickTime(shadow_word_pain) } Spell(shadow_word_pain) if target.HealthPercent(less 20) Spell(shadow_word_death) if {not target.DebuffPresent(vampiric_touch) or target.DebuffRemains(vampiric_touch) <CastTime(vampiric_touch) +TickTime(vampiric_touch) } Spell(vampiric_touch) if ShadowOrbs() ==3 Spell(devouring_plague) Spell(halo_damage) if BuffPresent(surge_of_darkness) Spell(mind_spike) Spell(mind_flay) } AddIcon mastery=3 help=moving { if target.HealthPercent(less 20) Spell(shadow_word_death) if BuffPresent(divine_insight_shadow) and SpellCooldown(mind_blast) Spell(mind_blast) Spell(shadow_word_pain) } AddIcon mastery=3 help=aoe { Spell(mind_sear) } AddIcon mastery=3 help=cd { { Item(Trinket0Slot usable=1) Item(Trinket1Slot usable=1) } Spell(berserking) if SpellCooldown(shadowfiend) Spell(shadowfiend) Spell(dispersion) } ]]
Ovale.defaut["PRIEST"] = [[Define(berserking 26297) SpellInfo(berserking duration=10 cd=180 ) SpellAddBuff(berserking berserking=1) Define(devouring_plague 2944) SpellInfo(devouring_plague duration=6 shadoworbs=1 ) SpellAddTargetDebuff(devouring_plague devouring_plague=1) Define(dispersion 47585) SpellInfo(dispersion duration=6 cd=120 ) SpellAddBuff(dispersion dispersion=1) Define(divine_insight_shadow 124430) SpellInfo(divine_insight_shadow duration=12 ) SpellAddBuff(divine_insight_shadow divine_insight_shadow=1) Define(halo_damage 120517) SpellInfo(halo_damage cd=40 ) Define(inner_fire 588) SpellAddBuff(inner_fire inner_fire=1) Define(inner_will 73413) SpellAddBuff(inner_will inner_will=1) Define(mind_blast 8092) SpellInfo(mind_blast shadoworbs=-1 cd=8 test) Define(mind_flay 15407) SpellInfo(mind_flay duration=3 canStopChannelling=1 ) SpellAddTargetDebuff(mind_flay mind_flay=1) Define(mind_sear 48045) SpellInfo(mind_sear duration=5 canStopChannelling=1 ) SpellAddBuff(mind_sear mind_sear=1) Define(mind_spike 73510) Define(power_word_fortitude 21562) SpellInfo(power_word_fortitude duration=3600 ) SpellAddBuff(power_word_fortitude power_word_fortitude=1) Define(shadow_word_death 32379) SpellInfo(shadow_word_death cd=8 ) Define(shadow_word_pain 589) SpellInfo(shadow_word_pain duration=18 ) SpellAddTargetDebuff(shadow_word_pain shadow_word_pain=1) Define(shadowfiend 34433) SpellInfo(shadowfiend duration=12 cd=180 ) Define(shadowform 15473) SpellInfo(shadowform cd=1.5 ) SpellAddBuff(shadowform shadowform=1) Define(surge_of_darkness 87160) SpellInfo(surge_of_darkness duration=10 ) SpellAddBuff(surge_of_darkness surge_of_darkness=1) Define(vampiric_touch 34914) SpellInfo(vampiric_touch duration=15 ) SpellAddTargetDebuff(vampiric_touch vampiric_touch=1) AddIcon mastery=3 help=main { if not InCombat() { if not BuffPresent(stamina) Spell(power_word_fortitude) if BuffExpires(inner_fire) and BuffExpires(inner_will) Spell(inner_fire) if BuffExpires(shadowform) Spell(shadowform) } if BuffExpires(shadowform) Spell(shadowform) if ShadowOrbs() ==3 and {SpellCooldown(mind_blast) <2 or target.HealthPercent() <20 } Spell(devouring_plague) if SpellCooldown(mind_blast) Spell(mind_blast) if {not target.DebuffPresent(shadow_word_pain) or target.DebuffRemains(shadow_word_pain) <TickTime(shadow_word_pain) } Spell(shadow_word_pain) if target.HealthPercent(less 20) Spell(shadow_word_death) if {not target.DebuffPresent(vampiric_touch) or target.DebuffRemains(vampiric_touch) <CastTime(vampiric_touch) +TickTime(vampiric_touch) } Spell(vampiric_touch) if ShadowOrbs() ==3 Spell(devouring_plague) Spell(halo_damage) if BuffPresent(surge_of_darkness) Spell(mind_spike) Spell(mind_flay) } AddIcon mastery=3 help=moving { if target.HealthPercent(less 20) Spell(shadow_word_death) if BuffPresent(divine_insight_shadow) and SpellCooldown(mind_blast) Spell(mind_blast) Spell(shadow_word_pain) } AddIcon mastery=3 help=aoe { Spell(mind_sear) } AddIcon mastery=3 help=cd { { Item(Trinket0Slot usable=1) Item(Trinket1Slot usable=1) } Spell(berserking) if SpellCooldown(shadowfiend) Spell(shadowfiend) Spell(dispersion) } ]]
Shadow form fix
Shadow form fix git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@549 d5049fe3-3747-40f7-a4b5-f36d6801af5f
Lua
mit
eXhausted/Ovale,Xeltor/ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale
f9ec3d6a6dc3bb035586b79da49d59dadd2086a5
lua/entities/gmod_wire_expression2/core/timer.lua
lua/entities/gmod_wire_expression2/core/timer.lua
/******************************************************************************\ Timer support \******************************************************************************/ local timerid = 0 local runner local function Execute(self, name) runner = name self.data['timer'].timers[name] = nil if(self.entity and self.entity.Execute) then self.entity:Execute() end if !self.data['timer'].timers[name] then timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name) end runner = nil end local function AddTimer(self, name, delay) if delay < 10 then delay = 10 end if runner == name then timer.Adjust("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 1, function() Execute(self, name) end) timer.Start("e2_" .. self.data['timer'].timerid .. "_" .. name) elseif !self.data['timer'].timers[name] then timer.Create("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 1, function() Execute(self, name) end) end self.data['timer'].timers[name] = true end local function RemoveTimer(self, name) if self.data['timer'].timers[name] then timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name) self.data['timer'].timers[name] = nil end end /******************************************************************************/ registerCallback("construct", function(self) self.data['timer'] = {} self.data['timer'].timerid = timerid self.data['timer'].timers = {} timerid = timerid + 1 end) registerCallback("destruct", function(self) for name,_ in pairs(self.data['timer'].timers) do RemoveTimer(self, name) end end) /******************************************************************************/ __e2setcost(5) -- approximation e2function void interval(rv1) AddTimer(self, "interval", rv1) end e2function void timer(string rv1, rv2) AddTimer(self, rv1, rv2) end e2function void stoptimer(string rv1) RemoveTimer(self, rv1) end e2function number clk() if runner == "interval" then return 1 else return 0 end end e2function number clk(string rv1) if runner == rv1 then return 1 else return 0 end end e2function string clkName() return runner or "" end e2function array getTimers() local ret = {} local i = 0 for name,_ in pairs( self.data.timer.timers ) do i = i + 1 ret[i] = name end self.prf = self.prf + i * 5 return ret end e2function void stopAllTimers() for name,_ in pairs(self.data.timer.timers) do self.prf = self.prf + 5 RemoveTimer(self,name) end end /******************************************************************************/ e2function number curtime() return CurTime() end e2function number realtime() return RealTime() end e2function number systime() return SysTime() end ----------------------------------------------------------------------------------- local function luaDateToE2Table( time ) local ret = {n={},ntypes={},s={},stypes={},size=0} local time = os.date("*t",time) for k,v in pairs( time ) do if k == "isdst" then ret.s.isdst = (v and 1 or 0) ret.stypes.isdst = "n" else ret.s[k] = v ret.stypes[k] = "n" end ret.size = ret.size + 1 end return ret end -- Returns the server's current time formatted neatly in a table e2function table date() return luaDateToE2Table() end -- Returns the specified time formatted neatly in a table e2function table date( time ) return luaDateToE2Table(time) end -- This function has a strange and slightly misleading name, but changing it might break older E2s, so I'm leaving it -- It's essentially the same as the date function above e2function number time(string component) local ostime = os.date("!*t") local ret = ostime[component] return tonumber(ret) or ret and 1 or 0 -- the later parts account for invalid components and isdst end ----------------------------------------------------------------------------------- -- Returns the time in seconds e2function number time() return os.time() end -- Attempts to construct the time from the data in the given table (same as lua's os.time) -- The table structure must be the same as in the above date functions -- If any values are missing or of the wrong type, that value is ignored (it will be nil) local validkeys = {hour = true, min = true, day = true, sec = true, yday = true, wday = true, month = true, year = true, isdst = true} e2function number time(table data) local args = {} for k,v in pairs( data.s ) do if data.stypes[k] ~= "n" or not validkeys[k] then continue end if k == "isdst" then args.isdst = (v == 1) else args[k] = v end end return os.time( args ) end
/******************************************************************************\ Timer support \******************************************************************************/ local timerid = 0 local runner local function Execute(self, name) runner = name self.data['timer'].timers[name] = nil if(self.entity and self.entity.Execute) then self.entity:Execute() end if !self.data['timer'].timers[name] then timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name) end runner = nil end local function AddTimer(self, name, delay) if delay < 10 then delay = 10 end if runner == name then timer.Adjust("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 1, function() Execute(self, name) end) timer.Start("e2_" .. self.data['timer'].timerid .. "_" .. name) elseif !self.data['timer'].timers[name] then timer.Create("e2_" .. self.data['timer'].timerid .. "_" .. name, delay/1000, 1, function() Execute(self, name) end) end self.data['timer'].timers[name] = true end local function RemoveTimer(self, name) if self.data['timer'].timers[name] then timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name) self.data['timer'].timers[name] = nil end end /******************************************************************************/ registerCallback("construct", function(self) self.data['timer'] = {} self.data['timer'].timerid = timerid self.data['timer'].timers = {} timerid = timerid + 1 end) registerCallback("destruct", function(self) for name,_ in pairs(self.data['timer'].timers) do RemoveTimer(self, name) end end) /******************************************************************************/ __e2setcost(5) -- approximation e2function void interval(rv1) AddTimer(self, "interval", rv1) end e2function void timer(string rv1, rv2) AddTimer(self, rv1, rv2) end e2function void stoptimer(string rv1) RemoveTimer(self, rv1) end e2function number clk() if runner == "interval" then return 1 else return 0 end end e2function number clk(string rv1) if runner == rv1 then return 1 else return 0 end end e2function string clkName() return runner or "" end e2function array getTimers() local ret = {} local i = 0 for name,_ in pairs( self.data.timer.timers ) do i = i + 1 ret[i] = name end self.prf = self.prf + i * 5 return ret end e2function void stopAllTimers() for name,_ in pairs(self.data.timer.timers) do self.prf = self.prf + 5 RemoveTimer(self,name) end end /******************************************************************************/ e2function number curtime() return CurTime() end e2function number realtime() return RealTime() end e2function number systime() return SysTime() end ----------------------------------------------------------------------------------- local function luaDateToE2Table( time ) local ret = {n={},ntypes={},s={},stypes={},size=0} local time = os.date("*t",time) if not time then return ret end -- this happens if you give it a negative time for k,v in pairs( time ) do if k == "isdst" then ret.s.isdst = (v and 1 or 0) ret.stypes.isdst = "n" else ret.s[k] = v ret.stypes[k] = "n" end ret.size = ret.size + 1 end return ret end -- Returns the server's current time formatted neatly in a table e2function table date() return luaDateToE2Table() end -- Returns the specified time formatted neatly in a table e2function table date( time ) return luaDateToE2Table(time) end -- This function has a strange and slightly misleading name, but changing it might break older E2s, so I'm leaving it -- It's essentially the same as the date function above e2function number time(string component) local ostime = os.date("!*t") local ret = ostime[component] return tonumber(ret) or ret and 1 or 0 -- the later parts account for invalid components and isdst end ----------------------------------------------------------------------------------- -- Returns the time in seconds e2function number time() return os.time() end -- Attempts to construct the time from the data in the given table (same as lua's os.time) -- The table structure must be the same as in the above date functions -- If any values are missing or of the wrong type, that value is ignored (it will be nil) local validkeys = {hour = true, min = true, day = true, sec = true, yday = true, wday = true, month = true, year = true, isdst = true} e2function number time(table data) local args = {} for k,v in pairs( data.s ) do if data.stypes[k] ~= "n" or not validkeys[k] then continue end if k == "isdst" then args.isdst = (v == 1) else args[k] = v end end return os.time( args ) end
fixed errors if you give the new date functions a negative number
fixed errors if you give the new date functions a negative number
Lua
apache-2.0
mms92/wire,wiremod/wire,immibis/wiremod,Python1320/wire,NezzKryptic/Wire,garrysmodlua/wire,Grocel/wire,sammyt291/wire,notcake/wire,plinkopenguin/wiremod,dvdvideo1234/wire,CaptainPRICE/wire,rafradek/wire,mitterdoo/wire,thegrb93/wire,bigdogmat/wire
4d0c2b549934538e7829419701af4cf06bf74dd7
app/log.lua
app/log.lua
-- Oxypanel Core -- File: app/log.lua -- Desc: logging of all actions for Oxypanel local os = os local database, user = luawa.database, luawa.user local function log() local request = luawa.request local status, err = database:insert( 'log', { 'time', 'object_type', 'object_id', 'user_id', 'action', 'module', 'module_request', 'request' }, {{ os.time(), request.get.type or '', request.get.id or 0, user:checkLogin() and user:getData().id or 0, request.get.action or 'view', request.get.module or '', request.get.module_request or '', request.get.request }}, { delayed = true } ) end return log
-- Oxypanel Core -- File: app/log.lua -- Desc: logging of all actions for Oxypanel local os = os local database, user, request = luawa.database, luawa.user, luawa.request local function log() -- require both id & type for object local id, type = 0, '' if request.get.type and request.get.id then id = request.get.id type = request.get.type end -- insert the log local status, err = database:insert( 'log', { 'time', 'object_type', 'object_id', 'user_id', 'action', 'module', 'module_request', 'request' }, {{ os.time(), type, id, user:checkLogin() and user:getData().id or 0, request.get.action or 'view', request.get.module or '', request.get.module_request or '', request.get.request }}, { delayed = true } ) end return log
Fix for when one of id/type set
Fix for when one of id/type set
Lua
mit
Oxygem/Oxycore,Oxygem/Oxycore,Oxygem/Oxycore
5230125b7f0cf102abf3ba263d00b6a3bd36b5be
bhop/gamemode/init.lua
bhop/gamemode/init.lua
--------------------------- -- Bunny Hop -- -- Created by xAaron113x -- --------------------------- include("shared.lua") include("sv_config.lua") include("sh_levels.lua") include("sh_maps.lua") include("sh_viewoffsets.lua") include("player_class/player_bhop.lua") AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") AddCSLuaFile("cl_difficulty_menu.lua") AddCSLuaFile("sh_levels.lua") AddCSLuaFile("sh_viewoffsets.lua") GM.PSaveData = {} -- Save last known positions and angles for respawn here. /* Setup the bhop spawn and finish */ function GM:AreaSetup() local MapData = SS.MapList[game.GetMap()] if MapData then -- We will assume the rest is valid self.MapSpawn = ents.Create("bhop_area") self.MapSpawn:SetPos(MapData.spawnarea.max-(MapData.spawnarea.max-MapData.spawnarea.min)/2) self.MapSpawn:Setup(MapData.spawnarea.min, MapData.spawnarea.max, true) self.MapSpawn:Spawn() self.MapFinish = ents.Create("bhop_area") self.MapFinish:SetPos(MapData.finisharea.max-(MapData.finisharea.max-MapData.finisharea.min)/2) self.MapFinish:Setup(MapData.finisharea.min, MapData.finisharea.max) self.MapFinish:Spawn() for k,v in pairs(self.SpawnPoints) do v:SetPos(MapData.spawnpos) v:SetAngles(MapData.spawnang) end end end function GM:LevelSetup(ply, Level) if !Level or !isnumber(Level) or !self.Levels[Level] then return end ply:SetNetworkedInt("ssbhop_level", Level) ply.LevelData = self.Levels[Level] if !ply.LevelData then return end ply:SetGravity(ply.LevelData.gravity) ply.StayTime = ply.LevelData.staytime print(game.GetMap()) ply.Payout = SS.MapList[game.GetMap()].payout or 100 ply:ChatPrint("Your difficulty is ".. ply.LevelData.name ..".") if ply:Team() == TEAM_BHOP then ply:ResetTimer() ply.Winner = false end ply:SetTeam(TEAM_BHOP) ply:Spawn() end concommand.Add("level_select", function(ply, cmd, args) GAMEMODE:LevelSetup(ply, tonumber(args[1])) end) function GM:ShowTeam(ply) if ply:Team() != TEAM_BHOP and ply:HasTimer() then -- Just resume if they already played. self:LevelSetup(ply, self.PSaveData[ply:SteamID()].Level) else ply:ConCommand("open_difficulties") end end function GM:PlayerSpawn(ply) if ply:IsBot() then ply:SetTeam(TEAM_BHOP) end -- always spawn bots if ply:Team() == TEAM_BHOP then ply:UnSpectate() player_manager.SetPlayerClass( ply, "player_bhop" ) self.BaseClass:PlayerSpawn( ply ) player_manager.OnPlayerSpawn( ply ) player_manager.RunClass( ply, "Spawn" ) hook.Call( "PlayerSetModel", GAMEMODE, ply ) ply:SetHull(Vector(-16, -16, 0), Vector(16, 16, 62)) ply:SetHullDuck(Vector(-16, -16, 0), Vector(16, 16, 45)) if ply:IsSuperAdmin() then ply:Give("ss_mapeditor") end if !ply.LevelData then self:LevelSetup(ply,2) --default level end if ply:HasTimer() and self.PSaveData[ply:SteamID()] then ply.AreaIgnore = true local PosInfo = self.PSaveData[ply:SteamID()] ply:SetPos(PosInfo.LastPosition) ply:SetEyeAngles(PosInfo.LastAngle) ply:StartTimer() ply.AreaIgnore = false elseif !ply.InSpawn then ply:StartTimer() end local oldhands = ply:GetHands() if ( IsValid( oldhands ) ) then oldhands:Remove() end local hands = ents.Create( "gmod_hands" ) if ( IsValid( hands ) ) then ply:SetHands( hands ) hands:SetOwner( ply ) -- Which hands should we use? local cl_playermodel = ply:GetInfo( "cl_playermodel" ) local info = player_manager.TranslatePlayerHands( cl_playermodel ) if ( info ) then hands:SetModel( info.model ) hands:SetSkin( info.skin ) hands:SetBodyGroups( info.body ) end -- Attach them to the viewmodel local vm = ply:GetViewModel( 0 ) hands:AttachToViewmodel( vm ) vm:DeleteOnRemove( hands ) ply:DeleteOnRemove( hands ) hands:Spawn() end else ply:SetTeam(TEAM_SPECTATOR) ply:Spectate(OBS_MODE_ROAMING) end end function GM:PlayerDisconnected(ply) ply:PauseTimer() end function GM:PlayerShouldTakeDamage(ply, attacker) return false end function GM:IsSpawnpointSuitable() -- Overwrite so we don't run into death problems return true end /* Setup the teleports, platforms, spawns, and finish lines */ function GM:InitPostEntity() if !SS.MapList[game.GetMap()] or !SS.MapList[game.GetMap()].ignoredoors then for k,v in pairs(ents.FindByClass("func_door")) do if(!v.IsP) then continue end local mins = v:OBBMins() local maxs = v:OBBMaxs() local h = maxs.z - mins.z if(h > 80 && game.GetMap() != "bhop_monster_jam") then continue end local tab = ents.FindInBox( v:LocalToWorld(mins)-Vector(0,0,10), v:LocalToWorld(maxs)+Vector(0,0,5) ) if(tab) then for _,v2 in pairs(tab) do if(v2 && v2:IsValid() && v2:GetClass() == "trigger_teleport") then tele = v2 end end if(tele) then v:Fire("Lock") v:SetKeyValue("spawnflags","1024") v:SetKeyValue("speed","0") v:SetRenderMode(RENDERMODE_TRANSALPHA) if(v.BHS) then v:SetKeyValue("locked_sound",v.BHS) else v:SetKeyValue("locked_sound","DoorSound.DefaultMove") end v:SetNWInt("Platform",1) end end end for k,v in pairs(ents.FindByClass("func_button")) do if(!v.IsP) then continue end if(v.SpawnFlags == "256") then local mins = v:OBBMins() local maxs = v:OBBMaxs() local tab = ents.FindInBox( v:LocalToWorld(mins)-Vector(0,0,10), v:LocalToWorld(maxs)+Vector(0,0,5) ) if(tab) then for _,v2 in pairs(tab) do if(v2 && v2:IsValid() && v2:GetClass() == "trigger_teleport") then tele = v2 end end if(tele) then v:Fire("Lock") v:SetKeyValue("spawnflags","257") v:SetKeyValue("speed","0") v:SetRenderMode(RENDERMODE_TRANSALPHA) if(v.BHS) then v:SetKeyValue("locked_sound",v.BHS) else v:SetKeyValue("locked_sound","None (Silent)") end v:SetNWInt("Platform",1) end end end end end self:AreaSetup() end function GM:PlayerFootstep(ply) if ply:Alive() then -- If alive, assume we save positions if !self.PSaveData[ply:SteamID()] then self.PSaveData[ply:SteamID()] = {} end self.PSaveData[ply:SteamID()].LastPosition = ply:GetPos() self.PSaveData[ply:SteamID()].LastAngle = ply:GetAngles() self.PSaveData[ply:SteamID()].Level = ply:GetNetworkedInt("ssbhop_level", 0) end end function GM:PlayerWon(ply) ply:EndTimer() ply.Winner = true ply:ChatPrintAll(ply:Name().." has won in ".. FormatTime(ply:GetTotalTime(true))) print(ply.Payout) ply:GiveMoney(ply.Payout) end
--------------------------- -- Bunny Hop -- -- Created by xAaron113x -- --------------------------- include("shared.lua") include("sv_config.lua") include("sh_levels.lua") include("sh_maps.lua") include("sh_viewoffsets.lua") include("player_class/player_bhop.lua") AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") AddCSLuaFile("cl_difficulty_menu.lua") AddCSLuaFile("sh_levels.lua") AddCSLuaFile("sh_viewoffsets.lua") GM.PSaveData = {} -- Save last known positions and angles for respawn here. /* Setup the bhop spawn and finish */ function GM:AreaSetup() local MapData = SS.MapList[game.GetMap()] if MapData then -- We will assume the rest is valid self.MapSpawn = ents.Create("bhop_area") self.MapSpawn:SetPos(MapData.spawnarea.max-(MapData.spawnarea.max-MapData.spawnarea.min)/2) self.MapSpawn:Setup(MapData.spawnarea.min, MapData.spawnarea.max, true) self.MapSpawn:Spawn() self.MapFinish = ents.Create("bhop_area") self.MapFinish:SetPos(MapData.finisharea.max-(MapData.finisharea.max-MapData.finisharea.min)/2) self.MapFinish:Setup(MapData.finisharea.min, MapData.finisharea.max) self.MapFinish:Spawn() for k,v in pairs(self.SpawnPoints) do v:SetPos(MapData.spawnpos) v:SetAngles(MapData.spawnang) end end end function GM:LevelSetup(ply, Level) if !Level or !isnumber(Level) or !self.Levels[Level] then return end ply:SetNetworkedInt("ssbhop_level", Level) ply.LevelData = self.Levels[Level] if !ply.LevelData then return end ply:SetGravity(ply.LevelData.gravity) ply.StayTime = ply.LevelData.staytime print(game.GetMap()) ply.Payout = SS.MapList[game.GetMap()] and SS.MapList[game.GetMap()].payout or 100 ply:ChatPrint("Your difficulty is ".. ply.LevelData.name ..".") if ply:Team() == TEAM_BHOP then ply:ResetTimer() ply.Winner = false end ply:SetTeam(TEAM_BHOP) ply:Spawn() end concommand.Add("level_select", function(ply, cmd, args) GAMEMODE:LevelSetup(ply, tonumber(args[1])) end) function GM:ShowTeam(ply) if ply:Team() != TEAM_BHOP and ply:HasTimer() then -- Just resume if they already played. self:LevelSetup(ply, self.PSaveData[ply:SteamID()].Level) else ply:ConCommand("open_difficulties") end end function GM:PlayerSpawn(ply) if ply:IsBot() then ply:SetTeam(TEAM_BHOP) end -- always spawn bots if ply:Team() == TEAM_BHOP then ply:UnSpectate() player_manager.SetPlayerClass( ply, "player_bhop" ) self.BaseClass:PlayerSpawn( ply ) player_manager.OnPlayerSpawn( ply ) player_manager.RunClass( ply, "Spawn" ) hook.Call( "PlayerSetModel", GAMEMODE, ply ) ply:SetHull(Vector(-16, -16, 0), Vector(16, 16, 62)) ply:SetHullDuck(Vector(-16, -16, 0), Vector(16, 16, 45)) if ply:IsSuperAdmin() then ply:Give("ss_mapeditor") end if !ply.LevelData then self:LevelSetup(ply,2) --default level end if ply:HasTimer() and self.PSaveData[ply:SteamID()] then ply.AreaIgnore = true local PosInfo = self.PSaveData[ply:SteamID()] ply:SetPos(PosInfo.LastPosition) ply:SetEyeAngles(PosInfo.LastAngle) ply:StartTimer() ply.AreaIgnore = false elseif !ply.InSpawn then ply:StartTimer() end local oldhands = ply:GetHands() if ( IsValid( oldhands ) ) then oldhands:Remove() end local hands = ents.Create( "gmod_hands" ) if ( IsValid( hands ) ) then ply:SetHands( hands ) hands:SetOwner( ply ) -- Which hands should we use? local cl_playermodel = ply:GetInfo( "cl_playermodel" ) local info = player_manager.TranslatePlayerHands( cl_playermodel ) if ( info ) then hands:SetModel( info.model ) hands:SetSkin( info.skin ) hands:SetBodyGroups( info.body ) end -- Attach them to the viewmodel local vm = ply:GetViewModel( 0 ) hands:AttachToViewmodel( vm ) vm:DeleteOnRemove( hands ) ply:DeleteOnRemove( hands ) hands:Spawn() end else ply:SetTeam(TEAM_SPECTATOR) ply:Spectate(OBS_MODE_ROAMING) end end function GM:PlayerDisconnected(ply) ply:PauseTimer() end function GM:PlayerShouldTakeDamage(ply, attacker) return false end function GM:IsSpawnpointSuitable() -- Overwrite so we don't run into death problems return true end /* Setup the teleports, platforms, spawns, and finish lines */ function GM:InitPostEntity() if !SS.MapList[game.GetMap()] or !SS.MapList[game.GetMap()].ignoredoors then for k,v in pairs(ents.FindByClass("func_door")) do if(!v.IsP) then continue end local mins = v:OBBMins() local maxs = v:OBBMaxs() local h = maxs.z - mins.z if(h > 80 && game.GetMap() != "bhop_monster_jam") then continue end local tab = ents.FindInBox( v:LocalToWorld(mins)-Vector(0,0,10), v:LocalToWorld(maxs)+Vector(0,0,5) ) if(tab) then for _,v2 in pairs(tab) do if(v2 && v2:IsValid() && v2:GetClass() == "trigger_teleport") then tele = v2 end end if(tele) then v:Fire("Lock") v:SetKeyValue("spawnflags","1024") v:SetKeyValue("speed","0") v:SetRenderMode(RENDERMODE_TRANSALPHA) if(v.BHS) then v:SetKeyValue("locked_sound",v.BHS) else v:SetKeyValue("locked_sound","DoorSound.DefaultMove") end v:SetNWInt("Platform",1) end end end for k,v in pairs(ents.FindByClass("func_button")) do if(!v.IsP) then continue end if(v.SpawnFlags == "256") then local mins = v:OBBMins() local maxs = v:OBBMaxs() local tab = ents.FindInBox( v:LocalToWorld(mins)-Vector(0,0,10), v:LocalToWorld(maxs)+Vector(0,0,5) ) if(tab) then for _,v2 in pairs(tab) do if(v2 && v2:IsValid() && v2:GetClass() == "trigger_teleport") then tele = v2 end end if(tele) then v:Fire("Lock") v:SetKeyValue("spawnflags","257") v:SetKeyValue("speed","0") v:SetRenderMode(RENDERMODE_TRANSALPHA) if(v.BHS) then v:SetKeyValue("locked_sound",v.BHS) else v:SetKeyValue("locked_sound","None (Silent)") end v:SetNWInt("Platform",1) end end end end end self:AreaSetup() end function GM:PlayerFootstep(ply) if ply:Alive() then -- If alive, assume we save positions if !self.PSaveData[ply:SteamID()] then self.PSaveData[ply:SteamID()] = {} end self.PSaveData[ply:SteamID()].LastPosition = ply:GetPos() self.PSaveData[ply:SteamID()].LastAngle = ply:GetAngles() self.PSaveData[ply:SteamID()].Level = ply:GetNetworkedInt("ssbhop_level", 0) end end function GM:PlayerWon(ply) ply:EndTimer() ply.Winner = true ply:ChatPrintAll(ply:Name().." has won in ".. FormatTime(ply:GetTotalTime(true))) print(ply.Payout) ply:GiveMoney(ply.Payout) end
Tiny little bugfix :( (for making non listed maps work)
Tiny little bugfix :( (for making non listed maps work)
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
9514027f65b22933010be8664ae584bdd6e631bd
lib/pairwise_transform_jpeg_scale.lua
lib/pairwise_transform_jpeg_scale.lua
local pairwise_utils = require 'pairwise_transform_utils' local iproc = require 'iproc' local gm = require 'graphicsmagick' local pairwise_transform = {} local function add_jpeg_noise_(x, quality, options) for i = 1, #quality do x = gm.Image(x, "RGB", "DHW") x:format("jpeg"):depth(8) if torch.uniform() < options.jpeg_chroma_subsampling_rate then -- YUV 420 x:samplingFactors({2.0, 1.0, 1.0}) else -- YUV 444 x:samplingFactors({1.0, 1.0, 1.0}) end local blob, len = x:toBlob(quality[i]) x:fromBlob(blob, len) x = x:toTensor("byte", "RGB", "DHW") end return x end local function add_jpeg_noise(src, style, level, options) if style == "art" then if level == 1 then return add_jpeg_noise_(src, {torch.random(65, 85)}, options) elseif level == 2 or level == 3 then -- level 2/3 adjusting by -nr_rate. for level3, -nr_rate=1 local r = torch.uniform() if r > 0.6 then return add_jpeg_noise_(src, {torch.random(27, 70)}, options) elseif r > 0.3 then local quality1 = torch.random(37, 70) local quality2 = quality1 - torch.random(5, 10) return add_jpeg_noise_(src, {quality1, quality2}, options) else local quality1 = torch.random(52, 70) local quality2 = quality1 - torch.random(5, 15) local quality3 = quality1 - torch.random(15, 25) return add_jpeg_noise_(src, {quality1, quality2, quality3}, options) end else error("unknown noise level: " .. level) end elseif style == "photo" then -- level adjusting by -nr_rate return add_jpeg_noise_(src, {torch.random(30, 70)}, options) else error("unknown style: " .. style) end end function pairwise_transform.jpeg_scale(src, scale, style, noise_level, size, offset, n, options) local filters = options.downsampling_filters if options.data.filters then filters = options.data.filters end local unstable_region_offset = 8 local downsampling_filter = filters[torch.random(1, #filters)] local blur = torch.uniform(options.resize_blur_min, options.resize_blur_max) local y = pairwise_utils.preprocess(src, size, options) assert(y:size(2) % 4 == 0 and y:size(3) % 4 == 0) local down_scale = 1.0 / scale local x if options.gamma_correction then local small = iproc.scale_with_gamma22(y, y:size(3) * down_scale, y:size(2) * down_scale, downsampling_filter, blur) if options.x_upsampling then x = iproc.scale(small, y:size(3), y:size(2), options.upsampling_filter) else x = small end else local small = iproc.scale(y, y:size(3) * down_scale, y:size(2) * down_scale, downsampling_filter, blur) if options.x_upsampling then x = iproc.scale(small, y:size(3), y:size(2), options.upsampling_filter) else x = small end end x = add_jpeg_noise(x, style, noise_level, options) local scale_inner = scale if options.x_upsampling then scale_inner = 1 end x = iproc.crop(x, unstable_region_offset, unstable_region_offset, x:size(3) - unstable_region_offset, x:size(2) - unstable_region_offset) y = iproc.crop(y, unstable_region_offset * scale_inner, unstable_region_offset * scale_inner, y:size(3) - unstable_region_offset * scale_inner, y:size(2) - unstable_region_offset * scale_inner) if options.x_upsampling then assert(x:size(2) % 4 == 0 and x:size(3) % 4 == 0) assert(x:size(1) == y:size(1) and x:size(2) == y:size(2) and x:size(3) == y:size(3)) else assert(x:size(1) == y:size(1) and x:size(2) * scale == y:size(2) and x:size(3) * scale == y:size(3)) end local batch = {} local lowres_y = gm.Image(y, "RGB", "DHW"): size(y:size(3) * 0.5, y:size(2) * 0.5, "Box"): size(y:size(3), y:size(2), "Box"): toTensor(t, "RGB", "DHW") local xs = {} local ys = {} local lowreses = {} for j = 1, 2 do -- TTA local xi, yi, ri if j == 1 then xi = x yi = y ri = lowres_y else xi = x:transpose(2, 3):contiguous() yi = y:transpose(2, 3):contiguous() ri = lowres_y:transpose(2, 3):contiguous() end local xv = image.vflip(xi) local yv = image.vflip(yi) local rv = image.vflip(ri) table.insert(xs, xi) table.insert(ys, yi) table.insert(lowreses, ri) table.insert(xs, xv) table.insert(ys, yv) table.insert(lowreses, rv) table.insert(xs, image.hflip(xi)) table.insert(ys, image.hflip(yi)) table.insert(lowreses, image.hflip(ri)) table.insert(xs, image.hflip(xv)) table.insert(ys, image.hflip(yv)) table.insert(lowreses, image.hflip(rv)) end for i = 1, n do local t = (i % #xs) + 1 local xc, yc = pairwise_utils.active_cropping(xs[t], ys[t], lowreses[t], size, scale_inner, options.active_cropping_rate, options.active_cropping_tries) xc = iproc.byte2float(xc) yc = iproc.byte2float(yc) if options.rgb then else yc = image.rgb2yuv(yc)[1]:reshape(1, yc:size(2), yc:size(3)) xc = image.rgb2yuv(xc)[1]:reshape(1, xc:size(2), xc:size(3)) end table.insert(batch, {xc, iproc.crop(yc, offset, offset, size - offset, size - offset)}) end return batch end function pairwise_transform.test_jpeg_scale(src) torch.setdefaulttensortype("torch.FloatTensor") local options = {random_color_noise_rate = 0.5, random_half_rate = 0.5, random_overlay_rate = 0.5, random_unsharp_mask_rate = 0.5, active_cropping_rate = 0.5, active_cropping_tries = 10, max_size = 256, x_upsampling = false, downsampling_filters = "Box", rgb = true } local image = require 'image' local src = image.lena() for i = 1, 10 do local xy = pairwise_transform.jpeg_scale(src, 2.0, "art", 1, 128, 7, 1, options) image.display({image = xy[1][1], legend = "y:" .. (i * 10), min = 0, max = 1}) image.display({image = xy[1][2], legend = "x:" .. (i * 10), min = 0, max = 1}) end end return pairwise_transform
local pairwise_utils = require 'pairwise_transform_utils' local iproc = require 'iproc' local gm = require 'graphicsmagick' local pairwise_transform = {} local function add_jpeg_noise_(x, quality, options) for i = 1, #quality do x = gm.Image(x, "RGB", "DHW") x:format("jpeg"):depth(8) if torch.uniform() < options.jpeg_chroma_subsampling_rate then -- YUV 420 x:samplingFactors({2.0, 1.0, 1.0}) else -- YUV 444 x:samplingFactors({1.0, 1.0, 1.0}) end local blob, len = x:toBlob(quality[i]) x:fromBlob(blob, len) x = x:toTensor("byte", "RGB", "DHW") end return x end local function add_jpeg_noise(src, style, level, options) if style == "art" then if level == 1 then return add_jpeg_noise_(src, {torch.random(65, 85)}, options) elseif level == 2 or level == 3 then -- level 2/3 adjusting by -nr_rate. for level3, -nr_rate=1 local r = torch.uniform() if r > 0.6 then return add_jpeg_noise_(src, {torch.random(27, 70)}, options) elseif r > 0.3 then local quality1 = torch.random(37, 70) local quality2 = quality1 - torch.random(5, 10) return add_jpeg_noise_(src, {quality1, quality2}, options) else local quality1 = torch.random(52, 70) local quality2 = quality1 - torch.random(5, 15) local quality3 = quality1 - torch.random(15, 25) return add_jpeg_noise_(src, {quality1, quality2, quality3}, options) end else error("unknown noise level: " .. level) end elseif style == "photo" then -- level adjusting by -nr_rate return add_jpeg_noise_(src, {torch.random(30, 70)}, options) else error("unknown style: " .. style) end end function pairwise_transform.jpeg_scale(src, scale, style, noise_level, size, offset, n, options) local filters = options.downsampling_filters if options.data.filters then filters = options.data.filters end local unstable_region_offset = 8 local downsampling_filter = filters[torch.random(1, #filters)] local blur = torch.uniform(options.resize_blur_min, options.resize_blur_max) local y = pairwise_utils.preprocess(src, size, options) assert(y:size(2) % 4 == 0 and y:size(3) % 4 == 0) local down_scale = 1.0 / scale local x if options.gamma_correction then local small = iproc.scale_with_gamma22(y, y:size(3) * down_scale, y:size(2) * down_scale, downsampling_filter, blur) if options.x_upsampling then x = iproc.scale(small, y:size(3), y:size(2), options.upsampling_filter) else x = small end else local small = iproc.scale(y, y:size(3) * down_scale, y:size(2) * down_scale, downsampling_filter, blur) if options.x_upsampling then x = iproc.scale(small, y:size(3), y:size(2), options.upsampling_filter) else x = small end end local scale_inner = scale if options.x_upsampling then scale_inner = 1 end x = iproc.crop(x, unstable_region_offset, unstable_region_offset, x:size(3) - unstable_region_offset, x:size(2) - unstable_region_offset) y = iproc.crop(y, unstable_region_offset * scale_inner, unstable_region_offset * scale_inner, y:size(3) - unstable_region_offset * scale_inner, y:size(2) - unstable_region_offset * scale_inner) if options.x_upsampling then assert(x:size(2) % 4 == 0 and x:size(3) % 4 == 0) assert(x:size(1) == y:size(1) and x:size(2) == y:size(2) and x:size(3) == y:size(3)) else assert(x:size(1) == y:size(1) and x:size(2) * scale == y:size(2) and x:size(3) * scale == y:size(3)) end local batch = {} local lowres_y = gm.Image(y, "RGB", "DHW"): size(y:size(3) * 0.5, y:size(2) * 0.5, "Box"): size(y:size(3), y:size(2), "Box"): toTensor(t, "RGB", "DHW") local xs = {} local ns = {} local ys = {} local lowreses = {} for j = 1, 2 do -- TTA local xi, yi, ri if j == 1 then xi = x yi = y ri = lowres_y else xi = x:transpose(2, 3):contiguous() yi = y:transpose(2, 3):contiguous() ri = lowres_y:transpose(2, 3):contiguous() end local xv = image.vflip(xi) local yv = image.vflip(yi) local rv = image.vflip(ri) table.insert(xs, xi) table.insert(ys, yi) table.insert(lowreses, ri) table.insert(xs, xv) table.insert(ys, yv) table.insert(lowreses, rv) table.insert(xs, image.hflip(xi)) table.insert(ys, image.hflip(yi)) table.insert(lowreses, image.hflip(ri)) table.insert(xs, image.hflip(xv)) table.insert(ys, image.hflip(yv)) table.insert(lowreses, image.hflip(rv)) end for i = 1, n do local t = (i % #xs) + 1 local xc, yc if torch.uniform() < options.nr_rate then -- scale + noise reduction if not ns[t] then ns[t] = add_jpeg_noise(xs[t], style, noise_level, options) end xc, yc = pairwise_utils.active_cropping(ns[t], ys[t], lowreses[t], size, scale_inner, options.active_cropping_rate, options.active_cropping_tries) else -- scale xc, yc = pairwise_utils.active_cropping(xs[t], ys[t], lowreses[t], size, scale_inner, options.active_cropping_rate, options.active_cropping_tries) end xc = iproc.byte2float(xc) yc = iproc.byte2float(yc) if options.rgb then else yc = image.rgb2yuv(yc)[1]:reshape(1, yc:size(2), yc:size(3)) xc = image.rgb2yuv(xc)[1]:reshape(1, xc:size(2), xc:size(3)) end table.insert(batch, {xc, iproc.crop(yc, offset, offset, size - offset, size - offset)}) end return batch end function pairwise_transform.test_jpeg_scale(src) torch.setdefaulttensortype("torch.FloatTensor") local options = {random_color_noise_rate = 0.5, random_half_rate = 0.5, random_overlay_rate = 0.5, random_unsharp_mask_rate = 0.5, active_cropping_rate = 0.5, active_cropping_tries = 10, max_size = 256, x_upsampling = false, downsampling_filters = "Box", rgb = true } local image = require 'image' local src = image.lena() for i = 1, 10 do local xy = pairwise_transform.jpeg_scale(src, 2.0, "art", 1, 128, 7, 1, options) image.display({image = xy[1][1], legend = "y:" .. (i * 10), min = 0, max = 1}) image.display({image = xy[1][2], legend = "x:" .. (i * 10), min = 0, max = 1}) end end return pairwise_transform
Fix a bug that -nr_rate is not used
Fix a bug that -nr_rate is not used
Lua
mit
zyhkz/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,Spitfire1900/upscaler
89aa9920e1a22147b55ccd96f84031866ad069de
util/dialog.lua
util/dialog.lua
-------------------------------------------------------------------------------- -- Copyright (c) 2015 Jason Lynch <[email protected]> -- -- 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 _M = {} local bridge = require "util.bridge" local game = require "util.game" local input = require "util.input" local memory = require "util.memory" -------------------------------------------------------------------------------- -- Variables -------------------------------------------------------------------------------- local _mash_button = "P1 A" local _pending_spoils -------------------------------------------------------------------------------- -- Dialog Splits -------------------------------------------------------------------------------- local _splits = { ["Sage Tel"] = {message = "Tellah", done = false}, ["Prince E"] = {message = "Edward", done = false}, ["Palom th"] = {message = "Twins", done = false}, ["Cecil be"] = {message = "Paladin", done = false}, ["Ninja Ed"] = {message = "Edge", done = false}, [" The Big"] = {message = "Big Whale", done = false}, ["Lost the"] = {message = "Lost the Dark Crystal!", done = false}, ["Lunarian"] = {message = "FuSoYa", done = false}, } -------------------------------------------------------------------------------- -- Private Functions -------------------------------------------------------------------------------- local function _get_text(category, key, base, characters) local text = "" if not characters then characters = 24 end for i = base, base + characters - 1 do local character = memory.read(category, key, i) if character then text = text .. character end end return text end -------------------------------------------------------------------------------- -- Public Functions -------------------------------------------------------------------------------- function _M.is_dialog() local battle_dialog_state = memory.read("battle_dialog", "state") local dialog_height = memory.read("dialog", "height") local dialog_state = memory.read("dialog", "state") local dialog_prompt = memory.read("dialog", "prompt") local spoils = memory.read("dialog", "spoils_state") > 0 if _pending_spoils == 1 and spoils then _pending_spoils = 2 elseif _pending_spoils == 2 and memory.read("menu", "state") == 0 then _pending_spoils = nil end return battle_dialog_state == 1 or spoils or _pending_spoils or dialog_height == 7 or (dialog_height > 0 and (dialog_state == 0 or dialog_prompt == 0)) end function _M.cycle() if _M.is_dialog() then local text = _M.get_text(8) if _splits[text] and not _splits[text].done then bridge.split(_splits[text].message) _splits[text].done = true end input.press({_mash_button}, input.DELAY.MASH) return true end return false end function _M.get_battle_spell() if game.battle.get_type() == game.battle.TYPE.BACK_ATTACK then return _get_text("battle_dialog", "text", 0, 6) else return _get_text("battle_dialog", "text", 18, 6) end end function _M.get_battle_text(characters) return _get_text("battle_dialog", "text", 1, characters) end function _M.get_save_text(characters) return _get_text("menu_save", "text", 0, characters) end function _M.get_text(characters) return _get_text("dialog", "text", 0, characters) end function _M.reset() for key, _ in pairs(_splits) do _splits[key].done = false end _M.set_mash_button("P1 A") end function _M.set_mash_button(mash_button) _mash_button = mash_button return true end function _M.set_pending_spoils() _pending_spoils = 1 end return _M
-------------------------------------------------------------------------------- -- Copyright (c) 2015 Jason Lynch <[email protected]> -- -- 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 _M = {} local bridge = require "util.bridge" local game = require "util.game" local input = require "util.input" local memory = require "util.memory" -------------------------------------------------------------------------------- -- Variables -------------------------------------------------------------------------------- local _mash_button = "P1 A" local _pending_spoils -------------------------------------------------------------------------------- -- Dialog Splits -------------------------------------------------------------------------------- local _splits = { ["Sage Tel"] = {message = "Tellah", done = false}, ["Prince E"] = {message = "Edward", done = false}, ["Palom th"] = {message = "Twins", done = false}, ["Cecil be"] = {message = "Paladin", done = false}, ["Ninja Ed"] = {message = "Edge", done = false}, [" The Big"] = {message = "Big Whale", done = false}, ["Lost the"] = {message = "Lost the Dark Crystal!", done = false}, ["Lunarian"] = {message = "FuSoYa", done = false}, } -------------------------------------------------------------------------------- -- Private Functions -------------------------------------------------------------------------------- local function _get_text(category, key, base, characters) local text = "" if not characters then characters = 24 end for i = base, base + characters - 1 do local character = memory.read(category, key, i) if character then text = text .. character end end return text end -------------------------------------------------------------------------------- -- Public Functions -------------------------------------------------------------------------------- function _M.is_dialog() local battle_dialog_state = memory.read("battle_dialog", "state") local dialog_height = memory.read("dialog", "height") local dialog_state = memory.read("dialog", "state") local dialog_prompt = memory.read("dialog", "prompt") local spoils = memory.read("dialog", "spoils_state") > 0 if _pending_spoils == 1 and spoils then _pending_spoils = 2 elseif _pending_spoils == 2 and memory.read("menu", "state") == 0 then _pending_spoils = nil end return battle_dialog_state == 1 or spoils or _pending_spoils ~= nil or dialog_height == 7 or (dialog_height > 0 and (dialog_state == 0 or dialog_prompt == 0)) end function _M.cycle() if _M.is_dialog() then local text = _M.get_text(8) if _splits[text] and not _splits[text].done then bridge.split(_splits[text].message) _splits[text].done = true end input.press({_mash_button}, input.DELAY.MASH) return true end return false end function _M.get_battle_spell() if game.battle.get_type() == game.battle.TYPE.BACK_ATTACK then return _get_text("battle_dialog", "text", 0, 6) else return _get_text("battle_dialog", "text", 18, 6) end end function _M.get_battle_text(characters) return _get_text("battle_dialog", "text", 1, characters) end function _M.get_save_text(characters) return _get_text("menu_save", "text", 0, characters) end function _M.get_text(characters) return _get_text("dialog", "text", 0, characters) end function _M.reset() for key, _ in pairs(_splits) do _splits[key].done = false end _pending_spoils = nil _M.set_mash_button("P1 A") end function _M.set_mash_button(mash_button) _mash_button = mash_button return true end function _M.set_pending_spoils() _pending_spoils = 1 end return _M
Fix a bug with the dialog code during reset.
Fix a bug with the dialog code during reset. Note that this doesn't actually make any sense to me, since it seems to stem from a variable carrying over between runs. I figured reboot_core would successfully clear the environments, but apparently not. If the bug continues to occur we can investigate further. (Specifically, during the next run, the bot is unable to set seed 92 because the dialog code is intensely mashing A.) Signed-off-by: Jason Lynch <[email protected]>
Lua
mit
aexoden/edge
7dc9ce0803eacf1e9d78f7fcfea05e574993af18
scripts/tundra/syntax/pkgconfig.lua
scripts/tundra/syntax/pkgconfig.lua
module(..., package.seeall) function ConfigureRaw(cmdline, name, constructor) local fh = assert(io.popen(cmdline)) local data = fh:read("*all") fh:close() local cpppath = {} local libpath = {} local libs = {} local defines = {} local frameworks = {} for kind, value in data:gmatch("-([ILlD])([^ \n\r]+)") do if kind == "I" then cpppath[#cpppath + 1] = value elseif kind == "D" then defines[#defines + 1] = value elseif kind == "L" then libpath[#libpath + 1] = value elseif kind == "l" then libs[#libs + 1] = value end end for value in data:gmatch("-framework ([^ \n\r]+)") do frameworks[#frameworks + 1] = value end -- We don't have access to ExternalLibrary here - user has to pass it in. return constructor({ Name = name, Propagate = { Env = { FRAMEWORKS = frameworks, CPPDEFS = defines, CPPPATH = cpppath, LIBS = libs, LIBPATH = libpath } } }) end function Configure(name, ctor) return ConfigureRaw("pkg-config " .. name .. " --cflags --libs", name, ctor) end function ConfigureWithTool(tool, name, ctor) return ConfigureRaw(tool .. " --cflags --libs", name, ctor) end
module(..., package.seeall) function ConfigureRaw(cmdline, name, constructor) local fh = assert(io.popen(cmdline)) local data = fh:read("*all") fh:close() local cpppath = {} local libpath = {} local libs = {} local defines = {} local frameworks = {} for kind, value in data:gmatch("-([ILlD])([^ \n\r]+)") do if kind == "I" then cpppath[#cpppath + 1] = value elseif kind == "D" then defines[#defines + 1] = value elseif kind == "L" then libpath[#libpath + 1] = value elseif kind == "l" then libs[#libs + 1] = value end end for value in data:gmatch("-framework ([^ \n\r]+)") do if value:match('^-Wl,') then value = string.sub(value, 5) end frameworks[#frameworks + 1] = value end -- We don't have access to ExternalLibrary here - user has to pass it in. return constructor({ Name = name, Propagate = { Env = { FRAMEWORKS = frameworks, CPPDEFS = defines, CPPPATH = cpppath, LIBS = libs, LIBPATH = libpath } } }) end function Configure(name, ctor) return ConfigureRaw("pkg-config " .. name .. " --cflags --libs", name, ctor) end function ConfigureWithTool(tool, name, ctor) return ConfigureRaw(tool .. " --cflags --libs", name, ctor) end
Ignore -Wl, arguments from pkgconfig
Ignore -Wl, arguments from pkgconfig Fixes #315
Lua
mit
bmharper/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra,deplinenoise/tundra
0f90e378ca68ba80cc489b15898511419d8a8378
mod_pastebin/mod_pastebin.lua
mod_pastebin/mod_pastebin.lua
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local length_threshold = config.get("*", "core", "pastebin_threshold") or 500; local base_url; local pastes = {}; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; local function pastebin_message(text) local uuid = uuid_new(); pastes[uuid] = { text = text, time = os_time() }; return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid].text; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtml then htmlindex = k; end end if not body then return; end body = body:get_text(); module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and #body > length_threshold then local url = pastebin_message(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local length_threshold = config.get("*", "core", "pastebin_threshold") or 500; local base_url = config.get(module.host, "core", "pastebin_url"); local pastes = {}; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; local function pastebin_message(text) local uuid = uuid_new(); pastes[uuid] = { text = text, time = os_time() }; return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid].text; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtml then htmlindex = k; end end if not body then return; end body = body:get_text(); module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and #body > length_threshold then local url = pastebin_message(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
mod_pastebin: Small fix to read the pastebin URL from the config
mod_pastebin: Small fix to read the pastebin URL from the config
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
3995295c02a343534da5d54f2231f23cfdfc3c95
src/main.lua
src/main.lua
-- Load libs msg = require("src.msg") opt = require("src.opt") rava = require("src.rava") -- set version APPNAME = "Rava Micro-Service Compiler" VERSION = "2.0.1" OPLEVEL = 1 RAVABIN = arg[0] -- Make sure ravabin is defined properly if arg[-1] ~= nil then RAVABIN = arg[-1].." "..arg[0] end -- Help opt.add("h", "Show this help dialog", function(r) msg.format("%s v%s - %s", APPNAME, VERSION, jit.version) msg.line("\tUsage:\n") msg.line("\t"..RAVABIN:gsub("^.*/", "").." [opt] files objects\n") msg.line("\tOptions:\n") opt.show() msg.line("") msg.line("\tExamples:\n") msg.line("\t"..RAVABIN:gsub("^.*/", "").." --exec test.lua") msg.line("\t"..RAVABIN:gsub("^.*/", "").." --eval \"print('hello world.')\"") msg.line("\t"..RAVABIN:gsub("^.*/", "").." --compile=appsvr app.lua server.a") msg.line("\t"..RAVABIN:gsub("^.*/", "").." --generate=main main.lua main.lua.o\n") os.exit(r == false) end) -- No output, except Errors.. opt.add("q", "Quiet for the most part, excludes Errors", function() function msg.warning(...) end function msg.info(...) end function msg.done(...) end function msg.fail(...) end function print(...) end end) -- No output at all. opt.add("Q", nil, function() function msg.add() end function print(...) end end) -- No Check file opt.add("n", "Don't check the source file for syntax errors") -- Debug symbols opt.add("g", "Leave debug sybols intact in lua object files") local modules = rava.scandir("modules") for _,mod in pairs(modules) do local mod, match = mod:gsub(".lua$", "") if match == 1 then require("modules/"..mod) end end -- Run lua from commandline opt.add("eval", "Evaluates a string lua code", function(flag, ...) rava.eval(...) os.exit(0) end) -- Run files instead of compiling opt.add("exec", "Executes files in rava runtime environment", function(flag, ...) rava.exec(...) os.exit(0) end) -- Generate binary data store opt.add("store=variable", "Generate a lua data store of binary files", function(name, store, ...) msg.format("%s v%s - %s", APPNAME, VERSION, jit.version) rava.store(name, store, ...) os.exit(0) end) -- Compile binary opt.add("compile=binary", "Compile a binary from lua files", function(binary, alt, ...) if alt == nil then return opt.run("h") end if binary == true then binary = alt:gsub("%..-$", "") end msg.format("%s v%s - %s", APPNAME, VERSION, jit.version) msg.line("Compiling "..binary.." from:") msg.dump(...) rava.compile(binary, nil, ...) msg.line() os.exit(0) end) -- Generate bytecode object opt.add("generate=module", "Generate a lua file to bytecode object", function(module, ...) local arg = {...} if #arg < 2 then msg.format("%s v%s - %s", APPNAME, VERSION, jit.version) msg.line("\tUsage: "..RAVABIN:gsub("^.*/", "").." --generate [opt]\n") end rava.generate(module, ...) os.exit(0) end) -- Run options opt.run("*all", unpack(arg)) -- Make sure we have enough to do something if #arg > 0 then opt.run("exec", unpack(arg)) else opt.run("h", 0) end
-- Load libs msg = require("src.msg") opt = require("src.opt") rava = require("src.rava") -- set version APPNAME = "Rava Micro-Service Compiler" VERSION = "2.0.1" OPLEVEL = 1 RAVABIN = arg[0] -- Make sure ravabin is defined properly if arg[-1] ~= nil then RAVABIN = arg[-1].." "..arg[0] end -- Help opt.add("h", "Show this help dialog", function(r) msg.format("%s v%s - %s", APPNAME, VERSION, jit.version) msg.line("\tUsage:\n") msg.line("\t"..RAVABIN:gsub("^.*/", "").." [opt] files objects\n") msg.line("\tOptions:\n") opt.show() msg.line("") msg.line("\tExamples:\n") msg.line("\t"..RAVABIN:gsub("^.*/", "").." --exec test.lua") msg.line("\t"..RAVABIN:gsub("^.*/", "").." --eval \"print('hello world.')\"") msg.line("\t"..RAVABIN:gsub("^.*/", "").." --compile=appsvr app.lua server.a") msg.line("\t"..RAVABIN:gsub("^.*/", "").." --generate=main main.lua main.lua.o\n") os.exit(r == false) end) -- No output, except Errors.. opt.add("q", "Quiet for the most part, excludes Errors", function() function msg.warning(...) end function msg.info(...) end function msg.done(...) end function msg.fail(...) end function print(...) end end) -- No output at all. opt.add("Q", nil, function() function msg.add() end function print(...) end end) -- No Check file opt.add("n", "Don't check the source file for syntax errors") -- Debug symbols opt.add("g", "Leave debug sybols intact in lua object files") local modules = rava.scandir("modules") for _,mod in pairs(modules) do local mod, match = mod:gsub(".lua$", "") if match == 1 then require("modules/"..mod) end end -- Run lua from commandline opt.add("eval", "Evaluates a string lua code", function(flag, ...) rava.eval(...) os.exit(0) end) -- Run files instead of compiling opt.add("exec", "Executes files in rava runtime environment", function(flag, ...) rava.exec(...) os.exit(0) end) -- Compile binary opt.add("compile=name", "Compile a binary from lua files", function(name, file, ...) if file == nil then return opt.run("h") end if name == true then name = file:gsub("%..-$", "") end msg.format("%s v%s - %s", APPNAME, VERSION, jit.version) msg.line("Compiling "..name.." from:") msg.dump(...) rava.compile(name, file, ...) msg.line() os.exit(0) end) -- Generate bytecode object opt.add("generate=name", "Generate a lua file to bytecode object", function(name, ...) local arg = {...} if #arg < 2 then msg.format("%s v%s - %s", APPNAME, VERSION, jit.version) msg.line("\tUsage: "..RAVABIN:gsub("^.*/", "").." --generate [opt]\n") end rava.generate(name, ...) os.exit(0) end) -- Generate binary data store opt.add("datastore=name", "Generate a lua data store of binary files", function(name, store, ...) msg.format("%s v%s - %s", APPNAME, VERSION, jit.version) rava.datastore(name, store, ...) os.exit(0) end) -- Run options opt.run("*all", unpack(arg)) -- Make sure we have enough to do something if #arg > 0 then opt.run("exec", unpack(arg)) else opt.run("h", 0) end
Fixed broken data store
Fixed broken data store
Lua
mit
frinknet/rava,frinknet/rava,frinknet/rava
4823a3f6eb1a6078bba4c2773e76391414e9b0a3
classes/objectqueue.class.lua
classes/objectqueue.class.lua
include("object.class.lua"); include("objectlists.settings.lua"); CObjectQueue = class( function (self) self.Queue = {}; self.first = 0; self.last = -1; end ); function CObjectQueue:update() self.Queue = {}; -- Flush all objects. local evalAddresse = objectslists.funcs["objectlists_eval_addresse"]; local size = memoryReadInt(getProc(), addresses.staticTableSize); for i = 0,size do local addr = memoryReadUIntPtr(getProc(), addresses.staticTablePtr, i*4); if( evalAddresse( addr )) then object = CObject(addr); if(object ~= nil)then self:add(object); end end end --self.Pointer = #self.Queue; end function CObjectQueue:peek( type ) local first = self.first: if first > self.last then return nil; end if(self.Queue[first] ~= nil)then --update object self.Queue[first]:update(); if(self.Queue[first] ~= nil)then if(not type or self.Queue[first].Type == type)then local value = self.Queue[first] -- we peek only --self.Queue[first] = nil -- to allow garbage collection --self.first = first + 1 return value; else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:peek(); end else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:peek(); end else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:peek(); end end function CObjectQueue:poll( type ) local first = self.first: if first > self.last then return nil; end if(self.Queue[first] ~= nil)then --update object self.Queue[first]:update(); if(self.Queue[first] ~= nil)then if(not type or self.Queue[first].Type == type)then local value = self.Queue[first] self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return value; else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:poll(); end else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:poll(); end else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:poll(); end end - function CObjectQueue:add(object) --pushright local last = self.last + 1 self.last = last; self.Queue[last] = object; end function CObjectQueue:size() return #self.Queue; end
include("object.class.lua"); include("objectlists.settings.lua"); CObjectQueue = class( function (self) self.Queue = {}; self.first = 0; self.last = -1; end ); function CObjectQueue:update() self.Queue = {}; -- Flush all objects. -- rest the counters self.first = 0; self.last = -1; local evalAddresse = objectslists.funcs["objectlists_eval_addresse"]; local size = memoryReadInt(getProc(), addresses.staticTableSize); for i = 0,size do local addr = memoryReadUIntPtr(getProc(), addresses.staticTablePtr, i*4); if( evalAddresse( addr )) then object = CObject(addr); if(object ~= nil)then self:add(object); end end end --self.Pointer = #self.Queue; end function CObjectQueue:peek( type ) local first = self.first: if first > self.last then return nil; end if(self.Queue[first] ~= nil)then --update object self.Queue[first]:update(); if(self.Queue[first] ~= nil)then if(not type or self.Queue[first].Type == type)then local value = self.Queue[first] -- we peek only --self.Queue[first] = nil -- to allow garbage collection --self.first = first + 1 return value; else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:peek(); end else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:peek(); end else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:peek(); end end function CObjectQueue:poll( type ) local first = self.first: if first > self.last then return nil; end if(self.Queue[first] ~= nil)then --update object self.Queue[first]:update(); if(self.Queue[first] ~= nil)then if(not type or self.Queue[first].Type == type)then local value = self.Queue[first] self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return value; else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:poll(); end else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:poll(); end else self.Queue[first] = nil -- to allow garbage collection self.first = first + 1 return self:poll(); end end - function CObjectQueue:add(object) --pushright local last = self.last + 1 self.last = last; self.Queue[last] = object; end function CObjectQueue:size() return #self.Queue; end
fix small bug forgot to reset the counters
fix small bug forgot to reset the counters
Lua
mit
BlubBlab/Micromacro-2-Bot-Framework
b28582e174019684ab038ce38f53918b23214302
mod_muc_restrict_rooms/mod_muc_restrict_rooms.lua
mod_muc_restrict_rooms/mod_muc_restrict_rooms.lua
local st = require "util.stanza"; local nodeprep = require "util.encodings".stringprep.nodeprep; local rooms = module:shared "muc/rooms"; if not rooms then module:log("error", "This module only works on MUC components!"); return; end local admins = module:get_option_set("admins", {}); local restrict_patterns = module:get_option("muc_restrict_matching", {}); local restrict_excepts = module:get_option_set("muc_restrict_exceptions", {}); local restrict_allow_admins = module:get_option_set("muc_restrict_allow_admins", false); local function is_restricted(room, who) -- If admins can join prohibited rooms, we allow them to if (restrict_allow_admins == true) and (admins:contains(who)) then module:log("debug", "Admins are allowed to enter restricted rooms (%s on %s)", who, room) return false; end -- Don't evaluate exceptions if restrict_excepts:contains(room:lower()) then module:log("debug", "Room %s is amongst restriction exceptions", room:lower()) return false; end -- Evaluate regexps of restricted patterns for pattern,reason in pairs(restrict_patterns) do if room:match(pattern) then module:log("debug", "Room %s is restricted by pattern %s, user %s is not allowed to join (%s)", room, pattern, who, reason) return reason; end end return nil end module:hook("presence/full", function(event) local stanza = event.stanza; if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Leaving events get discarded return; end -- Get the room local room = stanza.attr.from:match("([^@]+)@[^@]+") if not room then return; end -- Get who has tried to join it local who = stanza.attr.to:match("([^\/]+)\/[^\/]+") -- Checking whether room is restricted local check_restricted = is_restricted(room, who) if check_restricted ~= nil then event.allowed = false; event.stanza.attr.type = 'error'; return event.origin.send(st.error_reply(event.stanza, "cancel", "forbidden", "You're not allowed to enter this room: " .. check_restricted)); end end, 10);
local st = require "util.stanza"; local jid = require "util.jid"; local nodeprep = require "util.encodings".stringprep.nodeprep; local rooms = module:shared "muc/rooms"; if not rooms then module:log("error", "This module only works on MUC components!"); return; end local restrict_patterns = module:get_option("muc_restrict_matching", {}); local restrict_excepts = module:get_option_set("muc_restrict_exceptions", {}); local restrict_allow_admins = module:get_option_boolean("muc_restrict_allow_admins", false); local function is_restricted(room, who) -- If admins can join prohibited rooms, we allow them to if restrict_allow_admins and usermanager.is_admin(who, module.host) then module:log("debug", "Admins are allowed to enter restricted rooms (%s on %s)", who, room) return nil; end -- Don't evaluate exceptions if restrict_excepts:contains(room) then module:log("debug", "Room %s is amongst restriction exceptions", room()) return nil; end -- Evaluate regexps of restricted patterns for pattern,reason in pairs(restrict_patterns) do if room:match(pattern) then module:log("debug", "Room %s is restricted by pattern %s, user %s is not allowed to join (%s)", room, pattern, who, reason) return reason; end end return nil end module:hook("presence/full", function(event) local stanza = event.stanza; if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Leaving events get discarded return; end -- Get the room local room = jid.split(stanza.attr.from); if not room then return; end -- Get who has tried to join it local who = jid.bare(stanza.attr.to) -- Checking whether room is restricted local check_restricted = is_restricted(room, who) if check_restricted ~= nil then event.allowed = false; event.stanza.attr.type = 'error'; return event.origin.send(st.error_reply(event.stanza, "cancel", "forbidden", "You're not allowed to enter this room: " .. check_restricted)); end end, 10);
mod_muc_restrict_rooms: Some fixes based on Matthew's comments + a few more
mod_muc_restrict_rooms: Some fixes based on Matthew's comments + a few more
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
833327d971d0911404014be1f2a411f8e36b5f84
mods/inventory_icon/init.lua
mods/inventory_icon/init.lua
inventory_icon = {} inventory_icon.hudids = {} inventory_icon.COLORIZE_STRING = "[colorize:#A00000:192" function inventory_icon.get_inventory_state(inv, listname) local size = inv:get_size(listname) local occupied = 0 for i=1,size do local stack = inv:get_stack(listname, i) if not stack:is_empty() then occupied = occupied + 1 end end return occupied, size end function inventory_icon.replace_icon(name) return "inventory_icon_"..name end minetest.register_on_joinplayer(function(player) local name = player:get_player_name() inventory_icon.hudids[name] = {} local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "main") local icon if occupied >= size then icon = "inventory_icon_backpack_full.png" else icon = "inventory_icon_backpack_free.png" end inventory_icon.hudids[name].main = {} inventory_icon.hudids[name].main.icon = player:hud_add({ hud_elem_type = "image", position = {x=1,y=1}, scale = {x=1,y=1}, offset = {x=-32,y=-32}, text = icon, }) inventory_icon.hudids[name].main.text = player:hud_add({ hud_elem_type = "text", position = {x=1,y=1}, scale = {x=1,y=1}, offset = {x=-36,y=-20}, alignment = {x=0,y=0}, number = 0xFFFFFF, text = string.format("%d/%d", occupied, size) }) if minetest.get_modpath("unified_inventory") ~= nil then inventory_icon.hudids[name].bags = {} local bags_inv = minetest.get_inventory({type = "detached", name = name.."_bags"}) for i=1,4 do local bag = bags_inv:get_stack("bag"..i, 1) local scale, text, icon if bag:is_empty() then scale = { x = 0, y = 0 } text = "" icon = "inventory_icon_bags_small.png" else scale = { x = 1, y = 1 } local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "bag"..i.."contents") text = string.format("%d/%d", occupied, size) icon = inventory_icon.replace_icon(minetest.registered_items[bag:get_name()].inventory_image) if occupied >= size then icon = icon .. "^" .. inventory_icon.COLORIZE_STRING end end inventory_icon.hudids[name].bags[i] = {} inventory_icon.hudids[name].bags[i].icon = player:hud_add({ hud_elem_type = "image", position = {x=1,y=1}, scale = scale, size = { x=32, y=32 }, offset = {x=-36,y=-32 -40*i}, text = icon, }) inventory_icon.hudids[name].bags[i].text = player:hud_add({ hud_elem_type = "text", position = {x=1,y=1}, scale = scale, offset = {x=-36,y=-20 -40*i}, alignment = {x=0,y=0}, number = 0xFFFFFF, text = text, }) end end end) minetest.register_on_leaveplayer(function(player) inventory_icon.hudids[player:get_player_name()] = nil end) local function tick() minetest.after(1, tick) for playername,hudids in pairs(inventory_icon.hudids) do local player = minetest.get_player_by_name(playername) if player then local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "main") local icon, color if occupied >= size then icon = "inventory_icon_backpack_full.png" else icon = "inventory_icon_backpack_free.png" end player:hud_change(hudids.main.icon, "text", icon) player:hud_change(hudids.main.text, "text", string.format("%d/%d", occupied, size)) if minetest.get_modpath("unified_inventory") ~= nil then local bags_inv = minetest.get_inventory({type = "detached", name = playername.."_bags"}) for i=1,4 do local bag = bags_inv:get_stack("bag"..i, 1) local scale, text, icon if bag:is_empty() then scale = { x = 0, y = 0 } text = "" icon = "inventory_icon_bags_small.png" else scale = { x = 1, y = 1 } local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "bag"..i.."contents") text = string.format("%d/%d", occupied, size) icon = inventory_icon.replace_icon(minetest.registered_items[bag:get_name()].inventory_image) if occupied >= size then icon = icon .. "^" .. inventory_icon.COLORIZE_STRING end end player:hud_change(inventory_icon.hudids[playername].bags[i].icon, "text", icon) player:hud_change(inventory_icon.hudids[playername].bags[i].icon, "scale", scale) player:hud_change(inventory_icon.hudids[playername].bags[i].text, "text", text) player:hud_change(inventory_icon.hudids[playername].bags[i].text, "scale", scale) end end end end end tick()
inventory_icon = {} inventory_icon.hudids = {} inventory_icon.COLORIZE_STRING = "[colorize:#A00000:192" function inventory_icon.get_inventory_state(inv, listname) local size = inv:get_size(listname) local occupied = 0 for i=1,size do local stack = inv:get_stack(listname, i) if not stack:is_empty() then occupied = occupied + 1 end end return occupied, size end function inventory_icon.replace_icon(name) local icon = "" if name:find("small") then icon = "inventory_icon_bags_small.png" elseif name:find("medium") then icon = "inventory_icon_bags_medium.png" elseif name:find("large") then icon = "inventory_icon_bags_large.png" end return icon end minetest.register_on_joinplayer(function(player) local name = player:get_player_name() inventory_icon.hudids[name] = {} local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "main") local icon if occupied >= size then icon = "inventory_icon_backpack_full.png" else icon = "inventory_icon_backpack_free.png" end inventory_icon.hudids[name].main = {} inventory_icon.hudids[name].main.icon = player:hud_add({ hud_elem_type = "image", position = {x=1,y=1}, scale = {x=1,y=1}, offset = {x=-32,y=-32}, text = icon, }) inventory_icon.hudids[name].main.text = player:hud_add({ hud_elem_type = "text", position = {x=1,y=1}, scale = {x=1,y=1}, offset = {x=-36,y=-20}, alignment = {x=0,y=0}, number = 0xFFFFFF, text = string.format("%d/%d", occupied, size) }) if minetest.get_modpath("unified_inventory") ~= nil then inventory_icon.hudids[name].bags = {} local bags_inv = minetest.get_inventory({type = "detached", name = name.."_bags"}) for i=1,4 do local bag = bags_inv:get_stack("bag"..i, 1) local scale, text, icon if bag:is_empty() then scale = { x = 0, y = 0 } text = "" icon = "inventory_icon_bags_small.png" else scale = { x = 1, y = 1 } local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "bag"..i.."contents") text = string.format("%d/%d", occupied, size) icon = inventory_icon.replace_icon(bag:get_name()) if occupied >= size then icon = icon .. "^" .. inventory_icon.COLORIZE_STRING end end inventory_icon.hudids[name].bags[i] = {} inventory_icon.hudids[name].bags[i].icon = player:hud_add({ hud_elem_type = "image", position = {x=1,y=1}, scale = scale, size = { x=32, y=32 }, offset = {x=-36,y=-32 -40*i}, text = icon, }) inventory_icon.hudids[name].bags[i].text = player:hud_add({ hud_elem_type = "text", position = {x=1,y=1}, scale = scale, offset = {x=-36,y=-20 -40*i}, alignment = {x=0,y=0}, number = 0xFFFFFF, text = text, }) end end end) minetest.register_on_leaveplayer(function(player) inventory_icon.hudids[player:get_player_name()] = nil end) local function tick() minetest.after(1, tick) for playername,hudids in pairs(inventory_icon.hudids) do local player = minetest.get_player_by_name(playername) if player then local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "main") local icon, color if occupied >= size then icon = "inventory_icon_backpack_full.png" else icon = "inventory_icon_backpack_free.png" end player:hud_change(hudids.main.icon, "text", icon) player:hud_change(hudids.main.text, "text", string.format("%d/%d", occupied, size)) if minetest.get_modpath("unified_inventory") ~= nil then local bags_inv = minetest.get_inventory({type = "detached", name = playername.."_bags"}) for i=1,4 do local bag = bags_inv:get_stack("bag"..i, 1) local scale, text, icon if bag:is_empty() then scale = { x = 0, y = 0 } text = "" icon = "inventory_icon_bags_small.png" else scale = { x = 1, y = 1 } local occupied, size = inventory_icon.get_inventory_state(player:get_inventory(), "bag"..i.."contents") text = string.format("%d/%d", occupied, size) icon = inventory_icon.replace_icon(bag:get_name()) if occupied >= size then icon = icon .. "^" .. inventory_icon.COLORIZE_STRING end end player:hud_change(inventory_icon.hudids[playername].bags[i].icon, "text", icon) player:hud_change(inventory_icon.hudids[playername].bags[i].icon, "scale", scale) player:hud_change(inventory_icon.hudids[playername].bags[i].text, "text", text) player:hud_change(inventory_icon.hudids[playername].bags[i].text, "scale", scale) end end end end end tick()
fix wrong icon name due to new colored bags
fix wrong icon name due to new colored bags
Lua
unlicense
Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server
2078028ae0a5f6d7c60ea6365a880cc328ae32a5
otouto/plugins/twitter.lua
otouto/plugins/twitter.lua
local twitter = {} function twitter:init(config) if not cred_data.tw_consumer_key then print('Missing config value: tw_consumer_key.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_consumer_secret then print('Missing config value: tw_consumer_secret.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token then print('Missing config value: tw_access_token.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token_secret then print('Missing config value: tw_access_token_secret.') print('twitter.lua will not be enabled.') return end twitter.triggers = { 'twitter.com/[^/]+/statuse?s?/([0-9]+)', 'twitter.com/statuse?s?/([0-9]+)' } twitter.doc = [[*Twitter-Link*: Postet Tweet]] end local consumer_key = cred_data.tw_consumer_key local consumer_secret = cred_data.tw_consumer_secret local access_token = cred_data.tw_access_token local access_token_secret = cred_data.tw_access_token_secret local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function twitter:action(msg, config, matches) if not matches[2] then id = matches[1] else id = matches[2] end local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. id.. ".json" local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url) local response = json.decode(response_body) local full_name = response.user.name local user_name = response.user.screen_name if response.user.verified then verified = ' ✅' else verified = '' end local header = '<b>Tweet von '..full_name..'</b> (<a href="https://twitter.com/'..user_name..'">@' ..user_name..'</a>'..verified..'):' local text = response.text -- favorites & retweets if response.retweet_count == 0 then retweets = "" else retweets = response.retweet_count..'x retweeted' end if response.favorite_count == 0 then favorites = "" else favorites = response.favorite_count..'x favorisiert' end if retweets == "" and favorites ~= "" then footer = '<i>'..favorites..'</i>' elseif retweets ~= "" and favorites == "" then footer = '<i>'..retweets..'</i>' elseif retweets ~= "" and favorites ~= "" then footer = '<i>'..retweets..' - '..favorites..'</i>' else footer = "" end -- replace short URLs if response.entities.urls then for k, v in pairs(response.entities.urls) do local short = v.url local long = v.expanded_url local long = long:gsub('%%', '%%%%') text = text:gsub(short, long) end end -- remove images local images = {} local videos = {} if response.entities.media and response.extended_entities.media then for k, v in pairs(response.extended_entities.media) do local url = v.url local pic = v.media_url_https if v.video_info then if not v.video_info.variants[3] then local vid = v.video_info.variants[1].url videos[#videos+1] = vid else local vid = v.video_info.variants[3].url videos[#videos+1] = vid end end text = text:gsub(url, "") images[#images+1] = pic end end -- quoted tweet if response.quoted_status then local quoted_text = response.quoted_status.text local quoted_name = response.quoted_status.user.name local quoted_screen_name = response.quoted_status.user.screen_name if response.quoted_status.user.verified then quoted_verified = ' ✅' else quoted_verified = '' end quote = '<b>Als Antwort auf '..quoted_name..'</b> (<a href="https://twitter.com/'..quoted_screen_name..'">@' ..quoted_screen_name..'</a>'..quoted_verified..'):\n'..quoted_text text = text..'\n\n'..quote..'\n' end -- send the parts utilities.send_reply(msg, header .. "\n" .. text.."\n"..footer, 'HTML') if videos[1] then images = {} end for k, v in pairs(images) do local file = download_to_file(v) utilities.send_photo(msg.chat.id, file, nil, msg.message_id) end for k, v in pairs(videos) do local file = download_to_file(v) utilities.send_video(msg.chat.id, file, nil, msg.message_id) end end return twitter
local twitter = {} function twitter:init(config) if not cred_data.tw_consumer_key then print('Missing config value: tw_consumer_key.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_consumer_secret then print('Missing config value: tw_consumer_secret.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token then print('Missing config value: tw_access_token.') print('twitter.lua will not be enabled.') return elseif not cred_data.tw_access_token_secret then print('Missing config value: tw_access_token_secret.') print('twitter.lua will not be enabled.') return end twitter.triggers = { 'twitter.com/[^/]+/statuse?s?/([0-9]+)', 'twitter.com/statuse?s?/([0-9]+)' } twitter.doc = [[*Twitter-Link*: Postet Tweet]] end local consumer_key = cred_data.tw_consumer_key local consumer_secret = cred_data.tw_consumer_secret local access_token = cred_data.tw_access_token local access_token_secret = cred_data.tw_access_token_secret local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function twitter:action(msg, config, matches) if not matches[2] then id = matches[1] else id = matches[2] end local twitter_url = "https://api.twitter.com/1.1/statuses/show/" .. id.. ".json" local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url) local response = json.decode(response_body) local full_name = response.user.name local user_name = response.user.screen_name if response.user.verified then verified = ' ✅' else verified = '' end local header = '<b>Tweet von '..full_name..'</b> (<a href="https://twitter.com/'..user_name..'">@' ..user_name..'</a>'..verified..'):' local text = response.text -- favorites & retweets if response.retweet_count == 0 then retweets = "" else retweets = response.retweet_count..'x retweeted' end if response.favorite_count == 0 then favorites = "" else favorites = response.favorite_count..'x favorisiert' end if retweets == "" and favorites ~= "" then footer = '<i>'..favorites..'</i>' elseif retweets ~= "" and favorites == "" then footer = '<i>'..retweets..'</i>' elseif retweets ~= "" and favorites ~= "" then footer = '<i>'..retweets..' - '..favorites..'</i>' else footer = "" end -- replace short URLs if response.entities.urls then for k, v in pairs(response.entities.urls) do local short = v.url local long = v.expanded_url local long = long:gsub('%%', '%%%%') text = text:gsub(short, long) end end -- remove images local images = {} local videos = {} if response.entities.media and response.extended_entities.media then for k, v in pairs(response.extended_entities.media) do local url = v.url if v.video_info then if v.video_info.variants[#v.video_info.variants].bitrate == 2176000 then local vid = v.video_info.variants[#v.video_info.variants].url videos[#videos+1] = vid else local vid = v.video_info.variants[1].url videos[#videos+1] = vid end else images[#images+1] = v.media_url_https end text = text:gsub(url, '') end end -- quoted tweet if response.quoted_status then local quoted_text = response.quoted_status.text local quoted_name = response.quoted_status.user.name local quoted_screen_name = response.quoted_status.user.screen_name if response.quoted_status.user.verified then quoted_verified = ' ✅' else quoted_verified = '' end quote = '<b>Als Antwort auf '..quoted_name..'</b> (<a href="https://twitter.com/'..quoted_screen_name..'">@' ..quoted_screen_name..'</a>'..quoted_verified..'):\n'..quoted_text text = text..'\n\n'..quote..'\n' end -- send the parts utilities.send_reply(msg, header .. "\n" .. utilities.trim(text).."\n"..footer, 'HTML') for k, v in pairs(images) do local file = download_to_file(v) utilities.send_photo(msg.chat.id, file, nil, msg.message_id) end for k, v in pairs(videos) do local file = download_to_file(v) utilities.send_video(msg.chat.id, file, nil, msg.message_id) end end return twitter
Twitter: Fixe Videos, da Twitter WebM nicht mehr ausliefert
Twitter: Fixe Videos, da Twitter WebM nicht mehr ausliefert
Lua
agpl-3.0
Brawl345/Brawlbot-v2
954b2e90d4ab5958a216d09ef498cc2a968d1c3f
config/nvim/lua/init/null_ls.lua
config/nvim/lua/init/null_ls.lua
require("null-ls").setup({ sources = { require("null-ls").builtins.completion.spell, require("null-ls").builtins.diagnostics.eslint, require("null-ls").builtins.formatting.black, require("null-ls").builtins.formatting.clang_format, require("null-ls").builtins.formatting.elm_format, require("null-ls").builtins.formatting.eslint, require("null-ls").builtins.formatting.pg_format, require("null-ls").builtins.formatting.prettier, require("null-ls").builtins.formatting.rubocop, require("null-ls").builtins.formatting.shfmt, require("null-ls").builtins.formatting.stylua, require("null-ls").builtins.formatting.taplo, require("null-ls").builtins.formatting.terraform_fmt, }, })
require("null-ls").setup({ sources = { require("null-ls").builtins.completion.spell, require("null-ls").builtins.diagnostics.eslint, require("null-ls").builtins.formatting.black, require("null-ls").builtins.formatting.clang_format, require("null-ls").builtins.formatting.elm_format, require("null-ls").builtins.formatting.eslint, require("null-ls").builtins.formatting.pg_format, require("null-ls").builtins.formatting.prettier, require("null-ls").builtins.formatting.rubocop, require("null-ls").builtins.formatting.shfmt.with({ extra_args = { "-i", "2" } }), require("null-ls").builtins.formatting.stylua, require("null-ls").builtins.formatting.taplo, require("null-ls").builtins.formatting.terraform_fmt, }, })
Fix shfmt configuration
Fix shfmt configuration
Lua
unlicense
raviqqe/dotfiles
8d3f279d9b95b69eaf7936f940e0cd5b5cd8786f
deps/ustring.lua
deps/ustring.lua
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[lit-meta name = "luvit/ustring" version = "2.0.0" homepage = "https://github.com/luvit/luvit/blob/master/deps/ustring.lua" description = "A light-weight UTF-8 module in pure lua(jit)." tags = {"ustring", "utf8", "utf-8", "unicode"} license = "Apache 2" ]] local ustring = {} local tostring = tostring local _meta = {} local strsub = string.sub local strbyte = string.byte local band = bit.band local rshift = bit.rshift local function chlen(byte) if rshift(byte,7) == 0x00 then return 1 elseif rshift(byte,5) == 0x06 then return 2 elseif rshift(byte,4) == 0x0E then return 3 elseif rshift(byte,3) == 0x1E then return 4 else -- RFC 3629 (2003.11) says UTF-8 don't have characters larger than 4 bytes. -- They will not be processed although they may be appeared in some old systems. return 0 end end ustring.chlen = chlen function ustring.new(str,allowInvaild) local str = str and tostring(str) or "" local ustr = {} local index = 1; local append = 0; for i = 1,#str do repeat local char = strsub(str,i,i) local byte = strbyte(char) if append ~= 0 then if not allowInvaild then if rshift(byte,6) ~= 0x02 then error("Invaild UTF-8 sequence at "..i) end end ustr[index] = ustr[index] .. char append = append - 1 if append == 0 then index = index + 1 end break end local charLen = chlen(byte) if charLen == 0 and not allowInvaild then error("Invaild UTF-8 sequence at "..tostring(i)..",byte:"..tostring(byte)) end ustr[index] = char if charLen == 1 then index = index + 1 end append = append + charLen - 1 until true end setmetatable(ustr,_meta) return ustr end function ustring.copy(ustr) local u = ustring.new() for i = 1,#ustr do u[i] = ustr[i] end return u end function ustring.uindex(ustr,rawindex,initrawindex,initindex) -- get the index of the UTF-8 character from a raw string index -- return `nil` when rawindex is invaild -- the last 2 arguments is used for speed up local index = (initindex or 1) rawindex = rawindex - (initrawindex or 1) + 1 repeat local byte = ustr[index] if byte == nil then return nil end local len = #byte index = index + 1 rawindex = rawindex - len until rawindex <= 0 return index - 1 end local gsub = string.gsub local find = string.find local format = string.format local gmatch = string.gmatch local match = string.match local lower = string.lower local upper = string.upper ustring.len = rawlen function ustring.gsub(ustr,pattern,repl,n) return ustring.new(gsub(tostring(ustr),tostring(pattern),tostring(repl),n)) end function ustring.sub(ustr,i,j) local u = ustring.new() j = j or -1 local len = #ustr if i < 0 then i = len + i + 1 end if j < 0 then j = len + j + 1 end for ii = i,math.min(j,len) do u[#u + 1] = ustr[ii] end return u end function ustring.find(ustr,pattern,init,plain) local first,last = find(tostring(ustr),tostring(pattern),init,plain) if first == nil then return nil end local ufirst = ustring.uindex(ustr,first) local ulast = ustring.uindex(ustr,last,first,ufirst) return ufirst,ulast end function ustring.format(formatstring,...) return ustring.new(format(tostring(formatstring),...)) end function ustring.gmatch(ustr,pattern) return gmatch(tostring(ustr),pattern) end function ustring.match(ustr,pattern,init) return match(tostring(ustr),tostring(pattern),init) end function ustring.lower(ustr) local u = ustring.copy(ustr) for i = 1,#u do u[i] = lower(u[i]) end return u end function ustring.upper(ustr) local u = ustring.copy(ustr) for i = 1,#u do u[i] = upper(u[i]) end return u end function ustring.rep(ustr,n) local u = ustring.new() for i = 1,n do for ii = 1,#ustr do u[#u + 1] = ustr[ii] end end return u end function ustring.reverse(ustr) local u = ustring.copy(ustr) local len = #ustr; for i = 1,len do u[i] = ustr[len - i + 1] end return u end _meta.__index = ustring function _meta.__eq(ustr1,ustr2) local len1 = #ustr1 local len2 = #ustr2 if len1 ~= len2 then return false end for i = 1,len1 do if ustr1[i] ~= ustr2[i] then return false end end return true end function _meta.__tostring(self) return tostring(table.concat(self)) end function _meta.__concat(ustr1,ustr2) local u = ustring.copy(ustr1) for i = 1,#ustr2 do u[#u + 1] = ustr2[i] end return u end _meta.__len = ustring.len return ustring
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[lit-meta name = "luvit/ustring" version = "2.0.0" homepage = "https://github.com/luvit/luvit/blob/master/deps/ustring.lua" description = "A light-weight UTF-8 module in pure lua(jit)." tags = {"ustring", "utf8", "utf-8", "unicode"} license = "Apache 2" ]] local ustring = {} local tostring = tostring local _meta = {} local strsub = string.sub local strbyte = string.byte local band = bit.band local rshift = bit.rshift local function chlen(byte) if rshift(byte,7) == 0x00 then return 1 elseif rshift(byte,5) == 0x06 then return 2 elseif rshift(byte,4) == 0x0E then return 3 elseif rshift(byte,3) == 0x1E then return 4 else -- RFC 3629 (2003.11) says UTF-8 don't have characters larger than 4 bytes. -- They will not be processed although they may be appeared in some old systems. return 0 end end ustring.chlen = chlen function ustring.new(str,allowInvaild) local str = str and tostring(str) or "" local ustr = {} local index = 1; local append = 0; for i = 1,#str do repeat local char = strsub(str,i,i) local byte = strbyte(char) if append ~= 0 then if not allowInvaild then if rshift(byte,6) ~= 0x02 then error("Invaild UTF-8 sequence at "..i) end end ustr[index] = ustr[index] .. char append = append - 1 if append == 0 then index = index + 1 end break end local charLen = chlen(byte) if charLen == 0 and not allowInvaild then error("Invaild UTF-8 sequence at "..tostring(i)..",byte:"..tostring(byte)) end ustr[index] = char if charLen == 1 then index = index + 1 end append = append + charLen - 1 until true end setmetatable(ustr,_meta) return ustr end function ustring.copy(ustr) local u = ustring.new() for i = 1,#ustr do u[i] = ustr[i] end return u end function ustring.index2uindex(ustr,rawindex,initrawindex,initindex) -- convert a raw index into the index of a UTF-8 -- return `nil` if uindex is invaild -- the last 2 arguments are optional and used for better performance (only if rawindex isn't negative) if rawindex < 0 then local index = 1 repeat local uchar = ustr[index] if uchar == nil then return nil end local len = #uchar index = index + 1 rawindex = rawindex + len until rawindex >= 0 return -(index - 1) else rawindex = rawindex - (initrawindex or 1) + 1 local index = (initindex or 1) repeat local uchar = ustr[index] if uchar == nil then return nil end local len = #uchar index = index + 1 rawindex = rawindex - len until rawindex <= 0 return index - 1 end end function ustring.uindex2index(ustr,uindex,initrawindex,inituindex) -- convert the index of a UIF-8 char into a raw index -- return `nil` if rawindex is invaild -- the last 2 arguments are optional and used for better performance (only if uindex isn't negative) local ulen = #ustr if uindex < 0 then local index = 0 for i = ulen,ulen + uindex + 1,-1 do index = index + #ustr[i] end return -index else local index = (initindex or 1) inituindex = inituindex or 1 for i = inituindex,uindex - 1 do index = index + #ustr[i] end return index end end local gsub = string.gsub local find = string.find local format = string.format local gmatch = string.gmatch local match = string.match local lower = string.lower local upper = string.upper ustring.len = rawlen function ustring.gsub(ustr,pattern,repl,n) return ustring.new(gsub(tostring(ustr),tostring(pattern),tostring(repl),n)) end function ustring.sub(ustr,i,j) local u = ustring.new() j = j or -1 local len = #ustr if i < 0 then i = len + i + 1 end if j < 0 then j = len + j + 1 end for ii = i,math.min(j,len) do u[#u + 1] = ustr[ii] end return u end function ustring.find(ustr,pattern,init,plain) local first,last = find(tostring(ustr),tostring(pattern),ustring.uindex2index(ustr,init),plain) if first == nil then return nil end local ufirst = ustring.index2uindex(ustr,first) local ulast = ustring.index2uindex(ustr,last,first,ufirst) return ufirst,ulast end function ustring.format(formatstring,...) return ustring.new(format(tostring(formatstring),...)) end function ustring.gmatch(ustr,pattern) return gmatch(tostring(ustr),pattern) end function ustring.match(ustr,pattern,init) return match(tostring(ustr),tostring(pattern),ustring.uindex2index(ustr,init)) end function ustring.lower(ustr) local u = ustring.copy(ustr) for i = 1,#u do u[i] = lower(u[i]) end return u end function ustring.upper(ustr) local u = ustring.copy(ustr) for i = 1,#u do u[i] = upper(u[i]) end return u end function ustring.rep(ustr,n) local u = ustring.new() for i = 1,n do for ii = 1,#ustr do u[#u + 1] = ustr[ii] end end return u end function ustring.reverse(ustr) local u = ustring.copy(ustr) local len = #ustr; for i = 1,len do u[i] = ustr[len - i + 1] end return u end _meta.__index = ustring function _meta.__eq(ustr1,ustr2) local len1 = #ustr1 local len2 = #ustr2 if len1 ~= len2 then return false end for i = 1,len1 do if ustr1[i] ~= ustr2[i] then return false end end return true end function _meta.__tostring(self) return tostring(table.concat(self)) end function _meta.__concat(ustr1,ustr2) local u = ustring.copy(ustr1) for i = 1,#ustr2 do u[#u + 1] = ustr2[i] end return u end _meta.__len = ustring.len return ustring
fix ustring.find's behavior when used `init`
fix ustring.find's behavior when used `init`
Lua
apache-2.0
zhaozg/luvit,zhaozg/luvit,luvit/luvit,luvit/luvit
7f99ba0158707aaf0507fad4257756b36584942e
src/romdisk/system/lib/org/xboot/timer/timer.lua
src/romdisk/system/lib/org/xboot/timer/timer.lua
local class = require("org.xboot.lang.class") --- -- The 'timer' class is used to execute a code at specified intervals. -- -- @module timer local M = class() local __timer_list = {} --- -- Creates a new 'timer' object with the specified delay and iteration. -- -- @function [parent=#timer] new -- @param delay (number) The delay in seconds -- @param iteration (number) The number of times listener is to be invoked. pass 0 if you want it to loop forever. -- @param listener (function) The listener to invoke after the delay. -- @param data (optional) An optional data parameter that is passed to the listener function. -- @return New 'timer' object. function M:init(delay, iteration, listener, data) self.__delay = delay or 1 self.__iteration = iteration or 1 self.__listener = listener self.__data = data or nil self.__time = 0 self.__count = 0 self.__running = true table.insert(__timer_list, self) end --- -- Returns the current running status of timer. -- -- @function [parent=#timer] isrunning -- @param self -- @return 'true' if the timer is running, 'false' otherwise. function M:isrunning() return self.__running end --- -- Resumes the timer that was paused. -- -- @function [parent=#timer] resume -- @param self function M:resume() self.__running = true end --- -- Pauses the timer that was resumed. -- -- @function [parent=#timer] pause -- @param self function M:pause() self.__running = false end --- -- Resets and pauses the timer. -- -- @function [parent=#timer] reset -- @param self function M:reset() self.__time = 0 self.__count = 0 self.__running = false end --- -- Modify the timer parameters. -- -- @function [parent=#timer] modify -- @param self -- @param delay (number) The delay in seconds, nil for no changed. -- @param iteration (number) The number of times listener is to be invoked, nil for no changed. function M:modify(delay, iteration) self.__delay = delay or self.__delay self.__iteration = iteration or self.__iteration end --- -- Cancels the timer operation initiated with timer:new(). -- -- @function [parent=#timer] cancel -- @param self function M:cancel() for i, v in ipairs(__timer_list) do if v.__delay == self.__delay and v.__iteration == self.__iteration and v.__listener == self.__listener and v.__data == self.__data then table.remove(__timer_list, i) break end end end --- -- Schedule all timers in list. -- -- @function [parent=#timer] schedule -- @param self -- @param delta (number) The time interval in seconds. function M:schedule(delta) for i, v in ipairs(__timer_list) do if v.__running then v.__time = v.__time + delta if v.__time > v.__delay then v.__count = v.__count + 1 v.__listener(v, {time = v.__time, count = v.__count, data = v.__data}) if v.__iteration ~= 0 and v.__count >= v.__iteration then v.__running = false end v.__time = 0 end end end end return M
local class = require("org.xboot.lang.class") --- -- The 'timer' class is used to execute a code at specified intervals. -- -- @module timer local M = class() local __timer_list = {} --- -- Creates a new 'timer' object with the specified delay and iteration. -- -- @function [parent=#timer] new -- @param delay (number) The delay in seconds -- @param iteration (number) The number of times listener is to be invoked. pass 0 if you want it to loop forever. -- @param listener (function) The listener to invoke after the delay. -- @param data (optional) An optional data parameter that is passed to the listener function. -- @return New 'timer' object. function M:init(delay, iteration, listener, data) self.__delay = delay or 1 self.__iteration = iteration or 1 self.__listener = listener self.__data = data or nil self.__time = 0 self.__count = 0 self.__running = true table.insert(__timer_list, self) end --- -- Returns the current running status of timer. -- -- @function [parent=#timer] isrunning -- @param self -- @return 'true' if the timer is running, 'false' otherwise. function M:isrunning() return self.__running end --- -- Resumes the timer that was paused. -- -- @function [parent=#timer] resume -- @param self function M:resume() self.__running = true end --- -- Pauses the timer that was resumed. -- -- @function [parent=#timer] pause -- @param self function M:pause() self.__running = false end --- -- Cancels the timer operation initiated with timer:new(). -- -- @function [parent=#timer] cancel -- @param self -- @return the number of iterations. function M:cancel() for i, v in ipairs(__timer_list) do if v.__delay == self.__delay and v.__iteration == self.__iteration and v.__listener == self.__listener and v.__data == self.__data then v.__running = false table.remove(__timer_list, i) return v.__count end end end --- -- Schedule all timers in list. -- -- @function [parent=#timer] schedule -- @param self -- @param delta (number) The time interval in seconds. function M:schedule(delta) for i, v in ipairs(__timer_list) do if v.__running then v.__time = v.__time + delta if v.__time > v.__delay then v.__count = v.__count + 1 v.__listener(v, {time = v.__time, count = v.__count, data = v.__data}) v.__time = 0 if v.__iteration ~= 0 and v.__count >= v.__iteration then v.__running = false table.remove(__timer_list, i) end end end end end return M
fix timer.lua
fix timer.lua
Lua
mit
xboot/xboot,xboot/xboot
cedc0b997fe39751726632622f52ccc547e85395
L1HingeEmbeddingCriterion.lua
L1HingeEmbeddingCriterion.lua
local L1HingeEmbeddingCriterion, parent = torch.class('nn.L1HingeEmbeddingCriterion', 'nn.Criterion') function L1HingeEmbeddingCriterion:__init(margin) parent.__init(self) margin = margin or 1 self.margin = margin self.gradInput = {torch.Tensor(), torch.Tensor()} end function L1HingeEmbeddingCriterion:updateOutput(input,y) self.output=input[1]:dist(input[2],1); if y == -1 then self.output = math.max(0,self.margin - self.output); end return self.output end local function mathsign(t) if t>0 then return 1; end if t<0 then return -1; end return 2*torch.random(2)-3; end function L1HingeEmbeddingCriterion:updateGradInput(input, y) self.gradInput[1]:resizeAs(input[1]) self.gradInput[2]:resizeAs(input[2]) self.gradInput[1]:copy(input[1]) self.gradInput[1]:add(-1, input[2]) local dist = self.gradInput[1]:norm(1); self.gradInput[1]:apply(mathsign) -- L1 gradient if y == -1 then -- just to avoid a mul by 1 if dist > self.margin then self.gradInput[1]:zero() else self.gradInput[1]:mul(-1) end end self.gradInput[2]:zero():add(-1, self.gradInput[1]) return self.gradInput end
local L1HingeEmbeddingCriterion, parent = torch.class('nn.L1HingeEmbeddingCriterion', 'nn.Criterion') function L1HingeEmbeddingCriterion:__init(margin) parent.__init(self) margin = margin or 1 self.margin = margin self.gradInput = {torch.Tensor(), torch.Tensor()} end function L1HingeEmbeddingCriterion:updateOutput(input,y) self.output=input[1]:dist(input[2],1); if y == -1 then self.output = math.max(0,self.margin - self.output); end return self.output end local function mathsign(t) if t>0 then return 1; end if t<0 then return -1; end return 2*torch.random(2)-3; end function L1HingeEmbeddingCriterion:updateGradInput(input, y) self.gradInput[1]:resizeAs(input[1]) self.gradInput[2]:resizeAs(input[2]) self.gradInput[1]:copy(input[1]) self.gradInput[1]:add(-1, input[2]) local dist = self.gradInput[1]:norm(1); self.gradInput[1]:apply(mathsign) -- L1 gradient if y == -1 then -- just to avoid a mul by 1 if dist > self.margin then self.gradInput[1]:zero() else self.gradInput[1]:mul(-1) end end self.gradInput[2]:zero():add(-1, self.gradInput[1]) return self.gradInput end function L1HingeEmbeddingCriterion:type(type) self.gradInput[1] = self.gradInput[1]:type(type) self.gradInput[2] = self.gradInput[2]:type(type) return parent.type(self, type) end
type fix for L1HingeEmbeddingCriterion
type fix for L1HingeEmbeddingCriterion
Lua
bsd-3-clause
abeschneider/nn,jzbontar/nn,davidBelanger/nn,eriche2016/nn,caldweln/nn,colesbury/nn,boknilev/nn,mlosch/nn,vgire/nn,zhangxiangxiao/nn,nicholas-leonard/nn,PierrotLC/nn,bartvm/nn,fmassa/nn,apaszke/nn,kmul00/nn,diz-vara/nn,EnjoyHacking/nn,szagoruyko/nn,PraveerSINGH/nn,jhjin/nn,clementfarabet/nn,andreaskoepf/nn,Aysegul/nn,jonathantompson/nn,mys007/nn,hughperkins/nn,LinusU/nn,zchengquan/nn,ivendrov/nn,lvdmaaten/nn,Djabbz/nn,aaiijmrtt/nn,noa/nn,Moodstocks/nn,witgo/nn,rotmanmi/nn,eulerreich/nn,Jeffyrao/nn,sbodenstein/nn,GregSatre/nn,ominux/nn,karpathy/nn,joeyhng/nn,elbamos/nn,douwekiela/nn,sagarwaghmare69/nn,xianjiec/nn,lukasc-ch/nn,hery/nn,forty-2/nn,adamlerer/nn
7205967d8963fc9ac0720376f5f419d9f4617816
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> 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.tools.webadmin") m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with a fixed hostname while having a dynamically changing IP-Address.")) s = m:section(TypedSection, "service", "") s.addremove = true s:option(Flag, "enabled", translate("enable")) svc = s:option(ListValue, "service_name", translate("Service")) svc.rmempty = true svc:value("") svc:value("dyndns.org") svc:value("changeip.com") svc:value("zoneedit.com") svc:value("no-ip.com") svc:value("freedns.afraid.org") s:option(Value, "domain", translate("Hostname")).rmempty = true s:option(Value, "username", translate("Username")).rmempty = true pw = s:option(Value, "password", translate("Password")) pw.rmempty = true pw.password = true src = s:option(ListValue, "ip_source") src:value("network", translate("Network")) src:value("interface", translate("Interface")) src:value("web", "URL") iface = s:option(ListValue, "ip_network", translate("Network")) iface:depends("ip_source", "network") iface.rmempty = true luci.tools.webadmin.cbi_add_networks(iface) iface = s:option(ListValue, "ip_interface", translate("Interface")) iface:depends("ip_source", "interface") iface.rmempty = true for k, v in pairs(luci.sys.net.devices()) do iface:value(v) end web = s:option(Value, "ip_url", "URL") web:depends("ip_source", "web") web.rmempty = true s:option(Value, "update_url").optional = true s:option(Value, "check_interval").default = 10 unit = s:option(ListValue, "check_unit") unit.default = "minutes" unit:value("minutes", "min") unit:value("hours", "h") s:option(Value, "force_interval").default = 72 unit = s:option(ListValue, "force_unit") unit.default = "hours" unit:value("minutes", "min") unit:value("hours", "h") return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> 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.tools.webadmin") m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with a fixed hostname while having a dynamically changing IP-Address.")) s = m:section(TypedSection, "service", "") s.addremove = true s:option(Flag, "enabled", translate("enable")) svc = s:option(ListValue, "service_name", translate("Service")) svc.rmempty = true svc:value("") svc:value("dyndns.org") svc:value("changeip.com") svc:value("zoneedit.com") svc:value("no-ip.com") svc:value("freedns.afraid.org") s:option(Value, "domain", translate("Hostname")).rmempty = true s:option(Value, "username", translate("Username")).rmempty = true pw = s:option(Value, "password", translate("Password")) pw.rmempty = true pw.password = true src = s:option(ListValue, "ip_source", translate("Source of IP-Address")) src:value("network", translate("Network")) src:value("interface", translate("Interface")) src:value("web", "URL") iface = s:option(ListValue, "ip_network", translate("Network")) iface:depends("ip_source", "network") iface.rmempty = true luci.tools.webadmin.cbi_add_networks(iface) iface = s:option(ListValue, "ip_interface", translate("Interface")) iface:depends("ip_source", "interface") iface.rmempty = true for k, v in pairs(luci.sys.net.devices()) do iface:value(v) end web = s:option(Value, "ip_url", "URL") web:depends("ip_source", "web") web.rmempty = true s:option(Value, "update_url", translate("Custom Update-URL")).optional = true s:option(Value, "check_interval", translate("Check for changed IP every")).default = 10 unit = s:option(ListValue, "check_unit", translate("Check-Time unit")) unit.default = "minutes" unit:value("minutes", "min") unit:value("hours", "h") s:option(Value, "force_interval", translate("Force update every")).default = 72 unit = s:option(ListValue, "force_unit", translate("Force-Time unit")) unit.default = "hours" unit:value("minutes", "min") unit:value("hours", "h") return m
applications/luci-ddns: fix dyndns config page
applications/luci-ddns: fix dyndns config page
Lua
apache-2.0
deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci
e9131c266bf2ffedfa0e272afd1b365863374a55
spotify-widget/spotify.lua
spotify-widget/spotify.lua
------------------------------------------------- -- Spotify Widget for Awesome Window Manager -- Shows currently playing song on Spotify for Linux client -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/spotify-widget -- @author Pavel Makhov -- @copyright 2018 Pavel Makhov ------------------------------------------------- local awful = require("awful") local wibox = require("wibox") local watch = require("awful.widget.watch") local GET_SPOTIFY_STATUS_CMD = 'sp status' local GET_CURRENT_SONG_CMD = 'sp current-oneline' local spotify_widget = {} local function worker(args) local args = args or {} local play_icon = args.play_icon or '/usr/share/icons/Arc/actions/24/player_play.png' local pause_icon = args.pause_icon or '/usr/share/icons/Arc/actions/24/player_pause.png' local font = args.font or 'Play 9' spotify_widget = wibox.widget { { id = "icon", widget = wibox.widget.imagebox, }, { id = 'current_song', widget = wibox.widget.textbox, font = font }, layout = wibox.layout.align.horizontal, set_status = function(self, is_playing) self.icon.image = (is_playing and play_icon or pause_icon) end, set_text = function(self, path) self.current_song.markup = path end, } local update_widget_icon = function(widget, stdout, _, _, _) stdout = string.gsub(stdout, "\n", "") widget:set_status(stdout == 'Playing' and true or false) end local update_widget_text = function(widget, stdout, _, _, _) if string.find(stdout, 'Error: Spotify is not running.') ~= nil then widget:set_text('') widget:set_visible(false) else widget:set_text(stdout) widget:set_visible(true) end end watch(GET_SPOTIFY_STATUS_CMD, 1, update_widget_icon, spotify_widget) watch(GET_CURRENT_SONG_CMD, 1, update_widget_text, spotify_widget) --- Adds mouse controls to the widget: -- - left click - play/pause -- - scroll up - play next song -- - scroll down - play previous song spotify_widget:connect_signal("button::press", function(_, _, _, button) if (button == 1) then awful.spawn("sp play", false) -- left click elseif (button == 4) then awful.spawn("sp next", false) -- scroll up elseif (button == 5) then awful.spawn("sp prev", false) -- scroll down end awful.spawn.easy_async(GET_SPOTIFY_STATUS_CMD, function(stdout, stderr, exitreason, exitcode) update_widget_icon(spotify_widget, stdout, stderr, exitreason, exitcode) end) end) return spotify_widget end return setmetatable(spotify_widget, { __call = function(_, ...) return worker(...) end })
------------------------------------------------- -- Spotify Widget for Awesome Window Manager -- Shows currently playing song on Spotify for Linux client -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/spotify-widget -- @author Pavel Makhov -- @copyright 2018 Pavel Makhov ------------------------------------------------- local awful = require("awful") local wibox = require("wibox") local watch = require("awful.widget.watch") local GET_SPOTIFY_STATUS_CMD = 'sp status' local GET_CURRENT_SONG_CMD = 'sp current-oneline' local spotify_widget = {} local function worker(args) local args = args or {} local play_icon = args.play_icon or '/usr/share/icons/Arc/actions/24/player_play.png' local pause_icon = args.pause_icon or '/usr/share/icons/Arc/actions/24/player_pause.png' local font = args.font or 'Play 9' spotify_widget = wibox.widget { { id = "icon", widget = wibox.widget.imagebox, }, { id = 'current_song', widget = wibox.widget.textbox, font = font }, layout = wibox.layout.align.horizontal, set_status = function(self, is_playing) self.icon.image = (is_playing and play_icon or pause_icon) end, set_text = function(self, path) self.current_song.markup = path end, } local update_widget_icon = function(widget, stdout, _, _, _) stdout = string.gsub(stdout, "\n", "") widget:set_status(stdout == 'Playing' and true or false) end local update_widget_text = function(widget, stdout, _, _, _) local escaped = string.gsub(stdout, "&", '&amp;') if string.find(stdout, 'Error: Spotify is not running.') ~= nil then widget:set_text('') widget:set_visible(false) else widget:set_text(escaped) widget:set_visible(true) end end watch(GET_SPOTIFY_STATUS_CMD, 1, update_widget_icon, spotify_widget) watch(GET_CURRENT_SONG_CMD, 1, update_widget_text, spotify_widget) --- Adds mouse controls to the widget: -- - left click - play/pause -- - scroll up - play next song -- - scroll down - play previous song spotify_widget:connect_signal("button::press", function(_, _, _, button) if (button == 1) then awful.spawn("sp play", false) -- left click elseif (button == 4) then awful.spawn("sp next", false) -- scroll up elseif (button == 5) then awful.spawn("sp prev", false) -- scroll down end awful.spawn.easy_async(GET_SPOTIFY_STATUS_CMD, function(stdout, stderr, exitreason, exitcode) update_widget_icon(spotify_widget, stdout, stderr, exitreason, exitcode) end) end) return spotify_widget end return setmetatable(spotify_widget, { __call = function(_, ...) return worker(...) end })
escape ampersand, fix #136
escape ampersand, fix #136
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
fd27aef3b1e5bce2413dcae133254c9a37b731aa
lua/entities/gmod_wire_expression2/core/selfaware.lua
lua/entities/gmod_wire_expression2/core/selfaware.lua
/******************************************************************************\ Selfaware support \******************************************************************************/ __e2setcost(1) -- temporary e2function entity entity() return self.entity end e2function entity owner() return self.player end __e2setcost(nil) -- temporary e2function void selfDestruct() self.entity:Remove() end e2function void selfDestructAll() for k,v in pairs(constraint.GetAllConstrainedEntities(self.entity)) do if(getOwner(self,v)==self.player) then v:Remove() end end //constraint.RemoveAll(self.entity) self.entity:Remove() end /******************************************************************************/ -- i/o functions __e2setcost(10) -- Returns an array of all entities wired to the output e2function array ioOutputEntities( string output ) local ret = {} if (self.entity.Outputs[output]) then local tbl = self.entity.Outputs[output].Connected for i=1,#tbl do if (IsValid(tbl[i].Entity)) then ret[#ret+1] = tbl[i].Entity end end self.prf = self.prf + #ret end return ret end -- Returns the entity the input is wired to e2function entity ioInputEntity( string input ) if (self.entity.Inputs[input] and self.entity.Inputs[input].Src and IsValid(self.entity.Inputs[input].Src)) then return self.entity.Inputs[input].Src end end local function setOutput( self, args, Type ) local op1, op2 = args[2], args[3] local rv1, rv2 = op1[1](self,op1), op2[1](self,op2) if (self.entity.Outputs[rv1] and self.entity.Outputs[rv1].Type == Type) then self.GlobalScope[rv1] = rv2 self.GlobalScope.vclk[rv1] = true end end local function getInput( self, args, default, Type ) local op1 = args[2] local rv1 = op1[1](self,op1) if istable(default) then default = table.Copy(default) end if (self.entity.Inputs[rv1] and self.entity.Inputs[rv1].Type == Type) then return self.GlobalScope[rv1] or default end return default end local excluded_types = { xgt = true, } local function upperfirst( word ) return word:Left(1):upper() .. word:Right(-2):lower() end __e2setcost(5) registerCallback("postinit",function() for k,v in pairs( wire_expression_types ) do local short = v[1] if (!excluded_types[short]) then registerFunction("ioSetOutput","s"..short,""..short,function(self,args) return setOutput(self,args,k) end) registerFunction("ioGetInput"..upperfirst(k == "NORMAL" and "NUMBER" or k),"s",short,function(self,args) return getInput(self,args,v[2],k) end) end end end) /******************************************************************************/ -- Name functions -- Set the name of the E2 itself e2function void setName( string name ) local e = self.entity if( #name > 12000 ) then name = string.sub( name, 1, 12000 ) end if (e.name == name) then return end if (name == "generic" or name == "") then name = "generic" e.WireDebugName = "Expression 2" else e.WireDebugName = "E2 - " .. name end e.name = name e:SetNWString( "name", e.name ) e:SetOverlayText(name) end -- Get the name of another E2 e2function string entity:getName() if IsValid(this) and this.GetGateName then return this:GetGateName() or "" end return "" end /******************************************************************************/ registerCallback("construct", function(self) self.data.changed = {} end) __e2setcost(1) -- This is the prototype for everything that can be compared using the == operator e2function number changed(value) local chg = self.data.changed if value == chg[args] then return 0 end chg[args] = value return 1 end -- vectors can be of gmod type Vector, so we need to treat them separately e2function number changed(vector value) local chg = self.data.changed local this_chg = chg[args] if not this_chg then chg[args] = value return 1 end if this_chg and value[1] == this_chg[1] and value[2] == this_chg[2] and value[3] == this_chg[3] then return 0 end chg[args] = value return 1 end -- This is the prototype for all table types. e2function number changed(angle value) local chg = self.data.changed local this_chg = chg[args] if not this_chg then chg[args] = value return 1 end for i,v in pairs(value) do if v ~= this_chg[i] then chg[args] = value return 1 end end return 0 end local excluded_types = { n = true, v = true, a = true, r = true, t = true, } local comparable_types = { s = true, e = true, xwl = true, b = true, } registerCallback("postinit", function() -- generate this function for all types for typeid,_ in pairs(wire_expression_types2) do if not excluded_types[typeid] then if comparable_types[typeid] then registerFunction("changed", typeid, "n", e2_changed_n) else registerFunction("changed", typeid, "n", e2_changed_a) end end end end) /******************************************************************************/ __e2setcost( 5 ) local getHash = E2Lib.getHash e2function number hash() return getHash( self, self.entity.original ) end e2function number hashNoComments() return getHash( self, self.entity.buffer ) end e2function number hash( string str ) return getHash( self, str ) end
/******************************************************************************\ Selfaware support \******************************************************************************/ __e2setcost(1) -- temporary e2function entity entity() return self.entity end e2function entity owner() return self.player end __e2setcost(nil) -- temporary e2function void selfDestruct() self.entity:Remove() end e2function void selfDestructAll() for k,v in pairs(constraint.GetAllConstrainedEntities(self.entity)) do if(getOwner(self,v)==self.player) then v:Remove() end end //constraint.RemoveAll(self.entity) self.entity:Remove() end /******************************************************************************/ -- i/o functions __e2setcost(10) -- Returns an array of all entities wired to the output e2function array ioOutputEntities( string output ) local ret = {} if (self.entity.Outputs[output]) then local tbl = self.entity.Outputs[output].Connected for i=1,#tbl do if (IsValid(tbl[i].Entity)) then ret[#ret+1] = tbl[i].Entity end end self.prf = self.prf + #ret end return ret end -- Returns the entity the input is wired to e2function entity ioInputEntity( string input ) if (self.entity.Inputs[input] and self.entity.Inputs[input].Src and IsValid(self.entity.Inputs[input].Src)) then return self.entity.Inputs[input].Src end end local function setOutput( self, args, Type ) local op1, op2 = args[2], args[3] local rv1, rv2 = op1[1](self,op1), op2[1](self,op2) if (self.entity.Outputs[rv1] and self.entity.Outputs[rv1].Type == Type) then self.GlobalScope[rv1] = rv2 self.GlobalScope.vclk[rv1] = true end end local function getInput( self, args, default, Type ) local op1 = args[2] local rv1 = op1[1](self,op1) if istable(default) then default = table.Copy(default) end if (self.entity.Inputs[rv1] and self.entity.Inputs[rv1].Type == Type) then return self.GlobalScope[rv1] or default end return default end local excluded_types = { xgt = true, } local function upperfirst( word ) return word:Left(1):upper() .. word:Right(-2):lower() end __e2setcost(5) registerCallback("postinit",function() for k,v in pairs( wire_expression_types ) do local short = v[1] if (!excluded_types[short]) then registerFunction("ioSetOutput","s"..short,""..short,function(self,args) return setOutput(self,args,k) end) registerFunction("ioGetInput"..upperfirst(k == "NORMAL" and "NUMBER" or k),"s",short,function(self,args) return getInput(self,args,v[2],k) end) end end end) /******************************************************************************/ -- Name functions -- Set the name of the E2 itself e2function void setName( string name ) local e = self.entity if( #name > 12000 ) then name = string.sub( name, 1, 12000 ) end if (e.name == name) then return end if (name == "generic" or name == "") then name = "generic" e.WireDebugName = "Expression 2" else e.WireDebugName = "E2 - " .. name end e.name = name e:SetNWString( "name", e.name ) e:SetOverlayText(name) end -- Set the name of a entity (component name if not E2). Thanks CaptainPRICE for idea and basic implementation e2function void entity:setName( string name ) if not ( IsValid(this) and E2Lib.getOwner(this) == self.player ) then return end if this:GetClass() == "gmod_wire_expression2" then if this.name == name then return end if name == "generic" or name == "" then name = "generic" this.WireDebugName = "Expression 2" else this.WireDebugName = "E2 - " .. name end this.name = name this:SetNWString( "name", e.name ) this:SetOverlayText(name) else if ( this.wireName and this.wireName == name ) or string.find(name, "[\n\r\"]") ~= nil then return end this.wireName = name this:SetNWString("WireName", name) duplicator.StoreEntityModifier(this, "WireName", { name = name }) end end -- Get the name of another E2 or compatible entity or component name of wiremod components e2function string entity:getName() if not IsValid(this) then return "" end if this.GetGateName then return this:GetGateName() or "" end return ent:GetNWString("WireName", ent.PrintName) or "" end /******************************************************************************/ registerCallback("construct", function(self) self.data.changed = {} end) __e2setcost(1) -- This is the prototype for everything that can be compared using the == operator e2function number changed(value) local chg = self.data.changed if value == chg[args] then return 0 end chg[args] = value return 1 end -- vectors can be of gmod type Vector, so we need to treat them separately e2function number changed(vector value) local chg = self.data.changed local this_chg = chg[args] if not this_chg then chg[args] = value return 1 end if this_chg and value[1] == this_chg[1] and value[2] == this_chg[2] and value[3] == this_chg[3] then return 0 end chg[args] = value return 1 end -- This is the prototype for all table types. e2function number changed(angle value) local chg = self.data.changed local this_chg = chg[args] if not this_chg then chg[args] = value return 1 end for i,v in pairs(value) do if v ~= this_chg[i] then chg[args] = value return 1 end end return 0 end local excluded_types = { n = true, v = true, a = true, r = true, t = true, } local comparable_types = { s = true, e = true, xwl = true, b = true, } registerCallback("postinit", function() -- generate this function for all types for typeid,_ in pairs(wire_expression_types2) do if not excluded_types[typeid] then if comparable_types[typeid] then registerFunction("changed", typeid, "n", e2_changed_n) else registerFunction("changed", typeid, "n", e2_changed_a) end end end end) /******************************************************************************/ __e2setcost( 5 ) local getHash = E2Lib.getHash e2function number hash() return getHash( self, self.entity.original ) end e2function number hashNoComments() return getHash( self, self.entity.buffer ) end e2function number hash( string str ) return getHash( self, str ) end
E2: Add "Namer" functionality (Fixes #1365)
E2: Add "Namer" functionality (Fixes #1365) Fixes: #1365 Much simpler implementation than #1366, although i based the code on that.
Lua
apache-2.0
Grocel/wire,wiremod/wire,garrysmodlua/wire,bigdogmat/wire,thegrb93/wire,sammyt291/wire,dvdvideo1234/wire,NezzKryptic/Wire
66b09eb3bd7ef631a050fbafa8abc36f17accfc5
src/romdisk/application/examples/TestCase.lua
src/romdisk/application/examples/TestCase.lua
local Easing = Easing local M = Class(DisplayObject) function M:init(width, height, cases) self.super:init(width, height) self.width = width or 640 self.height = height or 480 self.cases = cases or {} self.index = 1 if #self.cases > 0 then self.case1 = self.cases[self.index].new(self.width, self.height) self.case2 = nil self:addChild(self.case1) end self.tweening = false self:addEventListener(Event.ENTER_FRAME, self.onEnterFrame) end function M:onEnterFrame(e) if not self.tweening then return end local elapsed = self.watch:elapsed() if elapsed < self.duration then self.transition(elapsed) else self.transition(self.duration) self:removeChild(self.case1) self.case1 = self.case2 self.case2 = nil self.transition = nil self.ease = nil self.watch = nil self.tweening = false collectgarbage() end end function M:select(index, duration, transition, ease) if self.tweening then return end if index < 1 then index = 1; elseif index > #self.cases then index = #self.cases end if index == self.index then return end self.index = index if self.case1 == nil then self.case1 = self.cases[self.index].new(self.width, self.height) self:addChild(self.case) return end self.case2 = self.cases[self.index].new(self.width, self.height) self:addChild(self.case2) self.duration = duration or 1 local transition = transition or "moveFromLeft" local ease = ease or "outBounce" if transition == "moveFromLeft" then self.transition = function(t) local x = self.ease:easing(t) self.case1:setX(x) self.case2:setX(x - self.width) end self.ease = Easing.new(0, self.width, self.duration, ease) elseif transition == "moveFromRight" then self.transition = function(t) local x = self.ease:easing(t) self.case1:setX(-x) self.case2:setX(self.width - x) end self.ease = Easing.new(0, self.width, self.duration, ease) elseif transition == "moveFromTop" then self.transition = function(t) local y = self.ease:easing(t) self.case1:setY(y) self.case2:setY(y - self.height) end self.ease = Easing.new(0, self.height, self.duration, ease) elseif transition == "moveFromBottom" then self.transition = function(t) local y = self.ease:easing(t) self.case1:setY(-y) self.case2:setY(self.height - y) end self.ease = Easing.new(0, self.height, self.duration, ease) elseif transition == "overFromLeft" then self.transition = function(t) local x = self.ease:easing(t) self.case2:setX(x - self.width) end self.ease = Easing.new(0, self.width, self.duration, ease) elseif transition == "overFromRight" then self.transition = function(t) local x = self.ease:easing(t) self.case2:setX(self.width - x) end self.ease = Easing.new(0, self.width, self.duration, ease) elseif transition == "overFromTop" then self.transition = function(t) local y = self.ease:easing(t) self.case2:setY(y - self.height) end self.ease = Easing.new(0, self.height, self.duration, ease) elseif transition == "overFromBottom" then self.transition = function(t) local y = self.ease:easing(t) self.case2:setY(self.height - y) end self.ease = Easing.new(0, self.height, self.duration, ease) end self.watch = Stopwatch.new() self.tweening = true end function M:prev() self:select(self.index - 1, 0.6, "moveFromLeft", "outBounce") end function M:next() self:select(self.index + 1, 0.6, "moveFromRight", "outBounce") end return M
local Easing = Easing local M = Class(DisplayObject) function M:init(width, height, cases) self.super:init(width, height) self.width = width or 640 self.height = height or 480 self.cases = cases or {} self.index = 1 if #self.cases > 0 then self.case1 = self.cases[self.index].new(self.width, self.height) self.case2 = nil self:addChild(self.case1) end self.tweening = false self:addEventListener(Event.ENTER_FRAME, self.onEnterFrame) end function M:onEnterFrame(e) if not self.tweening then return end local elapsed = self.watch:elapsed() if elapsed < self.duration then self.transition(elapsed) else self.transition(self.duration) self:removeChild(self.case1) self.case1 = self.case2 self.case2 = nil self.transition = nil self.ease = nil self.watch = nil self.tweening = false collectgarbage() end end function M:select(index, duration, transition, ease) if self.tweening then return end if index < 1 then index = 1; elseif index > #self.cases then index = #self.cases end if index == self.index then return end self.index = index if self.case1 == nil then self.case1 = self.cases[self.index].new(self.width, self.height) self:addChild(self.case) return end self.case2 = self.cases[self.index].new(self.width, self.height) self:addChild(self.case2) self.duration = duration or 1 local transition = transition or "move-from-left" local ease = ease or "bounce-out" if transition == "move-from-left" then self.transition = function(t) local x = self.ease(t) self.case1:setX(x) self.case2:setX(x - self.width) end self.ease = Easing.new(0, self.width, self.duration, ease) elseif transition == "move-from-right" then self.transition = function(t) local x = self.ease(t) self.case1:setX(-x) self.case2:setX(self.width - x) end self.ease = Easing.new(0, self.width, self.duration, ease) elseif transition == "move-from-top" then self.transition = function(t) local y = self.ease(t) self.case1:setY(y) self.case2:setY(y - self.height) end self.ease = Easing.new(0, self.height, self.duration, ease) elseif transition == "move-from-bottom" then self.transition = function(t) local y = self.ease(t) self.case1:setY(-y) self.case2:setY(self.height - y) end self.ease = Easing.new(0, self.height, self.duration, ease) elseif transition == "over-from-left" then self.transition = function(t) local x = self.ease(t) self.case2:setX(x - self.width) end self.ease = Easing.new(0, self.width, self.duration, ease) elseif transition == "over-from-right" then self.transition = function(t) local x = self.ease(t) self.case2:setX(self.width - x) end self.ease = Easing.new(0, self.width, self.duration, ease) elseif transition == "over-from-top" then self.transition = function(t) local y = self.ease(t) self.case2:setY(y - self.height) end self.ease = Easing.new(0, self.height, self.duration, ease) elseif transition == "over-from-bottom" then self.transition = function(t) local y = self.ease(t) self.case2:setY(self.height - y) end self.ease = Easing.new(0, self.height, self.duration, ease) end self.watch = Stopwatch.new() self.tweening = true end function M:prev() self:select(self.index - 1, 0.6, "move-from-left", "bounce-out") end function M:next() self:select(self.index + 1, 0.6, "move-from-right", "bounce-out") end return M
[application]fix application
[application]fix application
Lua
mit
xboot/xboot,xboot/xboot
b694702343a923087a8d14fd8694cb0f9f37a517
game/scripts/vscripts/heroes/hero_sara/dark_blink.lua
game/scripts/vscripts/heroes/hero_sara/dark_blink.lua
sara_dark_blink = class({}) if IsServer() then function sara_dark_blink:OnSpellStart() local caster = self:GetCaster() if caster.GetEnergy then local energyBeforeCast = caster:GetEnergy() local wasted = math.max(self:GetSpecialValueFor("min_cost"), caster:GetEnergy() * self:GetSpecialValueFor("energy_pct") * 0.01) if caster:GetEnergy() >= wasted then caster:ModifyEnergy(-wasted) local point = self:GetCursorPosition() local casterPos = caster:GetAbsOrigin() local blinkRange = self:GetSpecialValueFor("blink_range") + self:GetSpecialValueFor("energy_to_blink_range") * energyBeforeCast * 0.01 if (point - casterPos):Length2D() > blinkRange then point = casterPos + (point - casterPos):Normalized() * blinkRange end caster:EmitSound('Hero_Antimage.Blink_out') ParticleManager:CreateParticle("particles/units/heroes/hero_antimage/antimage_blink_start.vpcf", PATTACH_ABSORIGIN, caster) FindClearSpaceForUnit(caster, point, false) caster:EmitSound('Hero_Antimage.Blink_in') ParticleManager:CreateParticle("particles/units/heroes/hero_antimage/antimage_blink_end.vpcf", PATTACH_ABSORIGIN, caster) ProjectileManager:ProjectileDodge(caster) end end end else function sara_dark_blink:GetCastRange() return self:GetSpecialValueFor("blink_range") + self:GetSpecialValueFor("energy_to_blink_range") * self:GetCaster():GetMana() * 0.01 end end
sara_dark_blink = class({}) if IsServer() then function sara_dark_blink:OnSpellStart() local caster = self:GetCaster() if caster.GetEnergy then local energyBeforeCast = caster:GetEnergy() local wasted = math.max(self:GetSpecialValueFor("min_cost"), caster:GetEnergy() * self:GetSpecialValueFor("energy_pct") * 0.01) if caster:GetEnergy() >= wasted then caster:ModifyEnergy(-wasted) local point = self:GetCursorPosition() local casterPos = caster:GetAbsOrigin() local blinkRange = self:GetSpecialValueFor("blink_range") + self:GetSpecialValueFor("energy_to_blink_range") * energyBeforeCast * 0.01 if (point - casterPos):Length2D() > blinkRange then point = casterPos + (point - casterPos):Normalized() * blinkRange end caster:EmitSound('Hero_Antimage.Blink_out') ParticleManager:CreateParticle("particles/arena/units/heroes/hero_sara/dark_blink_start.vpcf", PATTACH_ABSORIGIN, caster) FindClearSpaceForUnit(caster, point, false) caster:EmitSound('Hero_Antimage.Blink_in') ParticleManager:CreateParticle("particles/arena/units/heroes/hero_sara/dark_blink_end.vpcf", PATTACH_ABSORIGIN, caster) ProjectileManager:ProjectileDodge(caster) end end end else function sara_dark_blink:GetCastRange() return self:GetSpecialValueFor("blink_range") + self:GetSpecialValueFor("energy_to_blink_range") * self:GetCaster():GetMana() * 0.01 end end
Fixed Sara - Dark Blink used wrong particles
Fixed Sara - Dark Blink used wrong particles
Lua
mit
ark120202/aabs
0575ba154b102c4a8a4f3b75c5d9747c488ab719
src/luarocks/command_line.lua
src/luarocks/command_line.lua
--- Functions for command-line scripts. module("luarocks.command_line", package.seeall) local util = require("luarocks.util") local cfg = require("luarocks.cfg") local fs = require("luarocks.fs") local path = require("luarocks.path") local dir = require("luarocks.dir") local deps = require("luarocks.deps") --- Display an error message and exit. -- @param message string: The error message. local function die(message) assert(type(message) == "string") local ok, err = pcall(util.run_scheduled_functions) if not ok then util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at [email protected]):\n"..err) end util.printerr("\nError: "..message) os.exit(1) end --- Main command-line processor. -- Parses input arguments and calls the appropriate driver function -- to execute the action requested on the command-line, forwarding -- to it any additional arguments passed by the user. -- Uses the global table "commands", which contains -- the loaded modules representing commands. -- @param ... string: Arguments given on the command-line. function run_command(...) local args = {...} local cmdline_vars = {} for i = #args, 1, -1 do local arg = args[i] if arg:match("^[^-][^=]*=") then local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)") if val then cmdline_vars[var] = val table.remove(args, i) else die("Invalid assignment: "..arg) end end end local nonflags = { util.parse_flags(unpack(args)) } local flags = table.remove(nonflags, 1) if flags["from"] then flags["server"] = flags["from"] end if flags["only-from"] then flags["only-server"] = flags["only-from"] end if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end if flags["to"] then flags["tree"] = flags["to"] end if flags["nodeps"] then flags["deps-mode"] = "none" end cfg.flags = flags local command if flags["version"] then util.printout(program_name.." "..cfg.program_version) util.printout(program_description) util.printout() os.exit(0) elseif flags["help"] or #nonflags == 0 then command = "help" args = nonflags else command = nonflags[1] for i, arg in ipairs(args) do if arg == command then table.remove(args, i) break end end end command = command:gsub("-", "_") if flags["extensions"] then cfg.use_extensions = true local type_check = require("luarocks.type_check") type_check.load_extensions() end if cfg.local_by_default then flags["local"] = true end if flags["deps-mode"] and not deps.check_dep_trees_flag(flags["deps-mode"]) then return nil, "Invalid entry for --deps-mode." end if flags["tree"] then if flags["tree"] == true then die("Argument error: use --tree=<path>") end local root_dir = fs.absolute_name(flags["tree"]) path.use_tree(root_dir) elseif flags["local"] then path.use_tree(cfg.home_tree) else local trees = cfg.rocks_trees path.use_tree(trees[#trees]) end if type(cfg.root_dir) == "string" then cfg.root_dir = cfg.root_dir:gsub("/+$", "") else cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "") end cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "") cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "") cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "") cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "") cfg.variables.ROCKS_TREE = cfg.rocks_dir cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir if flags["server"] then if flags["server"] == true then die("Argument error: use --server=<url>") end local protocol, path = dir.split_url(flags["server"]) table.insert(cfg.rocks_servers, 1, protocol.."://"..path) end if flags["only-server"] then if flags["only-server"] == true then die("Argument error: use --only-server=<url>") end cfg.rocks_servers = { flags["only-server"] } end if flags["only-sources"] then cfg.only_sources_from = flags["only-sources"] end if command ~= "help" then for k, v in pairs(cmdline_vars) do cfg.variables[k] = v end end if commands[command] then local xp, ok, err = xpcall(function() return commands[command].run(unpack(args)) end, function(err) die(debug.traceback("LuaRocks "..cfg.program_version .." bug (please report at [email protected]).\n" ..err, 2)) end) if xp and (not ok) then die(err) end else die("Unknown command: "..command) end util.run_scheduled_functions() end
--- Functions for command-line scripts. module("luarocks.command_line", package.seeall) local util = require("luarocks.util") local cfg = require("luarocks.cfg") local path = require("luarocks.path") local dir = require("luarocks.dir") local deps = require("luarocks.deps") --- Display an error message and exit. -- @param message string: The error message. local function die(message) assert(type(message) == "string") local ok, err = pcall(util.run_scheduled_functions) if not ok then util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at [email protected]):\n"..err) end util.printerr("\nError: "..message) os.exit(1) end --- Main command-line processor. -- Parses input arguments and calls the appropriate driver function -- to execute the action requested on the command-line, forwarding -- to it any additional arguments passed by the user. -- Uses the global table "commands", which contains -- the loaded modules representing commands. -- @param ... string: Arguments given on the command-line. function run_command(...) local args = {...} local cmdline_vars = {} for i = #args, 1, -1 do local arg = args[i] if arg:match("^[^-][^=]*=") then local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)") if val then cmdline_vars[var] = val table.remove(args, i) else die("Invalid assignment: "..arg) end end end local nonflags = { util.parse_flags(unpack(args)) } local flags = table.remove(nonflags, 1) if flags["from"] then flags["server"] = flags["from"] end if flags["only-from"] then flags["only-server"] = flags["only-from"] end if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end if flags["to"] then flags["tree"] = flags["to"] end if flags["nodeps"] then flags["deps-mode"] = "none" table.insert(args, "--deps-mode=none") end cfg.flags = flags local command if flags["version"] then util.printout(program_name.." "..cfg.program_version) util.printout(program_description) util.printout() os.exit(0) elseif flags["help"] or #nonflags == 0 then command = "help" args = nonflags else command = nonflags[1] for i, arg in ipairs(args) do if arg == command then table.remove(args, i) break end end end command = command:gsub("-", "_") if flags["extensions"] then cfg.use_extensions = true local type_check = require("luarocks.type_check") type_check.load_extensions() end if cfg.local_by_default then flags["local"] = true end if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then die("Invalid entry for --deps-mode.") end if flags["tree"] then if flags["tree"] == true or flags["tree"] == "" then die("Argument error: use --tree=<path>") end local fs = require("luarocks.fs") local root_dir = fs.absolute_name(flags["tree"]) path.use_tree(root_dir) elseif flags["local"] then path.use_tree(cfg.home_tree) else local trees = cfg.rocks_trees path.use_tree(trees[#trees]) end if type(cfg.root_dir) == "string" then cfg.root_dir = cfg.root_dir:gsub("/+$", "") else cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "") end cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "") cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "") cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "") cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "") cfg.variables.ROCKS_TREE = cfg.rocks_dir cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir if flags["server"] then if flags["server"] == true then die("Argument error: use --server=<url>") end local protocol, path = dir.split_url(flags["server"]) table.insert(cfg.rocks_servers, 1, protocol.."://"..path) end if flags["only-server"] then if flags["only-server"] == true then die("Argument error: use --only-server=<url>") end cfg.rocks_servers = { flags["only-server"] } end if flags["only-sources"] then cfg.only_sources_from = flags["only-sources"] end if command ~= "help" then for k, v in pairs(cmdline_vars) do cfg.variables[k] = v end end if commands[command] then -- TODO the interface of run should be modified, to receive the -- flags table and the (possibly unpacked) nonflags arguments. -- This would remove redundant parsing of arguments. -- I'm not changing this now to avoid messing with the run() -- interface, which I know some people use (even though -- I never published it as a public API...) local xp, ok, err = xpcall(function() return commands[command].run(unpack(args)) end, function(err) die(debug.traceback("LuaRocks "..cfg.program_version .." bug (please report at [email protected]).\n" ..err, 2)) end) if xp and (not ok) then die(err) end else die("Unknown command: "..command) end util.run_scheduled_functions() end
Fix behavior of --nodeps
Fix behavior of --nodeps
Lua
mit
ignacio/luarocks,xpol/luarocks,tarantool/luarocks,xpol/luainstaller,tarantool/luarocks,robooo/luarocks,aryajur/luarocks,xpol/luavm,leafo/luarocks,rrthomas/luarocks,ignacio/luarocks,coderstudy/luarocks,usstwxy/luarocks,coderstudy/luarocks,xpol/luarocks,keplerproject/luarocks,xpol/luavm,luarocks/luarocks,rrthomas/luarocks,starius/luarocks,leafo/luarocks,rrthomas/luarocks,tarantool/luarocks,usstwxy/luarocks,xpol/luavm,ignacio/luarocks,tst2005/luarocks,keplerproject/luarocks,xiaq/luarocks,keplerproject/luarocks,xiaq/luarocks,coderstudy/luarocks,tst2005/luarocks,starius/luarocks,coderstudy/luarocks,xpol/luainstaller,lxbgit/luarocks,lxbgit/luarocks,usstwxy/luarocks,aryajur/luarocks,xpol/luainstaller,luarocks/luarocks,xpol/luavm,usstwxy/luarocks,xpol/luarocks,robooo/luarocks,leafo/luarocks,aryajur/luarocks,aryajur/luarocks,lxbgit/luarocks,starius/luarocks,xpol/luainstaller,xiaq/luarocks,robooo/luarocks,rrthomas/luarocks,robooo/luarocks,keplerproject/luarocks,lxbgit/luarocks,xiaq/luarocks,tst2005/luarocks,xpol/luavm,starius/luarocks,xpol/luarocks,ignacio/luarocks,luarocks/luarocks,tst2005/luarocks
22a97b871c51429f11f546bb1fdc08b32660f761
build/premake4.lua
build/premake4.lua
-- This is the starting point of the build scripts for the project. -- It defines the common build settings that all the projects share -- and calls the build scripts of all the sub-projects. config = {} dofile "Helpers.lua" --dofile "Tests.lua" dofile "LLVM.lua" solution "SharpLang" configurations { "Debug", "Release" } platforms { "x32", "x64" } flags { common_flags } location (builddir) objdir (path.join(builddir, "obj")) targetdir (libdir) debugdir (bindir) framework "4.5" configuration "windows" defines { "WINDOWS" } configuration {} group "Libraries" include (srcdir .. "/SharpLang.Compiler") include (srcdir .. "/SharpLang.Compiler.Tests") include (srcdir .. "/SharpLang.RuntimeInline") include (srcdir .. "/SharpLLVM") include (srcdir .. "/SharpLLVM.Native") include (srcdir .. "/SharpLLVM.Tests") group "Class Libraries" external "corlib-net_4_5" location (srcdir .. "/mcs/class/corlib") uuid "33BF0182-AC5C-464C-995B-C9CFE74E1A95" kind "SharedLib" language "C#"
-- This is the starting point of the build scripts for the project. -- It defines the common build settings that all the projects share -- and calls the build scripts of all the sub-projects. config = {} dofile "Helpers.lua" --dofile "Tests.lua" dofile "LLVM.lua" solution "SharpLang" configurations { "Debug", "Release" } platforms { "x32", "x64" } flags { common_flags } location (builddir) objdir (path.join(builddir, "obj")) targetdir (libdir) debugdir (bindir) framework "4.5" configuration "windows" defines { "WINDOWS" } configuration {} group "Libraries" include (srcdir .. "/SharpLang.Compiler") include (srcdir .. "/SharpLang.Compiler.Tests") include (srcdir .. "/SharpLang.RuntimeInline") include (srcdir .. "/SharpLLVM") include (srcdir .. "/SharpLLVM.Native") include (srcdir .. "/SharpLLVM.Tests") group "Class Libraries" external "corlib-net_4_5" location (srcdir .. "/mcs/class/corlib") uuid "33BF0182-AC5C-464C-995B-C9CFE74E1A95" kind "SharedLib" language "C#" removeplatforms "*" platforms { "Any CPU" } configmap { ["x32"] = "Any CPU", ["x64"] = "Any CPU" }
[Build] Fixed platform mapping (AnyCPU) for corlib.
[Build] Fixed platform mapping (AnyCPU) for corlib.
Lua
bsd-2-clause
xen2/SharpLang,xen2/SharpLang,xen2/SharpLang,xen2/SharpLang,xen2/SharpLang
01dc1af5f4609580e5ea75ccf58dc57b88ea3aea
profile.lua
profile.lua
-- Begin of globals bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true, ["sally_port"] = true, ["gate"] = true} access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true } access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true } access_tag_restricted = { ["destination"] = true, ["delivery"] = true } access_tags = { "motorcar", "motor_vehicle", "vehicle" } service_tag_restricted = { ["parking_aisle"] = true } ignore_in_grid = { ["ferry"] = true, ["pier"] = true } speed_profile = { ["motorway"] = 90, ["motorway_link"] = 75, ["trunk"] = 85, ["trunk_link"] = 70, ["primary"] = 65, ["primary_link"] = 60, ["secondary"] = 55, ["secondary_link"] = 50, ["tertiary"] = 40, ["tertiary_link"] = 30, ["unclassified"] = 25, ["residential"] = 25, ["living_street"] = 10, ["service"] = 15, -- ["track"] = 5, ["ferry"] = 5, ["pier"] = 5, ["default"] = 50 } take_minimum_of_speeds = true obey_oneway = true obey_bollards = true use_restrictions = true ignore_areas = true -- future feature traffic_signal_penalty = 2 u_turn_penalty = 20 -- End of globals function node_function (node) local barrier = node.tags:Find ("barrier") local access = node.tags:Find ("access") local traffic_signal = node.tags:Find("highway") --flag node if it carries a traffic light if traffic_signal == "traffic_signals" then node.traffic_light = true; end if obey_bollards then --flag node as unpassable if it black listed as unpassable if access_tag_blacklist[barrier] then node.bollard = true; end --reverse the previous flag if there is an access tag specifying entrance if node.bollard and not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then node.bollard = false; end end return 1 end function way_function (way, numberOfNodesInWay) -- A way must have two nodes or more if(numberOfNodesInWay < 2) then return 0; end -- First, get the properties of each way that we come across local highway = way.tags:Find("highway") local name = way.tags:Find("name") local ref = way.tags:Find("ref") local junction = way.tags:Find("junction") local route = way.tags:Find("route") local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") ) local man_made = way.tags:Find("man_made") local barrier = way.tags:Find("barrier") local oneway = way.tags:Find("oneway") local cycleway = way.tags:Find("cycleway") local duration = way.tags:Find("duration") local service = way.tags:Find("service") local area = way.tags:Find("area") local access = way.tags:Find("access") -- Second parse the way according to these properties if ignore_areas and ("yes" == area) then return 0 end -- Check if we are allowed to access the way if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then return 0; end -- Check if our vehicle types are forbidden for i,v in ipairs(access_tags) do local mode_value = way.tags:Find(v) if nil ~= mode_value and "no" == mode_value then return 0; end end -- Set the name that will be used for instructions if "" ~= ref then way.name = ref elseif "" ~= name then way.name = name end if "roundabout" == junction then way.roundabout = true; end -- Handling ferries and piers if (speed_profile[route] ~= nil and speed_profile[route] > 0) or (speed_profile[man_made] ~= nil and speed_profile[man_made] > 0) then if durationIsValid(duration) then way.speed = math.max( duration / math.max(1, numberOfNodesInWay-1) ); way.is_duration_set = true; end way.direction = Way.bidirectional; if speed_profile[route] ~= nil then highway = route; elseif speed_profile[man_made] ~= nil then highway = man_made; end if not way.is_duration_set then way.speed = speed_profile[highway] end end -- Set the avg speed on the way if it is accessible by road class if (speed_profile[highway] ~= nil and way.speed == -1 ) then if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then maxspeed = math.huge end way.speed = math.min(speed_profile[highway], maxspeed) end -- Set the avg speed on ways that are marked accessible if access_tag_whitelist[access] and way.speed == -1 then if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then maxspeed = math.huge end way.speed = math.min(speed_profile["default"], maxspeed) end -- Set access restriction flag if access is allowed under certain restrictions only if access ~= "" and access_tag_restricted[access] then way.is_access_restricted = true end -- Set access restriction flag if service is allowed under certain restrictions only if service ~= "" and service_tag_restricted[service] then way.is_access_restricted = true end -- Set direction according to tags on way if obey_oneway then if oneway == "no" or oneway == "0" or oneway == "false" then way.direction = Way.bidirectional elseif oneway == "-1" then way.direction = Way.opposite elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then way.direction = Way.oneway else way.direction = Way.bidirectional end else way.direction = Way.bidirectional end -- Override general direction settings of there is a specific one for our mode of travel if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then way.ignore_in_grid = true end way.type = 1 return 1 end
-- Begin of globals bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true, ["sally_port"] = true, ["gate"] = true} access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true } access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true } access_tag_restricted = { ["destination"] = true, ["delivery"] = true } access_tags = { "motorcar", "motor_vehicle", "vehicle" } service_tag_restricted = { ["parking_aisle"] = true } ignore_in_grid = { ["ferry"] = true, ["pier"] = true } speed_profile = { ["motorway"] = 90, ["motorway_link"] = 75, ["trunk"] = 85, ["trunk_link"] = 70, ["primary"] = 65, ["primary_link"] = 60, ["secondary"] = 55, ["secondary_link"] = 50, ["tertiary"] = 40, ["tertiary_link"] = 30, ["unclassified"] = 25, ["residential"] = 25, ["living_street"] = 10, ["service"] = 15, -- ["track"] = 5, ["ferry"] = 5, ["pier"] = 5, ["default"] = 50 } take_minimum_of_speeds = true obey_oneway = true obey_bollards = true use_restrictions = true ignore_areas = true -- future feature traffic_signal_penalty = 2 u_turn_penalty = 20 -- End of globals function node_function (node) local barrier = node.tags:Find ("barrier") local access = node.tags:Find ("access") local traffic_signal = node.tags:Find("highway") --flag node if it carries a traffic light if traffic_signal == "traffic_signals" then node.traffic_light = true; end if access_tag_blacklist[barrier] then node.bollard = true; end if "" ~= barrier then if obey_bollards then --flag node as unpassable if it black listed as unpassable print(barrier) node.bollard = true; end --reverse the previous flag if there is an access tag specifying entrance if node.bollard and bollards_whitelist[barrier] and access_tag_whitelist[barrier] then node.bollard = false; return 1 end -- Check if our vehicle types are allowd to pass the barrier for i,v in ipairs(access_tags) do local mode_value = node.tags:Find(v) if nil ~= mode_value and "yes" == mode_value then return 1 node.bollard = false return end end else -- Check if our vehicle types are forbidden to pass the node for i,v in ipairs(access_tags) do local mode_value = node.tags:Find(v) if nil ~= mode_value and "no" == mode_value then node.bollard = true return 1 end end end return 1 end function way_function (way, numberOfNodesInWay) -- A way must have two nodes or more if(numberOfNodesInWay < 2) then return 0; end -- First, get the properties of each way that we come across local highway = way.tags:Find("highway") local name = way.tags:Find("name") local ref = way.tags:Find("ref") local junction = way.tags:Find("junction") local route = way.tags:Find("route") local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") ) local man_made = way.tags:Find("man_made") local barrier = way.tags:Find("barrier") local oneway = way.tags:Find("oneway") local cycleway = way.tags:Find("cycleway") local duration = way.tags:Find("duration") local service = way.tags:Find("service") local area = way.tags:Find("area") local access = way.tags:Find("access") -- Second parse the way according to these properties if ignore_areas and ("yes" == area) then return 0 end -- Check if we are allowed to access the way if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then return 0; end -- Check if our vehicle types are forbidden for i,v in ipairs(access_tags) do local mode_value = way.tags:Find(v) if nil ~= mode_value and "no" == mode_value then return 0; end end -- Set the name that will be used for instructions if "" ~= ref then way.name = ref elseif "" ~= name then way.name = name end if "roundabout" == junction then way.roundabout = true; end -- Handling ferries and piers if (speed_profile[route] ~= nil and speed_profile[route] > 0) or (speed_profile[man_made] ~= nil and speed_profile[man_made] > 0) then if durationIsValid(duration) then way.speed = math.max( duration / math.max(1, numberOfNodesInWay-1) ); way.is_duration_set = true; end way.direction = Way.bidirectional; if speed_profile[route] ~= nil then highway = route; elseif speed_profile[man_made] ~= nil then highway = man_made; end if not way.is_duration_set then way.speed = speed_profile[highway] end end -- Set the avg speed on the way if it is accessible by road class if (speed_profile[highway] ~= nil and way.speed == -1 ) then if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then maxspeed = math.huge end way.speed = math.min(speed_profile[highway], maxspeed) end -- Set the avg speed on ways that are marked accessible if access_tag_whitelist[access] and way.speed == -1 then if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then maxspeed = math.huge end way.speed = math.min(speed_profile["default"], maxspeed) end -- Set access restriction flag if access is allowed under certain restrictions only if access ~= "" and access_tag_restricted[access] then way.is_access_restricted = true end -- Set access restriction flag if service is allowed under certain restrictions only if service ~= "" and service_tag_restricted[service] then way.is_access_restricted = true end -- Set direction according to tags on way if obey_oneway then if oneway == "no" or oneway == "0" or oneway == "false" then way.direction = Way.bidirectional elseif oneway == "-1" then way.direction = Way.opposite elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then way.direction = Way.oneway else way.direction = Way.bidirectional end else way.direction = Way.bidirectional end -- Override general direction settings of there is a specific one for our mode of travel if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then way.ignore_in_grid = true end way.type = 1 return 1 end
Fixes issue #432
Fixes issue #432
Lua
bsd-2-clause
ramyaragupathy/osrm-backend,Conggge/osrm-backend,ramyaragupathy/osrm-backend,arnekaiser/osrm-backend,oxidase/osrm-backend,bjtaylor1/osrm-backend,frodrigo/osrm-backend,duizendnegen/osrm-backend,yuryleb/osrm-backend,bjtaylor1/Project-OSRM-Old,Tristramg/osrm-backend,hydrays/osrm-backend,keesklopt/matrix,arnekaiser/osrm-backend,Carsten64/OSRM-aux-git,bjtaylor1/osrm-backend,Project-OSRM/osrm-backend,chaupow/osrm-backend,hydrays/osrm-backend,skyborla/osrm-backend,KnockSoftware/osrm-backend,ibikecph/osrm-backend,atsuyim/osrm-backend,neilbu/osrm-backend,Project-OSRM/osrm-backend,Project-OSRM/osrm-backend,ibikecph/osrm-backend,felixguendling/osrm-backend,chaupow/osrm-backend,keesklopt/matrix,ammeurer/osrm-backend,neilbu/osrm-backend,agruss/osrm-backend,stevevance/Project-OSRM,stevevance/Project-OSRM,raymond0/osrm-backend,Conggge/osrm-backend,bitsteller/osrm-backend,felixguendling/osrm-backend,jpizarrom/osrm-backend,KnockSoftware/osrm-backend,Carsten64/OSRM-aux-git,arnekaiser/osrm-backend,keesklopt/matrix,felixguendling/osrm-backend,KnockSoftware/osrm-backend,yuryleb/osrm-backend,alex85k/Project-OSRM,antoinegiret/osrm-backend,oxidase/osrm-backend,alex85k/Project-OSRM,beemogmbh/osrm-backend,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,Carsten64/OSRM-aux-git,chaupow/osrm-backend,bjtaylor1/Project-OSRM-Old,raymond0/osrm-backend,raymond0/osrm-backend,hydrays/osrm-backend,bjtaylor1/Project-OSRM-Old,neilbu/osrm-backend,deniskoronchik/osrm-backend,duizendnegen/osrm-backend,bjtaylor1/osrm-backend,antoinegiret/osrm-geovelo,atsuyim/osrm-backend,agruss/osrm-backend,skyborla/osrm-backend,duizendnegen/osrm-backend,Project-OSRM/osrm-backend,ammeurer/osrm-backend,antoinegiret/osrm-backend,beemogmbh/osrm-backend,neilbu/osrm-backend,frodrigo/osrm-backend,keesklopt/matrix,prembasumatary/osrm-backend,bitsteller/osrm-backend,bjtaylor1/Project-OSRM-Old,tkhaxton/osrm-backend,tkhaxton/osrm-backend,ramyaragupathy/osrm-backend,alex85k/Project-OSRM,ibikecph/osrm-backend,beemogmbh/osrm-backend,prembasumatary/osrm-backend,Conggge/osrm-backend,nagyistoce/osrm-backend,skyborla/osrm-backend,atsuyim/osrm-backend,Tristramg/osrm-backend,oxidase/osrm-backend,nagyistoce/osrm-backend,hydrays/osrm-backend,stevevance/Project-OSRM,ammeurer/osrm-backend,bjtaylor1/osrm-backend,beemogmbh/osrm-backend,tkhaxton/osrm-backend,deniskoronchik/osrm-backend,frodrigo/osrm-backend,deniskoronchik/osrm-backend,yuryleb/osrm-backend,antoinegiret/osrm-geovelo,agruss/osrm-backend,ammeurer/osrm-backend,ammeurer/osrm-backend,duizendnegen/osrm-backend,antoinegiret/osrm-backend,yuryleb/osrm-backend,nagyistoce/osrm-backend,oxidase/osrm-backend,bitsteller/osrm-backend,prembasumatary/osrm-backend,jpizarrom/osrm-backend,arnekaiser/osrm-backend,raymond0/osrm-backend,KnockSoftware/osrm-backend,stevevance/Project-OSRM,deniskoronchik/osrm-backend,ammeurer/osrm-backend,Tristramg/osrm-backend,Conggge/osrm-backend,jpizarrom/osrm-backend,antoinegiret/osrm-geovelo,frodrigo/osrm-backend
b4acd30cca4dd5aa4682732ee29f48d6e04e8a1d
scripts/embed.lua
scripts/embed.lua
-- -- Embed the Lua scripts into src/host/scripts.c as static data buffers. -- Embeds minified versions of the actual scripts by default, rather than -- bytecode, as bytecodes are not portable to different architectures. Use -- the `--bytecode` flag to override. -- local scriptCount = 0 local function loadScript(fname) fname = path.getabsolute(fname) local f = io.open(fname, "rb") local s = assert(f:read("*all")) f:close() return s end local function stripScript(s) -- strip tabs local result = s:gsub("[\t]", "") -- strip any CRs result = result:gsub("[\r]", "") -- strip out block comments result = result:gsub("[^\"']%-%-%[%[.-%]%]", "") result = result:gsub("[^\"']%-%-%[=%[.-%]=%]", "") result = result:gsub("[^\"']%-%-%[==%[.-%]==%]", "") -- strip out inline comments result = result:gsub("\n%-%-[^\n]*", "\n") -- strip duplicate line feeds result = result:gsub("\n+", "\n") -- strip out leading comments result = result:gsub("^%-%-[^\n]*\n", "") return result end local function outputScript(result, script) local data = script.data local length = #data if length > 0 then script.table = string.format("builtin_script_%d", scriptCount) scriptCount = scriptCount + 1 buffered.writeln(result, "// ".. script.name) buffered.writeln(result, "static const unsigned char " .. script.table .. "[] = {") for i = 1, length do buffered.write(result, string.format("%3d, ", data:byte(i))) if (i % 32 == 0) then buffered.writeln(result) end end buffered.writeln(result, "};") buffered.writeln(result) end end local function addScript(result, filename, name, data) if not data then if _OPTIONS["bytecode"] then verbosef("Compiling... " .. filename) local output = path.replaceextension(filename, ".luac") local res, err = os.compile(filename, output); if res ~= nil then data = loadScript(output) os.remove(output) else print(err) print("Embedding source instead.") data = stripScript(loadScript(filename)) end else data = stripScript(loadScript(filename)) end end local script = {} script.filename = filename script.name = name script.data = data table.insert(result, script) end -- Prepare the file header local result = buffered.new() buffered.writeln(result, "/* Premake's Lua scripts, as static data buffers for release mode builds */") buffered.writeln(result, "/* DO NOT EDIT - this file is autogenerated - see BUILD.txt */") buffered.writeln(result, "/* To regenerate this file, run: premake5 embed */") buffered.writeln(result, "") buffered.writeln(result, '#include "host/premake.h"') buffered.writeln(result, "") -- Find all of the _manifest.lua files within the project local mask = path.join(_MAIN_SCRIPT_DIR, "**/_manifest.lua") local manifests = os.matchfiles(mask) -- Find all of the _user_modules.lua files within the project local userModuleFiles = {} userModuleFiles = table.join(userModuleFiles, os.matchfiles(path.join(_MAIN_SCRIPT_DIR, "**/_user_modules.lua"))) userModuleFiles = table.join(userModuleFiles, os.matchfiles(path.join(_MAIN_SCRIPT_DIR, "_user_modules.lua"))) -- Generate table of embedded content. local contentTable = {} local nativeTable = {} print("Compiling... ") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local moduleName = path.getbasename(manifestDir) local baseDir = path.getdirectory(manifestDir) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) addScript(contentTable, filename, path.getrelative(baseDir, filename)) end -- find native code in modules. if moduleName ~= "src" then local nativeFile = path.join(manifestDir, 'native', moduleName .. '.c') if os.isfile(nativeFile) then local pretty_name = moduleName:gsub("^%l", string.upper) table.insert(nativeTable, pretty_name) end end end addScript(contentTable, path.join(_SCRIPT_DIR, "../src/_premake_main.lua"), "src/_premake_main.lua") addScript(contentTable, path.join(_SCRIPT_DIR, "../src/_manifest.lua"), "src/_manifest.lua") -- Add the list of modules local modules = dofile("../src/_modules.lua") for _, userModules in ipairs(userModuleFiles) do modules = table.join(modules, dofile(userModules)) end addScript(contentTable, "_modules.lua", "src/_modules.lua", "return {" .. table.implode(modules, '"', '"', ', ') .. "}") -- Embed the actual script contents print("Embedding...") for mi = 1, #contentTable do outputScript(result, contentTable[mi]) end -- Generate an index of the script file names. Script names are stored -- relative to the directory containing the manifest, i.e. the main -- Xcode script, which is at $/modules/xcode/xcode.lua is stored as -- "xcode/xcode.lua". buffered.writeln(result, "const buildin_mapping builtin_scripts[] = {") for mi = 1, #contentTable do if contentTable[mi].table then buffered.writeln(result, string.format('\t{"%s", %s, sizeof(%s)},', contentTable[mi].name, contentTable[mi].table, contentTable[mi].table)) else buffered.writeln(result, string.format('\t{"%s", NULL, 0},', contentTable[mi].name)) end end buffered.writeln(result, "\t{NULL, NULL, 0}") buffered.writeln(result, "};") buffered.writeln(result, "") -- write out the registerModules method. for _, name in ipairs(nativeTable) do buffered.writeln(result, string.format("extern void register%s(lua_State* L);", name)) end buffered.writeln(result, "") buffered.writeln(result, "void registerModules(lua_State* L)") buffered.writeln(result, "{") for _, name in ipairs(nativeTable) do buffered.writeln(result, string.format("\tregister%s(L);", name)) end buffered.writeln(result, "}") buffered.writeln(result, "") -- Write it all out. Check against the current contents of scripts.c first, -- and only overwrite it if there are actual changes. print("Writing...") local scriptsFile = path.getabsolute(path.join(_SCRIPT_DIR, "../src/scripts.c")) local output = buffered.tostring(result) local f, err = os.writefile_ifnotequal(output, scriptsFile); if (f < 0) then error(err, 0) elseif (f > 0) then printf("Generated %s...", path.getrelative(os.getcwd(), scriptsFile)) end
-- -- Embed the Lua scripts into src/host/scripts.c as static data buffers. -- Embeds minified versions of the actual scripts by default, rather than -- bytecode, as bytecodes are not portable to different architectures. Use -- the `--bytecode` flag to override. -- local scriptCount = 0 local function loadScript(fname) fname = path.getabsolute(fname) local f = io.open(fname, "rb") local s = assert(f:read("*all")) f:close() return s end local function stripScript(s) -- strip tabs local result = s:gsub("[\t]", "") -- strip any CRs result = result:gsub("[\r]", "") -- strip out block comments result = result:gsub("[^\"']%-%-%[%[.-%]%]", "") result = result:gsub("[^\"']%-%-%[=%[.-%]=%]", "") result = result:gsub("[^\"']%-%-%[==%[.-%]==%]", "") -- strip out inline comments result = result:gsub("\n%-%-[^\n]*", "\n") -- strip duplicate line feeds result = result:gsub("\n+", "\n") -- strip out leading comments result = result:gsub("^%-%-[^\n]*\n", "") return result end local function outputScript(result, script) local data = script.data local length = #data if length > 0 then script.table = string.format("builtin_script_%d", scriptCount) scriptCount = scriptCount + 1 buffered.writeln(result, "// ".. script.name) buffered.writeln(result, "static const unsigned char " .. script.table .. "[] = {") for i = 1, length do buffered.write(result, string.format("%3d, ", data:byte(i))) if (i % 32 == 0) then buffered.writeln(result) end end buffered.writeln(result, "};") buffered.writeln(result) end end local function addScript(result, filename, name, data) if not data then if _OPTIONS["bytecode"] then verbosef("Compiling... " .. filename) local output = path.replaceextension(filename, ".luac") local res, err = os.compile(filename, output); if res ~= nil then data = loadScript(output) os.remove(output) else print(err) print("Embedding source instead.") data = stripScript(loadScript(filename)) end else data = stripScript(loadScript(filename)) end end local script = {} script.filename = filename script.name = name script.data = data table.insert(result, script) end -- Prepare the file header local result = buffered.new() buffered.writeln(result, "/* Premake's Lua scripts, as static data buffers for release mode builds */") buffered.writeln(result, "/* DO NOT EDIT - this file is autogenerated - see BUILD.txt */") buffered.writeln(result, "/* To regenerate this file, run: premake5 embed */") buffered.writeln(result, "") buffered.writeln(result, '#include "host/premake.h"') buffered.writeln(result, "") -- Find all of the _manifest.lua files within the project local mask = path.join(_MAIN_SCRIPT_DIR, "**/_manifest.lua") local manifests = os.matchfiles(mask) -- Find all of the _user_modules.lua files within the project local userModuleFiles = {} userModuleFiles = table.join(userModuleFiles, os.matchfiles(path.join(_MAIN_SCRIPT_DIR, "**/_user_modules.lua"))) userModuleFiles = table.join(userModuleFiles, os.matchfiles(path.join(_MAIN_SCRIPT_DIR, "_user_modules.lua"))) -- Generate table of embedded content. local contentTable = {} local nativeTable = {} print("Compiling... ") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local moduleName = path.getbasename(manifestDir) local baseDir = path.getdirectory(manifestDir) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) addScript(contentTable, filename, path.getrelative(baseDir, filename)) end -- find native code in modules. if moduleName ~= "src" then local nativeFile = path.join(manifestDir, 'native', moduleName .. '.c') if os.isfile(nativeFile) then local pretty_name = moduleName:gsub("^%l", string.upper) table.insert(nativeTable, pretty_name) end end end addScript(contentTable, path.join(_SCRIPT_DIR, "../src/_premake_main.lua"), "src/_premake_main.lua") addScript(contentTable, path.join(_SCRIPT_DIR, "../src/_manifest.lua"), "src/_manifest.lua") -- Add the list of modules local modules = dofile("../src/_modules.lua") for _, userModules in ipairs(userModuleFiles) do modules = table.join(modules, dofile(userModules)) end addScript(contentTable, "_modules.lua", "src/_modules.lua", "return {" .. table.implode(modules, '"', '"', ', ') .. "}") -- Embed the actual script contents print("Embedding...") for mi = 1, #contentTable do outputScript(result, contentTable[mi]) end -- Generate an index of the script file names. Script names are stored -- relative to the directory containing the manifest, i.e. the main -- Xcode script, which is at $/modules/xcode/xcode.lua is stored as -- "xcode/xcode.lua". buffered.writeln(result, "const buildin_mapping builtin_scripts[] = {") for mi = 1, #contentTable do if contentTable[mi].table then buffered.writeln(result, string.format('\t{"%s", %s, sizeof(%s)},', contentTable[mi].name, contentTable[mi].table, contentTable[mi].table)) else buffered.writeln(result, string.format('\t{"%s", NULL, 0},', contentTable[mi].name)) end end buffered.writeln(result, "\t{NULL, NULL, 0}") buffered.writeln(result, "};") buffered.writeln(result, "") -- write out the registerModules method. for _, name in ipairs(nativeTable) do buffered.writeln(result, string.format("extern void register%s(lua_State* L);", name)) end buffered.writeln(result, "") buffered.writeln(result, "void registerModules(lua_State* L)") buffered.writeln(result, "{") buffered.writeln(result, "\t(void)(L);") for _, name in ipairs(nativeTable) do buffered.writeln(result, string.format("\tregister%s(L);", name)) end buffered.writeln(result, "}") buffered.writeln(result, "") -- Write it all out. Check against the current contents of scripts.c first, -- and only overwrite it if there are actual changes. print("Writing...") local scriptsFile = path.getabsolute(path.join(_SCRIPT_DIR, "../src/scripts.c")) local output = buffered.tostring(result) local f, err = os.writefile_ifnotequal(output, scriptsFile); if (f < 0) then error(err, 0) elseif (f > 0) then printf("Generated %s...", path.getrelative(os.getcwd(), scriptsFile)) end
fix unreferenced argument warning.
fix unreferenced argument warning.
Lua
bsd-3-clause
starkos/premake-core,Blizzard/premake-core,Blizzard/premake-core,mandersan/premake-core,noresources/premake-core,Zefiros-Software/premake-core,premake/premake-core,starkos/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,dcourtois/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,LORgames/premake-core,mandersan/premake-core,aleksijuvani/premake-core,premake/premake-core,sleepingwit/premake-core,dcourtois/premake-core,dcourtois/premake-core,premake/premake-core,mendsley/premake-core,premake/premake-core,LORgames/premake-core,dcourtois/premake-core,sleepingwit/premake-core,soundsrc/premake-core,Blizzard/premake-core,LORgames/premake-core,TurkeyMan/premake-core,starkos/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,noresources/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,mendsley/premake-core,sleepingwit/premake-core,Blizzard/premake-core,starkos/premake-core,TurkeyMan/premake-core,noresources/premake-core,aleksijuvani/premake-core,mandersan/premake-core,sleepingwit/premake-core,mendsley/premake-core,dcourtois/premake-core,tvandijck/premake-core,starkos/premake-core,mendsley/premake-core,soundsrc/premake-core,premake/premake-core,starkos/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,noresources/premake-core,Blizzard/premake-core,sleepingwit/premake-core,LORgames/premake-core,mandersan/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,mendsley/premake-core,tvandijck/premake-core,premake/premake-core,noresources/premake-core,noresources/premake-core,noresources/premake-core,LORgames/premake-core,mandersan/premake-core,soundsrc/premake-core,starkos/premake-core,premake/premake-core,TurkeyMan/premake-core
c790f8e25a63166a15048266e5658f0c6ee9cd0b
src/lua-factory/sources/grl-radiofrance.lua
src/lua-factory/sources/grl-radiofrance.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] RADIOFRANCE_URL = 'http://app2.radiofrance.fr/rfdirect/config/Radio.js' FRANCEBLEU_URL = 'http://app2.radiofrance.fr/rfdirect/config/FranceBleu.js' local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'resource:///org/gnome/grilo/plugins/radiofrance/radiofrance.png', supported_media = 'audio', tags = { 'radio', 'country:fr', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/api/now&full=true' table.insert(urls, url) end grl.fetch(urls, "radiofrance_now_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results) for index, result in pairs(results) do local json = {} json = grl.lua.json.string_to_table(result) if not json or json.stat == "fail" or not json.stations then local url = 'http://www.' .. stations[index] .. '.fr/api/now&full=true' grl.warning ('Could not fetch ' .. url .. ' failed') else local media = create_media(stations[index], json.stations[1]) grl.callback(media, -1) end end grl.callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, station) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end if id == 'franceinfo' then media.url = 'http://mp3lg.tdf-cdn.com/' .. media.id .. '/all/' .. media.id .. '-32k.mp3' else media.url = 'http://mp3lg.tdf-cdn.com/' .. media.id .. '/all/' .. media.id .. 'hautdebit.mp3' end media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'resource:///org/gnome/grilo/plugins/radiofrance/radiofrance.png', supported_media = 'audio', tags = { 'radio', 'country:fr', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/player' table.insert(urls, url) end grl.fetch(urls, "radiofrance_now_fetch_cb") end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results) for index, result in pairs(results) do local media = create_media(stations[index], result) grl.callback(media, -1) end grl.callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, result) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end media.url = result:match("liveUrl: '(.-)',") if not media.url then media.url = result:match('"player" href="(http.-%.mp3)') end media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks -- Available in 'http://www.' .. item .. '.fr/api/now&full=true' return media end
lua-factory: Fix Radio France source again
lua-factory: Fix Radio France source again URLs for the CDN seem to change on a regular basis, so get them from the website directly instead.
Lua
lgpl-2.1
grilofw/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins
1e94f63654b3e91673e29529fbbf13d291bf9e84
src/ds18b20/send_temp.lua
src/ds18b20/send_temp.lua
-- -- -- -- function send_data(t, addr) local json = require("cjson") local devid = string.format("%02X-%02X%02X%02X%02X%02X%02X%02X", addr:byte(1),addr:byte(2),addr:byte(3),addr:byte(4), addr:byte(5),addr:byte(6),addr:byte(7),addr:byte(8)) local msg = {} local payload = {} payload["value"] = tostring(t.read(addr,t.C)) msg["dev-id"] = "dev."..devid..".temp" msg["payload"] = payload local msg1 = json.encode(msg) msg=nil payload=nil devid=nil print("["..msg1.."]") post("["..msg1.."]") msg1=nil json=nil end function send_temp_data() local addrs=t.addrs() for i=1,#addrs do send_data(t, addrs[i]) end addrs = nil end
-- **************************************************************************** -- ESP8266-01 -- -- Send DS18B20 sensor data connected to GPIO0 (3) -- -- dev-id: dev.<ID>.<TYPE> payload: {:value <VALUE>, :unit RH} -- -- **************************************************************************** function send_data(t, addr) local json = require("cjson") local devid = string.format("%02X-%02X%02X%02X%02X%02X%02X", addr:byte(1),addr:byte(7),addr:byte(6),addr:byte(5), addr:byte(4),addr:byte(3),addr:byte(2)) local msg = {} local payload = {} payload["value"] = tostring(t.read(addr,t.C)) msg["dev-id"] = "dev."..devid..".temp" msg["payload"] = payload local msg1 = json.encode(msg) msg=nil payload=nil devid=nil print("["..msg1.."]") post("["..msg1.."]") msg1=nil json=nil end function send_temp_data() local addrs=t.addrs() for i=1,#addrs do send_data(t, addrs[i]) end addrs = nil end
Fixed device id format
Fixed device id format
Lua
mit
JanneLindberg/ESP8266-code
57ca3b3e00fc63bb575c0f37dc3af9988c7df141
busted/init.lua
busted/init.lua
local unpack = require 'busted.compatibility'.unpack local shuffle = require 'busted.utils'.shuffle local function sort(elements) table.sort(elements, function(t1, t2) if t1.name and t2.name then return t1.name < t2.name end return t2.name ~= nil end) return elements end local function remove(descriptors, element) for _, descriptor in ipairs(descriptors) do element.env[descriptor] = function(...) error("'" .. descriptor .. "' not supported inside current context block", 2) end end end local function init(busted) local function exec(descriptor, element) if not element.env then element.env = {} end remove({ 'randomize' }, element) remove({ 'pending' }, element) remove({ 'describe', 'context', 'it', 'spec', 'test' }, element) remove({ 'setup', 'teardown', 'before_each', 'after_each' }, element) local parent = busted.context.parent(element) setmetatable(element.env, { __newindex = function(self, key, value) if not parent.env then parent.env = {} end parent.env[key] = value end }) local ret = { busted.safe(descriptor, element.run, element) } return unpack(ret) end local function execAll(descriptor, current, propagate) local parent = busted.context.parent(current) if propagate and parent then local success, ancestor = execAll(descriptor, parent, propagate) if not success then return success, ancestor end end local list = current[descriptor] or {} local success = true for _, v in pairs(list) do if not exec(descriptor, v):success() then success = nil end end return success, current end local function dexecAll(descriptor, current, propagate) local parent = busted.context.parent(current) local list = current[descriptor] or {} local success = true for _, v in pairs(list) do if not exec(descriptor, v):success() then success = nil end end if propagate and parent then if not dexecAll(descriptor, parent, propagate) then success = nil end end return success end local file = function(file) busted.publish({ 'file', 'start' }, file.name) busted.environment.wrap(file.run) if not file.env then file.env = {} end local randomize = busted.randomize file.env.randomize = function() randomize = true end if busted.safe('file', file.run, file):success() then if randomize then file.randomseed = busted.randomseed shuffle(busted.context.children(file), busted.randomseed) elseif busted.sort then sort(busted.context.children(file)) end if execAll('setup', file) then busted.execute(file) end dexecAll('teardown', file) end busted.publish({ 'file', 'end' }, file.name) end local describe = function(describe) local parent = busted.context.parent(describe) busted.publish({ 'describe', 'start' }, describe, parent) if not describe.env then describe.env = {} end local randomize = busted.randomize describe.env.randomize = function() randomize = true end if busted.safe('describe', describe.run, describe):success() then if randomize then describe.randomseed = busted.randomseed shuffle(busted.context.children(describe), busted.randomseed) elseif busted.sort then sort(busted.context.children(describe)) end if execAll('setup', describe) then busted.execute(describe) end dexecAll('teardown', describe) end busted.publish({ 'describe', 'end' }, describe, parent) end local it = function(element) local parent = busted.context.parent(element) local finally local parent = busted.context.parent(element) busted.publish({ 'test', 'start' }, element, parent) if not element.env then element.env = {} end remove({ 'randomize' }, element) remove({ 'describe', 'context', 'it', 'spec', 'test' }, element) remove({ 'setup', 'teardown', 'before_each', 'after_each' }, element) element.env.finally = function(fn) finally = fn end element.env.pending = function(msg) busted.pending(msg) end local status = busted.status('success') local updateErrorStatus = function(descriptor) if element.message then element.message = element.message .. '\n' end element.message = (element.message or '') .. 'Error in ' .. descriptor status:update('error') end local pass, ancestor = execAll('before_each', parent, true) if pass then status:update(busted.safe('it', element.run, element)) else updateErrorStatus('before_each') end if not element.env.done then remove({ 'pending' }, element) if finally then status:update(busted.safe('finally', finally, element)) end if not dexecAll('after_each', ancestor, true) then updateErrorStatus('after_each') end busted.publish({ 'test', 'end' }, element, parent, tostring(status)) end end local pending = function(element) local parent = busted.context.parent(element) busted.publish({ 'test', 'start' }, element, parent) busted.publish({ 'test', 'end' }, element, parent, 'pending') end busted.register('file', file) busted.register('describe', describe) busted.register('it', it) busted.register('pending', pending) busted.register('setup') busted.register('teardown') busted.register('before_each') busted.register('after_each') busted.alias('context', 'describe') busted.alias('spec', 'it') busted.alias('test', 'it') local assert = require 'luassert' local spy = require 'luassert.spy' local mock = require 'luassert.mock' local stub = require 'luassert.stub' busted.environment.set('assert', assert) busted.environment.set('spy', spy) busted.environment.set('mock', mock) busted.environment.set('stub', stub) busted.replaceErrorWithFail(assert) busted.replaceErrorWithFail(assert.True) return busted end return setmetatable({}, { __call = function(self, busted) local root = busted.context.get() init(busted) return setmetatable(self, { __index = function(self, key) return rawget(root.env, key) or busted.executors[key] end, __newindex = function(self, key, value) error('Attempt to modify busted') end }) end })
local unpack = require 'busted.compatibility'.unpack local shuffle = require 'busted.utils'.shuffle local function sort(elements) table.sort(elements, function(t1, t2) if t1.name and t2.name then return t1.name < t2.name end return t2.name ~= nil end) return elements end local function remove(descriptors, element) for _, descriptor in ipairs(descriptors) do element.env[descriptor] = function(...) error("'" .. descriptor .. "' not supported inside current context block", 2) end end end local function init(busted) local function exec(descriptor, element) if not element.env then element.env = {} end remove({ 'randomize' }, element) remove({ 'pending' }, element) remove({ 'describe', 'context', 'it', 'spec', 'test' }, element) remove({ 'setup', 'teardown', 'before_each', 'after_each' }, element) local parent = busted.context.parent(element) setmetatable(element.env, { __newindex = function(self, key, value) if not parent.env then parent.env = {} end parent.env[key] = value end }) local ret = { busted.safe(descriptor, element.run, element) } return unpack(ret) end local function execAll(descriptor, current, propagate) local parent = busted.context.parent(current) if propagate and parent then local success, ancestor = execAll(descriptor, parent, propagate) if not success then return success, ancestor end end local list = current[descriptor] or {} local success = true for _, v in pairs(list) do if not exec(descriptor, v):success() then success = nil end end return success, current end local function dexecAll(descriptor, current, propagate) local parent = busted.context.parent(current) local list = current[descriptor] or {} local success = true for _, v in pairs(list) do if not exec(descriptor, v):success() then success = nil end end if propagate and parent then if not dexecAll(descriptor, parent, propagate) then success = nil end end return success end local file = function(file) busted.publish({ 'file', 'start' }, file.name) busted.environment.wrap(file.run) if not file.env then file.env = {} end local randomize = busted.randomize file.env.randomize = function() randomize = true end if busted.safe('file', file.run, file):success() then if randomize then file.randomseed = busted.randomseed shuffle(busted.context.children(file), busted.randomseed) elseif busted.sort then sort(busted.context.children(file)) end if execAll('setup', file) then busted.execute(file) end dexecAll('teardown', file) end busted.publish({ 'file', 'end' }, file.name) end local describe = function(describe) local parent = busted.context.parent(describe) busted.publish({ 'describe', 'start' }, describe, parent) if not describe.env then describe.env = {} end local randomize = busted.randomize describe.env.randomize = function() randomize = true end if busted.safe('describe', describe.run, describe):success() then if randomize then describe.randomseed = busted.randomseed shuffle(busted.context.children(describe), busted.randomseed) elseif busted.sort then sort(busted.context.children(describe)) end if execAll('setup', describe) then busted.execute(describe) end dexecAll('teardown', describe) end busted.publish({ 'describe', 'end' }, describe, parent) end local it = function(element) local parent = busted.context.parent(element) local finally busted.publish({ 'test', 'start' }, element, parent) if not element.env then element.env = {} end remove({ 'randomize' }, element) remove({ 'describe', 'context', 'it', 'spec', 'test' }, element) remove({ 'setup', 'teardown', 'before_each', 'after_each' }, element) element.env.finally = function(fn) finally = fn end element.env.pending = function(msg) busted.pending(msg) end local status = busted.status('success') local updateErrorStatus = function(descriptor) if element.message then element.message = element.message .. '\n' end element.message = (element.message or '') .. 'Error in ' .. descriptor status:update('error') end local pass, ancestor = execAll('before_each', parent, true) if pass then status:update(busted.safe('it', element.run, element)) else updateErrorStatus('before_each') end if not element.env.done then remove({ 'pending' }, element) if finally then status:update(busted.safe('finally', finally, element)) end if not dexecAll('after_each', ancestor, true) then updateErrorStatus('after_each') end busted.publish({ 'test', 'end' }, element, parent, tostring(status)) end end local pending = function(element) local parent = busted.context.parent(element) busted.publish({ 'test', 'start' }, element, parent) busted.publish({ 'test', 'end' }, element, parent, 'pending') end busted.register('file', file) busted.register('describe', describe) busted.register('it', it) busted.register('pending', pending) busted.register('setup') busted.register('teardown') busted.register('before_each') busted.register('after_each') busted.alias('context', 'describe') busted.alias('spec', 'it') busted.alias('test', 'it') local assert = require 'luassert' local spy = require 'luassert.spy' local mock = require 'luassert.mock' local stub = require 'luassert.stub' busted.environment.set('assert', assert) busted.environment.set('spy', spy) busted.environment.set('mock', mock) busted.environment.set('stub', stub) busted.replaceErrorWithFail(assert) busted.replaceErrorWithFail(assert.True) return busted end return setmetatable({}, { __call = function(self, busted) local root = busted.context.get() init(busted) return setmetatable(self, { __index = function(self, key) return rawget(root.env, key) or busted.executors[key] end, __newindex = function(self, key, value) error('Attempt to modify busted') end }) end })
Fix duplicate parent variable
Fix duplicate parent variable
Lua
mit
leafo/busted,mpeterv/busted,ryanplusplus/busted,istr/busted,xyliuke/busted,nehz/busted,Olivine-Labs/busted,o-lim/busted,DorianGray/busted,sobrinho/busted
006a8cc9d284c7c0ee983f6963441d40f4877198
core/certmanager.lua
core/certmanager.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local configmanager = require "core.configmanager"; local log = require "util.logger".init("certmanager"); local ssl = ssl; local ssl_newcontext = ssl and ssl.newcontext; local tostring = tostring; local type = type; local io_open = io.open; local prosody = prosody; local resolve_path = configmanager.resolve_relative_path; local config_path = prosody.paths.config; local luasec_has_noticket, luasec_has_verifyext, luasec_has_no_compression; if ssl then local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)"); luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4; luasec_has_verifyext = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5; luasec_has_no_compression = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5; end module "certmanager" -- Global SSL options if not overridden per-host local default_ssl_config = configmanager.get("*", "ssl"); local default_capath = "/etc/ssl/certs"; local default_verify = (ssl and ssl.x509 and { "peer", "client_once", }) or "none"; local default_options = { "no_sslv2", "no_sslv3", luasec_has_noticket and "no_ticket" or nil, "cipher_server_preference" }; local default_verifyext = { "lsec_continue", "lsec_ignore_purpose" }; if ssl and not luasec_has_verifyext and ssl.x509 then -- COMPAT mw/luasec-hg for i=1,#default_verifyext do -- Remove lsec_ prefix default_verify[#default_verify+1] = default_verifyext[i]:sub(6); end end if luasec_has_no_compression and configmanager.get("*", "ssl_compression") ~= true then default_options[#default_options+1] = "no_compression"; end if luasec_has_no_compression then -- Has no_compression? Then it has these too... default_options[#default_options+1] = "single_dh_use"; default_options[#default_options+1] = "single_ecdh_use"; end function create_context(host, mode, user_ssl_config) user_ssl_config = user_ssl_config or default_ssl_config; if not ssl then return nil, "LuaSec (required for encryption) was not found"; end if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end local ssl_config = { mode = mode; protocol = user_ssl_config.protocol or "sslv23"; key = resolve_path(config_path, user_ssl_config.key); password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end; certificate = resolve_path(config_path, user_ssl_config.certificate); capath = resolve_path(config_path, user_ssl_config.capath or default_capath); cafile = resolve_path(config_path, user_ssl_config.cafile); verify = user_ssl_config.verify or default_verify; verifyext = user_ssl_config.verifyext or default_verifyext; options = user_ssl_config.options or default_options; depth = user_ssl_config.depth; curve = user_ssl_config.curve or "secp384r1"; ciphers = user_ssl_config.ciphers or "HIGH:!DSS:!aNULL@STRENGTH"; dhparam = user_ssl_config.dhparam; }; -- LuaSec expects dhparam to be a callback that takes two arguments. -- We ignore those because it is mostly used for having a separate -- set of params for EXPORT ciphers, which we don't have by default. if type(ssl_config.dhparam) == "string" then local f, err = io_open(resolve_path(config_path, ssl_config.dhparam)); if not f then return nil, "Could not open DH parameters: "..err end local dhparam = f:read("*a"); f:close(); ssl_config.dhparam = function() return dhparam; end end local ctx, err = ssl_newcontext(ssl_config); -- COMPAT: LuaSec 0.4.1 ignores the cipher list from the config, so we have to take -- care of it ourselves... if ctx and ssl_config.ciphers then local success; success, err = ssl.context.setcipher(ctx, ssl_config.ciphers); if not success then ctx = nil; end end if not ctx then err = err or "invalid ssl config" local file = err:match("^error loading (.-) %("); if file then if file == "private key" then file = ssl_config.key or "your private key"; elseif file == "certificate" then file = ssl_config.certificate or "your certificate file"; end local reason = err:match("%((.+)%)$") or "some reason"; if reason == "Permission denied" then reason = "Check that the permissions allow Prosody to read this file."; elseif reason == "No such file or directory" then reason = "Check that the path is correct, and the file exists."; elseif reason == "system lib" then reason = "Previous error (see logs), or other system error."; elseif reason == "(null)" or not reason then reason = "Check that the file exists and the permissions are correct"; else reason = "Reason: "..tostring(reason):lower(); end log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host); else log("error", "SSL/TLS: Error initialising for %s: %s", host, err); end end return ctx, err; end function reload_ssl_config() default_ssl_config = configmanager.get("*", "ssl"); end prosody.events.add_handler("config-reloaded", reload_ssl_config); return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local configmanager = require "core.configmanager"; local log = require "util.logger".init("certmanager"); local ssl = ssl; local ssl_newcontext = ssl and ssl.newcontext; local tostring = tostring; local type = type; local io_open = io.open; local prosody = prosody; local resolve_path = configmanager.resolve_relative_path; local config_path = prosody.paths.config; local luasec_has_noticket, luasec_has_verifyext, luasec_has_no_compression; if ssl then local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)"); luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4; luasec_has_verifyext = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5; luasec_has_no_compression = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5; end module "certmanager" -- Global SSL options if not overridden per-host local default_ssl_config = configmanager.get("*", "ssl"); local default_capath = "/etc/ssl/certs"; local default_verify = (ssl and ssl.x509 and { "peer", "client_once", }) or "none"; local default_options = { "no_sslv2", "no_sslv3", "cipher_server_preference", luasec_has_noticket and "no_ticket" or nil }; local default_verifyext = { "lsec_continue", "lsec_ignore_purpose" }; if ssl and not luasec_has_verifyext and ssl.x509 then -- COMPAT mw/luasec-hg for i=1,#default_verifyext do -- Remove lsec_ prefix default_verify[#default_verify+1] = default_verifyext[i]:sub(6); end end if luasec_has_no_compression and configmanager.get("*", "ssl_compression") ~= true then default_options[#default_options+1] = "no_compression"; end if luasec_has_no_compression then -- Has no_compression? Then it has these too... default_options[#default_options+1] = "single_dh_use"; default_options[#default_options+1] = "single_ecdh_use"; end function create_context(host, mode, user_ssl_config) user_ssl_config = user_ssl_config or default_ssl_config; if not ssl then return nil, "LuaSec (required for encryption) was not found"; end if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end local ssl_config = { mode = mode; protocol = user_ssl_config.protocol or "sslv23"; key = resolve_path(config_path, user_ssl_config.key); password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end; certificate = resolve_path(config_path, user_ssl_config.certificate); capath = resolve_path(config_path, user_ssl_config.capath or default_capath); cafile = resolve_path(config_path, user_ssl_config.cafile); verify = user_ssl_config.verify or default_verify; verifyext = user_ssl_config.verifyext or default_verifyext; options = user_ssl_config.options or default_options; depth = user_ssl_config.depth; curve = user_ssl_config.curve or "secp384r1"; ciphers = user_ssl_config.ciphers or "HIGH:!DSS:!aNULL@STRENGTH"; dhparam = user_ssl_config.dhparam; }; -- LuaSec expects dhparam to be a callback that takes two arguments. -- We ignore those because it is mostly used for having a separate -- set of params for EXPORT ciphers, which we don't have by default. if type(ssl_config.dhparam) == "string" then local f, err = io_open(resolve_path(config_path, ssl_config.dhparam)); if not f then return nil, "Could not open DH parameters: "..err end local dhparam = f:read("*a"); f:close(); ssl_config.dhparam = function() return dhparam; end end local ctx, err = ssl_newcontext(ssl_config); -- COMPAT: LuaSec 0.4.1 ignores the cipher list from the config, so we have to take -- care of it ourselves... if ctx and ssl_config.ciphers then local success; success, err = ssl.context.setcipher(ctx, ssl_config.ciphers); if not success then ctx = nil; end end if not ctx then err = err or "invalid ssl config" local file = err:match("^error loading (.-) %("); if file then if file == "private key" then file = ssl_config.key or "your private key"; elseif file == "certificate" then file = ssl_config.certificate or "your certificate file"; end local reason = err:match("%((.+)%)$") or "some reason"; if reason == "Permission denied" then reason = "Check that the permissions allow Prosody to read this file."; elseif reason == "No such file or directory" then reason = "Check that the path is correct, and the file exists."; elseif reason == "system lib" then reason = "Previous error (see logs), or other system error."; elseif reason == "(null)" or not reason then reason = "Check that the file exists and the permissions are correct"; else reason = "Reason: "..tostring(reason):lower(); end log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host); else log("error", "SSL/TLS: Error initialising for %s: %s", host, err); end end return ctx, err; end function reload_ssl_config() default_ssl_config = configmanager.get("*", "ssl"); end prosody.events.add_handler("config-reloaded", reload_ssl_config); return _M;
certmanager: Fix order of options, so that the dynamic option is at the end of the array
certmanager: Fix order of options, so that the dynamic option is at the end of the array
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
9c69c1f14eebc1df5854ba6057ace60ef068398e
frontend/ui/widget/container/underlinecontainer.lua
frontend/ui/widget/container/underlinecontainer.lua
local WidgetContainer = require("ui/widget/container/widgetcontainer") local Geom = require("ui/geometry") local Blitbuffer = require("ffi/blitbuffer") --[[ an UnderlineContainer is a WidgetContainer that is able to paint a line under its child node --]] local UnderlineContainer = WidgetContainer:new{ linesize = 2, padding = 1, -- TODO: shouldn't this default to black instead? color = Blitbuffer.COLOR_WHITE, vertical_align = "top", } function UnderlineContainer:getSize() return self:getContentSize() end function UnderlineContainer:getContentSize() local contentSize = self[1]:getSize() return Geom:new{ w = contentSize.w, h = contentSize.h + self.linesize + self.padding } end function UnderlineContainer:paintTo(bb, x, y) local container_size = self:getSize() local content_size = self:getContentSize() local p_y = y if self.vertical_align == "center" then p_y = math.floor((container_size.h - content_size.h) / 2) + y elseif self.vertical_align == "bottom" then p_y = (container_size.h - content_size.h) + y end self[1]:paintTo(bb, x, p_y) bb:paintRect(x, y + container_size.h - self.linesize, container_size.w, self.linesize, self.color) end return UnderlineContainer
local WidgetContainer = require("ui/widget/container/widgetcontainer") local Geom = require("ui/geometry") local Blitbuffer = require("ffi/blitbuffer") --[[ an UnderlineContainer is a WidgetContainer that is able to paint a line under its child node --]] local UnderlineContainer = WidgetContainer:new{ linesize = 2, padding = 1, -- TODO: shouldn't this default to black instead? color = Blitbuffer.COLOR_WHITE, vertical_align = "top", } function UnderlineContainer:getSize() return self:getContentSize() end function UnderlineContainer:getContentSize() local contentSize = self[1]:getSize() return Geom:new{ w = contentSize.w, h = contentSize.h + self.linesize + self.padding } end function UnderlineContainer:paintTo(bb, x, y) local container_size = self:getSize() self.dimen = Geom:new{ x = x, y = y, w = container_size.w, h = container_size.h } local content_size = self:getContentSize() local p_y = y if self.vertical_align == "center" then p_y = math.floor((container_size.h - content_size.h) / 2) + y elseif self.vertical_align == "bottom" then p_y = (container_size.h - content_size.h) + y end self[1]:paintTo(bb, x, p_y) bb:paintRect(x, y + container_size.h - self.linesize, container_size.w, self.linesize, self.color) end return UnderlineContainer
Fix #1299
Fix #1299
Lua
agpl-3.0
chihyang/koreader,robert00s/koreader,NiLuJe/koreader,chrox/koreader,Frenzie/koreader,mwoz123/koreader,Markismus/koreader,NickSavage/koreader,houqp/koreader,Frenzie/koreader,poire-z/koreader,noname007/koreader,ashang/koreader,Hzj-jie/koreader,pazos/koreader,NiLuJe/koreader,ashhher3/koreader,apletnev/koreader,mihailim/koreader,koreader/koreader,frankyifei/koreader,koreader/koreader,lgeek/koreader,poire-z/koreader
e72408a823322af472072e325570b77c95fba6bc
kong/runloop/certificate.lua
kong/runloop/certificate.lua
local singletons = require "kong.singletons" local ngx_ssl = require "ngx.ssl" local pl_utils = require "pl.utils" local mlcache = require "resty.mlcache" local ngx_log = ngx.log local ERR = ngx.ERR local DEBUG = ngx.DEBUG local re_sub = ngx.re.sub local find = string.find local server_name = ngx_ssl.server_name local clear_certs = ngx_ssl.clear_certs local parse_pem_cert = ngx_ssl.parse_pem_cert local parse_pem_priv_key = ngx_ssl.parse_pem_priv_key local set_cert = ngx_ssl.set_cert local set_priv_key = ngx_ssl.set_priv_key local default_cert_and_key local function log(lvl, ...) ngx_log(lvl, "[ssl] ", ...) end local function parse_key_and_cert(row) if row == false then return default_cert_and_key end -- parse cert and priv key for later usage by ngx.ssl local cert, err = parse_pem_cert(row.cert) if not cert then return nil, "could not parse PEM certificate: " .. err end local key, err = parse_pem_priv_key(row.key) if not key then return nil, "could not parse PEM private key: " .. err end return { cert = cert, key = key, } end local function produce_wild_snis(sni) if type(sni) ~= "string" then error("sni must be a string", 2) end local wild_prefix_sni local wild_suffix_sni local wild_idx = find(sni, "*", nil, true) if wild_idx == 1 then wild_prefix_sni = sni elseif not wild_idx then -- *.example.com lookup local wild_sni, n, err = re_sub(sni, [[([^.]+)(\.[^.]+\.\S+)]], "*$2", "ajo") if err then log(ERR, "could not create SNI wildcard for SNI lookup: ", err) elseif n > 0 then wild_prefix_sni = wild_sni end end if wild_idx == #sni then wild_suffix_sni = sni elseif not wild_idx then -- example.* lookup local wild_sni, n, err = re_sub(sni, [[([^.]+\.)([^.]+)$]], "$1*", "jo") if err then log(ERR, "could not create SNI wildcard for SNI lookup: ", err) elseif n > 0 then wild_suffix_sni = wild_sni end end return wild_prefix_sni, wild_suffix_sni end local function fetch_sni(sni, i) local row, err = singletons.db.snis:select_by_name(sni) if err then return nil, "failed to fetch '" .. sni .. "' SNI: " .. err, i end if not row then return false, nil, i end return row, nil, i end local function fetch_certificate(pk, sni_name) local certificate, err = singletons.db.certificates:select(pk) if err then if sni_name then return nil, "failed to fetch certificate for '" .. sni_name .. "' SNI: " .. err end return nil, "failed to fetch certificate " .. pk.id end if not certificate then if sni_name then return nil, "no SSL certificate configured for sni: " .. sni_name end return nil, "certificate " .. pk.id .. " not found" end return certificate end local get_certificate_opts = { l1_serializer = parse_key_and_cert, } local function init() default_cert_and_key = parse_key_and_cert { cert = assert(pl_utils.readfile(singletons.configuration.ssl_cert)), key = assert(pl_utils.readfile(singletons.configuration.ssl_cert_key)), } end local function get_certificate(pk, sni_name) return kong.core_cache:get("certificates:" .. pk.id, get_certificate_opts, fetch_certificate, pk, sni_name) end local function find_certificate(sni) if not sni then log(DEBUG, "no SNI provided by client, serving default SSL certificate") return default_cert_and_key end local sni_wild_pref, sni_wild_suf = produce_wild_snis(sni) local bulk = mlcache.new_bulk(3) bulk:add("snis:" .. sni, nil, fetch_sni, sni) if sni_wild_pref then bulk:add("snis:" .. sni_wild_pref, nil, fetch_sni, sni_wild_pref) end if sni_wild_suf then bulk:add("snis:" .. sni_wild_suf, nil, fetch_sni, sni_wild_suf) end local res, err = kong.core_cache:get_bulk(bulk) if err then return nil, err end for _, sni, err in mlcache.each_bulk_res(res) do if err then log(ERR, "failed to fetch SNI: ", err) elseif sni then return get_certificate(sni.certificate, sni.name) end end return default_cert_and_key end local function execute() local sn, err = server_name() if err then log(ERR, "could not retrieve SNI: ", err) return ngx.exit(ngx.ERROR) end local cert_and_key, err = find_certificate(sn) if err then log(ERR, err) return ngx.exit(ngx.ERROR) end if cert_and_key == default_cert_and_key then -- use (already set) fallback certificate return end -- set the certificate for this connection local ok, err = clear_certs() if not ok then log(ERR, "could not clear existing (default) certificates: ", err) return ngx.exit(ngx.ERROR) end ok, err = set_cert(cert_and_key.cert) if not ok then log(ERR, "could not set configured certificate: ", err) return ngx.exit(ngx.ERROR) end ok, err = set_priv_key(cert_and_key.key) if not ok then log(ERR, "could not set configured private key: ", err) return ngx.exit(ngx.ERROR) end end return { init = init, find_certificate = find_certificate, produce_wild_snis = produce_wild_snis, execute = execute, get_certificate = get_certificate, }
local singletons = require "kong.singletons" local ngx_ssl = require "ngx.ssl" local pl_utils = require "pl.utils" local mlcache = require "resty.mlcache" if jit.arch == 'arm64' then jit.off(mlcache.get_bulk) -- "temporary" workaround for issue #5748 on ARM end local ngx_log = ngx.log local ERR = ngx.ERR local DEBUG = ngx.DEBUG local re_sub = ngx.re.sub local find = string.find local server_name = ngx_ssl.server_name local clear_certs = ngx_ssl.clear_certs local parse_pem_cert = ngx_ssl.parse_pem_cert local parse_pem_priv_key = ngx_ssl.parse_pem_priv_key local set_cert = ngx_ssl.set_cert local set_priv_key = ngx_ssl.set_priv_key local default_cert_and_key local function log(lvl, ...) ngx_log(lvl, "[ssl] ", ...) end local function parse_key_and_cert(row) if row == false then return default_cert_and_key end -- parse cert and priv key for later usage by ngx.ssl local cert, err = parse_pem_cert(row.cert) if not cert then return nil, "could not parse PEM certificate: " .. err end local key, err = parse_pem_priv_key(row.key) if not key then return nil, "could not parse PEM private key: " .. err end return { cert = cert, key = key, } end local function produce_wild_snis(sni) if type(sni) ~= "string" then error("sni must be a string", 2) end local wild_prefix_sni local wild_suffix_sni local wild_idx = find(sni, "*", nil, true) if wild_idx == 1 then wild_prefix_sni = sni elseif not wild_idx then -- *.example.com lookup local wild_sni, n, err = re_sub(sni, [[([^.]+)(\.[^.]+\.\S+)]], "*$2", "ajo") if err then log(ERR, "could not create SNI wildcard for SNI lookup: ", err) elseif n > 0 then wild_prefix_sni = wild_sni end end if wild_idx == #sni then wild_suffix_sni = sni elseif not wild_idx then -- example.* lookup local wild_sni, n, err = re_sub(sni, [[([^.]+\.)([^.]+)$]], "$1*", "jo") if err then log(ERR, "could not create SNI wildcard for SNI lookup: ", err) elseif n > 0 then wild_suffix_sni = wild_sni end end return wild_prefix_sni, wild_suffix_sni end local function fetch_sni(sni, i) local row, err = singletons.db.snis:select_by_name(sni) if err then return nil, "failed to fetch '" .. sni .. "' SNI: " .. err, i end if not row then return false, nil, i end return row, nil, i end local function fetch_certificate(pk, sni_name) local certificate, err = singletons.db.certificates:select(pk) if err then if sni_name then return nil, "failed to fetch certificate for '" .. sni_name .. "' SNI: " .. err end return nil, "failed to fetch certificate " .. pk.id end if not certificate then if sni_name then return nil, "no SSL certificate configured for sni: " .. sni_name end return nil, "certificate " .. pk.id .. " not found" end return certificate end local get_certificate_opts = { l1_serializer = parse_key_and_cert, } local function init() default_cert_and_key = parse_key_and_cert { cert = assert(pl_utils.readfile(singletons.configuration.ssl_cert)), key = assert(pl_utils.readfile(singletons.configuration.ssl_cert_key)), } end local function get_certificate(pk, sni_name) return kong.core_cache:get("certificates:" .. pk.id, get_certificate_opts, fetch_certificate, pk, sni_name) end local function find_certificate(sni) if not sni then log(DEBUG, "no SNI provided by client, serving default SSL certificate") return default_cert_and_key end local sni_wild_pref, sni_wild_suf = produce_wild_snis(sni) local bulk = mlcache.new_bulk(3) bulk:add("snis:" .. sni, nil, fetch_sni, sni) if sni_wild_pref then bulk:add("snis:" .. sni_wild_pref, nil, fetch_sni, sni_wild_pref) end if sni_wild_suf then bulk:add("snis:" .. sni_wild_suf, nil, fetch_sni, sni_wild_suf) end local res, err = kong.core_cache:get_bulk(bulk) if err then return nil, err end for _, sni, err in mlcache.each_bulk_res(res) do if err then log(ERR, "failed to fetch SNI: ", err) elseif sni then return get_certificate(sni.certificate, sni.name) end end return default_cert_and_key end local function execute() local sn, err = server_name() if err then log(ERR, "could not retrieve SNI: ", err) return ngx.exit(ngx.ERROR) end local cert_and_key, err = find_certificate(sn) if err then log(ERR, err) return ngx.exit(ngx.ERROR) end if cert_and_key == default_cert_and_key then -- use (already set) fallback certificate return end -- set the certificate for this connection local ok, err = clear_certs() if not ok then log(ERR, "could not clear existing (default) certificates: ", err) return ngx.exit(ngx.ERROR) end ok, err = set_cert(cert_and_key.cert) if not ok then log(ERR, "could not set configured certificate: ", err) return ngx.exit(ngx.ERROR) end ok, err = set_priv_key(cert_and_key.key) if not ok then log(ERR, "could not set configured private key: ", err) return ngx.exit(ngx.ERROR) end end return { init = init, find_certificate = find_certificate, produce_wild_snis = produce_wild_snis, execute = execute, get_certificate = get_certificate, }
fix(cache) disable JIT mlcache:get_bulk() on ARM64 (#5797)
fix(cache) disable JIT mlcache:get_bulk() on ARM64 (#5797) The loop inside this function can trigger a trace restart that results in a wrong value in the local index variable. (kong#5748) until this is fixed in LuaJIT, disabling JIT for this function avoids the problem.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
35a6e73409be9978444cf767498c42b375a70ef6
test/performance/observed-concurrency/reporter.lua
test/performance/observed-concurrency/reporter.lua
-- Copyright 2018 The Knative Authors -- -- 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 -- -- https://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- parses a response as returned by the system under test function parse_response(res) local split_at, _ = res:find(',', 0) local start_ts = tonumber(res:sub(0, split_at-1)) local end_ts = tonumber(res:sub(split_at+1)) return start_ts, end_ts end -- converts nanoseconds to milliseconds function nanos_to_millis(n) return math.floor(n / 1000000) end -- returns the time it took to scale up to a certain scale -- returns -1 if that scale was never reached function time_to_scale(accumulated, scale) for _, result in pairs(accumulated) do if result['concurrency'] >= scale then return result['time'] end end return -1 end local threads = {} function setup(thread) table.insert(threads, thread) end function init(args) starts = {} ends = {} end function response(status, headers, body) start_ts, end_ts = parse_response(body) table.insert(starts, nanos_to_millis(start_ts)) table.insert(ends, nanos_to_millis(end_ts)) end function done(summary, latency, requests) local results = {} for _, thread in pairs(threads) do for _, start_ts in pairs(thread:get('starts')) do table.insert(results, {time=start_ts, concurrency_modifier=1}) end for _, end_ts in pairs(thread:get('ends')) do table.insert(results, {time=end_ts, concurrency_modifier=1}) end end table.sort(results, function(e1, e2) return e1['time'] < e2['time'] end) local accumulated_results = {} local start_time = results[1]['time'] local current_time = -1 local current_concurrency = 0 local bucket_interval = 50 for _, result in pairs(results) do local result_time = result['time'] local concurrency_modifier = result['concurrency_modifier'] current_concurrency = current_concurrency + concurrency_modifier if current_time - bucket_interval <= result_time and current_time + bucket_interval >= result_time then -- accumulate while still inside the bucket interval accumulated_results[-1]['concurrency'] = current_concurrency else -- create a new entry if outside the bucket interval table.insert(accumulated_results, {time=result_time - start_time, concurrency=current_concurrency}) end end -- caveat: need to set the target concurrency as an environment variables -- even though it should be the very same as the number of connections passed -- to wrk. That option is not available here. local concurrency = tonumber(os.getenv('concurrency')) print() print('Scaling statistics:') print(' Time to scale (to ' .. concurrency .. '): ' .. time_to_scale(accumulated_results, concurrency) .. ' ms') print(' Time to scale breakdown:') for scale = 1,concurrency,1 do print(' ' .. scale .. ': ' .. time_to_scale(accumulated_results, scale) .. ' ms') end end
-- Copyright 2018 The Knative Authors -- -- 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 -- -- https://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- parses a response as returned by the system under test function parse_response(res) local split_at, _ = res:find(',', 0) local start_ts = tonumber(res:sub(0, split_at-1)) local end_ts = tonumber(res:sub(split_at+1)) return start_ts, end_ts end -- converts nanoseconds to milliseconds function nanos_to_millis(n) return math.floor(n / 1000000) end -- returns the time it took to scale up to a certain scale -- returns -1 if that scale was never reached function time_to_scale(accumulated, scale) for _, result in pairs(accumulated) do if result['concurrency'] >= scale then return result['time'] end end return -1 end local threads = {} function setup(thread) table.insert(threads, thread) if tonumber(os.getenv('concurrency')) == nil then print('"concurrency" environment variable must be defined and be a number. Set it to the number of connections configured for wrk.') os.exit() end end function init(args) starts = {} ends = {} end function response(status, headers, body) start_ts, end_ts = parse_response(body) table.insert(starts, nanos_to_millis(start_ts)) table.insert(ends, nanos_to_millis(end_ts)) end function done(summary, latency, requests) local results = {} for _, thread in pairs(threads) do for _, start_ts in pairs(thread:get('starts')) do table.insert(results, {time=start_ts, concurrency_modifier=1}) end for _, end_ts in pairs(thread:get('ends')) do table.insert(results, {time=end_ts, concurrency_modifier=1}) end end table.sort(results, function(e1, e2) return e1['time'] < e2['time'] end) local accumulated_results = {} local start_time = results[1]['time'] local current_time = -1 local current_concurrency = 0 local bucket_interval = 50 for _, result in pairs(results) do local result_time = result['time'] local concurrency_modifier = result['concurrency_modifier'] current_concurrency = current_concurrency + concurrency_modifier if current_time - bucket_interval <= result_time and current_time + bucket_interval >= result_time then -- accumulate while still inside the bucket interval accumulated_results[-1]['concurrency'] = current_concurrency else -- create a new entry if outside the bucket interval table.insert(accumulated_results, {time=result_time - start_time, concurrency=current_concurrency}) end end -- caveat: need to set the target concurrency as an environment variables -- even though it should be the very same as the number of connections passed -- to wrk. That option is not available here. local concurrency = tonumber(os.getenv('concurrency')) print() print('Scaling statistics:') print(' Time to scale (to ' .. concurrency .. '): ' .. time_to_scale(accumulated_results, concurrency) .. ' ms') print(' Time to scale breakdown:') for scale = 1,concurrency,1 do print(' ' .. scale .. ': ' .. time_to_scale(accumulated_results, scale) .. ' ms') end end
Report clear error on missing configuration in observed-concurrency test. (#2023)
Report clear error on missing configuration in observed-concurrency test. (#2023) * Report clear error on missing configuration in observed-concurrency test. Due to a limitation of wrk's lua script, it's not possible to obtain the parameters passed to the wrk call itself inside the lua script. To work around that, the script needs an environment variable 'concurrency' set to the amount of connections configured for wrk. If that's not present, the script will panic in the end. This adds a validation step to exit early if the variable is not present. Fixes #2012. * Actually check for a number.
Lua
apache-2.0
knative/serving,knative/serving
af3e8b4a4da8e2ca20639b1a3f950c69b0e23a73
premake5.lua
premake5.lua
libyojimbo_version = "0.2.0-preview3" if os.is "windows" then sodium_debug = "sodium-debug" sodium_release = "sodium-release" else sodium_debug = "sodium" sodium_release = "sodium" end solution "Yojimbo" platforms { "x64" } includedirs { "." } if not os.is "windows" then targetdir "bin/" end configurations { "Debug", "Release" } flags { "ExtraWarnings", "FatalWarnings", "StaticRuntime", "FloatFast" } rtti "Off" configuration "Debug" flags { "Symbols" } defines { "DEBUG" } configuration "Release" optimize "Speed" defines { "NDEBUG" } project "test" language "C++" kind "ConsoleApp" files { "test.cpp" } links { "yojimbo" } --, "ucl" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "network_info" language "C++" kind "ConsoleApp" files { "network_info.cpp" } links { "yojimbo" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "yojimbo" language "C++" kind "StaticLib" files { "yojimbo.h", "yojimbo.cpp", "yojimbo_*.h", "yojimbo_*.cpp" } links { "sodium" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "client" language "C++" kind "ConsoleApp" files { "client.cpp", "shared.h" } links { "yojimbo" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "server" language "C++" kind "ConsoleApp" files { "server.cpp", "shared.h" } links { "yojimbo" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "client_server" language "C++" kind "ConsoleApp" files { "client_server.cpp", "shared.h" } links { "yojimbo" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } if _ACTION == "clean" then os.rmdir "obj" os.rmdir "ipch" os.rmdir "bin" os.rmdir ".vs" os.rmdir "Debug" os.rmdir "Release" os.rmdir "docker/libyojimbo" if not os.is "windows" then os.execute "rm -f Makefile" os.execute "rm -f *.7z" os.execute "rm -f *.zip" os.execute "rm -f *.tar.gz" os.execute "rm -f *.zip" os.execute "rm -f *.make" os.execute "rm -f test" os.execute "rm -f network_info" os.execute "rm -f client" os.execute "rm -f server" os.execute "rm -f client_server" os.execute "rm -rf docker/libyojimbo" os.execute "find . -name .DS_Store -delete" else os.execute "del /F /Q Makefile" os.execute "del /F /Q *.make" os.execute "del /F /Q *.db" os.execute "del /F /Q *.opendb" os.execute "del /F /Q *.vcproj" os.execute "del /F /Q *.vcxproj" os.execute "del /F /Q *.vcxproj.user" os.execute "del /F /Q *.sln" end end if not os.is "windows" then newaction { trigger = "release", description = "Create up a release of this project", execute = function () _ACTION = "clean" premake.action.call( "clean" ) files_to_zip = ".zip *.md *.cpp *.h premake5.lua sodium sodium-*.lib docker" os.execute( "rm -rf *.zip *.tar.gz *.7z" ); os.execute( "zip -9r libyojimbo-" .. libyojimbo_version .. files_to_zip ) os.execute( "7z a -mx=9 -p\"information wants to be free\" libyojimbo-" .. libyojimbo_version .. ".7z *.md *.cpp *.h premake5.lua sodium sodium-*.lib" ) os.execute( "unzip libyojimbo-" .. libyojimbo_version .. ".zip -d libyojimbo-" .. libyojimbo_version ); os.execute( "tar -zcvf libyojimbo-" .. libyojimbo_version .. ".tar.gz libyojimbo-" .. libyojimbo_version ); os.execute( "rm -rf libyojimbo-" .. libyojimbo_version ); os.execute( "echo" ); os.execute( "echo \"*** SUCCESSFULLY CREATED RELEASE - libyojimbo-" .. libyojimbo_version .. " *** \"" ); os.execute( "echo" ); end } newaction { trigger = "test", description = "Build and run all unit tests", execute = function () if os.execute "make -j4 test" == 0 then os.execute "./bin/test" end end } newaction { trigger = "info", description = "Build and run network info utility", execute = function () if os.execute "make -j4 network_info" == 0 then os.execute "./bin/network_info" end end } newaction { trigger = "yojimbo", description = "Build yojimbo client/server network protocol library", execute = function () os.execute "make -j4 yojimbo" end } newaction { trigger = "cs", description = "Build and run client/server testbed", execute = function () if os.execute "make -j4 client_server" == 0 then os.execute "./bin/client_server" end end } newoption { trigger = "serverAddress", value = "IP[:port]", description = "Specify the server address that the client should connect to", } newaction { trigger = "client", description = "Build and run client", valid_kinds = premake.action.get("gmake").valid_kinds, valid_languages = premake.action.get("gmake").valid_languages, valid_tools = premake.action.get("gmake").valid_tools, execute = function () if os.execute "make -j4 client" == 0 then if _OPTIONS["serverAddress"] then os.execute( "./bin/client " .. _OPTIONS["serverAddress"] ) else os.execute "./bin/client" end end end } newaction { trigger = "server", description = "Build and run server", execute = function () if os.execute "make -j4 server" == 0 then os.execute "./bin/server" end end } newaction { trigger = "docker", description = "Build and run a yojimbo server inside a docker container", execute = function () os.execute "rm -rf docker/libyojimbo && mkdir -p docker/libyojimbo && cp *.h docker/libyojimbo && cp *.cpp docker/libyojimbo && cp premake5.lua docker/libyojimbo && cd docker && docker build -t \"networkprotocol:yojimbo-server\" . && rm -rf libyojimbo && docker run -ti -p 127.0.0.1:50000:50000/udp networkprotocol:yojimbo-server" end } else newaction { trigger = "docker", description = "Build and run a yojimbo server inside a docker container", execute = function () os.execute "cd docker && copyFiles.bat && buildServer.bat && runServer.bat" end } end
libyojimbo_version = "0.2.0-preview3" if os.is "windows" then sodium_debug = "sodium-debug" sodium_release = "sodium-release" else sodium_debug = "sodium" sodium_release = "sodium" end solution "Yojimbo" platforms { "x64" } includedirs { "." } if not os.is "windows" then targetdir "bin/" end configurations { "Debug", "Release" } flags { "ExtraWarnings", "FatalWarnings", "StaticRuntime", "FloatFast" } rtti "Off" configuration "Debug" flags { "Symbols" } defines { "DEBUG" } configuration "Release" optimize "Speed" defines { "NDEBUG" } project "test" language "C++" kind "ConsoleApp" files { "test.cpp" } links { "yojimbo" } --, "ucl" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "network_info" language "C++" kind "ConsoleApp" files { "network_info.cpp" } links { "yojimbo" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "yojimbo" language "C++" kind "StaticLib" files { "yojimbo.h", "yojimbo.cpp", "yojimbo_*.h", "yojimbo_*.cpp" } links { "sodium" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "client" language "C++" kind "ConsoleApp" files { "client.cpp", "shared.h" } links { "yojimbo" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "server" language "C++" kind "ConsoleApp" files { "server.cpp", "shared.h" } links { "yojimbo" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } project "client_server" language "C++" kind "ConsoleApp" files { "client_server.cpp", "shared.h" } links { "yojimbo" } configuration "Debug" links { sodium_debug } configuration "Release" links { sodium_release } if _ACTION == "clean" then os.rmdir "obj" os.rmdir "ipch" os.rmdir "bin" os.rmdir ".vs" os.rmdir "Debug" os.rmdir "Release" os.rmdir "docker/libyojimbo" if not os.is "windows" then os.execute "rm -f Makefile" os.execute "rm -f *.7z" os.execute "rm -f *.zip" os.execute "rm -f *.tar.gz" os.execute "rm -f *.zip" os.execute "rm -f *.make" os.execute "rm -f test" os.execute "rm -f network_info" os.execute "rm -f client" os.execute "rm -f server" os.execute "rm -f client_server" os.execute "rm -rf docker/libyojimbo" os.execute "find . -name .DS_Store -delete" else os.execute "del /F /Q Makefile" os.execute "del /F /Q *.make" os.execute "del /F /Q *.db" os.execute "del /F /Q *.opendb" os.execute "del /F /Q *.vcproj" os.execute "del /F /Q *.vcxproj" os.execute "del /F /Q *.vcxproj.user" os.execute "del /F /Q *.sln" end end if not os.is "windows" then newaction { trigger = "release", description = "Create up a release of this project", execute = function () _ACTION = "clean" premake.action.call( "clean" ) files_to_zip = ".zip *.md *.cpp *.h premake5.lua sodium sodium-*.lib docker" os.execute( "rm -rf *.zip *.tar.gz *.7z" ); os.execute( "rm -rf docker/libyojimbo" ); os.execute( "zip -9r libyojimbo-" .. libyojimbo_version .. files_to_zip ) os.execute( "7z a -mx=9 -p\"information wants to be free\" libyojimbo-" .. libyojimbo_version .. ".7z *.md *.cpp *.h premake5.lua sodium sodium-*.lib" ) os.execute( "unzip libyojimbo-" .. libyojimbo_version .. ".zip -d libyojimbo-" .. libyojimbo_version ); os.execute( "tar -zcvf libyojimbo-" .. libyojimbo_version .. ".tar.gz libyojimbo-" .. libyojimbo_version ); os.execute( "rm -rf libyojimbo-" .. libyojimbo_version ); os.execute( "echo" ); os.execute( "echo \"*** SUCCESSFULLY CREATED RELEASE - libyojimbo-" .. libyojimbo_version .. " *** \"" ); os.execute( "echo" ); end } newaction { trigger = "test", description = "Build and run all unit tests", execute = function () if os.execute "make -j4 test" == 0 then os.execute "./bin/test" end end } newaction { trigger = "info", description = "Build and run network info utility", execute = function () if os.execute "make -j4 network_info" == 0 then os.execute "./bin/network_info" end end } newaction { trigger = "yojimbo", description = "Build yojimbo client/server network protocol library", execute = function () os.execute "make -j4 yojimbo" end } newaction { trigger = "cs", description = "Build and run client/server testbed", execute = function () if os.execute "make -j4 client_server" == 0 then os.execute "./bin/client_server" end end } newoption { trigger = "serverAddress", value = "IP[:port]", description = "Specify the server address that the client should connect to", } newaction { trigger = "client", description = "Build and run client", valid_kinds = premake.action.get("gmake").valid_kinds, valid_languages = premake.action.get("gmake").valid_languages, valid_tools = premake.action.get("gmake").valid_tools, execute = function () if os.execute "make -j4 client" == 0 then if _OPTIONS["serverAddress"] then os.execute( "./bin/client " .. _OPTIONS["serverAddress"] ) else os.execute "./bin/client" end end end } newaction { trigger = "server", description = "Build and run server", execute = function () if os.execute "make -j4 server" == 0 then os.execute "./bin/server" end end } newaction { trigger = "docker", description = "Build and run a yojimbo server inside a docker container", execute = function () os.execute "rm -rf docker/libyojimbo && mkdir -p docker/libyojimbo && cp *.h docker/libyojimbo && cp *.cpp docker/libyojimbo && cp premake5.lua docker/libyojimbo && cd docker && docker build -t \"networkprotocol:yojimbo-server\" . && rm -rf libyojimbo && docker run -ti -p 127.0.0.1:50000:50000/udp networkprotocol:yojimbo-server" end } else newaction { trigger = "docker", description = "Build and run a yojimbo server inside a docker container", execute = function () os.execute "cd docker && copyFiles.bat && buildServer.bat && runServer.bat" end } end
fix docker/libyojimbo source copy being pulled into release zip
fix docker/libyojimbo source copy being pulled into release zip
Lua
bsd-3-clause
networkprotocol/yojimbo,networkprotocol/yojimbo,networkprotocol/yojimbo
262578b257c38214fa0adad80a3318d9e53fd530
src_trunk/resources/chat-system/c_chat_icon.lua
src_trunk/resources/chat-system/c_chat_icon.lua
function checkForChat() local chatting = getElementData(getLocalPlayer(), "chatting") if (isChatBoxInputActive() and chatting==0) then setElementData(getLocalPlayer(), "chatting", true, 1) elseif (not isChatBoxInputActive() and chatting==1) then setElementData(getLocalPlayer(), "chatting", true, 0) end end setTimer(checkForChat, 50, 0) setElementData(getLocalPlayer(), "chatting", true, 0) function render() local x, y, z = getElementPosition(getLocalPlayer()) for key, value in ipairs(getElementsByType("player")) do if (value~=getLocalPlayer()) then local chatting = getElementData(value, "chatting") if (chatting==1) then local px, py, pz = getPedBonePosition(value, 6) local dist = getDistanceBetweenPoints3D(x, y, z, px, py, pz) if (dist < 50) then local reconning = getElementData(value, "reconx") if (isLineOfSightClear(x, y, z, px, py, pz, true, false, false, false ) and isElementOnScreen(value)) and not (reconning) then local screenX, screenY = getScreenFromWorldPosition(px, py, pz+0.5) if (screenX and screenY) then local draw = dxDrawImage(screenX, screenY, 70, 70, "chat.png") end end end end end end end addEventHandler("onClientRender", getRootElement(), render) chaticon = true function toggleChatIcon() if (chaticon) then outputChatBox("Chat icons are now disabled.", 255, 0, 0) chaticon = false removeEventHandler("onClientRender", getRootElement(), render) else outputChatBox("Chat icons are now enabled.", 0, 255, 0) chaticon = true addEventHandler("onClientRender", getRootElement(), render) end end addCommandHandler("togglechaticons", toggleChatIcon, false) addCommandHandler("togchaticons", toggleChatIcon, false)
function checkForChat() local chatting = getElementData(getLocalPlayer(), "chatting") if (isChatBoxInputActive() and chatting==0) then setElementData(getLocalPlayer(), "chatting", true, 1) elseif (not isChatBoxInputActive() and chatting==1) then setElementData(getLocalPlayer(), "chatting", true, 0) end end setTimer(checkForChat, 50, 0) setElementData(getLocalPlayer(), "chatting", true, 0) function render() local x, y, z = getElementPosition(getLocalPlayer()) for key, value in ipairs(getElementsByType("player")) do if (value~=getLocalPlayer()) then local chatting = getElementData(value, "chatting") if (chatting==1) then local px, py, pz = getPedBonePosition(value, 6) local dist = getDistanceBetweenPoints3D(x, y, z, px, py, pz) if (dist < 25) then local reconning = getElementData(value, "reconx") if (isLineOfSightClear(x, y, z, px, py, pz, true, false, false, false ) and isElementOnScreen(value)) and not (reconning) then local screenX, screenY = getScreenFromWorldPosition(px, py, pz+0.5) if (screenX and screenY) then dist = dist / 5 if (dist<1) then dist = 1 end --if (dist>2) then dist = 2 end local offset = 70 / dist local draw = dxDrawImage(screenX, screenY, 60 / dist, 60 / dist, "chat.png") end end end end end end end addEventHandler("onClientRender", getRootElement(), render) chaticon = true function toggleChatIcon() if (chaticon) then outputChatBox("Chat icons are now disabled.", 255, 0, 0) chaticon = false removeEventHandler("onClientRender", getRootElement(), render) else outputChatBox("Chat icons are now enabled.", 0, 255, 0) chaticon = true addEventHandler("onClientRender", getRootElement(), render) end end addCommandHandler("togglechaticons", toggleChatIcon, false) addCommandHandler("togchaticons", toggleChatIcon, false)
Fixed 516
Fixed 516 git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@554 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
4954054a8042d210535dad1a6409522e9a0b4904
src/core/Group.lua
src/core/Group.lua
-------------------------------------------------------------------------------- -- -- -- -------------------------------------------------------------------------------- local Group = class() Group.__index = MOAIProp.getInterfaceTable() Group.__moai_class = MOAIProp --- -- The constructor. -- @param layer (option)layer object -- @param width (option)width -- @param height (option)height function Group:init(layer, width, height) self.children = {} self.layer = layer self:setSize(width or 0, height or 0) end --- -- Sets the size. -- This is the size of a Group, rather than of the children. -- @param width width -- @param height height function Group:setSize(width, height) self:setBounds(-0.5 * width, -0.5 * height, 0, 0.5 * width, 0.5 * height, 0) end --- -- Sets scissor rect recursively for all children -- @param MOAIScissorRect scissor rect function Group:setScissorRect(scissorRect) self.scissorRect = scissorRect for i, child in ipairs(self.children) do child:setScissorRect(scissorRect) end end --- -- Returns child with specified name or nil if not found -- @param string name -- @return object function Group:getChildByName(name) for i, child in ipairs(self.children) do if child.name == name then return child end end return nil end --- -- Adds the specified child. -- @param child DisplayObject -- @param index (option) number index at which to insert child function Group:addChild(child, index) if not table.includes(self.children, child) then index = index or (1 + #self.children) index = math.clamp(index, 1, #self.children + 1) table.insert(self.children, index, child) child:setParent(self) child:setLayer(self.layer) if self.scissorRect then child:setScissorRect(self.scissorRect) end return true end return false end --- -- Add objects to group. -- Provides compatibility with propertyUtils -- @param vararg objects function Group:setChildren(...) local children = {...} for i, child in ipairs(children) do self:addChild(child) end end --- -- Removes a child. -- @param child DisplayObject -- @return True if removed. function Group:removeChild(child) if table.removeElement(self.children, child) then child:setParent(nil) child:setLayer(nil) child:setScissorRect(nil) return true end return false end --- -- Remove the children. function Group:removeChildren() local children = table.dup(self.children) for i, child in ipairs(children) do self:removeChild(child) end end --- -- Sets the layer for this group to use. -- @param layer MOAILayer object function Group:setLayer(layer) if self.layer == layer then return end if self.layer then for i, v in ipairs(self.children) do if v.setLayer then v:setLayer(nil) else self.layer:removeProp(v) end end end self.layer = layer if self.layer then for i, v in ipairs(self.children) do if v.setLayer then v:setLayer(self.layer) else self.layer:insertProp(v) end end end end --- -- Sets the group's priority. -- Also sets the priority of any children. -- @param number priority -- @param number stride -- @return number priority of the last child function Group:setPriority(priority, stride) local stride = stride or 0 local priority = priority or 0 for i, v in ipairs(self.children) do local diff = v:setPriority(priority, stride) priority = priority + (diff or stride) end return priority end return Group
-------------------------------------------------------------------------------- -- -- -- -------------------------------------------------------------------------------- local Group = class() Group.__index = MOAIProp.getInterfaceTable() Group.__moai_class = MOAIProp --- -- The constructor. -- @param layer (option)layer object -- @param width (option)width -- @param height (option)height function Group:init(layer, width, height) self.children = {} self.layer = layer self:setSize(width or 0, height or 0) end --- -- Sets the size. -- This is the size of a Group, rather than of the children. -- @param width width -- @param height height function Group:setSize(width, height) self:setBounds(-0.5 * width, -0.5 * height, 0, 0.5 * width, 0.5 * height, 0) end --- -- Sets scissor rect recursively for all children -- @param MOAIScissorRect scissor rect function Group:setScissorRect(scissorRect) self.scissorRect = scissorRect for i, child in ipairs(self.children) do child:setScissorRect(scissorRect) end end --- -- Returns child with specified name or nil if not found -- @param string name -- @return object function Group:getChildByName(name) for i, child in ipairs(self.children) do if child.name == name then return child end end return nil end --- -- Adds the specified child. -- @param child DisplayObject -- @param index (option) number index at which to insert child function Group:addChild(child, index) if not table.includes(self.children, child) then index = index or (1 + #self.children) index = math.clamp(index, 1, #self.children + 1) table.insert(self.children, index, child) child:setParent(self) child:setLayer(self.layer) if self.scissorRect then child:setScissorRect(self.scissorRect) end return true end return false end --- -- Add objects to group. -- Provides compatibility with propertyUtils -- @param vararg objects function Group:setChildren(...) local children = {...} for i, child in ipairs(children) do self:addChild(child) end end --- -- Removes a child. -- @param child DisplayObject -- @return True if removed. function Group:removeChild(child) if table.removeElement(self.children, child) then child:setParent(nil) child:setLayer(nil) child:setScissorRect(nil) return true end return false end --- -- Remove the children. function Group:removeChildren() local children = table.dup(self.children) for i, child in ipairs(children) do self:removeChild(child) end end --- -- Sets the layer for this group to use. -- @param layer MOAILayer object function Group:setLayer(layer) if self.layer == layer then return end if self.layer then for i, v in ipairs(self.children) do if v.setLayer then v:setLayer(nil) else self.layer:removeProp(v) end end end self.layer = layer if self.layer then for i, v in ipairs(self.children) do if v.setLayer then v:setLayer(self.layer) else self.layer:insertProp(v) end end end end --- -- Sets the group's priority. -- Also sets the priority of any children. -- @param number priority -- @param number stride -- @return number priority of the last child function Group:setPriority(priority, stride) local stride = stride or 0 local priority = priority or 0 local _priority = priority for i, v in ipairs(self.children) do local diff = v:setPriority(priority, stride) priority = priority + (diff or stride) end return priority - _priority end return Group
group priorities exp growth fixed
group priorities exp growth fixed
Lua
mit
Vavius/moai-framework,Vavius/moai-framework
8ee362f3351d078846da41b123e1b8ed486df7b9
Code/Tools/BuildScripts/mac-specific/CheckFreeType.lua
Code/Tools/BuildScripts/mac-specific/CheckFreeType.lua
------------------------------------------------------------------------------ -- Copyright (C) 2008-2012, Shane Liesegang -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the copyright holder nor the names of any -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ if (package.path == nil) then package.path = "" end local mydir = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] if (mydir == nil) then mydir = "." end mydir = mydir .. "/../" package.path = mydir .. "?.lua;" .. package.path package.path = package.path .. ";" .. mydir .. "lua-lib/penlight-0.8/lua/?/init.lua" package.path = package.path .. ";" .. mydir .. "lua-lib/penlight-0.8/lua/?.lua" require "angel_build" require "lfs" require "pl.path" local env = os.environ() if (env['PROJECT_DIR']:find(' ')) then env['PROJECT_DIR'] = '"' .. env['PROJECT_DIR'] .. '"' end local BASEDIR = fulljoin(env['PROJECT_DIR'], "Angel", "Libraries", "freetype-2.4.8") local CHECKFILE = fulljoin(BASEDIR, "builds", "unix", "ftconfig.h") lfs.chdir(BASEDIR:gsub('"', '')) if (not pl.path.exists(CHECKFILE:gsub('"', ''))) then local conf_string = 'env CFLAGS=' conf_string = conf_string .. '"-O -g -isysroot /Developer/SDKs/MacOSX10.6.sdk -arch i386" ' conf_string = conf_string .. 'LDFLAGS=' conf_string = conf_string .. '"-arch i386" ' conf_string = conf_string .. './configure' os.execute(conf_string) end
------------------------------------------------------------------------------ -- Copyright (C) 2008-2012, Shane Liesegang -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the copyright holder nor the names of any -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ if (package.path == nil) then package.path = "" end local mydir = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] if (mydir == nil) then mydir = "." end mydir = mydir .. "/../" package.path = mydir .. "?.lua;" .. package.path package.path = package.path .. ";" .. mydir .. "lua-lib/penlight-0.8/lua/?/init.lua" package.path = package.path .. ";" .. mydir .. "lua-lib/penlight-0.8/lua/?.lua" require "angel_build" require "lfs" require "pl.path" local env = os.environ() if (env['PROJECT_DIR']:find(' ')) then env['PROJECT_DIR'] = '"' .. env['PROJECT_DIR'] .. '"' end local BASEDIR = fulljoin(env['PROJECT_DIR'], "Angel", "Libraries", "freetype-2.4.8") local CHECKFILE = fulljoin(BASEDIR, "builds", "unix", "ftconfig.h") lfs.chdir(BASEDIR:gsub('"', '')) if (not pl.path.exists(CHECKFILE:gsub('"', ''))) then local conf_string = 'env CFLAGS=' conf_string = conf_string .. '"-O -g -arch i386" ' conf_string = conf_string .. 'LDFLAGS=' conf_string = conf_string .. '"-arch i386" ' conf_string = conf_string .. './configure' os.execute(conf_string) end
Fixing bad FreeType build script.
Fixing bad FreeType build script. --HG-- extra : convert_revision : svn%3A18234216-3d68-4496-97ee-3aadfc93d375/trunk%40665
Lua
bsd-3-clause
tks2103/angel-test,angel2d/angel2d,tks2103/angel-test,angel2d/angel2d,tks2103/angel-test,tks2103/angel-test,angel2d/angel2d,angel2d/angel2d,tks2103/angel-test,tks2103/angel-test,angel2d/angel2d,angel2d/angel2d,tks2103/angel-test,angel2d/angel2d,tks2103/angel-test
4f6cb3d1252b8ccd4bf9200b9a3c128f707b89a0
loot.lua
loot.lua
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local LLN = LibStub("LibLootNotify-1.0") local ignored_items = { [20725] = true, -- Nexus Crystal [22450] = true, -- Void Crystal [34057] = true, -- Abyss Crystal [29434] = true, -- Badge of Justice [40752] = true, -- Emblem of Heroism [40753] = true, -- Emblem of Valor [45624] = true, -- Emblem of Conquest [47241] = true, -- Emblem of Triumph [30311] = true, -- Warp Slicer [30312] = true, -- Infinity Blade [30313] = true, -- Staff of Disintegration [30314] = true, -- Phaseshift Bulwark [30316] = true, -- Devastation [30317] = true, -- Cosmic Infuser [30318] = true, -- Netherstrand Longbow [30319] = true, -- Nether Spikes [30320] = true, -- Bundle of Nether Spikes } local in_combat = false local loot_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopLootQueue() if in_combat then return end if #loot_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end local player, item = unpack(loot_queue[1]) -- In theory this should never happen. if not player or not item then tremove(loot_queue, 1) return end -- User is busy with other popup. if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then return end tremove(loot_queue, 1) local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(item) local r, g, b = GetItemQualityColor(itemRarity) if EPGP:GetEPGP(player) then local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", { texture = itemTexture, name = itemName, color = {r, g, b, 1}, link = itemLink }) if dialog then dialog.name = player end end end local function LootReceived(event_name, player, itemLink, quantity) if IsRLorML() and CanEditOfficerNote() then local itemID = tonumber(itemLink:match("item:(%d+)") or 0) if not itemID then return end local itemRarity = select(3, GetItemInfo(itemID)) if itemRarity < mod.db.profile.threshold then return end if ignored_items[itemID] then return end tinsert(loot_queue, {player, itemLink, quantity}) if not timer then timer = mod:ScheduleRepeatingTimer("PopLootQueue", 0.1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end mod.dbDefaults = { profile = { enabled = true, threshold = 4, -- Epic quality items } } mod.optionsName = L["Loot"] mod.optionsDesc = L["Automatic loot tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."] }, threshold = { order = 10, type = "select", name = L["Loot tracking threshold"], desc = L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."], values = { [2] = ITEM_QUALITY2_DESC, [3] = ITEM_QUALITY3_DESC, [4] = ITEM_QUALITY4_DESC, [5] = ITEM_QUALITY5_DESC, }, }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") LLN.RegisterCallback(self, "LootReceived", LootReceived) end function mod:OnDisable() LLN.UnregisterAllCallbacks(self) end
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local LLN = LibStub("LibLootNotify-1.0") local ignored_items = { [20725] = true, -- Nexus Crystal [22450] = true, -- Void Crystal [34057] = true, -- Abyss Crystal [29434] = true, -- Badge of Justice [40752] = true, -- Emblem of Heroism [40753] = true, -- Emblem of Valor [45624] = true, -- Emblem of Conquest [47241] = true, -- Emblem of Triumph [49426] = true, -- Emblem of Frost [30311] = true, -- Warp Slicer [30312] = true, -- Infinity Blade [30313] = true, -- Staff of Disintegration [30314] = true, -- Phaseshift Bulwark [30316] = true, -- Devastation [30317] = true, -- Cosmic Infuser [30318] = true, -- Netherstrand Longbow [30319] = true, -- Nether Spikes [30320] = true, -- Bundle of Nether Spikes } local in_combat = false local loot_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopLootQueue() if in_combat then return end if #loot_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end local player, item = unpack(loot_queue[1]) -- In theory this should never happen. if not player or not item then tremove(loot_queue, 1) return end -- User is busy with other popup. if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then return end tremove(loot_queue, 1) local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(item) local r, g, b = GetItemQualityColor(itemRarity) if EPGP:GetEPGP(player) then local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", { texture = itemTexture, name = itemName, color = {r, g, b, 1}, link = itemLink }) if dialog then dialog.name = player end end end local function LootReceived(event_name, player, itemLink, quantity) if IsRLorML() and CanEditOfficerNote() then local itemID = tonumber(itemLink:match("item:(%d+)") or 0) if not itemID then return end local itemRarity = select(3, GetItemInfo(itemID)) if itemRarity < mod.db.profile.threshold then return end if ignored_items[itemID] then return end tinsert(loot_queue, {player, itemLink, quantity}) if not timer then timer = mod:ScheduleRepeatingTimer("PopLootQueue", 0.1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end mod.dbDefaults = { profile = { enabled = true, threshold = 4, -- Epic quality items } } mod.optionsName = L["Loot"] mod.optionsDesc = L["Automatic loot tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."] }, threshold = { order = 10, type = "select", name = L["Loot tracking threshold"], desc = L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."], values = { [2] = ITEM_QUALITY2_DESC, [3] = ITEM_QUALITY3_DESC, [4] = ITEM_QUALITY4_DESC, [5] = ITEM_QUALITY5_DESC, }, }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") LLN.RegisterCallback(self, "LootReceived", LootReceived) end function mod:OnDisable() LLN.UnregisterAllCallbacks(self) end
Add emblem of frost to the ignore list.
Add emblem of frost to the ignore list. Fixes issue 579.
Lua
bsd-3-clause
ceason/epgp-tfatf,hayword/tfatf_epgp,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,sheldon/epgp,protomech/epgp-dkp-reloaded,sheldon/epgp
9815c19d7ea39b8585c2848b523e7182bb26b4c7
lib/lua/TFramedTransport.lua
lib/lua/TFramedTransport.lua
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- require 'TTransport' require 'libluabpack' TFramedTransport = TTransportBase:new{ __type = 'TFramedTransport', doRead = true, doWrite = true, wBuf = '', rBuf = '' } function TFramedTransport:new(obj) if ttype(obj) ~= 'table' then error(ttype(self) .. 'must be initialized with a table') end -- Ensure a transport is provided if not obj.trans then error('You must provide ' .. ttype(self) .. ' with a trans') end return TTransportBase:new(obj) end function TFramedTransport:isOpen() return self.trans:isOpen() end function TFramedTransport:open() return self.trans:open() end function TFramedTransport:close() return self.trans:close() end function TFramedTransport:read(len) if string.len(self.rBuf) == 0 then self:__readFrame() end if self.doRead == false then return self.trans:read(len) end if len > string.len(self.rBuf) then local val = self.rBuf self.rBuf = '' return val end local val = string.sub(self.rBuf, 0, len) self.rBuf = string.sub(self.rBuf, len) return val end function TFramedTransport:__readFrame() local buf = self.trans:readAll(4) local frame_len = libluabpack.bunpack('i', buf) self.rBuf = self.trans:readAll(frame_len) end function TFramedTransport:readAll(len) return self.trans:readAll(len) end function TFramedTransport:write(buf, len) if self.doWrite == false then return self.trans:write(buf, len) end if len and len < string.len(buf) then buf = string.sub(buf, 0, len) end self.wBuf = self.wBuf + buf end function TFramedTransport:flush() if self.doWrite == false then return self.trans:flush() end -- If the write fails we still want wBuf to be clear local tmp = self.wBuf self.wBuf = '' self.trans:write(tmp) self.trans:flush() end TFramedTransportFactory = TTransportFactoryBase:new{ __type = 'TFramedTransportFactory' } function TFramedTransportFactory:getTransport(trans) if not trans then terror(TProtocolException:new{ message = 'Must supply a transport to ' .. ttype(self) }) end return TFramedTransport:new{trans = trans} end
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- require 'TTransport' require 'libluabpack' TFramedTransport = TTransportBase:new{ __type = 'TFramedTransport', doRead = true, doWrite = true, wBuf = '', rBuf = '' } function TFramedTransport:new(obj) if ttype(obj) ~= 'table' then error(ttype(self) .. 'must be initialized with a table') end -- Ensure a transport is provided if not obj.trans then error('You must provide ' .. ttype(self) .. ' with a trans') end return TTransportBase.new(self, obj) end function TFramedTransport:isOpen() return self.trans:isOpen() end function TFramedTransport:open() return self.trans:open() end function TFramedTransport:close() return self.trans:close() end function TFramedTransport:read(len) if string.len(self.rBuf) == 0 then self:__readFrame() end if self.doRead == false then return self.trans:read(len) end if len > string.len(self.rBuf) then local val = self.rBuf self.rBuf = '' return val end local val = string.sub(self.rBuf, 0, len) self.rBuf = string.sub(self.rBuf, len+1) return val end function TFramedTransport:__readFrame() local buf = self.trans:readAll(4) local frame_len = libluabpack.bunpack('i', buf) self.rBuf = self.trans:readAll(frame_len) end function TFramedTransport:write(buf, len) if self.doWrite == false then return self.trans:write(buf, len) end if len and len < string.len(buf) then buf = string.sub(buf, 0, len) end self.wBuf = self.wBuf .. buf end function TFramedTransport:flush() if self.doWrite == false then return self.trans:flush() end -- If the write fails we still want wBuf to be clear local tmp = self.wBuf self.wBuf = '' local frame_len_buf = libluabpack.bpack("i", string.len(tmp)) self.trans:write(frame_len_buf) self.trans:write(tmp) self.trans:flush() end TFramedTransportFactory = TTransportFactoryBase:new{ __type = 'TFramedTransportFactory' } function TFramedTransportFactory:getTransport(trans) if not trans then terror(TProtocolException:new{ message = 'Must supply a transport to ' .. ttype(self) }) end return TFramedTransport:new{trans = trans} end
THRIFT-3180 fix framed transport
THRIFT-3180 fix framed transport This closes #515
Lua
apache-2.0
JoeEnnever/thrift,SuperAwesomeLTD/thrift,Sean-Der/thrift,koofr/thrift,dcelasun/thrift,mindcandy/thrift,selaselah/thrift,siemens/thrift,selaselah/thrift,vashstorm/thrift,chentao/thrift,apache/thrift,jeking3/thrift,wfxiang08/thrift,JoeEnnever/thrift,3013216027/thrift,bitemyapp/thrift,eonezhang/thrift,strava/thrift,zzmp/thrift,gadLinux/thrift,edvakf/thrift,tylertreat/thrift,dongjiaqiang/thrift,yongju-hong/thrift,bforbis/thrift,ykwd/thrift,bitfinder/thrift,strava/thrift,eamosov/thrift,nsuke/thrift,bufferoverflow/thrift,msonnabaum/thrift,theopolis/thrift,cjmay/thrift,mway08/thrift,joshuabezaleel/thrift,Jimdo/thrift,bitemyapp/thrift,authbox-lib/thrift,creker/thrift,3013216027/thrift,bitfinder/thrift,bitemyapp/thrift,x1957/thrift,elloray/thrift,jeking3/thrift,JoeEnnever/thrift,jeking3/thrift,huahang/thrift,zzmp/thrift,Jens-G/thrift,bitemyapp/thrift,haruwo/thrift-with-java-annotation-support,dongjiaqiang/thrift,jfarrell/thrift,pinterest/thrift,prashantv/thrift,pinterest/thrift,collinmsn/thrift,windofthesky/thrift,Jens-G/thrift,gadLinux/thrift,chentao/thrift,huahang/thrift,Jimdo/thrift,hcorg/thrift,selaselah/thrift,gadLinux/thrift,afds/thrift,roshan/thrift,cjmay/thrift,msonnabaum/thrift,theopolis/thrift,jfarrell/thrift,windofthesky/thrift,edvakf/thrift,fernandobt8/thrift,windofthesky/thrift,jackscott/thrift,prashantv/thrift,jackscott/thrift,strava/thrift,haruwo/thrift-with-java-annotation-support,bitfinder/thrift,jeking3/thrift,windofthesky/thrift,mway08/thrift,zhaorui1/thrift,tanmaykm/thrift,vashstorm/thrift,edvakf/thrift,collinmsn/thrift,dtmuller/thrift,bgould/thrift,zhaorui1/thrift,selaselah/thrift,ijuma/thrift,jpgneves/thrift,tanmaykm/thrift,collinmsn/thrift,roshan/thrift,guodongxiaren/thrift,ahnqirage/thrift,project-zerus/thrift,vashstorm/thrift,EasonYi/thrift,project-zerus/thrift,afds/thrift,msonnabaum/thrift,huahang/thrift,jackscott/thrift,jfarrell/thrift,dongjiaqiang/thrift,dcelasun/thrift,vashstorm/thrift,bitemyapp/thrift,creker/thrift,markerickson-wf/thrift,bgould/thrift,strava/thrift,authbox-lib/thrift,siemens/thrift,apache/thrift,windofthesky/thrift,ahnqirage/thrift,eamosov/thrift,bitemyapp/thrift,dcelasun/thrift,elloray/thrift,bitfinder/thrift,evanweible-wf/thrift,afds/thrift,creker/thrift,weweadsl/thrift,SirWellington/thrift,hcorg/thrift,3013216027/thrift,BluechipSystems/thrift,afds/thrift,guodongxiaren/thrift,chenbaihu/thrift,RobberPhex/thrift,jackscott/thrift,afds/thrift,project-zerus/thrift,vashstorm/thrift,x1957/thrift,bforbis/thrift,mway08/thrift,Jens-G/thrift,flandr/thrift,markerickson-wf/thrift,theopolis/thrift,dcelasun/thrift,zhaorui1/thrift,bholbrook73/thrift,dcelasun/thrift,jeking3/thrift,wfxiang08/thrift,JoeEnnever/thrift,eamosov/thrift,bmiklautz/thrift,SirWellington/thrift,bforbis/thrift,jeking3/thrift,dtmuller/thrift,SuperAwesomeLTD/thrift,fernandobt8/thrift,BluechipSystems/thrift,chenbaihu/thrift,SuperAwesomeLTD/thrift,dcelasun/thrift,eamosov/thrift,theopolis/thrift,mindcandy/thrift,evanweible-wf/thrift,springheeledjak/thrift,dtmuller/thrift,msonnabaum/thrift,bgould/thrift,Jens-G/thrift,x1957/thrift,pinterest/thrift,Sean-Der/thrift,zzmp/thrift,afds/thrift,eamosov/thrift,SirWellington/thrift,ahnqirage/thrift,eonezhang/thrift,EasonYi/thrift,elloray/thrift,markerickson-wf/thrift,yongju-hong/thrift,bufferoverflow/thrift,bmiklautz/thrift,crisish/thrift,authbox-lib/thrift,bmiklautz/thrift,bmiklautz/thrift,siemens/thrift,dtmuller/thrift,ahnqirage/thrift,cjmay/thrift,authbox-lib/thrift,bmiklautz/thrift,alfredtofu/thrift,windofthesky/thrift,mindcandy/thrift,chentao/thrift,cjmay/thrift,joshuabezaleel/thrift,jeking3/thrift,crisish/thrift,strava/thrift,Jens-G/thrift,alfredtofu/thrift,SentientTechnologies/thrift,authbox-lib/thrift,weweadsl/thrift,eamosov/thrift,dcelasun/thrift,evanweible-wf/thrift,bgould/thrift,alfredtofu/thrift,bgould/thrift,apache/thrift,evanweible-wf/thrift,pinterest/thrift,vashstorm/thrift,crisish/thrift,reTXT/thrift,huahang/thrift,jeking3/thrift,selaselah/thrift,weweadsl/thrift,markerickson-wf/thrift,tanmaykm/thrift,msonnabaum/thrift,zhaorui1/thrift,jpgneves/thrift,edvakf/thrift,bitemyapp/thrift,pinterest/thrift,RobberPhex/thrift,roshan/thrift,apache/thrift,bitfinder/thrift,wfxiang08/thrift,Jimdo/thrift,ykwd/thrift,flandr/thrift,msonnabaum/thrift,mway08/thrift,SirWellington/thrift,strava/thrift,eonezhang/thrift,reTXT/thrift,bmiklautz/thrift,Fitbit/thrift,crisish/thrift,bforbis/thrift,apache/thrift,huahang/thrift,guodongxiaren/thrift,Jens-G/thrift,eamosov/thrift,gadLinux/thrift,wfxiang08/thrift,markerickson-wf/thrift,reTXT/thrift,3013216027/thrift,guodongxiaren/thrift,nsuke/thrift,gadLinux/thrift,mway08/thrift,jpgneves/thrift,RobberPhex/thrift,jfarrell/thrift,theopolis/thrift,jeking3/thrift,SirWellington/thrift,guodongxiaren/thrift,nsuke/thrift,cjmay/thrift,bufferoverflow/thrift,guodongxiaren/thrift,Jens-G/thrift,strava/thrift,mindcandy/thrift,bholbrook73/thrift,msonnabaum/thrift,koofr/thrift,bholbrook73/thrift,hcorg/thrift,bforbis/thrift,bholbrook73/thrift,hcorg/thrift,apache/thrift,tylertreat/thrift,chentao/thrift,reTXT/thrift,dtmuller/thrift,collinmsn/thrift,project-zerus/thrift,bgould/thrift,creker/thrift,windofthesky/thrift,ijuma/thrift,fernandobt8/thrift,zhaorui1/thrift,bholbrook73/thrift,fernandobt8/thrift,authbox-lib/thrift,crisish/thrift,apache/thrift,mindcandy/thrift,project-zerus/thrift,haruwo/thrift-with-java-annotation-support,bufferoverflow/thrift,RobberPhex/thrift,eonezhang/thrift,bitemyapp/thrift,jeking3/thrift,3013216027/thrift,chentao/thrift,bgould/thrift,ahnqirage/thrift,reTXT/thrift,ahnqirage/thrift,elloray/thrift,haruwo/thrift-with-java-annotation-support,eamosov/thrift,dongjiaqiang/thrift,apache/thrift,bitfinder/thrift,yongju-hong/thrift,zzmp/thrift,wfxiang08/thrift,jpgneves/thrift,jfarrell/thrift,dcelasun/thrift,RobberPhex/thrift,bholbrook73/thrift,siemens/thrift,collinmsn/thrift,evanweible-wf/thrift,jackscott/thrift,guodongxiaren/thrift,nsuke/thrift,apache/thrift,wfxiang08/thrift,guodongxiaren/thrift,edvakf/thrift,hcorg/thrift,elloray/thrift,project-zerus/thrift,Sean-Der/thrift,theopolis/thrift,collinmsn/thrift,springheeledjak/thrift,jpgneves/thrift,yongju-hong/thrift,collinmsn/thrift,jpgneves/thrift,cjmay/thrift,gadLinux/thrift,huahang/thrift,markerickson-wf/thrift,BluechipSystems/thrift,jackscott/thrift,bitfinder/thrift,creker/thrift,nsuke/thrift,bforbis/thrift,jfarrell/thrift,dongjiaqiang/thrift,afds/thrift,mindcandy/thrift,reTXT/thrift,zhaorui1/thrift,chentao/thrift,ykwd/thrift,yongju-hong/thrift,yongju-hong/thrift,prashantv/thrift,BluechipSystems/thrift,dongjiaqiang/thrift,ahnqirage/thrift,vashstorm/thrift,crisish/thrift,SirWellington/thrift,flandr/thrift,siemens/thrift,theopolis/thrift,Fitbit/thrift,wfxiang08/thrift,mway08/thrift,Fitbit/thrift,authbox-lib/thrift,edvakf/thrift,JoeEnnever/thrift,ykwd/thrift,Sean-Der/thrift,msonnabaum/thrift,flandr/thrift,collinmsn/thrift,gadLinux/thrift,ykwd/thrift,siemens/thrift,jackscott/thrift,creker/thrift,3013216027/thrift,evanweible-wf/thrift,cjmay/thrift,bitfinder/thrift,Sean-Der/thrift,msonnabaum/thrift,dtmuller/thrift,SentientTechnologies/thrift,koofr/thrift,tylertreat/thrift,bitfinder/thrift,flandr/thrift,springheeledjak/thrift,jpgneves/thrift,Jens-G/thrift,strava/thrift,springheeledjak/thrift,weweadsl/thrift,koofr/thrift,zzmp/thrift,koofr/thrift,evanweible-wf/thrift,flandr/thrift,Sean-Der/thrift,ijuma/thrift,hcorg/thrift,bitemyapp/thrift,prashantv/thrift,JoeEnnever/thrift,prashantv/thrift,springheeledjak/thrift,yongju-hong/thrift,yongju-hong/thrift,x1957/thrift,weweadsl/thrift,project-zerus/thrift,bufferoverflow/thrift,afds/thrift,authbox-lib/thrift,BluechipSystems/thrift,collinmsn/thrift,afds/thrift,gadLinux/thrift,3013216027/thrift,markerickson-wf/thrift,RobberPhex/thrift,haruwo/thrift-with-java-annotation-support,wfxiang08/thrift,huahang/thrift,Jimdo/thrift,joshuabezaleel/thrift,dongjiaqiang/thrift,siemens/thrift,siemens/thrift,Jens-G/thrift,bmiklautz/thrift,roshan/thrift,evanweible-wf/thrift,jackscott/thrift,gadLinux/thrift,dtmuller/thrift,reTXT/thrift,dcelasun/thrift,tylertreat/thrift,yongju-hong/thrift,zhaorui1/thrift,koofr/thrift,dongjiaqiang/thrift,JoeEnnever/thrift,roshan/thrift,bufferoverflow/thrift,Jimdo/thrift,SirWellington/thrift,jfarrell/thrift,creker/thrift,dtmuller/thrift,nsuke/thrift,RobberPhex/thrift,bmiklautz/thrift,eonezhang/thrift,chenbaihu/thrift,Jens-G/thrift,gadLinux/thrift,strava/thrift,SirWellington/thrift,SentientTechnologies/thrift,RobberPhex/thrift,Sean-Der/thrift,apache/thrift,edvakf/thrift,fernandobt8/thrift,springheeledjak/thrift,strava/thrift,theopolis/thrift,chentao/thrift,markerickson-wf/thrift,bufferoverflow/thrift,joshuabezaleel/thrift,Fitbit/thrift,bforbis/thrift,x1957/thrift,bmiklautz/thrift,Fitbit/thrift,nsuke/thrift,yongju-hong/thrift,roshan/thrift,bitemyapp/thrift,tylertreat/thrift,Fitbit/thrift,edvakf/thrift,SirWellington/thrift,pinterest/thrift,Sean-Der/thrift,dtmuller/thrift,springheeledjak/thrift,zzmp/thrift,mindcandy/thrift,theopolis/thrift,bmiklautz/thrift,msonnabaum/thrift,msonnabaum/thrift,alfredtofu/thrift,windofthesky/thrift,jackscott/thrift,mindcandy/thrift,apache/thrift,3013216027/thrift,hcorg/thrift,roshan/thrift,nsuke/thrift,zzmp/thrift,x1957/thrift,Fitbit/thrift,roshan/thrift,theopolis/thrift,cjmay/thrift,windofthesky/thrift,EasonYi/thrift,project-zerus/thrift,strava/thrift,siemens/thrift,flandr/thrift,pinterest/thrift,jeking3/thrift,ijuma/thrift,Fitbit/thrift,markerickson-wf/thrift,Jens-G/thrift,ahnqirage/thrift,huahang/thrift,3013216027/thrift,chenbaihu/thrift,msonnabaum/thrift,bforbis/thrift,Fitbit/thrift,siemens/thrift,RobberPhex/thrift,dtmuller/thrift,SentientTechnologies/thrift,ykwd/thrift,evanweible-wf/thrift,JoeEnnever/thrift,jackscott/thrift,theopolis/thrift,prashantv/thrift,fernandobt8/thrift,Fitbit/thrift,flandr/thrift,authbox-lib/thrift,tanmaykm/thrift,koofr/thrift,wfxiang08/thrift,bforbis/thrift,bforbis/thrift,RobberPhex/thrift,guodongxiaren/thrift,bholbrook73/thrift,SentientTechnologies/thrift,ykwd/thrift,collinmsn/thrift,huahang/thrift,afds/thrift,EasonYi/thrift,Jimdo/thrift,jeking3/thrift,zzmp/thrift,koofr/thrift,windofthesky/thrift,creker/thrift,zhaorui1/thrift,roshan/thrift,selaselah/thrift,afds/thrift,chenbaihu/thrift,chentao/thrift,JoeEnnever/thrift,strava/thrift,chentao/thrift,pinterest/thrift,haruwo/thrift-with-java-annotation-support,yongju-hong/thrift,tylertreat/thrift,springheeledjak/thrift,JoeEnnever/thrift,reTXT/thrift,jfarrell/thrift,yongju-hong/thrift,prashantv/thrift,eamosov/thrift,apache/thrift,evanweible-wf/thrift,chenbaihu/thrift,dtmuller/thrift,bholbrook73/thrift,gadLinux/thrift,prashantv/thrift,springheeledjak/thrift,mway08/thrift,fernandobt8/thrift,nsuke/thrift,eonezhang/thrift,nsuke/thrift,project-zerus/thrift,RobberPhex/thrift,bmiklautz/thrift,selaselah/thrift,chenbaihu/thrift,SirWellington/thrift,jfarrell/thrift,zzmp/thrift,bgould/thrift,authbox-lib/thrift,ykwd/thrift,selaselah/thrift,jfarrell/thrift,Jens-G/thrift,x1957/thrift,ykwd/thrift,zhaorui1/thrift,koofr/thrift,collinmsn/thrift,x1957/thrift,joshuabezaleel/thrift,hcorg/thrift,creker/thrift,koofr/thrift,markerickson-wf/thrift,prashantv/thrift,chenbaihu/thrift,bforbis/thrift,pinterest/thrift,jfarrell/thrift,BluechipSystems/thrift,yongju-hong/thrift,reTXT/thrift,selaselah/thrift,mway08/thrift,springheeledjak/thrift,hcorg/thrift,dongjiaqiang/thrift,elloray/thrift,ijuma/thrift,dtmuller/thrift,eamosov/thrift,bholbrook73/thrift,tylertreat/thrift,JoeEnnever/thrift,Fitbit/thrift,jfarrell/thrift,dcelasun/thrift,theopolis/thrift,weweadsl/thrift,ijuma/thrift,guodongxiaren/thrift,bforbis/thrift,RobberPhex/thrift,hcorg/thrift,hcorg/thrift,selaselah/thrift,wfxiang08/thrift,elloray/thrift,afds/thrift,pinterest/thrift,eamosov/thrift,tylertreat/thrift,mindcandy/thrift,Jens-G/thrift,mway08/thrift,ahnqirage/thrift,fernandobt8/thrift,SuperAwesomeLTD/thrift,bgould/thrift,theopolis/thrift,msonnabaum/thrift,Sean-Der/thrift,yongju-hong/thrift,strava/thrift,crisish/thrift,mindcandy/thrift,vashstorm/thrift,chentao/thrift,ijuma/thrift,dongjiaqiang/thrift,fernandobt8/thrift,SuperAwesomeLTD/thrift,joshuabezaleel/thrift,RobberPhex/thrift,ijuma/thrift,bmiklautz/thrift,markerickson-wf/thrift,ykwd/thrift,bitfinder/thrift,nsuke/thrift,reTXT/thrift,eamosov/thrift,zzmp/thrift,cjmay/thrift,creker/thrift,joshuabezaleel/thrift,jackscott/thrift,BluechipSystems/thrift,springheeledjak/thrift,fernandobt8/thrift,gadLinux/thrift,Jimdo/thrift,wfxiang08/thrift,strava/thrift,wfxiang08/thrift,bmiklautz/thrift,eonezhang/thrift,eonezhang/thrift,jpgneves/thrift,siemens/thrift,roshan/thrift,collinmsn/thrift,SuperAwesomeLTD/thrift,crisish/thrift,Fitbit/thrift,BluechipSystems/thrift,project-zerus/thrift,chenbaihu/thrift,edvakf/thrift,project-zerus/thrift,crisish/thrift,bforbis/thrift,3013216027/thrift,pinterest/thrift,bholbrook73/thrift,creker/thrift,Jens-G/thrift,BluechipSystems/thrift,bufferoverflow/thrift,alfredtofu/thrift,bufferoverflow/thrift,Sean-Der/thrift,EasonYi/thrift,SentientTechnologies/thrift,EasonYi/thrift,EasonYi/thrift,cjmay/thrift,siemens/thrift,elloray/thrift,wfxiang08/thrift,creker/thrift,windofthesky/thrift,mway08/thrift,bitfinder/thrift,Jens-G/thrift,afds/thrift,3013216027/thrift,ahnqirage/thrift,nsuke/thrift,collinmsn/thrift,joshuabezaleel/thrift,weweadsl/thrift,jackscott/thrift,apache/thrift,Fitbit/thrift,Fitbit/thrift,reTXT/thrift,chenbaihu/thrift,bgould/thrift,apache/thrift,SirWellington/thrift,nsuke/thrift,edvakf/thrift,gadLinux/thrift,BluechipSystems/thrift,huahang/thrift,mindcandy/thrift,cjmay/thrift,weweadsl/thrift,bgould/thrift,bufferoverflow/thrift,vashstorm/thrift,jeking3/thrift,eamosov/thrift,tanmaykm/thrift,jfarrell/thrift,haruwo/thrift-with-java-annotation-support,vashstorm/thrift,SentientTechnologies/thrift,jeking3/thrift,roshan/thrift,reTXT/thrift,flandr/thrift,elloray/thrift,SuperAwesomeLTD/thrift,authbox-lib/thrift,SuperAwesomeLTD/thrift,jfarrell/thrift,wfxiang08/thrift,bgould/thrift,cjmay/thrift,creker/thrift,jpgneves/thrift,selaselah/thrift,collinmsn/thrift,dcelasun/thrift,bforbis/thrift,eonezhang/thrift,gadLinux/thrift,ahnqirage/thrift,yongju-hong/thrift,tanmaykm/thrift,Jens-G/thrift,mway08/thrift,chentao/thrift,RobberPhex/thrift,roshan/thrift,hcorg/thrift,nsuke/thrift,ahnqirage/thrift,jeking3/thrift,fernandobt8/thrift,SirWellington/thrift,haruwo/thrift-with-java-annotation-support,gadLinux/thrift,3013216027/thrift,theopolis/thrift,Jimdo/thrift,eonezhang/thrift,markerickson-wf/thrift,x1957/thrift,ahnqirage/thrift,zhaorui1/thrift,Jens-G/thrift,3013216027/thrift,chentao/thrift,vashstorm/thrift,nsuke/thrift,gadLinux/thrift,ijuma/thrift,Fitbit/thrift,crisish/thrift,Jimdo/thrift,roshan/thrift,alfredtofu/thrift,SentientTechnologies/thrift,SentientTechnologies/thrift,afds/thrift,tanmaykm/thrift,tanmaykm/thrift,eamosov/thrift,bitemyapp/thrift,Jimdo/thrift,dtmuller/thrift,SuperAwesomeLTD/thrift,x1957/thrift,hcorg/thrift,pinterest/thrift,strava/thrift,x1957/thrift,flandr/thrift,siemens/thrift,BluechipSystems/thrift,Sean-Der/thrift,alfredtofu/thrift,bgould/thrift,Sean-Der/thrift,haruwo/thrift-with-java-annotation-support,evanweible-wf/thrift,tanmaykm/thrift,Jimdo/thrift,SentientTechnologies/thrift,creker/thrift,bholbrook73/thrift,BluechipSystems/thrift,roshan/thrift,bforbis/thrift,dongjiaqiang/thrift,crisish/thrift,selaselah/thrift,dcelasun/thrift,haruwo/thrift-with-java-annotation-support,zzmp/thrift,EasonYi/thrift,Sean-Der/thrift,mindcandy/thrift,koofr/thrift,joshuabezaleel/thrift,EasonYi/thrift,springheeledjak/thrift,joshuabezaleel/thrift,huahang/thrift,haruwo/thrift-with-java-annotation-support,jfarrell/thrift,ykwd/thrift,zhaorui1/thrift,ijuma/thrift,RobberPhex/thrift,bufferoverflow/thrift,RobberPhex/thrift,tylertreat/thrift,Jimdo/thrift,bholbrook73/thrift,guodongxiaren/thrift,SentientTechnologies/thrift,nsuke/thrift,elloray/thrift,Fitbit/thrift,tanmaykm/thrift,EasonYi/thrift,dcelasun/thrift,chenbaihu/thrift,vashstorm/thrift,prashantv/thrift,Sean-Der/thrift,flandr/thrift,markerickson-wf/thrift,crisish/thrift,reTXT/thrift,ykwd/thrift,BluechipSystems/thrift,project-zerus/thrift,weweadsl/thrift,jpgneves/thrift,tylertreat/thrift,afds/thrift,gadLinux/thrift,joshuabezaleel/thrift,eonezhang/thrift,yongju-hong/thrift,apache/thrift,jpgneves/thrift,apache/thrift,tanmaykm/thrift,dongjiaqiang/thrift,zzmp/thrift,pinterest/thrift,project-zerus/thrift,SentientTechnologies/thrift,haruwo/thrift-with-java-annotation-support,Jimdo/thrift,flandr/thrift,fernandobt8/thrift,ahnqirage/thrift,bgould/thrift,authbox-lib/thrift,jpgneves/thrift,authbox-lib/thrift,jeking3/thrift,prashantv/thrift,strava/thrift,zhaorui1/thrift,bitemyapp/thrift,koofr/thrift,3013216027/thrift,cjmay/thrift,jackscott/thrift,bforbis/thrift,edvakf/thrift,tylertreat/thrift,weweadsl/thrift,SuperAwesomeLTD/thrift,EasonYi/thrift,eamosov/thrift,SuperAwesomeLTD/thrift,elloray/thrift,prashantv/thrift,tylertreat/thrift,eonezhang/thrift,hcorg/thrift,strava/thrift,bufferoverflow/thrift,alfredtofu/thrift,siemens/thrift,chentao/thrift,yongju-hong/thrift,RobberPhex/thrift,windofthesky/thrift,bufferoverflow/thrift,SuperAwesomeLTD/thrift,bmiklautz/thrift,mway08/thrift,alfredtofu/thrift,msonnabaum/thrift,evanweible-wf/thrift,dtmuller/thrift,edvakf/thrift,cjmay/thrift,huahang/thrift,ijuma/thrift,x1957/thrift,markerickson-wf/thrift,reTXT/thrift,nsuke/thrift,elloray/thrift,bforbis/thrift,wfxiang08/thrift,3013216027/thrift,SentientTechnologies/thrift,dcelasun/thrift,Jens-G/thrift,bitfinder/thrift,Jimdo/thrift,ijuma/thrift,EasonYi/thrift,jfarrell/thrift,apache/thrift,weweadsl/thrift,pinterest/thrift,bufferoverflow/thrift,BluechipSystems/thrift,apache/thrift,JoeEnnever/thrift,chentao/thrift,joshuabezaleel/thrift,dcelasun/thrift,dcelasun/thrift,tanmaykm/thrift,SentientTechnologies/thrift,guodongxiaren/thrift,bgould/thrift,alfredtofu/thrift,dcelasun/thrift,alfredtofu/thrift,chenbaihu/thrift,weweadsl/thrift,alfredtofu/thrift,eamosov/thrift
fc7dbe76b9f1282f924506c15e7f494f173bc5a9
lua/wincent/commandt/lib.lua
lua/wincent/commandt/lib.lua
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors. -- SPDX-License-Identifier: BSD-2-Clause local ffi = require('ffi') local lib = {} -- Lazy-load dynamic (C) library code on first access. local c = {} setmetatable(c, { __index = function(table, key) ffi.cdef[[ // Types. typedef struct { const char *contents; size_t length; size_t capacity; } str_t; typedef struct { str_t *candidate; long bitmask; float score; } haystack_t; typedef struct { str_t **candidates; unsigned count; unsigned capacity; unsigned clock; } scanner_t; typedef struct { scanner_t *scanner; haystack_t *haystacks; bool always_show_dot_files; bool case_sensitive; bool ignore_spaces; bool never_show_dot_files; bool recurse; unsigned limit; unsigned threads; const char *needle; size_t needle_length; long needle_bitmask; const char *last_needle; size_t last_needle_length; } matcher_t; typedef struct { str_t **matches; unsigned count; } result_t; typedef struct { str_t **files; unsigned count; } watchman_query_result_t; typedef struct { const char *watch; const char *relative_path; } watchman_watch_project_result_t; // Matcher methods. matcher_t *commandt_matcher_new( scanner_t *scanner, bool always_show_dot_files, bool case_sensitive, bool ignore_spaces, unsigned limit, bool never_show_dot_files, bool recurse ); void commandt_matcher_free(matcher_t *matcher); result_t *commandt_matcher_run(matcher_t *matcher, const char *needle); void commandt_result_free(result_t *result); // Scanner methods. scanner_t *scanner_new_copy(const char **candidates, unsigned count); void scanner_free(scanner_t *scanner); void commandt_print_scanner(scanner_t *scanner); // Watchman methods. int commandt_watchman_connect(const char *socket_path); int commandt_watchman_disconnect(int socket); watchman_query_result_t *commandt_watchman_query( const char *root, const char *relative_root, int socket ); void commandt_watchman_query_result_free(watchman_query_result_t *result); watchman_watch_project_result_t *commandt_watchman_watch_project( const char *root, int socket ); void commandt_watchman_watch_project_result_free( watchman_watch_project_result_t *result ); ]] local dirname = debug.getinfo(1).source:match('@?(.*/)') local extension = (function() -- Possible values listed here: http://luajit.org/ext_jit.html#jit_os if ffi.os == 'Windows' then return '.dll' end return '.so' end)() c = ffi.load(dirname .. 'commandt' .. extension) return c[key] end }) -- Utility function for working with functions that take optional arguments. -- -- Creates a merged table containing items from the supplied tables, working -- from left to right. -- -- ie. `merge(t1, t2, t3)` will insert elements from `t1`, then `t2`, then -- `t3` into a new table, then return the new table. local merge = function(...) local final = {} for _, t in ipairs({...}) do if t ~= nil then for k, v in pairs(t) do final[k] = v end end end return final end lib.commandt_matcher_new = function(scanner, options) options = merge({ always_show_dot_files = false, case_sensitive = false, ignore_spaces = true, limit = 15, never_show_dot_files = false, recurse = true, }, options) if options.limit < 1 then error("limit must be > 0") end local matcher = c.commandt_matcher_new( scanner, options.always_show_dot_files, options.case_sensitive, options.ignore_spaces, options.limit, options.never_show_dot_files, options.recurse ) ffi.gc(matcher, c.commandt_matcher_free) return matcher end lib.commandt_matcher_run = function(matcher, needle) print('searching for: ' .. needle) return c.commandt_matcher_run(matcher, needle) end lib.print_scanner = function(scanner) c.commandt_print_scanner(scanner) end lib.scanner_new_copy = function(candidates) local count = #candidates local scanner = c.scanner_new_copy( ffi.new('const char *[' .. count .. ']', candidates), count ) ffi.gc(scanner, c.scanner_free) return scanner end lib.commandt_watchman_connect = function(name) -- TODO: validate name is a string/path local socket = c.commandt_watchman_connect(name) if socket == -1 then error('commandt_watchman_connect(): failed') end return socket end lib.commandt_watchman_disconnect = function(socket) -- TODO: validate socket is a number local errno = c.commandt_watchman_disconnect(socket) if errno ~= 0 then error('commandt_watchman_disconnect(): failed with errno ' .. errno) end end lib.commandt_watchman_query = function(root, relative_root, socket) -- TODO: some stuff end lib.commandt_watchman_query_result_free = function(result) -- TODO: ... end lib.commandt_watchman_watch_project = function(root, socket) local result = c.commandt_watchman_watch_project(root, socket) local project = { watch = ffi.string(result['watch']), } if result['relative_path'] ~= nil then project['relative_path'] = ffi.string(result['relative_path']) end print(vim.inspect(project)) return project end lib.commandt_watchman_watch_project_result_free = function(result) end return lib
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors. -- SPDX-License-Identifier: BSD-2-Clause local ffi = require('ffi') local lib = {} -- Lazy-load dynamic (C) library code on first access. local c = {} setmetatable(c, { __index = function(table, key) ffi.cdef[[ // Types. typedef struct { const char *contents; size_t length; size_t capacity; } str_t; typedef struct { str_t *candidate; long bitmask; float score; } haystack_t; typedef struct { str_t **candidates; unsigned count; unsigned capacity; unsigned clock; } scanner_t; typedef struct { scanner_t *scanner; haystack_t *haystacks; bool always_show_dot_files; bool case_sensitive; bool ignore_spaces; bool never_show_dot_files; bool recurse; unsigned limit; unsigned threads; const char *needle; size_t needle_length; long needle_bitmask; const char *last_needle; size_t last_needle_length; } matcher_t; typedef struct { str_t **matches; unsigned count; } result_t; typedef struct { str_t **files; unsigned count; } watchman_query_result_t; typedef struct { const char *watch; const char *relative_path; } watchman_watch_project_result_t; // Matcher methods. matcher_t *commandt_matcher_new( scanner_t *scanner, bool always_show_dot_files, bool case_sensitive, bool ignore_spaces, unsigned limit, bool never_show_dot_files, bool recurse ); void commandt_matcher_free(matcher_t *matcher); result_t *commandt_matcher_run(matcher_t *matcher, const char *needle); void commandt_result_free(result_t *result); // Scanner methods. scanner_t *scanner_new_copy(const char **candidates, unsigned count); void scanner_free(scanner_t *scanner); void commandt_print_scanner(scanner_t *scanner); // Watchman methods. int commandt_watchman_connect(const char *socket_path); int commandt_watchman_disconnect(int socket); watchman_query_result_t *commandt_watchman_query( const char *root, const char *relative_root, int socket ); void commandt_watchman_query_result_free(watchman_query_result_t *result); watchman_watch_project_result_t *commandt_watchman_watch_project( const char *root, int socket ); void commandt_watchman_watch_project_result_free( watchman_watch_project_result_t *result ); ]] local dirname = debug.getinfo(1).source:match('@?(.*/)') local extension = (function() -- Possible values listed here: http://luajit.org/ext_jit.html#jit_os if ffi.os == 'Windows' then return '.dll' end return '.so' end)() c = ffi.load(dirname .. 'commandt' .. extension) return c[key] end }) -- Utility function for working with functions that take optional arguments. -- -- Creates a merged table containing items from the supplied tables, working -- from left to right. -- -- ie. `merge(t1, t2, t3)` will insert elements from `t1`, then `t2`, then -- `t3` into a new table, then return the new table. local merge = function(...) local final = {} for _, t in ipairs({...}) do if t ~= nil then for k, v in pairs(t) do final[k] = v end end end return final end lib.commandt_matcher_new = function(scanner, options) options = merge({ always_show_dot_files = false, case_sensitive = false, ignore_spaces = true, limit = 15, never_show_dot_files = false, recurse = true, }, options) if options.limit < 1 then error("limit must be > 0") end local matcher = c.commandt_matcher_new( scanner, options.always_show_dot_files, options.case_sensitive, options.ignore_spaces, options.limit, options.never_show_dot_files, options.recurse ) ffi.gc(matcher, c.commandt_matcher_free) return matcher end lib.commandt_matcher_run = function(matcher, needle) print('searching for: ' .. needle) return c.commandt_matcher_run(matcher, needle) end lib.print_scanner = function(scanner) c.commandt_print_scanner(scanner) end lib.scanner_new_copy = function(candidates) local count = #candidates local scanner = c.scanner_new_copy( ffi.new('const char *[' .. count .. ']', candidates), count ) ffi.gc(scanner, c.scanner_free) return scanner end lib.commandt_watchman_connect = function(name) -- TODO: validate name is a string/path local socket = c.commandt_watchman_connect(name) if socket == -1 then error('commandt_watchman_connect(): failed') end return socket end lib.commandt_watchman_disconnect = function(socket) -- TODO: validate socket is a number local errno = c.commandt_watchman_disconnect(socket) if errno ~= 0 then error('commandt_watchman_disconnect(): failed with errno ' .. errno) end end lib.commandt_watchman_query = function(root, relative_root, socket) -- TODO: some stuff end lib.commandt_watchman_query_result_free = function(result) -- TODO: ... end lib.commandt_watchman_watch_project = function(root, socket) local result = c.commandt_watchman_watch_project(root, socket) local project = { watch = ffi.string(result['watch']), } if result['relative_path'] ~= nil then project['relative_path'] = ffi.string(result['relative_path']) end c.commandt_watchman_watch_project_result_free(result) return project end return lib
fix(lua): clean up watch project result
fix(lua): clean up watch project result
Lua
bsd-2-clause
wincent/command-t,wincent/command-t,wincent/command-t
332f2425c711457ae255bd1fa685415302144eac
AceEvent-3.0/AceEvent-3.0.lua
AceEvent-3.0/AceEvent-3.0.lua
--[[ $Id$ ]] local ACEEVENT_MAJOR, ACEEVENT_MINOR = "AceEvent-3.0", 1 local AceEvent, oldminor = LibStub:NewLibrary(ACEEVENT_MAJOR, ACEEVENT_MINOR) if not AceEvent then return end local event_mt = {__index = function(tbl, key) tbl[key] = {} return tbl[key] end} AceEvent.events = AceEvent.events or setmetatable({}, event_mt) -- Blizzard events AceEvent.messages = AceEvent.messages or setmetatable({}, event_mt) -- Own messages AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib local type = type local pcall = pcall local pairs = pairs -- upgrading of embeds is done at the bottom of the file -- local upvalues local events, messages = AceEvent.events, AceEvent.messages local function safecall(func, ...) local success, err = pcall(func, ...) if success then return err end if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end geterrorhandler()(err) end -- generic event and message firing function -- fires the event/message into the given registry local function Fire(registry, event, ...) for obj, method in pairs(registry[event]) do if type(method) == "string" then safecall(obj[method], obj, event, ...) else safecall(method, event, ...) end end -- I've added event to the args passed in, in anticipation of our decision in jira. -- TODO: If its reversed reverse this change end -- Generic registration and unregisration for messages and events local function RegOrUnreg(self, unregister, registry, event, method) if type(event) ~= "string" then if unregister then error("Usage: UnregisterEvent(event): 'event' - string expected.", 3) else error("Usage: RegisterEvent(event, method): 'event' - string expected.", 3) end end if unregister then -- unregister registry[event][self] = nil else -- overwrite any old registration if not method then method = event end if type(method) ~= "string" and type(method) ~= "function" then error("Usage: RegisterEvent(event, method): 'method' - string or function expected.", 3) end if type(method) == "string" and type(self[method]) ~= "function" then error("Usage: RegisterEvent(event, method): 'method' - method not found on target object.", 3) end registry[event][self] = method end end --- embedding and embed handling local mixins = { "RegisterEvent", "UnregisterEvent", "RegisterMessage", "UnregisterMessage", "SendMessage", "UnregisterAllEvents", "UnregisterAllMessages", } -- AceEvent:Embed( target ) -- target (object) - target object to embed AceEvent in -- -- Embeds AceEevent into the target object making the functions from the mixins list available on target:.. function AceEvent:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true end -- AceEvent:OnEmbedDisable( target ) -- target (object) - target object that is being disabled -- -- Unregister all events messages etc when the target disables. -- this method should be called by the target manually or by an addon framework function AceEvent:OnEmbedDisable(target) target:UnregisterAllEvents() target:UnregisterAllMessages() end -- AceEvent:RegisterEvent( event, method ) -- event (string) - Blizzard event to register for -- method (string or function) - Method to call on self or function to call when event is triggered -- -- Registers a blizzard event and binds it to the given method function AceEvent:RegisterEvent(event, method) RegOrUnreg(self, false, events, event, method) AceEvent.frame:RegisterEvent(event) end -- AceEvent:UnregisterEvent( event ) -- event (string) - Blizzard event to unregister -- -- Unregisters a blizzard event function AceEvent:UnregisterEvent(event) RegOrUnreg(self, true, events, event) if not next(events[event]) then AceEvent.frame:UnregisterEvent(event) end end -- AceEvent:RegisterMessage( message, method ) -- message (string) - Inter Addon message to register for -- method (string or function) - Method to call on self or function to call when message is received -- -- Registers an inter addon message and binds it to the given method function AceEvent:RegisterMessage(message, method) RegOrUnreg(self, false, messages, message, method) end -- AceEvent:UnregisterMessage( message ) -- message (string) - Interaddon message to unregister -- -- Unregisters an interaddon message function AceEvent:UnregisterMessage(message) RegOrUnreg(self, true, messages, message) end -- AceEvent:SendMessage( message, ... ) -- message (string) - Message to send -- ... (tuple) - Arguments to the message -- -- Sends an interaddon message with arguments function AceEvent:SendMessage(message, ...) Fire(messages, message, ...) end -- AceEvent:UnregisterAllEvents() -- -- Unregisters all events registered by self function AceEvent:UnregisterAllEvents() for event, slot in pairs(events) do if slot[self] then self:UnregisterEvent(event) -- call unregisterevent instead of regunreg here to make sure the frame gets unregistered if needed end end end -- AceEvent:UnregisterAllMessages() -- -- Unregisters all messages registered by self function AceEvent:UnregisterAllMessages() for message, slot in pairs(messages) do if slot[self] then RegOrUnreg(self, true, messages, message) end end end -- Last step of upgrading -- Fire blizzard events into the event listeners AceEvent.frame:SetScript("OnEvent", function(this, event, ...) Fire(events, event, ...) end) --- Upgrade our old embeds for target, v in pairs(AceEvent.embeds) do AceEvent:Embed(target) end
--[[ $Id$ ]] local ACEEVENT_MAJOR, ACEEVENT_MINOR = "AceEvent-3.0", 1 local AceEvent, oldminor = LibStub:NewLibrary(ACEEVENT_MAJOR, ACEEVENT_MINOR) if not AceEvent then return end local event_mt = {__index = function(tbl, key) tbl[key] = {} return tbl[key] end} AceEvent.events = AceEvent.events or setmetatable({}, event_mt) -- Blizzard events AceEvent.messages = AceEvent.messages or setmetatable({}, event_mt) -- Own messages AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib local type = type local pcall = pcall local pairs = pairs -- upgrading of embeds is done at the bottom of the file -- local upvalues local events, messages = AceEvent.events, AceEvent.messages local function safecall(func, ...) local success, err = pcall(func, ...) if success then return err end if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end geterrorhandler()(err) end -- generic event and message firing function -- fires the event/message into the given registry local function Fire(registry, event, ...) for obj, method in pairs(registry[event]) do if type(method) == "string" then safecall(obj[method], obj, event, ...) else safecall(method, event, ...) end end -- I've added event to the args passed in, in anticipation of our decision in jira. -- TODO: If its reversed reverse this change end -- Generic registration for messages and events local function Register(self, registry, event, method) if type(event) ~= "string" then if registry == events then error("Usage: RegisterEvent(event, method): 'event' - string expected.", 3) elseif registry == messages then error("Usage: RegisterMessage(message, method): 'message' - string expected.", 3) end end if not method then method = event end if type(method) ~= "string" and type(method) ~= "function" then if registry == events then error("Usage: RegisterEvent(event, method): 'method' - string or function expected.", 3) elseif registry == messages then error("Usage: RegisterMessage(message, method): 'method' - string or function expected.", 3) end end if type(method) == "string" and type(self[method]) ~= "function" then if registry == events then error("Usage: RegisterEvent(event, method): 'method' - method not found on target object.", 3) elseif registry == messages then error("Usage: RegisterMessage(message, method): 'method' - method not found on target object.", 3) end end registry[event][self] = method -- overwrite any old registration end -- Generic unregisration for messages and events local function Unregister(self, registry, event, method) if type(event) ~= "string" then if registry == events then error("Usage: UnregisterEvent(event): 'event' - string expected.", 3) elseif registry == messages then error("Usage: UnregisterMessage(message): 'message' - string expected.", 3) end end registry[event][self] = nil end --- embedding and embed handling local mixins = { "RegisterEvent", "UnregisterEvent", "RegisterMessage", "UnregisterMessage", "SendMessage", "UnregisterAllEvents", "UnregisterAllMessages", } -- AceEvent:Embed( target ) -- target (object) - target object to embed AceEvent in -- -- Embeds AceEevent into the target object making the functions from the mixins list available on target:.. function AceEvent:Embed(target) for k, v in pairs(mixins) do target[v] = self[v] end self.embeds[target] = true end -- AceEvent:OnEmbedDisable( target ) -- target (object) - target object that is being disabled -- -- Unregister all events messages etc when the target disables. -- this method should be called by the target manually or by an addon framework function AceEvent:OnEmbedDisable(target) target:UnregisterAllEvents() target:UnregisterAllMessages() end -- AceEvent:RegisterEvent( event, method ) -- event (string) - Blizzard event to register for -- method (string or function) - Method to call on self or function to call when event is triggered -- -- Registers a blizzard event and binds it to the given method function AceEvent:RegisterEvent(event, method) Register(self, events, event, method) AceEvent.frame:RegisterEvent(event) end -- AceEvent:UnregisterEvent( event ) -- event (string) - Blizzard event to unregister -- -- Unregisters a blizzard event function AceEvent:UnregisterEvent(event) Unregister(self, events, event) if not next(events[event]) then AceEvent.frame:UnregisterEvent(event) end end -- AceEvent:RegisterMessage( message, method ) -- message (string) - Inter Addon message to register for -- method (string or function) - Method to call on self or function to call when message is received -- -- Registers an inter addon message and binds it to the given method function AceEvent:RegisterMessage(message, method) Register(self, messages, message, method) end -- AceEvent:UnregisterMessage( message ) -- message (string) - Interaddon message to unregister -- -- Unregisters an interaddon message function AceEvent:UnregisterMessage(message) Unregister(self, messages, message) end -- AceEvent:SendMessage( message, ... ) -- message (string) - Message to send -- ... (tuple) - Arguments to the message -- -- Sends an interaddon message with arguments function AceEvent:SendMessage(message, ...) Fire(messages, message, ...) end -- AceEvent:UnregisterAllEvents() -- -- Unregisters all events registered by self function AceEvent:UnregisterAllEvents() for event, slot in pairs(events) do if slot[self] then self:UnregisterEvent(event) -- call unregisterevent instead of regunreg here to make sure the frame gets unregistered if needed end end end -- AceEvent:UnregisterAllMessages() -- -- Unregisters all messages registered by self function AceEvent:UnregisterAllMessages() for message, slot in pairs(messages) do if slot[self] then Unregister(self, messages, message) end end end -- Last step of upgrading -- Fire blizzard events into the event listeners AceEvent.frame:SetScript("OnEvent", function(this, event, ...) Fire(events, event, ...) end) --- Upgrade our old embeds for target, v in pairs(AceEvent.embeds) do AceEvent:Embed(target) end
Ace3 - AceEvent - split RegOrUnreg into two functions - fixed error messages in that functions (since also messages could error)
Ace3 - AceEvent - split RegOrUnreg into two functions - fixed error messages in that functions (since also messages could error) git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@99 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
9d6d8a3e746b8774e41afbebf148dd2b7010ef07
nvim/session.lua
nvim/session.lua
local coxpcall = require('coxpcall') local uv = require('luv') local MsgpackRpcStream = require('nvim.msgpack_rpc_stream') require('nvim._compat') local Session = {} Session.__index = Session local function resume(co, ...) local status, result = coroutine.resume(co, ...) if coroutine.status(co) == 'dead' then if not status then error(result) end return end assert(coroutine.status(co) == 'suspended') result(co) end local function coroutine_exec(func, ...) local args = {...} local on_complete if #args > 0 and type(args[#args]) == 'function' then -- completion callback on_complete = table.remove(args) end resume(coroutine.create(function() local status, result, flag = coxpcall.pcall(func, unpack(args)) if on_complete then coroutine.yield(function() -- run the completion callback on the main thread on_complete(status, result, flag) end) end end)) end function Session.new(stream) return setmetatable({ _msgpack_rpc_stream = MsgpackRpcStream.new(stream), _pending_messages = {}, _prepare = uv.new_prepare(), _timer = uv.new_timer(), _is_running = false }, Session) end function Session:next_message(timeout) local function on_request(method, args, response) table.insert(self._pending_messages, {'request', method, args, response}) uv.stop() end local function on_notification(method, args) table.insert(self._pending_messages, {'notification', method, args}) uv.stop() end if self._is_running then error('Event loop already running') end if #self._pending_messages > 0 then return table.remove(self._pending_messages, 1) end self:_run(on_request, on_notification, timeout) return table.remove(self._pending_messages, 1) end function Session:notify(method, ...) self._msgpack_rpc_stream:write(method, {...}) end function Session:request(method, ...) local args = {...} local err, result if self._is_running then err, result = self:_yielding_request(method, args) else err, result = self:_blocking_request(method, args) end if err then return false, err end return true, result end function Session:run(request_cb, notification_cb, setup_cb, timeout) local function on_request(method, args, response) coroutine_exec(request_cb, method, args, function(status, result, flag) if status then response:send(result, flag) else response:send(result, true) end end) end local function on_notification(method, args) coroutine_exec(notification_cb, method, args) end self._is_running = true if setup_cb then coroutine_exec(setup_cb) end while #self._pending_messages > 0 do local msg = table.remove(self._pending_messages, 1) if msg[1] == 'request' then on_request(msg[2], msg[3], msg[4]) else on_notification(msg[2], msg[3]) end end self:_run(on_request, on_notification, timeout) self._is_running = false end function Session:stop() uv.stop() end function Session:close(signal) if not self._timer:is_closing() then self._timer:close() end if not self._prepare:is_closing() then self._prepare:close() end self._msgpack_rpc_stream:close(signal) end function Session:_yielding_request(method, args) return coroutine.yield(function(co) self._msgpack_rpc_stream:write(method, args, function(err, result) resume(co, err, result) end) end) end function Session:_blocking_request(method, args) local err, result local function on_request(method_, args_, response) table.insert(self._pending_messages, {'request', method_, args_, response}) end local function on_notification(method_, args_) table.insert(self._pending_messages, {'notification', method_, args_}) end self._msgpack_rpc_stream:write(method, args, function(e, r) err = e result = r uv.stop() end) self:_run(on_request, on_notification) return err, result end function Session:_run(request_cb, notification_cb, timeout) if type(timeout) == 'number' then self._prepare:start(function() self._timer:start(timeout, 0, function() uv.stop() end) self._prepare:stop() end) end self._msgpack_rpc_stream:read_start(request_cb, notification_cb, uv.stop) uv.run() self._prepare:stop() self._timer:stop() self._msgpack_rpc_stream:read_stop() end return Session
local coxpcall = require('coxpcall') local uv = require('luv') local MsgpackRpcStream = require('nvim.msgpack_rpc_stream') require('nvim._compat') local Session = {} Session.__index = Session local function resume(co, ...) local status, result = coroutine.resume(co, ...) if coroutine.status(co) == 'dead' then if not status then error(result) end return end assert(coroutine.status(co) == 'suspended') result(co) end local function coroutine_exec(func, ...) local args = {...} local on_complete if #args > 0 and type(args[#args]) == 'function' then -- completion callback on_complete = table.remove(args) end resume(coroutine.create(function() local status, result, flag = coxpcall.pcall(func, unpack(args)) if on_complete then coroutine.yield(function() -- run the completion callback on the main thread on_complete(status, result, flag) end) end end)) end function Session.new(stream) return setmetatable({ _msgpack_rpc_stream = MsgpackRpcStream.new(stream), _pending_messages = {}, _prepare = uv.new_prepare(), _timer = uv.new_timer(), _is_running = false }, Session) end function Session:next_message(timeout) local function on_request(method, args, response) table.insert(self._pending_messages, {'request', method, args, response}) uv.stop() end local function on_notification(method, args) table.insert(self._pending_messages, {'notification', method, args}) uv.stop() end if self._is_running then error('Event loop already running') end if #self._pending_messages > 0 then return table.remove(self._pending_messages, 1) end self:_run(on_request, on_notification, timeout) return table.remove(self._pending_messages, 1) end function Session:notify(method, ...) self._msgpack_rpc_stream:write(method, {...}) end function Session:request(method, ...) local args = {...} local err, result if self._is_running then err, result = self:_yielding_request(method, args) else err, result = self:_blocking_request(method, args) end if err then return false, err end return true, result end function Session:run(request_cb, notification_cb, setup_cb, timeout) local function on_request(method, args, response) coroutine_exec(request_cb, method, args, function(status, result, flag) if status then response:send(result, flag) else response:send(result, true) end end) end local function on_notification(method, args) coroutine_exec(notification_cb, method, args) end self._is_running = true if setup_cb then coroutine_exec(setup_cb) end while #self._pending_messages > 0 do local msg = table.remove(self._pending_messages, 1) if msg[1] == 'request' then on_request(msg[2], msg[3], msg[4]) else on_notification(msg[2], msg[3]) end end self:_run(on_request, on_notification, timeout) self._is_running = false end function Session:stop() uv.stop() end function Session:close(signal) if not self._timer:is_closing() then self._timer:close() end if not self._prepare:is_closing() then self._prepare:close() end self._msgpack_rpc_stream:close(signal) end function Session:_yielding_request(method, args) return coroutine.yield(function(co) self._msgpack_rpc_stream:write(method, args, function(err, result) resume(co, err, result) end) end) end function Session:_blocking_request(method, args) local err, result local function on_request(method_, args_, response) table.insert(self._pending_messages, {'request', method_, args_, response}) end local function on_notification(method_, args_) table.insert(self._pending_messages, {'notification', method_, args_}) end self._msgpack_rpc_stream:write(method, args, function(e, r) err = e result = r uv.stop() end) self:_run(on_request, on_notification) return (err or self.eof_err), result end function Session:_run(request_cb, notification_cb, timeout) if type(timeout) == 'number' then self._prepare:start(function() self._timer:start(timeout, 0, function() uv.stop() end) self._prepare:stop() end) end self._msgpack_rpc_stream:read_start(request_cb, notification_cb, function() uv.stop() self.eof_err = {1, "EOF was received from Nvim. Likely the Nvim process crashed."} end) uv.run() self._prepare:stop() self._timer:stop() self._msgpack_rpc_stream:read_stop() end return Session
fix(session): raise an error on EOF instead of implicit `nil` response
fix(session): raise an error on EOF instead of implicit `nil` response
Lua
apache-2.0
neovim/lua-client,neovim/lua-client,neovim/lua-client
d4f7a8c2bf20a373854c1f796dec9f9916642bbb
packages/lime-system/files/usr/lib/lua/lime/wireless.lua
packages/lime-system/files/usr/lib/lua/lime/wireless.lua
#!/usr/bin/lua local config = require("lime.config") local network = require("lime.network") local utils = require("lime.utils") local libuci = require("uci") local fs = require("nixio.fs") wireless = {} wireless.modeParamsSeparator=":" wireless.limeIfNamePrefix="lm_" wireless.wifiModeSeparator="-" function wireless.get_phy_mac(phy) local path = "/sys/class/ieee80211/"..phy.."/macaddress" local mac = assert(fs.readfile(path), "wireless.get_phy_mac(..) failed reading: "..path):gsub("\n","") return utils.split(mac, ":") end function wireless.clean() print("Clearing wireless config...") local uci = libuci:cursor() uci:foreach("wireless", "wifi-iface", function(s) uci:delete("wireless", s[".name"]) end) uci:save("wireless") end function wireless.scandevices() local devices = {} local uci = libuci:cursor() uci:foreach("wireless", "wifi-device", function(dev) devices[dev[".name"]] = dev end) return devices end function wireless.is5Ghz(radio) local uci = libuci:cursor() local hwmode = uci:get("wireless", radio, "hwmode") or "11ng" if hwmode:find("a") then return true end return false end wireless.availableModes = { adhoc=true, ap=true, apname=true } function wireless.isMode(m) return wireless.availableModes[m] end function wireless.createBaseWirelessIface(radio, mode, nameSuffix, extras) --! checks("table", "string", "?string", "?table") --! checks(...) come from http://lua-users.org/wiki/LuaTypeChecking -> https://github.com/fab13n/checks nameSuffix = nameSuffix or "" local radioName = radio[".name"] local phyIndex = radioName:match("%d+") local ifname = "wlan"..phyIndex..wireless.wifiModeSeparator..mode..nameSuffix --! sanitize generated ifname for constructing uci section name --! because only alphanumeric and underscores are allowed local wirelessInterfaceName = wireless.limeIfNamePrefix..ifname:gsub("[^%w_]", "_").."_"..radioName local networkInterfaceName = network.limeIfNamePrefix..ifname:gsub("[^%w_]", "_") local uci = libuci:cursor() uci:set("wireless", wirelessInterfaceName, "wifi-iface") uci:set("wireless", wirelessInterfaceName, "mode", mode) uci:set("wireless", wirelessInterfaceName, "device", radioName) uci:set("wireless", wirelessInterfaceName, "ifname", ifname) uci:set("wireless", wirelessInterfaceName, "network", networkInterfaceName) if extras then for key, value in pairs(extras) do uci:set("wireless", wirelessInterfaceName, key, value) end end uci:save("wireless") return uci:get_all("wireless", wirelessInterfaceName) end function wireless.configure() local specificRadios = {} config.foreach("wifi", function(radio) specificRadios[radio[".name"]] = radio end) local allRadios = wireless.scandevices() for _,radio in pairs(allRadios) do local radioName = radio[".name"] local phyIndex = radioName:match("%d+") if wireless.is5Ghz(radioName) then freqSuffix = "_5ghz" ignoredSuffix = "_2ghz" else freqSuffix = "_2ghz" ignoredSuffix = "_5ghz" end local modes = config.get("wifi", "modes") local options = config.get_all("wifi") local specRadio = specificRadios[radioName] if specRadio then modes = specRadio["modes"] options = specRadio end local uci = libuci:cursor() local distance = options["distance"..freqSuffix] if not distance then distance = 10000 -- up to 10km links by default end uci:set("wireless", radioName, "disabled", 0) uci:set("wireless", radioName, "distance", distance) uci:set("wireless", radioName, "noscan", 1) uci:set("wireless", radioName, "channel", options["channel"..freqSuffix]) local country = options["country"] if country then uci:set("wireless", radioName, "country", country) end local htmode = options["htmode"..freqSuffix] if htmode then uci:set("wireless", radioName, "htmode", htmode) end uci:save("wireless") for _,modeArgs in pairs(modes) do local args = utils.split(modeArgs, wireless.modeParamsSeparator) local modeName = args[1] if modeName == "manual" then break end local mode = require("lime.mode."..modeName) local wirelessInterfaceName = mode.setup_radio(radio, args)[".name"] local uci = libuci:cursor() for key,value in pairs(options) do local keyPrefix = utils.split(key, "_")[1] local isGoodOption = ( (key ~= "modes") and (not key:match("^%.")) and (not key:match("channel")) and (not key:match("country")) and (not key:match("htmode")) and (not (wireless.isMode(keyPrefix) and keyPrefix ~= modeName)) and (not key:match(ignoredSuffix)) ) if isGoodOption then local nk = key:gsub("^"..modeName.."_", ""):gsub(freqSuffix.."$", "") if nk == "ssid" then value = utils.applyHostnameTemplate(value) value = utils.applyMacTemplate16(value, network.primary_mac()) value = string.sub(value, 1, 32) end uci:set("wireless", wirelessInterfaceName, nk, value) end end uci:save("wireless") end end end return wireless
#!/usr/bin/lua local config = require("lime.config") local network = require("lime.network") local utils = require("lime.utils") local libuci = require("uci") local fs = require("nixio.fs") wireless = {} wireless.modeParamsSeparator=":" wireless.limeIfNamePrefix="lm_" wireless.wifiModeSeparator="-" function wireless.get_phy_mac(phy) local path = "/sys/class/ieee80211/"..phy.."/macaddress" local mac = assert(fs.readfile(path), "wireless.get_phy_mac(..) failed reading: "..path):gsub("\n","") return utils.split(mac, ":") end function wireless.clean() print("Clearing wireless config...") local uci = libuci:cursor() uci:foreach("wireless", "wifi-iface", function(s) uci:delete("wireless", s[".name"]) end) uci:save("wireless") end function wireless.scandevices() local devices = {} local uci = libuci:cursor() uci:foreach("wireless", "wifi-device", function(dev) devices[dev[".name"]] = dev end) return devices end function wireless.is5Ghz(radio) local uci = libuci:cursor() local hwmode = uci:get("wireless", radio, "hwmode") or "11ng" if hwmode:find("a") then return true end return false end wireless.availableModes = { adhoc=true, ap=true, apname=true } function wireless.isMode(m) return wireless.availableModes[m] end function wireless.createBaseWirelessIface(radio, mode, nameSuffix, extras) --! checks("table", "string", "?string", "?table") --! checks(...) come from http://lua-users.org/wiki/LuaTypeChecking -> https://github.com/fab13n/checks nameSuffix = nameSuffix or "" local radioName = radio[".name"] local phyIndex = radioName:match("%d+") local ifname = "wlan"..phyIndex..wireless.wifiModeSeparator..mode..nameSuffix --! sanitize generated ifname for constructing uci section name --! because only alphanumeric and underscores are allowed local wirelessInterfaceName = wireless.limeIfNamePrefix..ifname:gsub("[^%w_]", "_").."_"..radioName local networkInterfaceName = network.limeIfNamePrefix..ifname:gsub("[^%w_]", "_") local uci = libuci:cursor() uci:set("wireless", wirelessInterfaceName, "wifi-iface") uci:set("wireless", wirelessInterfaceName, "mode", mode) uci:set("wireless", wirelessInterfaceName, "device", radioName) uci:set("wireless", wirelessInterfaceName, "ifname", ifname) uci:set("wireless", wirelessInterfaceName, "network", networkInterfaceName) if extras then for key, value in pairs(extras) do uci:set("wireless", wirelessInterfaceName, key, value) end end uci:save("wireless") return uci:get_all("wireless", wirelessInterfaceName) end function wireless.configure() local specificRadios = {} config.foreach("wifi", function(radio) specificRadios[radio[".name"]] = radio end) local uci = libuci:cursor() local allRadios = wireless.scandevices() for _,radio in pairs(allRadios) do local radioName = radio[".name"] local specRadio = specificRadios[radioName] local modes = config.get("wifi", "modes") local options = config.get_all("wifi") if specRadio then modes = specRadio["modes"] options = specRadio end --! If manual mode is used toghether with other modes it results in an --! unpredictable behaviour if modes[1] ~= "manual" then local freqSuffix = "_2ghz" local ignoredSuffix = "_5ghz" if wireless.is5Ghz(radioName) then freqSuffix = "_5ghz" ignoredSuffix = "_2ghz" end --! up to 10km links by default local distance = options["distance"..freqSuffix] or options["distance"] or 10000 local htmode = options["htmode"..freqSuffix] or options["htmode"] uci:set("wireless", radioName, "disabled", 0) uci:set("wireless", radioName, "distance", distance) uci:set("wireless", radioName, "noscan", 1) uci:set("wireless", radioName, "channel", options["channel"..freqSuffix]) if options["country"] then uci:set("wireless", radioName, "country", options["country"]) end if htmode then uci:set("wireless", radioName, "htmode", htmode) end for _,modeArgs in pairs(modes) do local args = utils.split(modeArgs, wireless.modeParamsSeparator) local modeName = args[1] local mode = require("lime.mode."..modeName) local wirelessInterfaceName = mode.setup_radio(radio, args)[".name"] for key,value in pairs(options) do local keyPrefix = utils.split(key, "_")[1] local isGoodOption = ( (key ~= "modes") and (not key:match("^%.")) and (not key:match("channel")) and (not key:match("country")) and (not key:match("htmode")) and (not (wireless.isMode(keyPrefix) and keyPrefix ~= modeName)) and (not key:match(ignoredSuffix)) ) if isGoodOption then local nk = key:gsub("^"..modeName.."_", ""):gsub(freqSuffix.."$", "") if nk == "ssid" then value = utils.applyHostnameTemplate(value) value = utils.applyMacTemplate16(value, network.primary_mac()) value = string.sub(value, 1, 32) end uci:set("wireless", wirelessInterfaceName, nk, value) end end end end end uci:save("wireless") end return wireless
Fix wifi mode manual
Fix wifi mode manual
Lua
agpl-3.0
libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages
27705a276476cf5c7bf0d01a82fc96cad85392b6
packagemanager/dependency.lua
packagemanager/dependency.lua
local Misc = require 'packagemanager/misc' local Version = require 'packagemanager/version' local PackageDB = require 'packagemanager/packagedb' -- Requirement: -- { -- packageName = ..., -- versionRange = ..., -- } local Dependency = {} local function CopyContext( ctx ) return { db = ctx.db, selectedPackages = Misc.copyTable(ctx.selectedPackages), openRequirements = Misc.copyTable(ctx.openRequirements), closedRequirements = Misc.copyTable(ctx.closedRequirements) } end local function SortRequirements( requirements ) -- TODO end local function GetAvailablePackages( ctx, requirement ) local selectedPackage = ctx.selectedPackages[requirement.packageName] if selectedPackage then -- we already selected a package so we can't pick a different return {selectedPackage} else -- we didn't select a package yet so all packages are possible local packageVersions = PackageDB.gatherPackages(ctx.db, { name = requirement.packageName }) if not packageVersions then error(string.format('No package statisfies requirement: %s %s', requirement.packageName, requirement.versionRange)) end local packages = {} for _, package in pairs(packageVersions) do table.insert(packages, package) end if #packages == 0 then error(string.format('Package %s is empty.', requirement.packageName)) -- This should not happen. end return packages end end local function GetCompatiblePackages( ctx, requirement ) local available = GetAvailablePackages(ctx, requirement) return Version.getMatchingPackages(available, requirement.versionRange) end local function RequirementsAreEqual( a, b ) return a.packageName == b.packageName and a.versionRange == b.versionRange end local function IsRequirementClosed( requirement, ctx ) for _, closedRequirement in ipairs(ctx.closedRequirements) do if RequirementsAreEqual(closedRequirement, requirement) then return true end end end --- -- @param dependencies -- <package name> = <version range> local function AddDependenciesAsRequirements( ctx, dependencies ) for packageName, versionRange in pairs(dependencies) do local requirement = { packageName = packageName, versionRange = versionRange } if not IsRequirementClosed(requirement, ctx) then table.insert(ctx.openRequirements, requirement) end end SortRequirements(ctx.openRequirements) end --- Takes the last requirement and tries to resolve it. -- Returns either nil, if resolution failed, or a package table. local function ResolveRequirement( ctx ) local requirement = table.remove(ctx.openRequirements) if requirement then table.insert(ctx.closedRequirements, requirement) local compatiblePackages = GetCompatiblePackages(ctx, requirement) local conflictResolution = nil for _, package in ipairs(compatiblePackages) do if not conflictResolution then local newCtx = CopyContext(ctx) newCtx.selectedPackages[requirement.packageName] = package AddDependenciesAsRequirements(newCtx, package.dependencies or {}) conflictResolution = ResolveRequirement(newCtx) else break end end return conflictResolution else return ctx.selectedPackages end end --- Compute list, which statisfies all dependencies. -- -- @param dependencies -- <package name> = <version range> -- -- @return -- The first return value is a table, which contains all packages needed to -- statisfy the dependencies. -- If dependency resolution fails, the first return value is `nil` and a table -- describing the problem is the second return value. function Dependency.resolve( db, dependencies ) local ctx = { db = db, selectedPackages = {}, openRequirements = {}, closedRequirements = {} } AddDependenciesAsRequirements(ctx, dependencies) return assert(ResolveRequirement(ctx), '???') end return Dependency
local Misc = require 'packagemanager/misc' local Version = require 'packagemanager/version' local PackageDB = require 'packagemanager/packagedb' -- Requirement: -- { -- packageName = ..., -- versionRange = ..., -- } local Dependency = {} local function CopyContext( ctx ) return { db = ctx.db, selectedPackages = Misc.copyTable(ctx.selectedPackages), openRequirements = Misc.copyTable(ctx.openRequirements), closedRequirements = Misc.copyTable(ctx.closedRequirements) } end local function SortRequirements( requirements ) -- TODO end local function GetAvailablePackages( ctx, requirement ) local selectedPackage = ctx.selectedPackages[requirement.packageName] if selectedPackage then -- we already selected a package, so we can't pick a different return {selectedPackage} else -- we didn't select a package yet, so all packages are possible local packages = PackageDB.gatherPackages(ctx.db, { name = requirement.packageName }) if not packages or #packages == 0 then error(string.format('No package statisfies requirement: %s %s', requirement.packageName, requirement.versionRange)) end return packages end end local function GetCompatiblePackages( ctx, requirement ) local available = GetAvailablePackages(ctx, requirement) return Version.getMatchingPackages(available, requirement.versionRange) end local function RequirementsAreEqual( a, b ) return a.packageName == b.packageName and a.versionRange == b.versionRange end local function IsRequirementClosed( requirement, ctx ) for _, closedRequirement in ipairs(ctx.closedRequirements) do if RequirementsAreEqual(closedRequirement, requirement) then return true end end end --- -- @param dependencies -- <package name> = <version range> local function AddDependenciesAsRequirements( ctx, dependencies ) for packageName, versionRange in pairs(dependencies) do local requirement = { packageName = packageName, versionRange = versionRange } if not IsRequirementClosed(requirement, ctx) then table.insert(ctx.openRequirements, requirement) end end SortRequirements(ctx.openRequirements) end --- Takes the last requirement and tries to resolve it. -- Returns either nil, if resolution failed, or a package table. local function ResolveRequirement( ctx ) local requirement = table.remove(ctx.openRequirements) if requirement then table.insert(ctx.closedRequirements, requirement) local compatiblePackages = GetCompatiblePackages(ctx, requirement) local conflictResolution = nil for _, package in ipairs(compatiblePackages) do if not conflictResolution then local newCtx = CopyContext(ctx) newCtx.selectedPackages[requirement.packageName] = package AddDependenciesAsRequirements(newCtx, package.dependencies or {}) conflictResolution = ResolveRequirement(newCtx) else break end end return conflictResolution else return ctx.selectedPackages end end --- Compute list, which statisfies all dependencies. -- -- @param dependencies -- <package name> = <version range> -- -- @return -- The first return value is a table, which contains all packages needed to -- statisfy the dependencies. -- If dependency resolution fails, the first return value is `nil` and a table -- describing the problem is the second return value. function Dependency.resolve( db, dependencies ) local ctx = { db = db, selectedPackages = {}, openRequirements = {}, closedRequirements = {} } AddDependenciesAsRequirements(ctx, dependencies) return assert(ResolveRequirement(ctx), '???') end return Dependency
Fixed error message generated by dependency resolution
Fixed error message generated by dependency resolution
Lua
mit
henry4k/konstrukt-pkman
f18f13b3ebfb1d497713bf2e540ea1a869e44467
Modules/Shared/Binder/BinderGroup.lua
Modules/Shared/Binder/BinderGroup.lua
--- Groups binders together -- @classmod BinderGroup local BinderGroup = {} BinderGroup.ClassName = "BinderGroup" BinderGroup.__index = BinderGroup function BinderGroup.new(binders, validateConstructor) local self = setmetatable({}, BinderGroup) self._binders = {} self._bindersByTag = {} self._validateConstructor = validateConstructor self:AddList(binders) return self end function BinderGroup:AddList(binders) assert(type(binders) == "table") -- Assume to be using osyris's typechecking library, -- we have an optional constructor to validate binder classes. for _, binder in pairs(binders) do self:Add(binder) end end function BinderGroup:Add(binder) if self._validateConstructor then assert(self._validateConstructor(binder:GetConstructor())) end local tag = binder:GetTag() if self._bindersByTag[tag] then warn("[BinderGroup.Add] - Binder with tag %q already added. Adding again.") end self._bindersByTag[tag] = binder table.insert(self._binders, self._bindersByTag) end function BinderGroup:GetBinders() return self._binders end return BinderGroup
--- Groups binders together -- @classmod BinderGroup local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Binder = require("Binder") local BinderGroup = {} BinderGroup.ClassName = "BinderGroup" BinderGroup.__index = BinderGroup function BinderGroup.new(binders, validateConstructor) local self = setmetatable({}, BinderGroup) self._binders = {} self._bindersByTag = {} self._validateConstructor = validateConstructor self:AddList(binders) return self end function BinderGroup:AddList(binders) assert(type(binders) == "table") -- Assume to be using osyris's typechecking library, -- we have an optional constructor to validate binder classes. for _, binder in pairs(binders) do self:Add(binder) end end function BinderGroup:Add(binder) assert(Binder.isBinder(binder)) if self._validateConstructor then assert(self._validateConstructor(binder:GetConstructor())) end local tag = binder:GetTag() if self._bindersByTag[tag] then warn("[BinderGroup.Add] - Binder with tag %q already added. Adding again.") end self._bindersByTag[tag] = binder table.insert(self._binders, binder) end function BinderGroup:GetBinders() assert(self._binders, "No self._binders") return self._binders end return BinderGroup
Fix binder group, add sanity checks
Fix binder group, add sanity checks
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
26c644e8d3d944758ba8fe6d4f87f2613dd528ca
src/lua-factory/sources/grl-video-title-parsing.lua
src/lua-factory/sources/grl-video-title-parsing.lua
--[[ * Copyright (C) 2014 Grilo Project * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-video-title-parsing", name = "video-title-parsing", description = "Video title parsing", supported_keys = { "episode-title", 'show', 'publication-date', 'season', 'episode', 'title' }, supported_media = 'video', resolve_keys = { ["type"] = "video", required = { "title" }, }, } blacklisted_words = { "720p", "1080p", "x264", "ws", "proper", "real.repack", "repack", "hdtv", "pdtv", "notv", "dsr", "DVDRip", "divx", "xvid", } parsers = { tvshow = { "(.-)[sS](%d+)[%s.]*[eE][pP]?(%d+)(.+)", "(.-)(%d+)[xX.](%d+)(.+)", }, movies = { "(.-)(19%d%d)", "(.-)(20%d%d)", } } function clean_title(title) return title:gsub("^[%s%W]*(.-)[%s%W]*$", "%1"):gsub("%.", " ") end function clean_title_from_blacklist(title) local s = title:lower() local last_index -- remove movie sufix s = s:gsub("(.+)%..-$", "%1") -- ignore everything after the first blacklisted word last_index = #s for i, word in ipairs (blacklisted_words) do local index = s:find(word:lower()) if index and index < last_index then last_index = index - 1 end end return title:sub(1, last_index) end function parse_as_movie(media) local title, date local str = clean_title_from_blacklist (media.title) for i, parser in ipairs(parsers.movies) do title, date = str:match(parser) if title and date then media.title = clean_title(title) media.publication_date = date return true end end return false end function parse_as_episode(media) local show, season, episode, title for i, parser in ipairs(parsers.tvshow) do show, season, episode, title = media.title:match(parser) if show and season and episode and tonumber(season) < 50 then media.show = clean_title(show) media.season = season media.episode = episode media.episode_title = clean_title(clean_title_from_blacklist(title)) return true end end return false end function grl_source_resolve() local req local media = {} req = grl.get_media_keys() if not req or not req.title then grl.callback() return end media.title = req.title -- It is easier to identify a tv show due information -- related to episode and season number if parse_as_episode(media) then grl.debug(req.title .. " is an EPISODE") grl.callback(media, 0) return end if parse_as_movie(media) then grl.debug(req.title .. " is a MOVIE") grl.callback(media, 0) return end grl.debug("Fail to identify video: " .. req.title) grl.callback() end
--[[ * Copyright (C) 2014 Grilo Project * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-video-title-parsing", name = "video-title-parsing", description = "Video title parsing", supported_keys = { "episode-title", 'show', 'publication-date', 'season', 'episode', 'title' }, supported_media = 'video', resolve_keys = { ["type"] = "video", required = { "title" }, }, } blacklisted_words = { "720p", "1080p", "x264", "ws", "proper", "real.repack", "repack", "hdtv", "pdtv", "notv", "dsr", "DVDRip", "divx", "xvid", } -- https://en.wikipedia.org/wiki/Video_file_format video_suffixes = { "webm", "mkv", "flv", "ogv", "ogg", "avi", "mov", "wmv", "mp4", "m4v", "mpeg", "mpg" } parsers = { tvshow = { "(.-)[sS](%d+)[%s.]*[eE][pP]?(%d+)(.+)", "(.-)(%d+)[xX.](%d+)(.+)", }, movies = { "(.-)(19%d%d)", "(.-)(20%d%d)", } } -- in case suffix is recognized, remove it and return true -- or return the title and false if it fails function remove_suffix(title) local s = title:gsub(".*%.(.-)$", "%1") if s then for _, suffix in ipairs(video_suffixes) do if s:find(suffix) then local t = title:gsub("(.*)%..-$", "%1") return t, true end end end return title, false end function clean_title(title) return title:gsub("^[%s%W]*(.-)[%s%W]*$", "%1"):gsub("%.", " ") end function clean_title_from_blacklist(title) local s = title:lower() local last_index local suffix_removed -- remove movie suffix s, suffix_removed = remove_suffix(s) if suffix_removed == false then grl.debug ("Suffix not find in " .. title) end -- ignore everything after the first blacklisted word last_index = #s for i, word in ipairs (blacklisted_words) do local index = s:find(word:lower()) if index and index < last_index then last_index = index - 1 end end return title:sub(1, last_index) end function parse_as_movie(media) local title, date local str = clean_title_from_blacklist (media.title) for i, parser in ipairs(parsers.movies) do title, date = str:match(parser) if title and date then media.title = clean_title(title) media.publication_date = date return true end end return false end function parse_as_episode(media) local show, season, episode, title for i, parser in ipairs(parsers.tvshow) do show, season, episode, title = media.title:match(parser) if show and season and episode and tonumber(season) < 50 then media.show = clean_title(show) media.season = season media.episode = episode media.episode_title = clean_title(clean_title_from_blacklist(title)) return true end end return false end function grl_source_resolve() local req local media = {} req = grl.get_media_keys() if not req or not req.title then grl.callback() return end media.title = req.title -- It is easier to identify a tv show due information -- related to episode and season number if parse_as_episode(media) then grl.debug(req.title .. " is an EPISODE") grl.callback(media, 0) return end if parse_as_movie(media) then grl.debug(req.title .. " is a MOVIE") grl.callback(media, 0) return end local suffix_removed media.title, suffix_removed = remove_suffix(media.title) if media.title and suffix_removed then grl.debug(req.title .. " is a MOVIE (without suffix)") grl.callback(media, 0) return end grl.debug("Fail to identify video: " .. req.title) grl.callback() end
lua-factory: improve title parsing for movies
lua-factory: improve title parsing for movies When our parser does not work for tv shows nor movies, the default is to remove the suffix if it is possible. https://bugzilla.gnome.org/show_bug.cgi?id=755464
Lua
lgpl-2.1
MikePetullo/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins
770c8edaa868751e5efd5dee101836b509147902
modules/admin-full/luasrc/controller/admin/uci.lua
modules/admin-full/luasrc/controller/admin/uci.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.uci", package.seeall) function index() local i18n = luci.i18n.translate entry({"admin", "uci"}, nil, i18n("config")) entry({"admin", "uci", "changes"}, call("action_changes"), i18n("changes"), 40) entry({"admin", "uci", "revert"}, call("action_revert"), i18n("revert"), 30) entry({"admin", "uci", "apply"}, call("action_apply"), i18n("apply"), 20) entry({"admin", "uci", "saveapply"}, call("action_apply"), i18n("saveapply"), 10) end function convert_changes(changes) local ret = {} for r, tbl in pairs(changes) do for s, os in pairs(tbl) do for o, v in pairs(os) do local val, str if (v == "") then str = "-" val = "" else str = "" val = "="..luci.util.pcdata(v) end str = r.."."..s if o ~= ".type" then str = str.."."..o end table.insert(ret, str..val) end end end return table.concat(ret, "\n") end function action_changes() local changes = convert_changes(luci.model.uci.cursor():changes()) luci.template.render("admin_uci/changes", {changes=changes}) end function action_apply() local path = luci.dispatcher.context.path local changes = luci.model.uci.changes() local output = "" local uci = luci.model.uci.cursor() if changes then local com = {} local run = {} -- Collect files to be applied and commit changes for r, tbl in pairs(changes) do if r then if path[#path] ~= "apply" then uci:load(r) uci:commit(r) uci:unload(r) end if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then run[luci.config.uci_oncommit[r]] = true end end end -- Search for post-commit commands for cmd, i in pairs(run) do output = output .. cmd .. ":" .. luci.util.exec(cmd) .. "\n" end end luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output}) end function action_revert() local uci = luci.model.uci.cursor() local changes = uci:changes() if changes then local revert = {} -- Collect files to be reverted for r, tbl in pairs(changes) do uci:load(r) uci:revert(r) uci:unload(r) end end luci.template.render("admin_uci/revert", {changes=convert_changes(changes)}) end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.uci", package.seeall) function index() local i18n = luci.i18n.translate entry({"admin", "uci"}, nil, i18n("config")) entry({"admin", "uci", "changes"}, call("action_changes"), i18n("changes"), 40) entry({"admin", "uci", "revert"}, call("action_revert"), i18n("revert"), 30) entry({"admin", "uci", "apply"}, call("action_apply"), i18n("apply"), 20) entry({"admin", "uci", "saveapply"}, call("action_apply"), i18n("saveapply"), 10) end function convert_changes(changes) local ret = {} for r, tbl in pairs(changes) do for s, os in pairs(tbl) do for o, v in pairs(os) do local val, str if (v == "") then str = "-" val = "" else str = "" val = "="..luci.util.pcdata(v) end str = r.."."..s if o ~= ".type" then str = str.."."..o end table.insert(ret, str..val) end end end return table.concat(ret, "\n") end function action_changes() local changes = convert_changes(luci.model.uci.cursor():changes()) luci.template.render("admin_uci/changes", {changes=changes}) end function action_apply() local path = luci.dispatcher.context.path local output = "" local uci = luci.model.uci.cursor() local changes = uci:changes() if changes then local com = {} local run = {} -- Collect files to be applied and commit changes for r, tbl in pairs(changes) do if r then if path[#path] ~= "apply" then uci:load(r) uci:commit(r) uci:unload(r) end if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then run[luci.config.uci_oncommit[r]] = true end end end -- Search for post-commit commands for cmd, i in pairs(run) do output = output .. cmd .. ":" .. luci.util.exec(cmd) .. "\n" end end luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output}) end function action_revert() local uci = luci.model.uci.cursor() local changes = uci:changes() if changes then local revert = {} -- Collect files to be reverted for r, tbl in pairs(changes) do uci:load(r) uci:revert(r) uci:unload(r) end end luci.template.render("admin_uci/revert", {changes=convert_changes(changes)}) end
Fix missing UCI transition
Fix missing UCI transition git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2967 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
Canaan-Creative/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,alxhh/piratenluci,gwlim/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,vhpham80/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,saraedum/luci-packages-old,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,Flexibity/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,jschmidlapp/luci,stephank/luci,gwlim/luci,projectbismark/luci-bismark,Canaan-Creative/luci,ch3n2k/luci,Flexibity/luci,8devices/carambola2-luci,Flexibity/luci,ch3n2k/luci,Canaan-Creative/luci,ch3n2k/luci,8devices/carambola2-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,vhpham80/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,vhpham80/luci,ch3n2k/luci,jschmidlapp/luci,freifunk-gluon/luci,gwlim/luci,vhpham80/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,gwlim/luci,yeewang/openwrt-luci,stephank/luci,Canaan-Creative/luci,Flexibity/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,alxhh/piratenluci,Canaan-Creative/luci,ch3n2k/luci,stephank/luci,alxhh/piratenluci,alxhh/piratenluci,vhpham80/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,alxhh/piratenluci,freifunk-gluon/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,phi-psi/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,saraedum/luci-packages-old,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,8devices/carambola2-luci,projectbismark/luci-bismark,phi-psi/luci,phi-psi/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,jschmidlapp/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,projectbismark/luci-bismark,8devices/carambola2-luci,Flexibity/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,stephank/luci,zwhfly/openwrt-luci,Flexibity/luci,gwlim/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,projectbismark/luci-bismark,vhpham80/luci,gwlim/luci,yeewang/openwrt-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,stephank/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,freifunk-gluon/luci,alxhh/piratenluci,saraedum/luci-packages-old,alxhh/piratenluci,8devices/carambola2-luci,Canaan-Creative/luci,saraedum/luci-packages-old,stephank/luci,ch3n2k/luci,phi-psi/luci,jschmidlapp/luci,gwlim/luci
3ddd2f567cfa8ee44c115a8f9449b0ffb5af32ea
lib/tolua++/src/bin/lua/compat-5.1.lua
lib/tolua++/src/bin/lua/compat-5.1.lua
if string.find(_VERSION, "5%.0") then return end -- "loadfile" local function pp_dofile(path) local loaded = false local getfile = function() if loaded then return else local file,err = io.open(path) if not file then error("error loading file "..path..": "..err) end local ret = file:read("*a") file:close() ret = string.gsub(ret, "%.%.%.%s*%)$", "...) local arg = {n=select('#', ...), ...};") loaded = true return ret end end local f, err = load(getfile, path) if not f then error("error loading file " .. path .. ": " .. err) end return f() end old_dofile = dofile dofile = pp_dofile -- string.gsub --[[ local ogsub = string.gsub local function compgsub(a,b,c,d) if type(c) == "function" then local oc = c c = function (...) return oc(...) or '' end end return ogsub(a,b,c,d) end string.repl = ogsub --]] --string.gsub = compgsub
if string.find(_VERSION, "5%.0") then return end -- "loadfile" local function pp_dofile(path) local loaded = false local getfile = function() if loaded then return else local file,err = io.open(path) if not file then error("error loading file "..path..": "..err) end local ret = file:read("*a") file:close() ret = string.gsub(ret, "%.%.%.%s*%)$", "...) local arg = {n=select('#', ...), ...};") loaded = true return ret end end local f, err = load(getfile, path) if not f then error("error loading file " .. path .. ": " .. err) end return f() end old_dofile = dofile dofile = pp_dofile -- string.gsub --[[ local ogsub = string.gsub local function compgsub(a,b,c,d) if type(c) == "function" then local oc = c c = function (...) return oc(...) or '' end end return ogsub(a,b,c,d) end string.repl = ogsub --]] --string.gsub = compgsub -- Lua 5.2+ and LuaJit don't have string.gfind(). Use string.gmatch() instead: if not(string.gfind) then string.gfind = string.gmatch end
ToLua: Fixed LuaJit compatibility.
ToLua: Fixed LuaJit compatibility.
Lua
apache-2.0
Howaner/MCServer,mc-server/MCServer,bendl/cuberite,marvinkopf/cuberite,Frownigami1/cuberite,guijun/MCServer,zackp30/cuberite,birkett/cuberite,Fighter19/cuberite,linnemannr/MCServer,Tri125/MCServer,tonibm19/cuberite,tonibm19/cuberite,guijun/MCServer,ionux/MCServer,mjssw/cuberite,linnemannr/MCServer,Schwertspize/cuberite,Altenius/cuberite,birkett/MCServer,kevinr/cuberite,birkett/cuberite,birkett/cuberite,nounoursheureux/MCServer,mjssw/cuberite,mc-server/MCServer,Haxi52/cuberite,HelenaKitty/EbooMC,ionux/MCServer,tonibm19/cuberite,thetaeo/cuberite,nicodinh/cuberite,SamOatesPlugins/cuberite,mmdk95/cuberite,nichwall/cuberite,nounoursheureux/MCServer,johnsoch/cuberite,birkett/MCServer,Howaner/MCServer,tonibm19/cuberite,guijun/MCServer,Tri125/MCServer,bendl/cuberite,Howaner/MCServer,Frownigami1/cuberite,bendl/cuberite,nevercast/cuberite,nevercast/cuberite,Fighter19/cuberite,Fighter19/cuberite,HelenaKitty/EbooMC,nichwall/cuberite,ionux/MCServer,zackp30/cuberite,birkett/MCServer,zackp30/cuberite,mc-server/MCServer,nichwall/cuberite,birkett/MCServer,thetaeo/cuberite,thetaeo/cuberite,electromatter/cuberite,birkett/cuberite,Haxi52/cuberite,kevinr/cuberite,Frownigami1/cuberite,ionux/MCServer,nevercast/cuberite,johnsoch/cuberite,Altenius/cuberite,mjssw/cuberite,SamOatesPlugins/cuberite,kevinr/cuberite,Frownigami1/cuberite,Howaner/MCServer,QUSpilPrgm/cuberite,mmdk95/cuberite,mmdk95/cuberite,nicodinh/cuberite,HelenaKitty/EbooMC,nevercast/cuberite,Frownigami1/cuberite,birkett/cuberite,nicodinh/cuberite,Fighter19/cuberite,marvinkopf/cuberite,johnsoch/cuberite,ionux/MCServer,Haxi52/cuberite,QUSpilPrgm/cuberite,zackp30/cuberite,QUSpilPrgm/cuberite,mjssw/cuberite,electromatter/cuberite,zackp30/cuberite,bendl/cuberite,nichwall/cuberite,nevercast/cuberite,nounoursheureux/MCServer,Altenius/cuberite,tonibm19/cuberite,linnemannr/MCServer,Schwertspize/cuberite,marvinkopf/cuberite,Haxi52/cuberite,electromatter/cuberite,nounoursheureux/MCServer,Haxi52/cuberite,guijun/MCServer,nicodinh/cuberite,guijun/MCServer,mjssw/cuberite,marvinkopf/cuberite,SamOatesPlugins/cuberite,thetaeo/cuberite,nicodinh/cuberite,kevinr/cuberite,mjssw/cuberite,Altenius/cuberite,SamOatesPlugins/cuberite,thetaeo/cuberite,johnsoch/cuberite,electromatter/cuberite,SamOatesPlugins/cuberite,Haxi52/cuberite,kevinr/cuberite,HelenaKitty/EbooMC,Fighter19/cuberite,QUSpilPrgm/cuberite,marvinkopf/cuberite,Altenius/cuberite,Fighter19/cuberite,nevercast/cuberite,HelenaKitty/EbooMC,Tri125/MCServer,Schwertspize/cuberite,QUSpilPrgm/cuberite,mc-server/MCServer,linnemannr/MCServer,Tri125/MCServer,linnemannr/MCServer,Howaner/MCServer,nichwall/cuberite,nichwall/cuberite,Schwertspize/cuberite,ionux/MCServer,mc-server/MCServer,marvinkopf/cuberite,electromatter/cuberite,tonibm19/cuberite,birkett/MCServer,electromatter/cuberite,Schwertspize/cuberite,johnsoch/cuberite,nounoursheureux/MCServer,birkett/MCServer,mmdk95/cuberite,birkett/cuberite,linnemannr/MCServer,thetaeo/cuberite,Tri125/MCServer,nicodinh/cuberite,mc-server/MCServer,mmdk95/cuberite,mmdk95/cuberite,QUSpilPrgm/cuberite,bendl/cuberite,guijun/MCServer,Howaner/MCServer,zackp30/cuberite,kevinr/cuberite,Tri125/MCServer,nounoursheureux/MCServer
4f0c1c89223bbcbe7a35d16895a95001f6ddf1bc
shared/unit.lua
shared/unit.lua
local flux = require "smee.libs.flux" local blocking = require "smee.logic.blocking" local GameMath = require "smee.logic.gamemath" local Entity = require "smee.game_core.entity" local Unit = Entity:subclass("Unit") -- speed: pixels/second -- orientation: radians function Unit:initialize(entityStatic, player) Entity.initialize(self, entityStatic, player) self.speed = self.speed or 300 -- self.orientation = orientation self.targetPosition = GameMath.Vector2:new(self.position.x, self.position.y) self.targetEntity = nil self.targetDirection = GameMath.Vector2:new(0,0) self.stopRange = 30 self.waypoints = false self.dead = false end function Unit:moveTo(targetPos, stopRange) -- RESET OLD TARGET / SET NEW self.targetEntity = nil self.targetPosition = targetPos self.stopRange = stopRange or self.stopRange -- CAN RETURN NIL! Careful, in one behavior we expected to get always something self.waypoints = blocking.findPath(self.position.x, self.position.y, targetPos.x, targetPos.y) return self.waypoints end function Unit:moveToTarget(targetEntity) -- SET NEW TARGET local targetPos = targetEntity:getPosition() self.targetEntity = targetEntity self.targetPosition = targetPos self.targetDirection = targetPos - self.position self.waypoints = blocking.findPath(self.position.x, self.position.y, targetPos.x, targetPos.y) return self.waypoints end function Unit:reachedTarget(target, step) local direction = (target - self.position) local length = direction:length() -- RETURN REACHED, direction vector, direction length return length <= step, direction, length end function Unit:checkDirection() if self.targetEntity then -- COMPARE ANGLE TO ANGLE AT PATHFIND: If the angle has changed too much we need to pathfind again local angle = math.acos(self.targetDir:dot(self.targetPosition)) if angle > 15 then self:moveToTarget(self.targetEntity) end end end function Unit:updateMove(dt) self:checkDirection() if self.waypoints and #self.waypoints > 0 then local waypoints = self.waypoints -- TODO: not create new vector every turn local target = GameMath.Vector2:new(waypoints[1].x, waypoints[1].y) local step = dt * self.speed local reached, direction, length = self:reachedTarget(target, step) -- Update orientation if length > 0 then local newOrientation = math.atan2(direction.y, direction.x) -- self.orientation = newOrientation flux.to(self, 0.04, { orientation = newOrientation }):ease("quadinout") end if #waypoints > 1 or length > self.stopRange then if reached then self:setPosition(target.x, target.y) table.remove(waypoints, 1) else direction:normalize() local newPosition = self.position + direction * step self:setPosition(newPosition.x, newPosition.y) end return false else self.waypoints = nil return true end end return true end function Unit:drawPath() if self.waypoints and #self.waypoints > 0 then local waypoints = self.waypoints -- Draw the path to the destination love.graphics.setColor(255,0,0,64) love.graphics.setPointSize(5) local px, py = self.position.x, self.position.y for i, waypoint in ipairs(waypoints) do local x, y = waypoint.x, waypoint.y if px then love.graphics.line(px, py, x, y) else love.graphics.point(x, y) end px, py = x, y end love.graphics.point(px, py) end end function Unit:setPosition(x, y) self.targetPosition.x = x self.targetPosition.y = y Entity.setPosition(self, x, y) end function Unit:getTargetPosition() return self.targetPosition.x, self.targetPosition.y end return Unit
local flux = require "smee.libs.flux" local blocking = require "smee.logic.blocking" local GameMath = require "smee.logic.gamemath" local Entity = require "smee.game_core.entity" local Unit = Entity:subclass("Unit") -- speed: pixels/second -- orientation: radians function Unit:initialize(entityStatic, player) Entity.initialize(self, entityStatic, player) self.speed = self.speed or 300 -- self.orientation = orientation self.targetPosition = GameMath.Vector2:new(self.position.x, self.position.y) self.targetEntity = nil self.targetDirection = GameMath.Vector2:new(0,0) self.stopRange = 30 self.waypoints = false self.dead = false end function Unit:moveTo(targetPos, stopRange) -- RESET OLD TARGET / SET NEW self.targetEntity = nil self.targetPosition.x = targetPos.x self.targetPosition.y = targetPos.y self.stopRange = stopRange or self.stopRange -- CAN RETURN NIL! Careful, in one behavior we expected to get always something self.waypoints = blocking.findPath(self.position.x, self.position.y, targetPos.x, targetPos.y) return self.waypoints end function Unit:moveToTarget(targetEntity) -- SET NEW TARGET local targetPos = targetEntity:getPosition() self.targetEntity = targetEntity self.targetPosition.x = targetPos.x self.targetPosition.y = targetPos.y self.targetDirection = targetPos - self.position self.waypoints = blocking.findPath(self.position.x, self.position.y, targetPos.x, targetPos.y) return self.waypoints end function Unit:reachedTarget(target, step) local direction = (target - self.position) local length = direction:length() -- RETURN REACHED, direction vector, direction length return length <= step, direction, length end function Unit:checkDirection() if self.targetEntity then -- COMPARE ANGLE TO ANGLE AT PATHFIND: If the angle has changed too much we need to pathfind again local angle = math.acos(self.targetDir:dot(self.targetPosition)) if angle > 15 then self:moveToTarget(self.targetEntity) end end end function Unit:updateMove(dt) self:checkDirection() if self.waypoints and #self.waypoints > 0 then local waypoints = self.waypoints -- TODO: not create new vector every turn local target = GameMath.Vector2:new(waypoints[1].x, waypoints[1].y) local step = dt * self.speed local reached, direction, length = self:reachedTarget(target, step) -- Update orientation if length > 0 then local newOrientation = math.atan2(direction.y, direction.x) -- self.orientation = newOrientation flux.to(self, 0.04, { orientation = newOrientation }):ease("quadinout") end if #waypoints > 1 or length > self.stopRange then if reached then self:setPosition(target.x, target.y) table.remove(waypoints, 1) else direction:normalize() local newPosition = self.position + direction * step self:setPosition(newPosition.x, newPosition.y) end return false else self.waypoints = nil return true end end return true end function Unit:drawPath() if self.waypoints and #self.waypoints > 0 then local waypoints = self.waypoints -- Draw the path to the destination love.graphics.setColor(255,0,0,64) love.graphics.setPointSize(5) local px, py = self.position.x, self.position.y for i, waypoint in ipairs(waypoints) do local x, y = waypoint.x, waypoint.y if px then love.graphics.line(px, py, x, y) else love.graphics.point(x, y) end px, py = x, y end love.graphics.point(px, py) end end function Unit:setPosition(x, y) self.targetPosition.x = x self.targetPosition.y = y Entity.setPosition(self, x, y) end function Unit:getTargetPosition() return self.targetPosition.x, self.targetPosition.y end return Unit
Fixed Minion Master jumping to enemy position
Fixed Minion Master jumping to enemy position Unit:moveTo and Unit:moveToTarget were changed to have targetPosition refer directly to the vector representing the position of another entity. Then, when Entity:setPosition was called, the target position was getting modified, in effect changing the position of the target entity. Solved by not sharing references to the same vector instance.
Lua
mit
ExcelF/project-navel
39c7db4cc9e6eaa383155ec3fa6b4ac9ad3ae152
src/common/premake.lua
src/common/premake.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] -- Handy little helper function os.outputoff(...) return os.outputof(string.format(...)) end function os.fexecutef(...) local result, f, code = os.executef(...) if code ~= 0 then printf("Failed to execute command '%s' exited with code '%s'!", string.format(...), code) os.exit(1) end end premake.override(os, "execute", function(base, exec) if _OPTIONS["verbose"] then print(os.getcwd() .. "\t" .. exec) end return base(exec) end ) premake.override(os, "outputof", function(base, exec) if _OPTIONS["verbose"] then print(os.getcwd() .. "\t" .. exec) end return base(exec) end ) premake.override(os, "getenv", function(base, varname, default) local val = base(varname) if val == nil and default ~= nil then val = default end return val end ) -- Unfortunately premake normalises most paths, -- which results in some links like http:// to be -- reduced to http:/ which of course is incorrect premake.override(path, "normalize", function(base, p) if not zpm.util.hasGitUrl(p) and not zpm.util.hasUrl(p) and not p:contains("\\\"") then return base(p) end return p end ) premake.override(premake.main, "preAction", function() local action = premake.action.current() end ) -- this was taken from -- https://github.com/premake/premake-core/blob/785671fad5946a129300ffcd0f61561f690bddb4/src/_premake_main.lua premake.override(premake.main, "processCommandLine", function() -- Process special options if (_OPTIONS["version"]) then printf("ZPM (Zefiros Package Manager) %s", zpm._VERSION) printf("premake5 (Premake Build Script Generator) %s", _PREMAKE_VERSION) os.exit(0) end if (_OPTIONS["help"] and _ACTION ~= "run") then premake.showhelp() os.exit(1) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options local ok, err = premake.option.validate(_OPTIONS) if not ok then printf("Error: %s", err) os.exit(1) end -- If no further action is possible, show a short help message if not _OPTIONS.interactive then if not _ACTION then print("Type 'zpm --help' for help") os.exit(1) end local action = premake.action.current() if not action then printf("Error: no such action '%s'", _ACTION) os.exit(1) end if premake.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then printf("No zpm script (%s) found!", path.getname(_MAIN_SCRIPT)) os.exit(1) end end end) premake.override(premake.main, "postAction", function(base) if zpm.cli.profile() then if profiler then profiler:stop() profiler:report(io.open(path.join(_MAIN_SCRIPT_DIR, "profile.txt"), 'w')) elseif ProFi then ProFi:stop() ProFi:writeReport(path.join(_MAIN_SCRIPT_DIR, "profile.txt")) end end base() end) premake.override(premake.main, "locateUserScript", function() local defaults = { "zpm.lua", "premake5.lua", "premake4.lua" } for _, default in ipairs(defaults) do if os.isfile(default) then _MAIN_SCRIPT = default break end end if not _MAIN_SCRIPT then _MAIN_SCRIPT = defaults[1] end if _OPTIONS.file then _MAIN_SCRIPT = _OPTIONS.file end _MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT) _MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT) end) premake.override(_G, "workspace", function(base, name) if not zpm.meta.exporting then if name then zpm.meta.workspace = name else zpm.meta.project = "" end end return base(name) end) premake.override(_G, "project", function(base, name) if name then zpm.meta.project = name if not zpm.meta.building and not zpm.meta.exporting then zpm.util.insertUniqueTable(zpm.loader.project.builder.cursor, {"projects", name, "workspaces"}, zpm.meta.workspace) end end return base(name) end) premake.override(_G, "cppdialect", function(base, dialect) if dialect then if not zpm.meta.building then zpm.loader.project.builder.cursor.cppdialect = base if zpm.meta.project ~= "" then tab = zpm.util.insertUniqueTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "cppdialects"}, dialect) else tab = zpm.util.insertUniqueTable(zpm.loader.project.builder.cursor, {"cppdialects"}, dialect) end end end end) premake.override(_G, "group", function(base, name) if (name or name == "") and not zpm.meta.exporting then zpm.meta.group = name end return base(name) end) premake.override(_G, "filter", function(base, fltr) if (fltr or fltr == "") then zpm.meta.filter = fltr end return base(fltr) end) premake.override(_G, "kind", function(base, knd) if kind and not zpm.meta.exporting then zpm.meta.kind = knd if not zpm.meta.building then zpm.util.setTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "kind"}, knd) end end return base(knd) end) premake.override(premake.main, "preBake", function(base) if zpm.loader and not zpm.util.isMainScriptDisabled() then zpm.loader.project.builder:walkDependencies() end return base() end)
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] -- Handy little helper function os.outputoff(...) return os.outputof(string.format(...)) end function os.fexecutef(...) local result, f, code = os.executef(...) if code ~= 0 then printf("Failed to execute command '%s' exited with code '%s'!", string.format(...), code) os.exit(1) end end premake.override(os, "execute", function(base, exec) if _OPTIONS["verbose"] then print(os.getcwd() .. "\t" .. exec) end return base(exec) end ) premake.override(os, "outputof", function(base, exec) if _OPTIONS["verbose"] then print(os.getcwd() .. "\t" .. exec) end return base(exec) end ) premake.override(os, "getenv", function(base, varname, default) local val = base(varname) if val == nil and default ~= nil then val = default end return val end ) -- Unfortunately premake normalises most paths, -- which results in some links like http:// to be -- reduced to http:/ which of course is incorrect premake.override(path, "normalize", function(base, p) if not zpm.util.hasGitUrl(p) and not zpm.util.hasUrl(p) and not p:contains("\\\"") then return base(p) end return p end ) premake.override(premake.main, "preAction", function() local action = premake.action.current() end ) -- this was taken from -- https://github.com/premake/premake-core/blob/785671fad5946a129300ffcd0f61561f690bddb4/src/_premake_main.lua premake.override(premake.main, "processCommandLine", function() -- Process special options if (_OPTIONS["version"]) then printf("ZPM (Zefiros Package Manager) %s", zpm._VERSION) printf("premake5 (Premake Build Script Generator) %s", _PREMAKE_VERSION) os.exit(0) end if (_OPTIONS["help"] and _ACTION ~= "run") then premake.showhelp() os.exit(1) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options local ok, err = premake.option.validate(_OPTIONS) if not ok then printf("Error: %s", err) os.exit(1) end -- If no further action is possible, show a short help message if not _OPTIONS.interactive then if not _ACTION then print("Type 'zpm --help' for help") os.exit(1) end local action = premake.action.current() if not action then printf("Error: no such action '%s'", _ACTION) os.exit(1) end if premake.action.isConfigurable() and not os.isfile(_MAIN_SCRIPT) then printf("No zpm script (%s) found!", path.getname(_MAIN_SCRIPT)) os.exit(1) end end end) premake.override(premake.main, "postAction", function(base) if zpm.cli.profile() then if profiler then profiler:stop() profiler:report(io.open(path.join(_MAIN_SCRIPT_DIR, "profile.txt"), 'w')) elseif ProFi then ProFi:stop() ProFi:writeReport(path.join(_MAIN_SCRIPT_DIR, "profile.txt")) end end base() end) premake.override(premake.main, "locateUserScript", function() local defaults = { "zpm.lua", "premake5.lua", "premake4.lua" } for _, default in ipairs(defaults) do if os.isfile(default) then _MAIN_SCRIPT = default break end end if not _MAIN_SCRIPT then _MAIN_SCRIPT = defaults[1] end if _OPTIONS.file then _MAIN_SCRIPT = _OPTIONS.file end _MAIN_SCRIPT = path.getabsolute(_MAIN_SCRIPT) _MAIN_SCRIPT_DIR = path.getdirectory(_MAIN_SCRIPT) end) premake.override(_G, "workspace", function(base, name) if not zpm.meta.exporting then if name then zpm.meta.workspace = name else zpm.meta.project = "" end end return base(name) end) premake.override(_G, "project", function(base, name) if name then zpm.meta.project = name if not zpm.meta.building and not zpm.meta.exporting then zpm.util.insertUniqueTable(zpm.loader.project.builder.cursor, {"projects", name, "workspaces"}, zpm.meta.workspace) end end return base(name) end) premake.override(_G, "cppdialect", function(base, dialect) if dialect then if not zpm.meta.building then zpm.loader.project.builder.cursor.cppdialect = base if zpm.meta.project ~= "" then tab = zpm.util.insertUniqueTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "cppdialects"}, dialect) else tab = zpm.util.insertUniqueTable(zpm.loader.project.builder.cursor, {"cppdialects"}, dialect) end end end end) premake.override(_G, "group", function(base, name) if (name or name == "") and not zpm.meta.exporting then zpm.meta.group = name end return base(name) end) premake.override(_G, "filter", function(base, fltr) if (fltr or fltr == "") then zpm.meta.filter = fltr end return base(fltr) end) premake.override(_G, "kind", function(base, knd) if kind and not zpm.meta.exporting then zpm.meta.kind = knd if not zpm.meta.building then zpm.util.setTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "kind"}, knd) end end return base(knd) end) premake.override(premake.main, "preBake", function(base) if zpm.loader and not zpm.util.isMainScriptDisabled() then zpm.loader.project.builder:walkDependencies() end return base() end) -- we need a lto compatible version of ar premake.tools.gcc.ar = "gcc-ar"
Fix gcc lto
Fix gcc lto
Lua
mit
Zefiros-Software/ZPM
3f888d86bc85bf70afd3d4d57f03acdb7cdaff8d
GTWsmoke/smoke.lua
GTWsmoke/smoke.lua
--[[ ******************************************************************************** Project: GTW RPG [2.0.4] Owner: GTW Games Location: Sweden Developers: MrBrutus Copyrights: See: "license.txt" Website: http://code.albonius.com Version: 2.0.4 Status: Stable release ******************************************************************************** ]]-- local cigarettes = { } local cooldowns = { } local syncTimer = { } function startSmoking ( thePlayer ) if isPedInVehicle(thePlayer) then return end setElementData ( thePlayer, "smoking", not getElementData ( thePlayer, "smoking" ) ) if cigarettes[thePlayer] == nil and not isTimer(cooldowns[thePlayer]) then -- Bink keys to control the smoking bindKey( thePlayer, "mouse2", "down", "smoke_drag" ) bindKey( thePlayer, "W", "down", "stopsmoke2" ) bindKey( thePlayer, "A", "down", "stopsmoke" ) bindKey( thePlayer, "D", "down", "stopsmoke" ) -- Info message exports.GTWtopbar:dm( "Smoking: Right or Left click to smoke, walk forward to stop smoke.", thePlayer, 255, 200, 0 ) setTimer( showDelayInfo, 2000, 1, "Smoking: Use /stopsmoke to throw your ciggarete away", thePlayer, 255, 200, 0) -- Anim in setPedAnimation( thePlayer, "SMOKING", "M_smk_in", -1, false, false ) cooldowns[thePlayer] = setTimer( function() end, 3000, 1 ) -- Sync interiors and dimension syncTimer[thePlayer] = setTimer(function() if thePlayer and cigarettes[thePlayer] then setElementInterior( cigarettes[thePlayer], getElementInterior(thePlayer)) setElementDimension( cigarettes[thePlayer], getElementDimension(thePlayer)) elseif isTimer(syncTimer[thePlayer]) then killTimer(syncTimer[thePlayer]) end end, 1000, 0) -- Create and attach cigarrete local sigarette = createObject ( 1485, 0, 0, 0 ) cigarettes[thePlayer] = sigarette exports.bone_attach:attachElementToBone(sigarette,thePlayer,11,0.15,0.1,0.15,0,180,30) end end addCommandHandler( "smoke", startSmoking ) function showDelayInfo(msgText, thePlayer, r, g, b) exports.GTWtopbar:dm(msgText, thePlayer, r, g, b) end function stopSmoke2( thePlayer ) -- Stop animation setPedAnimation ( thePlayer ) end addCommandHandler( "stopsmoke2", stopSmoke2 ) function stopSmoke( thePlayer ) -- Unbind control keys unbindKey( thePlayer, "mouse2", "down", "smoke_drag" ) unbindKey( thePlayer, "W", "down", "stopsmoke2" ) unbindKey( thePlayer, "A", "down", "stopsmoke" ) unbindKey( thePlayer, "D", "down", "stopsmoke" ) -- Stop smoking with animation if isElement(cigarettes[thePlayer]) then setPedAnimation( thePlayer, "SMOKING", "M_smk_out", -1, false, false ) end setTimer( function() setPedAnimation ( thePlayer ) if isElement(cigarettes[thePlayer]) then -- Free memory destroyElement (cigarettes[thePlayer]) cigarettes[thePlayer]=nil end end, 3000, 1) end addCommandHandler( "stopsmoke", stopSmoke ) function smokeDrag( thePlayer ) setPedAnimation( thePlayer, "SMOKING", "M_smkstnd_loop", -1, false, false ) end addCommandHandler( "smoke_drag", smokeDrag ) function quitPlayer( quitType ) if cigarettes[source] and isElement(cigarettes[source]) then -- Free memory destroyElement (cigarettes[source]) cigarettes[source]=nil end if isTimer(syncTimer[source]) then killTimer(syncTimer[source] ) end end addEventHandler( "onPlayerQuit", getRootElement(), quitPlayer )
--[[ ******************************************************************************** Project: GTW RPG [2.0.4] Owner: GTW Games Location: Sweden Developers: MrBrutus Copyrights: See: "license.txt" Website: http://code.albonius.com Version: 2.0.4 Status: Stable release ******************************************************************************** ]]-- local cigarettes = { } local cooldowns = { } local syncTimer = { } function startSmoking ( thePlayer ) if isPedInVehicle(thePlayer) then return end setElementData ( thePlayer, "smoking", not getElementData ( thePlayer, "smoking" ) ) if cigarettes[thePlayer] == nil and not isTimer(cooldowns[thePlayer]) then -- Bink keys to control the smoking bindKey( thePlayer, "mouse2", "down", "smoke_drag" ) bindKey( thePlayer, "W", "down", "stopsmoke2" ) bindKey( thePlayer, "A", "down", "stopsmoke" ) bindKey( thePlayer, "D", "down", "stopsmoke" ) -- Info message exports.GTWtopbar:dm( "Smoking: Right click to smoke, walk forward to stop smoke (W).", thePlayer, 255, 200, 0 ) setTimer( showDelayInfo, 2000, 1, "Smoking: Use /stopsmoke or walk sideways (A or D) to throw your ciggarete away", thePlayer, 255, 200, 0) -- Anim in setPedAnimation( thePlayer, "SMOKING", "M_smk_in", -1, false, false ) cooldowns[thePlayer] = setTimer( function() end, 3000, 1 ) -- Sync interiors and dimension syncTimer[thePlayer] = setTimer(function() if thePlayer and cigarettes[thePlayer] then setElementInterior( cigarettes[thePlayer], getElementInterior(thePlayer)) setElementDimension( cigarettes[thePlayer], getElementDimension(thePlayer)) elseif isTimer(syncTimer[thePlayer]) then killTimer(syncTimer[thePlayer]) end end, 1000, 0) -- Create and attach cigarrete local sigarette = createObject ( 1485, 0, 0, 0 ) cigarettes[thePlayer] = sigarette exports.bone_attach:attachElementToBone(sigarette,thePlayer,11,0.15,0.1,0.15,0,180,30) end end addCommandHandler( "smoke", startSmoking ) function showDelayInfo(msgText, thePlayer, r, g, b) exports.GTWtopbar:dm(msgText, thePlayer, r, g, b) end function stopSmoke2( thePlayer ) -- Stop animation setPedAnimation ( thePlayer ) end addCommandHandler( "stopsmoke2", stopSmoke2 ) function stopSmoke( thePlayer ) -- Unbind control keys unbindKey( thePlayer, "mouse2", "down", "smoke_drag" ) unbindKey( thePlayer, "W", "down", "stopsmoke2" ) unbindKey( thePlayer, "A", "down", "stopsmoke" ) unbindKey( thePlayer, "D", "down", "stopsmoke" ) -- Stop smoking with animation if isElement(cigarettes[thePlayer]) then setPedAnimation( thePlayer, "SMOKING", "M_smk_out", -1, false, false ) end setTimer( function() setPedAnimation ( thePlayer ) if isElement(cigarettes[thePlayer]) then -- Free memory destroyElement (cigarettes[thePlayer]) cigarettes[thePlayer]=nil end end, 3000, 1) end addCommandHandler( "stopsmoke", stopSmoke ) function smokeDrag( thePlayer ) setPedAnimation( thePlayer, "SMOKING", "M_smkstnd_loop", -1, false, false ) end addCommandHandler( "smoke_drag", smokeDrag ) function quitPlayer( quitType ) if cigarettes[source] and isElement(cigarettes[source]) then -- Free memory destroyElement (cigarettes[source]) cigarettes[source]=nil end if isTimer(syncTimer[source]) then killTimer(syncTimer[source] ) end end addEventHandler( "onPlayerQuit", getRootElement(), quitPlayer )
Info message change
Info message change Fixed an incorrect info message to the player.
Lua
bsd-2-clause
GTWCode/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,SpRoXx/GTW-RPG,SpRoXx/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG
a892903e774a7e904b7d9e269579b280633a97b5
nvim/nvim/lua/_/formatter.lua
nvim/nvim/lua/_/formatter.lua
local has_formatter, formatter = pcall(require, 'formatter') local M = {} local function prettier() local local_prettier = '.yarn/sdks/prettier/index.js' local prettier_exe = 'prettier'; if vim.fn.executable(local_prettier) == 0 then prettier_exe = './node_modules/.bin/prettier' end return { exe=prettier_exe, args={ -- Config prettier '--config-precedence', 'prefer-file', '--no-bracket-spacing', '--single-quote', '--trailing-comma', 'all', -- Get file '--stdin-filepath', vim.api.nvim_buf_get_name(0) }, stdin=true } end local function shfmt() return {exe='shfmt', args={'-'}, stdin=true} end local ftConfigs = { lua={ function() return { exe='lua-format', args={ vim.fn.shellescape(vim.api.nvim_buf_get_name(0)), '--tab-width=2', '--indent-width=2', '--align-table-field', '--chop-down-table', '--chop-down-parameter', '--double-quote-to-single-quote', '--no-break-after-operator', '--no-spaces-inside-table-braces', '--no-spaces-around-equals-in-field', '--no-spaces-inside-functioncall-parens', '--no-spaces-inside-functiondef-parens' }, stdin=true } end }, rust={ function() return {exe='rustfmt', args={'--emit=stdout'}, stdin=true} end }, nix={function() return {exe='nixpkgs-fmt', stdin=true} end}, sh={shfmt}, bash={shfmt} } local commonPrettierFTs = { 'css', 'scss', 'less', 'html', 'yaml', 'java', 'javascript', 'javascript.jsx', 'javascriptreact', 'typescript', 'typescript.tsx', 'typescriptreact', 'markdown', 'markdown.mdx', 'json', 'jsonc' } for _, ft in ipairs(commonPrettierFTs) do ftConfigs[ft] = {prettier} end local function setup() local formatter_group = vim.api.nvim_create_augroup('Formatter', {clear=true}) vim.api.nvim_create_autocmd('BufWritePost', { command='FormatWrite', group=formatter_group, pattern='*.js,*.jsx,*.ts,*.tsx,*.rs,*.md,*.json,*.lua' }) return {logging=true, filetype=ftConfigs} end function M.setup() if not has_formatter then return end formatter.setup(setup()) end return M
local has_formatter, formatter = pcall(require, 'formatter') local M = {} local function prettier() local pnp_prettier = '.yarn/sdks/prettier/index.js' local node_modules_prettier = './node_modules/.bin/prettier' local prettier_exe = 'prettier'; if vim.fn.executable(pnp_prettier) == 1 then prettier_exe = pnp_prettier; elseif vim.fn.executable(node_modules_prettier) == 1 then prettier_exe = node_modules_prettier; end return { exe=prettier_exe, args={ -- Config prettier '--config-precedence', 'prefer-file', '--no-bracket-spacing', '--single-quote', '--trailing-comma', 'all', -- Get file '--stdin-filepath', vim.api.nvim_buf_get_name(0) }, stdin=true } end local function shfmt() return {exe='shfmt', args={'-'}, stdin=true} end local ftConfigs = { lua={ function() return { exe='lua-format', args={ vim.fn.shellescape(vim.api.nvim_buf_get_name(0)), '--tab-width=2', '--indent-width=2', '--align-table-field', '--chop-down-table', '--chop-down-parameter', '--double-quote-to-single-quote', '--no-break-after-operator', '--no-spaces-inside-table-braces', '--no-spaces-around-equals-in-field', '--no-spaces-inside-functioncall-parens', '--no-spaces-inside-functiondef-parens' }, stdin=true } end }, rust={ function() return {exe='rustfmt', args={'--emit=stdout'}, stdin=true} end }, nix={function() return {exe='nixpkgs-fmt', stdin=true} end}, sh={shfmt}, bash={shfmt} } local commonPrettierFTs = { 'css', 'scss', 'less', 'html', 'yaml', 'java', 'javascript', 'javascript.jsx', 'javascriptreact', 'typescript', 'typescript.tsx', 'typescriptreact', 'markdown', 'markdown.mdx', 'json', 'jsonc' } for _, ft in ipairs(commonPrettierFTs) do ftConfigs[ft] = {prettier} end local function setup() local formatter_group = vim.api.nvim_create_augroup('Formatter', {clear=true}) vim.api.nvim_create_autocmd('BufWritePost', { command='FormatWrite', group=formatter_group, pattern='*.js,*.jsx,*.ts,*.tsx,*.rs,*.md,*.json,*.lua' }) return {logging=true, filetype=ftConfigs} end function M.setup() if not has_formatter then return end formatter.setup(setup()) end return M
fix(nvim): prettier formatter path
fix(nvim): prettier formatter path diff --git a/nvim/nvim/lua/_/formatter.lua b/nvim/nvim/lua/_/formatter.lua index 89a0294..1637d44 100644 --- a/nvim/nvim/lua/_/formatter.lua +++ b/nvim/nvim/lua/_/formatter.lua @@ -3,10 +3,13 @@ local has_formatter, formatter = pcall(require, 'formatter') local M = {} local function prettier() - local local_prettier = '.yarn/sdks/prettier/index.js' + local pnp_prettier = '.yarn/sdks/prettier/index.js' + local node_modules_prettier = './node_modules/.bin/prettier' local prettier_exe = 'prettier'; - if vim.fn.executable(local_prettier) == 0 then - prettier_exe = './node_modules/.bin/prettier' + if vim.fn.executable(pnp_prettier) == 1 then + prettier_exe = pnp_prettier; + elseif vim.fn.executable(node_modules_prettier) == 1 then + prettier_exe = node_modules_prettier; end return { exe=prettier_exe,
Lua
mit
skyuplam/dotfiles,skyuplam/dotfiles
8fec0f330f3f9eeb4d7598cc11d12acf2d7cef1e
frontend/ui/elements/screen_eink_opt_menu_table.lua
frontend/ui/elements/screen_eink_opt_menu_table.lua
local _ = require("gettext") local Screen = require("device").screen return { text = _("E-ink settings"), sub_item_table = { require("ui/elements/refresh_menu_table"), { text = _("Use smaller panning rate"), checked_func = function() return Screen.low_pan_rate end, callback = function() Screen.low_pan_rate = not Screen.low_pan_rate G_reader_settings:saveSetting("low_pan_rate", Screen.low_pan_rate) end, }, { text = _("Avoid mandatory black flashes in UI"), checked_func = function() return G_reader_settings:isTrue("avoid_flashing_ui") end, callback = function() G_reader_settings:flipNilOrFalse("avoid_flashing_ui") end, }, }, }
local Device = require("device") local _ = require("gettext") local Screen = Device.screen local eink_settings_table = { text = _("E-ink settings"), sub_item_table = { { text = _("Use smaller panning rate"), checked_func = function() return Screen.low_pan_rate end, callback = function() Screen.low_pan_rate = not Screen.low_pan_rate G_reader_settings:saveSetting("low_pan_rate", Screen.low_pan_rate) end, }, { text = _("Avoid mandatory black flashes in UI"), checked_func = function() return G_reader_settings:isTrue("avoid_flashing_ui") end, callback = function() G_reader_settings:flipNilOrFalse("avoid_flashing_ui") end, }, }, } -- TODO reactivate if someone reverse engineers Android E Ink stuff if not Device:isAndroid() then table.insert(eink_settings_table.sub_item_table, 1, require("ui/elements/refresh_menu_table")) end return eink_settings_table
[UX, Android] Hide E Ink full refresh setting on Android (#4397)
[UX, Android] Hide E Ink full refresh setting on Android (#4397) Fixes confusion caused by its appearance such as in #4396.
Lua
agpl-3.0
Frenzie/koreader,Markismus/koreader,mihailim/koreader,houqp/koreader,koreader/koreader,Frenzie/koreader,pazos/koreader,NiLuJe/koreader,Hzj-jie/koreader,koreader/koreader,NiLuJe/koreader,mwoz123/koreader,poire-z/koreader,poire-z/koreader
4b952c66241ae74c395139fb0fc229e36a784cff
agents/monitoring/tests/fixtures/protocol/server.lua
agents/monitoring/tests/fixtures/protocol/server.lua
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local lineEmitter = LineEmitter:new() local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end tls.createServer(options, function (client) client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) respond(log, client, payload) end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end):listen(port) end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local lineEmitter = LineEmitter:new() local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) set_option(opts, "listen_ip", '127.0.0.1') local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end tls.createServer(options, function (client) client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) respond(log, client, payload) end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end):listen(port, opts.listen_ip) end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
monitoring: fixtures: server: add listen_ip option
monitoring: fixtures: server: add listen_ip option make it possible to run this thing over the internet
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
17bb959a10ed55e246b9a92dffe82114f628427e
mod_pastebin/mod_pastebin.lua
mod_pastebin/mod_pastebin.lua
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local t_insert, t_remove = table.insert, table.remove; local add_task = require "util.timer".add_task; local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500; local line_threshold = config.get(module.host, "core", "pastebin_line_threshold") or 4; local base_url = config.get(module.host, "core", "pastebin_url"); -- Seconds a paste should live for in seconds (config is in hours), default 24 hours local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600); local trigger_string = config.get(module.host, "core", "pastebin_trigger"); trigger_string = (trigger_string and trigger_string .. " "); local pastes = {}; local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" }; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; function pastebin_text(text) local uuid = uuid_new(); pastes[uuid] = { body = text, time = os_time(), headers = default_headers }; pastes[#pastes+1] = uuid; if not pastes[2] then -- No other pastes, give the timer a kick add_task(expire_after, expire_pastes); end return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid]; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then htmlindex = k; end end if not body then return; end body = body:get_text(); --module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and ( (#body > length_threshold) or (trigger_string and body:find(trigger_string, 1, true) == 1) or (select(2, body:gsub("\n", "%0")) >= line_threshold) ) then if trigger_string then body = body:gsub("^" .. trigger_string, "", 1); end local url = pastebin_text(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150):gsub("[\128-\255]+$", "")):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); function expire_pastes(time) time = time or os_time(); -- COMPAT with 0.5 if pastes[1] then pastes[pastes[1]] = nil; t_remove(pastes, 1); if pastes[1] then return (expire_after - (time - pastes[pastes[1]].time)) + 1; end end end local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local t_insert, t_remove = table.insert, table.remove; local add_task = require "util.timer".add_task; local function drop_invalid_utf8(seq) local start = seq:byte(); module:log("utf8: %d, %d", start, #seq); if (start <= 223 and #seq < 2) or (start >= 224 and start <= 239 and #seq < 3) or (start >= 240 and start <= 244 and #seq < 4) or (start > 244) then return ""; end return seq; end local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500; local line_threshold = config.get(module.host, "core", "pastebin_line_threshold") or 4; local base_url = config.get(module.host, "core", "pastebin_url"); -- Seconds a paste should live for in seconds (config is in hours), default 24 hours local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600); local trigger_string = config.get(module.host, "core", "pastebin_trigger"); trigger_string = (trigger_string and trigger_string .. " "); local pastes = {}; local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" }; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; function pastebin_text(text) local uuid = uuid_new(); pastes[uuid] = { body = text, time = os_time(), headers = default_headers }; pastes[#pastes+1] = uuid; if not pastes[2] then -- No other pastes, give the timer a kick add_task(expire_after, expire_pastes); end return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid]; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then htmlindex = k; end end if not body then return; end body = body:get_text(); --module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and ( (#body > length_threshold) or (trigger_string and body:find(trigger_string, 1, true) == 1) or (select(2, body:gsub("\n", "%0")) >= line_threshold) ) then if trigger_string then body = body:gsub("^" .. trigger_string, "", 1); end local url = pastebin_text(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150):gsub("[\194-\244][\128-\191]*$", drop_invalid_utf8)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); function expire_pastes(time) time = time or os_time(); -- COMPAT with 0.5 if pastes[1] then pastes[pastes[1]] = nil; t_remove(pastes, 1); if pastes[1] then return (expire_after - (time - pastes[pastes[1]].time)) + 1; end end end local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
mod_pastebin: Better fix for stripping truncated UFT-8 sequences
mod_pastebin: Better fix for stripping truncated UFT-8 sequences
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
d6b8a6191ea5e0b281e89dcaacf47a8f0aa22580
test_scripts/RC/SetInteriorVehicleData/011_Check_cut-off_read-only_parameters_in_case_request_SetInteriorVehicleData_from_mobile_with_read-only_and_not_read-only_parameters.lua
test_scripts/RC/SetInteriorVehicleData/011_Check_cut-off_read-only_parameters_in_case_request_SetInteriorVehicleData_from_mobile_with_read-only_and_not_read-only_parameters.lua
--------------------------------------------------------------------------------------------------- -- Description -- In case: -- 1) Application sends valid SetInteriorVehicleData with read-only parameters -- 2) and one or more settable parameters in "radioControlData" struct, for moduleType: RADIO, -- SDL must: -- 1) Cut the read-only parameters off and process this RPC as assigned -- (that is, check policies, send to HMI, and etc. per existing requirements) --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') --[[ Local Variables ]] local modules = { "CLIMATE", "RADIO" } --[[ Local Functions ]] local function getNonReadOnlyParams(pModuleType) if pModuleType == "CLIMATE" then return { fanSpeed = 55 } elseif pModuleType == "RADIO" then return { band = "FM" } end end local function getModuleParams(pModuleData) if pModuleData.climateControlData then return pModuleData.climateControlData elseif pModuleData.radioControlData then return pModuleData.radioControlData end end local function setVehicleData(pModuleType, self) local moduleDataReadOnly = commonRC.getReadOnlyParamsByModule(pModuleType) local moduleDataCombined = commonFunctions:cloneTable(moduleDataReadOnly) for k, v in pairs(getNonReadOnlyParams(pModuleType)) do getModuleParams(moduleDataCombined)[k] = v end local cid = self.mobileSession:SendRPC("SetInteriorVehicleData", { moduleData = moduleDataCombined }) EXPECT_HMICALL("RC.SetInteriorVehicleData", { appID = self.applications["Test Application"], moduleData = moduleDataReadOnly }) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { moduleData = moduleDataReadOnly }) end) :ValidIf(function(_, data) local isFalse = false for k1, _ in pairs(getModuleParams(commonRC.getReadOnlyParamsByModule(pModuleType))) do for k2, _ in pairs(getModuleParams(data.params.moduleData)) do if k1 == k2 then isFalse = true commonFunctions:userPrint(36, "Unexpected read-only parameter: " .. k1) end end end if isFalse then return false, "Test step failed, see prints" end return true end) self.mobileSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI, PTU", commonRC.rai_ptu) runner.Title("Test") for _, mod in pairs(modules) do runner.Step("SetInteriorVehicleData " .. mod, setVehicleData, { mod }) end runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
--------------------------------------------------------------------------------------------------- -- Description -- In case: -- 1) Application sends valid SetInteriorVehicleData with read-only parameters -- 2) and one or more settable parameters in "radioControlData" struct, for moduleType: RADIO, -- SDL must: -- 1) Cut the read-only parameters off and process this RPC as assigned -- (that is, check policies, send to HMI, and etc. per existing requirements) --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local commonRC = require('test_scripts/RC/commonRC') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') --[[ Local Variables ]] local modules = { "CLIMATE", "RADIO" } --[[ Local Functions ]] local function getNonReadOnlyParams(pModuleType) if pModuleType == "CLIMATE" then return { fanSpeed = 55 } elseif pModuleType == "RADIO" then return { band = "FM" } end end local function getModuleParams(pModuleData) if pModuleData.climateControlData then return pModuleData.climateControlData elseif pModuleData.radioControlData then return pModuleData.radioControlData end end local function setVehicleData(pModuleType, self) local moduleDataReadOnly = commonRC.getReadOnlyParamsByModule(pModuleType) local moduleDataCombined = commonFunctions:cloneTable(moduleDataReadOnly) for k, v in pairs(getNonReadOnlyParams(pModuleType)) do getModuleParams(moduleDataCombined)[k] = v end local cid = self.mobileSession:SendRPC("SetInteriorVehicleData", { moduleData = moduleDataCombined }) EXPECT_HMICALL("RC.SetInteriorVehicleData", { appID = self.applications["Test Application"], moduleData = moduleDataReadOnly }) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { moduleData = moduleDataReadOnly }) end) :ValidIf(function(_, data) local isFalse = false for param_readonly, _ in pairs(getModuleParams(commonRC.getReadOnlyParamsByModule(pModuleType))) do for param_actual, _ in pairs(getModuleParams(data.params.moduleData)) do if param_readonly == param_actual then isFalse = true commonFunctions:userPrint(36, "Unexpected read-only parameter: " .. param_readonly) end end end if isFalse then return false, "Test step failed, see prints" end return true end) self.mobileSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonRC.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start) runner.Step("RAI, PTU", commonRC.rai_ptu) runner.Title("Test") for _, mod in pairs(modules) do runner.Step("SetInteriorVehicleData " .. mod, setVehicleData, { mod }) end runner.Title("Postconditions") runner.Step("Stop SDL", commonRC.postconditions)
SetInteriorVehicleData: Minor fix of parameter names
SetInteriorVehicleData: Minor fix of parameter names
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
1310c86b58ca2268e1a48d94665c1502546735bd
src/lua-factory/sources/grl-video-title-parsing.lua
src/lua-factory/sources/grl-video-title-parsing.lua
--[[ * Copyright (C) 2014 Grilo Project * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-video-title-parsing", name = "video-title-parsing", description = "Video title parsing", supported_keys = { "episode-title", 'show', 'publication-date', 'season', 'episode', 'title' }, supported_media = 'video', resolve_keys = { ["type"] = "video", required = { "title" }, }, } blacklisted_words = { "720p", "1080p", "x264", "ws", "proper", "real.repack", "repack", "hdtv", "pdtv", "notv", "dsr", "DVDRip", "divx", "xvid", } -- https://en.wikipedia.org/wiki/Video_file_format video_suffixes = { "webm", "mkv", "flv", "ogv", "ogg", "avi", "mov", "wmv", "mp4", "m4v", "mpeg", "mpg" } parsers = { tvshow = { "(.-)[sS](%d+)[%s.]*[eE][pP]?(%d+)(.+)", "(.-)(%d+)[xX.](%d+)(.+)", }, movies = { "(.-)(19%d%d)", "(.-)(20%d%d)", } } -- in case suffix is recognized, remove it and return true -- or return the title and false if it fails function remove_suffix(title) local s = title:gsub(".*%.(.-)$", "%1") if s then for _, suffix in ipairs(video_suffixes) do if s:find(suffix) then local t = title:gsub("(.*)%..-$", "%1") return t, true end end end return title, false end function clean_title(title) return title:gsub("^[%s%W]*(.-)[%s%W]*$", "%1"):gsub("%.", " ") end function clean_title_from_blacklist(title) local s = title:lower() local last_index local suffix_removed -- remove movie suffix s, suffix_removed = remove_suffix(s) if suffix_removed == false then grl.debug ("Suffix not find in " .. title) end -- ignore everything after the first blacklisted word last_index = #s for i, word in ipairs (blacklisted_words) do local index = s:find(word:lower()) if index and index < last_index then last_index = index - 1 end end return title:sub(1, last_index) end function parse_as_movie(media) local title, date local str = clean_title_from_blacklist (media.title) for i, parser in ipairs(parsers.movies) do title, date = str:match(parser) if title and date then media.title = clean_title(title) media.publication_date = date return true end end return false end function parse_as_episode(media) local show, season, episode, title for i, parser in ipairs(parsers.tvshow) do show, season, episode, title = media.title:match(parser) if show and season and episode and tonumber(season) < 50 then media.show = clean_title(show) media.season = season media.episode = episode media.episode_title = clean_title(clean_title_from_blacklist(title)) return true end end return false end function grl_source_resolve(media, options, callback) if not media or not media.title then callback() return end -- It is easier to identify a tv show due information -- related to episode and season number if parse_as_episode(media) then grl.debug(media.title .. " is an EPISODE") callback(media, 0) return end if parse_as_movie(media) then grl.debug(media.title .. " is a MOVIE") callback(media, 0) return end local suffix_removed media.title, suffix_removed = remove_suffix(media.title) if media.title and suffix_removed then grl.debug(media.title .. " is a MOVIE (without suffix)") callback(media, 0) return end grl.debug("Fail to identify video: " .. media.title) callback() end
--[[ * Copyright (C) 2014 Grilo Project * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-video-title-parsing", name = "video-title-parsing", description = "Video title parsing", supported_keys = { "episode-title", 'show', 'publication-date', 'season', 'episode', 'title' }, supported_media = 'video', resolve_keys = { ["type"] = "video", required = { "title" }, }, } blacklisted_words = { "720p", "1080p", "x264", "ws", "proper", "real.repack", "repack", "hdtv", "pdtv", "notv", "dsr", "DVDRip", "divx", "xvid", } -- https://en.wikipedia.org/wiki/Video_file_format video_suffixes = { "webm", "mkv", "flv", "ogv", "ogg", "avi", "mov", "wmv", "mp4", "m4v", "mpeg", "mpg" } parsers = { tvshow = { "(.-)[sS](%d+)[%s.]*[eE][pP]?(%d+)(.+)", "(.-)(%d+)[xX.](%d+)(.+)", }, movies = { "(.-)(19%d%d)", "(.-)(20%d%d)", } } -- in case suffix is recognized, remove it and return true -- or return the title and false if it fails function remove_suffix(title) local s = title:gsub(".*%.(.-)$", "%1") if s then for _, suffix in ipairs(video_suffixes) do if s:find(suffix) then local t = title:gsub("(.*)%..-$", "%1") return t, true end end end return title, false end function clean_title(title) return title:gsub("^[%s%W]*(.-)[%s%W]*$", "%1"):gsub("%.", " ") end function clean_title_from_blacklist(title) local s = title:lower() local last_index local suffix_removed -- remove movie suffix s, suffix_removed = remove_suffix(s) if suffix_removed == false then grl.debug ("Suffix not find in " .. title) end -- ignore everything after the first blacklisted word last_index = #s for i, word in ipairs (blacklisted_words) do local index = s:find(word:lower()) if index and index < last_index then last_index = index - 1 end end return title:sub(1, last_index) end function parse_as_movie(media) local title, date local str = clean_title_from_blacklist (media.title) for i, parser in ipairs(parsers.movies) do title, date = str:match(parser) if title and date then media.title = clean_title(title) media.publication_date = date return true end end return false end function parse_as_episode(media) local show, season, episode, title for i, parser in ipairs(parsers.tvshow) do show, season, episode, title = media.title:match(parser) if show and season and episode and tonumber(season) < 50 then media.show = clean_title(show) media.season = season media.episode = episode media.episode_title = clean_title(clean_title_from_blacklist(title)) return true end end return false end function grl_source_resolve() local req local media = {} req = grl.get_media_keys() if not req or not req.title then grl.callback() return end media.title = req.title -- It is easier to identify a tv show due information -- related to episode and season number if parse_as_episode(media) then grl.debug(req.title .. " is an EPISODE") grl.callback(media, 0) return end if parse_as_movie(media) then grl.debug(req.title .. " is a MOVIE") grl.callback(media, 0) return end local suffix_removed media.title, suffix_removed = remove_suffix(media.title) if media.title and suffix_removed then grl.debug(req.title .. " is a MOVIE (without suffix)") grl.callback(media, 0) return end grl.debug("Fail to identify video: " .. req.title) grl.callback() end
Revert "lua-factory: port grl-video-title-parsing.lua to the new lua system"
Revert "lua-factory: port grl-video-title-parsing.lua to the new lua system" This reverts commit 46b127a9ccee3a01f95bee47e81305238ab17f3a. https://bugzilla.gnome.org/show_bug.cgi?id=763046
Lua
lgpl-2.1
MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins
5a7e0f8b115dd5f19aa676bcfd2ca67a797aae02
scripts/chem_extract_auto.lua
scripts/chem_extract_auto.lua
dofile("chem_notepad.lua"); cheapRecipes = nil; allRecipes = nil; local types = {"Ra", "Thoth", "Osiris", "Set", "Maat", "Geb"}; local typePlus = {"+++++", "++++", "++++", "+++", "+++", "++"}; local typeMinus = {"-----", "----", "----", "---", "---", "--"}; local typeEnabled = {true, true, true, true, true, true}; local properties = {"Aromatic", "Astringent", "Bitter", "Salty", "Sour", "Spicy", "Sweet", "Toxic"}; local props = {"Ar", "As", "Bi", "Sa", "So", "Sp", "Sw", "To"}; function doit() cheapRecipes = loadNotes("scripts/chem-cheap.txt"); allRecipes = loadNotes("scripts/chem-all.txt"); askForWindow("Setup for this macro is complicated. To view detailed instructions:\n \nClick Exit button, Open Folder button\nDouble click 'chem_extract_auto.txt'.\n \nClick Shift over ATITD window to continue."); while true do tryAllTypes(); sleepWithStatus(2000, "Making more magic"); end end function tryAllTypes() for i=1,#types do local done = false; if typeEnabled[i] then statusScreen("Trying type " .. types[i]); srReadScreen(); clickAllText(types[i] .. "'s Compound"); local anchor = waitForText("Required:"); if anchor then local tags = {types[i]}; local window = getWindowBorders(anchor[0], anchor[1]); addRequirements(tags, findAllText(typePlus[i], window), typePlus[i]); addRequirements(tags, findAllText(typeMinus[i], window), typeMinus[i]); local recipe = lookupData(cheapRecipes, tags); if not recipe and i <= 2 then recipe = lookupData(allRecipes, tags); end if recipe then lsPrintln("tags: " .. table.concat(tags, ", ")); -- if not recipe then -- lsPrintln("Boohoo"); -- end -- if recipe then -- lsPrintln("Impossible"); -- else -- lsPrintln("else"); -- end -- lsPrintln("Recipe: " .. table.concat(recipe, "---")); local recipeList = csplit(recipe, ","); lsPrintln("After csplit"); done = true; local done = makeRecipe(recipeList, window); if done then break; end else lsPrintln("No recipe for " .. table.concat(tags, ",")); end end while clickAllImages("Cancel.png") == 1 do sleepWithStatus(200, types[i] .. " not found: Cancel"); end end end end function addRequirements(tags, lines, sign) for i=1,#lines do lsPrintln("Line: " .. lines[i][2]); for j=1,#properties do if string.match(lines[i][2], properties[j]) or (properties[j] == "Toxic" and string.match(lines[i][2], "Txic")) then table.insert(tags, props[j] .. sign); break; end end end end function makeRecipe(recipe, window) statusScreen("Checking ingredients: " .. table.concat(recipe, ", ")); local ingredients = findIngredients(recipe); if #ingredients < 5 then askForWindow("Not enough essences for recipe " .. table.concat(recipe, ", ")); return false; end local t = nil; for i=1,#ingredients do local status = "Recipe: " .. table.concat(recipe, ", ") .. "\n\n\n" .. "Adding Essence of " .. recipe[i]; -- statusScreen("Adding Essence of " .. recipe[i]); safeClick(ingredients[i][0]+10, ingredients[i][1]+5); waitForText("many?", 5000, status, nil, nil, NOPIN); srKeyEvent("7\n"); local ingredientWindow = getWindowBorders(ingredients[i][0]+10, ingredients[i][1]+5); safeClick(ingredientWindow.x + 2, ingredientWindow.y + 2); t = waitForText("Manufacture", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Essential Mixture", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Add Essence", nil, status); safeClick(t[0]+10, t[1]+5); local done = false; while not done do local spot = findWithoutParen(recipe[i]); if spot then safeClick(spot[0]+10, spot[1]+5); done = true; end checkBreak(); end end local status = "Mixing Compound"; t = waitForText("Manufacture", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Essential Mixture", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Mix Comp", nil, status); safeClick(t[0]+10, t[1]+5); waitForText("do you wish to name it?", nil, status); srKeyEvent("autocompound\n"); sleepWithStatus(300, status); clickAllText("This is [a-z]+ Chemistry Lab", nil, REGEX); sleepWithStatus(300, status); t = waitForText("Take...", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Everything", nil, status); safeClick(t[0]+10, t[1]+5); statusScreen("Creating extract", nil, status); t = waitForText("Essential Comp", nil, status .. "\n\nWaiting for autocompound", makeBox(window.x + 10, window.y, window.width - 10, window.height)); safeClick(t[0]+10, t[1]+5); sleepWithStatus(200, status); clickAllImages("Okb.png"); sleepWithStatus(200, status); return true; end function findIngredients(names) local result = {}; for i=1,#names do local current = findTextPrefix(names[i]); if current then local window = getWindowBorders(current[0], current[1]); safeClick(window.x+2, window.y+2); lsSleep(100); current = findTextPrefix(names[i], window); if current then local first, len, match = string.find(current[2], "%(([0-9]+)"); local count = tonumber(match); if count and count >= 7 then table.insert(result, current); elseif count then lsPrintln("No essences for: " .. names[i] .. " (" .. count .. ")"); else lsPrintln("No count for: " .. names[i]); end end end end return result; end function findTextPrefix(text, window) local result = nil; local matches = findAllText(text, window); for i=1,#matches do local first = string.find(matches[i][2], text); if first == 1 then result = matches[i]; break; end end return result; end function findWithoutParen(text) local result = nil; local matches = findAllText(text); for i=1,#matches do local found = string.match(matches[i][2], "%("); if not found then result = matches[i]; break; end end return result; end
dofile("chem_notepad.lua"); cheapRecipes = nil; allRecipes = nil; local types = {"Ra", "Thoth", "Osiris", "Set", "Maat", "Geb"}; local typePlus = {"+++++", "++++", "++++", "+++", "+++", "++"}; local typeMinus = {"-----", "----", "----", "---", "---", "--"}; local typeEnabled = {true, true, true, true, true, true}; local properties = {"Aromatic", "Astringent", "Bitter", "Salty", "Sour", "Spicy", "Sweet", "Toxic"}; local props = {"Ar", "As", "Bi", "Sa", "So", "Sp", "Sw", "To"}; function doit() cheapRecipes = loadNotes("scripts/chem-cheap.txt"); allRecipes = loadNotes("scripts/chem-all.txt"); askForWindow("Setup for this macro is complicated. To view detailed instructions:\n \nClick Exit button, Open Folder button\nDouble click 'chem_extract_auto.txt'.\n \nClick Shift over ATITD window to continue."); while true do tryAllTypes(); sleepWithStatus(2000, "Making more magic"); end end function tryAllTypes() for i=1,#types do local done = false; if typeEnabled[i] then statusScreen("Trying type " .. types[i]); srReadScreen(); clickAllText(types[i] .. "'s Compound"); local anchor = waitForText("Required:"); if anchor then local tags = {types[i]}; local window = getWindowBorders(anchor[0], anchor[1]); addRequirements(tags, findAllText(typePlus[i], window), typePlus[i]); addRequirements(tags, findAllText(typeMinus[i], window), typeMinus[i]); local recipe = lookupData(cheapRecipes, tags); if not recipe and i <= 2 then recipe = lookupData(allRecipes, tags); end if recipe then lsPrintln("tags: " .. table.concat(tags, ", ")); -- if not recipe then -- lsPrintln("Boohoo"); -- end -- if recipe then -- lsPrintln("Impossible"); -- else -- lsPrintln("else"); -- end -- lsPrintln("Recipe: " .. table.concat(recipe, "---")); local recipeList = csplit(recipe, ","); lsPrintln("After csplit"); done = true; local done = makeRecipe(recipeList, window); if done then break; end else lsPrintln("No recipe for " .. table.concat(tags, ",")); end end while clickAllImages("Cancel.png") == 1 do sleepWithStatus(200, types[i] .. " not found: Cancel"); end end end end function addRequirements(tags, lines, sign) for i=1,#lines do lsPrintln("Line: " .. lines[i][2]); for j=1,#properties do if string.match(lines[i][2], properties[j]) or (properties[j] == "Toxic" and string.match(lines[i][2], "Txic")) then table.insert(tags, props[j] .. sign); break; end end end end function makeRecipe(recipe, window) statusScreen("Checking ingredients: " .. table.concat(recipe, ", ")); local ingredients = findIngredients(recipe); if #ingredients < 5 then askForWindow("Not enough essences for recipe " .. table.concat(recipe, ", ")); return false; end local t = nil; for i=1,#ingredients do local status = "Recipe: " .. table.concat(recipe, ", ") .. "\n\n\n" .. "Adding Essence of " .. recipe[i]; -- statusScreen("Adding Essence of " .. recipe[i]); safeClick(ingredients[i][0]+10, ingredients[i][1]+5); waitForText("many?", 5000, status, nil, nil, NOPIN); srKeyEvent("7\n"); local ingredientWindow = getWindowBorders(ingredients[i][0]+10, ingredients[i][1]+5); safeClick(ingredientWindow.x + 2, ingredientWindow.y + 2); t = waitForText("Manufacture...", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Essential Mixture", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Add Essence", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText(recipe[i], nil, status, nil, EXACT); clickText(t); end local status = "Mixing Compound"; t = waitForText("Manufacture...", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Essential Mixture", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Mix Comp", nil, status); safeClick(t[0]+10, t[1]+5); waitForText("do you wish to name it?", nil, status); srKeyEvent("autocompound\n"); sleepWithStatus(300, status); clickAllText("This is [a-z]+ Chemistry Lab", nil, REGEX); sleepWithStatus(300, status); t = waitForText("Take...", nil, status); safeClick(t[0]+10, t[1]+5); t = waitForText("Everything", nil, status); safeClick(t[0]+10, t[1]+5); statusScreen("Creating extract", nil, status); t = waitForText("Essential Comp", nil, status .. "\n\nWaiting for autocompound", makeBox(window.x + 10, window.y, window.width - 10, window.height)); safeClick(t[0]+10, t[1]+5); sleepWithStatus(200, status); clickAllImages("Okb.png"); sleepWithStatus(200, status); return true; end function findIngredients(names) local result = {}; for i=1,#names do local current = findTextPrefix(names[i]); if current then local window = getWindowBorders(current[0], current[1]); safeClick(window.x+2, window.y+2); lsSleep(100); current = findTextPrefix(names[i], window); if current then local first, len, match = string.find(current[2], "%(([0-9]+)"); local count = tonumber(match); if count and count >= 7 then table.insert(result, current); elseif count then lsPrintln("No essences for: " .. names[i] .. " (" .. count .. ")"); else lsPrintln("No count for: " .. names[i]); end end end end return result; end function findTextPrefix(text, window) local result = nil; local matches = findAllText(text, window); for i=1,#matches do local first = string.find(matches[i][2], text); if first == 1 then result = matches[i]; break; end end return result; end function findWithoutParen(text) local result = nil; local matches = findAllText(text); for i=1,#matches do local found = string.match(matches[i][2], "%("); if not found then result = matches[i]; break; end end return result; end
fixes for "Manufacture..." menu item, autocompound naming, material selection
fixes for "Manufacture..." menu item, autocompound naming, material selection
Lua
mit
DashingStrike/Automato-ATITD,DashingStrike/Automato-ATITD,TheRealMaxion/Automato-ATITD,wzydhek/Automato-ATITD,TheRealMaxion/Automato-ATITD,wzydhek/Automato-ATITD
90b9c41c65d211ef07233f0e1c575e0b7e03644d
lua/weapons/pktfw_minigun.lua
lua/weapons/pktfw_minigun.lua
AddCSLuaFile() SWEP.ViewModel = "models/weapons/c_arms_citizen.mdl" SWEP.WorldModel = "models/weapons/w_models/w_minigun.mdl" SWEP.Primary.ClipSize = 200 SWEP.Primary.DefaultClip = 200 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "AR2" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = true SWEP.Secondary.Ammo = "none" SWEP.Spawnable=true SWEP.AdminSpawnable=true SWEP.PrintName="Minigun" SWEP.Category = "Pill Pack Weapons - TF2" SWEP.Slot=2 function SWEP:Initialize() self:SetHoldType("slam") if SERVER then self.sound_shoot = CreateSound(self,"weapons/minigun_shoot.wav") self.sound_spin = CreateSound(self,"weapons/minigun_spin.wav") self.sound_windup = CreateSound(self,"weapons/minigun_wind_up.wav") self.sound_winddown = CreateSound(self,"weapons/minigun_wind_down.wav") self.lastattack = 0 //self.windupstart = -1 end end function SWEP:PrimaryAttack() if SERVER then self.primaryAttackCalled=true end if !self:CanPrimaryAttack() or CurTime()<self.lastattack+.1 or !self.windupstart or self.windupstart+.87>CurTime() then return end self:ShootBullet(9, 1, 0.04) self:TakePrimaryAmmo(1) self.Owner:SetAnimation(PLAYER_ATTACK1) self.lastattack=CurTime() //self:SetNextPrimaryFire(CurTime() + .1) end if SERVER then function SWEP:Think() /*if self.lastShot+.11>=CurTime() then if !self.sound_shoot:IsPlaying() then self.sound_shoot:Play() end else if self.sound_shoot:IsPlaying() then self.sound_shoot:Stop() end end*/ /*if self.primaryAttackCalled then self.primaryAttackCalled=false if !self.sound_shoot:IsPlaying() then self.sound_shoot:Play() end else if self.sound_shoot:IsPlaying() then self.sound_shoot:Stop() end end*/ if self.primaryAttackCalled or self.secondaryAttackCalled then if !self.windupstart then self.windupstart=CurTime() self.sound_windup:Stop() self.sound_winddown:Stop() self.sound_windup:Play() self:SetHoldType("physgun") //self:EmitSound("weapons/minigun_wind_up.wav") end else if self.windupstart then self.windupstart=nil self.sound_windup:Stop() self.sound_winddown:Stop() self.sound_winddown:Play() self:SetHoldType("slam") //self:EmitSound("weapons/minigun_wind_down.wav") end end if self.windupstart and self.windupstart+.87<=CurTime() then if self.primaryAttackCalled then self.sound_shoot:Play() self.sound_spin:Stop() else self.sound_shoot:Stop() self.sound_spin:Play() end /*if self:GetHoldType() != "physgun" then self:SetWeaponHoldType("physgun") end*/ else self.sound_shoot:Stop() self.sound_spin:Stop() /*if self:GetHoldType() != "slam" then self:SetWeaponHoldType("slam") end*/ end self.primaryAttackCalled = false self.secondaryAttackCalled = false end else function SWEP:Think() if self.primaryAttackCalled or self.secondaryAttackCalled then if !self.windupstart then self.windupstart=CurTime() end else if self.windupstart then self.windupstart=nil end end self.primaryAttackCalled = false self.secondaryAttackCalled = false end end //function SWEP:Remove() function SWEP:SecondaryAttack() if SERVER then self.secondaryAttackCalled=true end end function SWEP:Reload() /*if self.ReloadingTime and CurTime() <= self.ReloadingTime then return end if (self:Clip1() < self.Primary.ClipSize and self.Owner:GetAmmoCount(self.Primary.Ammo) > 0) then self:EmitSound("weapons/pistol_worldreload.wav") self:DefaultReload(ACT_INVALID) self.ReloadingTime = CurTime() + 1.3 self:SetNextPrimaryFire(CurTime() + 1.3) end*/ end function SWEP:OnRemove() if CLIENT then return end self.sound_shoot:Stop() self.sound_spin:Stop() self.sound_windup:Stop() self.sound_winddown:Stop() end function SWEP:Holster() return !self.windupstart end
AddCSLuaFile() SWEP.ViewModel = "models/weapons/c_arms_citizen.mdl" SWEP.WorldModel = "models/weapons/w_models/w_minigun.mdl" SWEP.Primary.ClipSize = 200 SWEP.Primary.DefaultClip = 200 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "AR2" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = true SWEP.Secondary.Ammo = "none" SWEP.Spawnable=true SWEP.AdminSpawnable=true SWEP.PrintName="Minigun" SWEP.Category = "Pill Pack Weapons - TF2" SWEP.Slot=2 function SWEP:Initialize() self:SetHoldType("slam") if SERVER then self.sound_shoot = CreateSound(self,"weapons/minigun_shoot.wav") self.sound_spin = CreateSound(self,"weapons/minigun_spin.wav") self.sound_windup = CreateSound(self,"weapons/minigun_wind_up.wav") self.sound_winddown = CreateSound(self,"weapons/minigun_wind_down.wav") self.lastattack = 0 //self.windupstart = -1 end end function SWEP:PrimaryAttack() if SERVER then self.primaryAttackCalled=true end if !self:CanPrimaryAttack() or CurTime()<self.lastattack+.1 or !self.windupstart or self.windupstart+.87>CurTime() then return end self:ShootBullet(9, 1, 0.04) self:TakePrimaryAmmo(1) self.Owner:SetAnimation(PLAYER_ATTACK1) self.lastattack=CurTime() //self:SetNextPrimaryFire(CurTime() + .1) end if SERVER then function SWEP:Think() /*if self.lastShot+.11>=CurTime() then if !self.sound_shoot:IsPlaying() then self.sound_shoot:Play() end else if self.sound_shoot:IsPlaying() then self.sound_shoot:Stop() end end*/ /*if self.primaryAttackCalled then self.primaryAttackCalled=false if !self.sound_shoot:IsPlaying() then self.sound_shoot:Play() end else if self.sound_shoot:IsPlaying() then self.sound_shoot:Stop() end end*/ if self.primaryAttackCalled or self.secondaryAttackCalled then if !self.windupstart then self.windupstart=CurTime() self.sound_windup:Stop() self.sound_winddown:Stop() self.sound_windup:Play() self:SetHoldType("physgun") //self:EmitSound("weapons/minigun_wind_up.wav") end else if self.windupstart then self.windupstart=nil self.sound_windup:Stop() self.sound_winddown:Stop() self.sound_winddown:Play() self:SetHoldType("slam") //self:EmitSound("weapons/minigun_wind_down.wav") end end if self.windupstart and self.windupstart+.87<=CurTime() then if self.primaryAttackCalled then self.sound_shoot:Play() self.sound_spin:Stop() else self.sound_shoot:Stop() self.sound_spin:Play() end /*if self:GetHoldType() != "physgun" then self:SetWeaponHoldType("physgun") end*/ else self.sound_shoot:Stop() self.sound_spin:Stop() /*if self:GetHoldType() != "slam" then self:SetWeaponHoldType("slam") end*/ end self.primaryAttackCalled = false self.secondaryAttackCalled = false end else function SWEP:Think() if self.primaryAttackCalled or self.secondaryAttackCalled then if !self.windupstart then self.windupstart=CurTime() end else if self.windupstart then self.windupstart=nil end end self.primaryAttackCalled = false self.secondaryAttackCalled = false end end //function SWEP:Remove() function SWEP:SecondaryAttack() if SERVER then self.secondaryAttackCalled=true end end function SWEP:Reload() /*if self.ReloadingTime and CurTime() <= self.ReloadingTime then return end if (self:Clip1() < self.Primary.ClipSize and self.Owner:GetAmmoCount(self.Primary.Ammo) > 0) then self:EmitSound("weapons/pistol_worldreload.wav") self:DefaultReload(ACT_INVALID) self.ReloadingTime = CurTime() + 1.3 self:SetNextPrimaryFire(CurTime() + 1.3) end*/ end function SWEP:MoMoMoveSpeedMod() if self.windupstart then return .478 end end function SWEP:OnRemove() if CLIENT then return end self.sound_shoot:Stop() self.sound_spin:Stop() self.sound_windup:Stop() self.sound_winddown:Stop() end function SWEP:Holster() return !self.windupstart end
Fixed minigun movement speed.
Fixed minigun movement speed.
Lua
mit
birdbrainswagtrain/GmodPillPack-TeamFortress
da28912f1b8ea438935762f1cf6cd396305c1998
minionmaster/minionmaster.lua
minionmaster/minionmaster.lua
local Unit = require "shared.unit" local MinionMaster = Unit:subclass("MinionMaster") local content = require "minionmaster.content" local state = require "minionmaster.state" -- speed: pixels/second function MinionMaster:initialize(entityStatics) Unit.initialize(self, entityStatics, state.player) self.joystick = love.joystick.getJoysticks()[1] end function MinionMaster:update(dt) local moveX = (love.keyboard.isDown("d") and 2 or 0) - (love.keyboard.isDown("a") and 2 or 0) local moveY = (love.keyboard.isDown("s") and 2 or 0) - (love.keyboard.isDown("w") and 2 or 0) if self.joystick then local x = self.joystick:getGamepadAxis("leftx") local y = self.joystick:getGamepadAxis("lefty") if math.abs(x) > 0.2 then moveX = moveX + x * 2 end if math.abs(y) > 0.2 then moveY = moveY + y * 2 end end self:moveTo(self.position.x + moveX, self.position.y + moveY) Unit.update(self, dt) end function MinionMaster:draw(dt) local x, y = self.position.x, self.position.y love.graphics.setColor(0, 0, 255, 255) love.graphics.circle("fill", x, y, self.radius, self.radius) end return MinionMaster
local Unit = require "shared.unit" local MinionMaster = Unit:subclass("MinionMaster") local content = require "minionmaster.content" local state = require "minionmaster.state" -- speed: pixels/second function MinionMaster:initialize(entityStatics) Unit.initialize(self, entityStatics, state.player) self.joystick = love.joystick.getJoysticks()[1] end function MinionMaster:update(dt) local moveX = (love.keyboard.isDown("d") and 2 or 0) - (love.keyboard.isDown("a") and 2 or 0) local moveY = (love.keyboard.isDown("s") and 2 or 0) - (love.keyboard.isDown("w") and 2 or 0) if self.joystick then local x = self.joystick:getGamepadAxis("leftx") local y = self.joystick:getGamepadAxis("lefty") if math.abs(x) > 0.2 then moveX = moveX + x * 2 end if math.abs(y) > 0.2 then moveY = moveY + y * 2 end end self:moveTo(self.position.x + moveX, self.position.y + moveY) Unit.update(self, dt) end function MinionMaster:draw(dt) local x, y = self.position.x, self.position.y love.graphics.setColor(0, 0, 255, 255) love.graphics.circle("fill", x, y, self.radius, self.radius) love.graphics.setColor(255, 255, 255, 255) end return MinionMaster
fixed enemy color
fixed enemy color
Lua
mit
ExcelF/project-navel
4b5bd35bea9c506a5bdb59283e852308260babc3
[resources]/GTWgates/gates.lua
[resources]/GTWgates/gates.lua
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- ***************************************************************************** -- BELOW TABLE ARE MADE FOR SERVERS OWNED BY GRAND THEFT WALRUS, USE IT ONLY AS -- AN EXAMPLE OF THE LAYOUT TO UNDERSTAND HOW THIS SYSTEM WORKS -- ***************************************************************************** gate_data = { -- ObjectID closeX closeY closeZ openX openY openZ rotX rotY rotZ colX colY colZ colRad Group Scale Interior Dimension [1]={ 986, 1588.6, -1638.4, 13.4, 1578.6, -1638.4, 13.4, 0, 0, 0, 1588, -1638, 10, 5, "Government", 1, 0, 0 }, [2]={ 10671, -1631, 688.4, 8.587, -1631, 688.4, 20.187, 0, 0, 90, -1631, 688, 7.187, 10, "Government", 2, 0, 0 }, [3]={ 11327, 2334.6, 2443.7, 7.70, 2334.6, 2443.7, 15.70, 0, 0, -30, 2334.6, 2443.7, 5.70, 10, "Government", 1.3, 0, 0 }, [4]={ 2957, 2294, 2498.8, 5.1, 2294, 2498.8, 14.3, 0, 0, 90, 2294, 2498.8, 5.1, 10, "Government", 1.8, 0, 0 }, [5]={ 980, 3159, -1962.8, 12.5, 3159, -1947.8, 12.5, 0, 0, 90, 3159, -1967, 10, 10, "SAPD", 1, 0, 0 }, [6]={ 2938, 97.5, 508.5, 13.6, 97.5, 508.5, 3.6, 0, 0, 90, 97.5, 508.5, 13.6, 10, "SWAT", 1, 0, 0 }, [7]={ 2938, 107.6, 414.9, 13.6, 107.6, 414.9, 3.6, 0, 0, 90, 107.6, 414.9, 13.6, 10, "SWAT", 1, 0, 0 }, [8]={ 16773, 60.8, 504.4, 24.9, 70.8, 504.4, 24.9, 90, 0, 0, 60.8, 504.4, 24.9, 10, "SWAT", 1, 0, 0 }, [9]={ 986, -1571.8, 662.1, 7.4, -1571.8, 654.6, 7.4, 0, 0, 90, -1571, 661.8, 6.8, 10, "Government", 1, 0, 0 }, [10]={ 985, -1641.4, 689, 7.4, -1641.4, 689, 7.4, 0, 0, 90, -1643, 682, 7.5, 10, "Government", 1, 0, 0 }, [11]={ 986, -1641.4, 681, 7.4, -1641.4, 673.1, 7.4, 0, 0, 90, -1643, 682, 7.5, 10, "Government", 1, 0, 0 }, [12]={ 985, -2990.75, 2358.6, 7.6, -2984.2, 2358.6, 7.6, 0, 0, 0, -2991, 2359, 7.2, 5, "Government", 0.83, 0, 0 }, [13]={ 985, 2237.5, 2453.3, 8.55, 2237.5, 2461.1, 8.55, 0, 0, 90, 2237, 2454, 10.6, 15, "Government", 1, 0, 0 }, [14]={ 986, 1543.55, -1627.1, 13.6, 1543.55, -1634.7, 13.6, 0, 0, 90, 1543, -1627, 13.1, 15, "Government", 0.93, 0, 0 }, [15]={ 985, -2228.5, 2373.3, 4.1, -2234.8, 2379.6, 4.1, 0, 0, 135, -2228, 2373, 4.9, 15, "Government", 1, 0, 0 }, [16]={ 985, 284.7, 1818.0, 17.0, 284.7, 1811.6, 17.0, 0, 0, 270, 284.7, 1818.0, 16.6, 5, "Government", 1, 0, 0 }, [17]={ 986, 284.7, 1826.0, 17.0, 284.7, 1831.2, 17.0, 0, 0, 270, 284.7, 1826.0, 16.6, 5, "Government", 1, 0, 0 }, [18]={ 985, 131, 1941.8, 17.8, 123, 1941.8, 17.8, 0, 0, 180, 131, 1941.4, 18.0, 5, "Government", 1, 0, 0 }, [19]={ 986, 139, 1941.8, 17.8, 147, 1941.8, 17.8, 0, 0, 180, 139, 1941.4, 18.0, 5, "Government", 1, 0, 0 }, [20]={ 986, -2995.7, 2252.7, 6.9, -2999.7, 2252.7, 6.9, 0, 0, 0, -2995.7, 2252.6, 7.0, 5, "Government", 1, 0, 0 }, [21]={ 986, -2954.8, 2136.5, 7.0, -2949.0, 2138, 7.0, 0, 0, 190, -2954, 2136.7, 7.0, 6, "Government", 1, 0, 0 }, [22]={ 986, -2996.1, 2305.1, 7.9, -2995.86, 2306.6, 7.9, 0, 0, 268.6, -2996, 2303.9, 7.0, 6, "Government", 1, 0, 0 }, [23]={ 985, -3085.2, 2314.7, 7.0, -3085.5, 2307.5, 7.0, 0, 0, 267, -3084.8,2314.6, 7.0, 6, "Government", 1, 0, 0 }, [24]={ 986, -2953.4, 2255.8, 6.7, -2953.4, 2249.1, 6.7, 0, 0, 90, -2953.4,2256.3, 7.0, 5, "Government", 1, 0, 0 }, [25]={ 986, -2944.7, 2254.1, 6.7, -2944.7, 2246.7, 6.7, 0, 0, 90, -2944.7,2254.3, 7.0, 5, "Government", 1, 0, 0 }, -- ObjectID closeX closeY closeZ openX openY openZ rotX rotY rotZ colX colY colZ colRad Group Scale Interior Dimension [26]={ 986, -2995.7, 2264.7, 6.9, -2999.7, 2264.7, 6.9, 0, 0, 0, -2992.7, 2264.6, 7.0, 5, "Government", 1, 0, 0 }, [27]={ 986, -2990.7, 2348.7, 7.6, -2996.2, 2348.7, 7.6, 0, 0, 0, -2989.7, 2348.7, 7.6, 5, "Government", 0.83, 0, 0 }, } -- Global data members gates = { } cols = { } openSpeed = 2000 -- Add all gates function load_gates(name) for k=1, #gate_data do -- Create objects local gat = createObject( gate_data[k][1], gate_data[k][2], gate_data[k][3], gate_data[k][4], gate_data[k][8], gate_data[k][9], gate_data[k][10] ) local col = createColSphere( gate_data[k][11], gate_data[k][12], gate_data[k][13]+2, gate_data[k][14] ) setObjectScale( gat, gate_data[k][16] ) -- Assign arrays of object pointers gates[col] = gat cols[col] = k -- Set interior setElementInterior(gat, gate_data[k][17]) setElementInterior(col, gate_data[k][17]) -- Set dimension setElementDimension(gat, gate_data[k][18]) setElementDimension(col, gate_data[k][18]) -- Add event handlers addEventHandler("onColShapeHit", col, open_gate ) addEventHandler("onColShapeLeave", col, close_gate ) end end addEventHandler("onResourceStart", resourceRoot, load_gates) -- Gates open function open_gate(plr, matching_dimension) if not matching_dimension then return end local ID = cols[source] local px,py,pz = getElementPosition(plr) if plr and isElement(plr) and getElementType(plr) == "player" and ( getElementData(plr, "Group") == gate_data[ID][15] or getPlayerTeam(plr) == getTeamFromName(gate_data[ID][15]) or getPlayerTeam(plr) == getTeamFromName("Staff")) and pz + 5 > gate_data[ID][4] and pz - 5 < gate_data[ID][4] then -- Open the gate moveObject(gates[source], openSpeed, gate_data[ID][5], gate_data[ID][6], gate_data[ID][7] ) end end -- Gates close function close_gate(plr, matching_dimension) if not matching_dimension then return end local ID = cols[source] local plr_count = #getElementsWithinColShape(source, "player") plr_count = plr_count + #getElementsWithinColShape(source, "vehicle") if plr and isElement(plr) and getElementType(plr) == "player" and plr_count == 0 then moveObject(gates[source], openSpeed, gate_data[ID][2], gate_data[ID][3], gate_data[ID][4]) end end addCommandHandler("gtwinfo", function(plr, cmd) outputChatBox("[GTW-RPG] "..getResourceName( getThisResource())..", by: "..getResourceInfo( getThisResource(), "author")..", v-"..getResourceInfo( getThisResource(), "version")..", is represented", plr) end)
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- ***************************************************************************** -- BELOW TABLE ARE MADE FOR SERVERS OWNED BY GRAND THEFT WALRUS, USE IT ONLY AS -- AN EXAMPLE OF THE LAYOUT TO UNDERSTAND HOW THIS SYSTEM WORKS -- ***************************************************************************** gate_data = { -- ObjectID closeX closeY closeZ openX openY openZ rotX rotY rotZ colX colY colZ colRad Group Scale Interior Dimension [1]={ 986, 1588.6, -1638.4, 13.4, 1578.6, -1638.4, 13.4, 0, 0, 0, 1588, -1638, 10, 5, "Government", 1, 0, 0 }, [2]={ 10671, -1631, 688.4, 8.587, -1631, 688.4, 20.187, 0, 0, 90, -1631, 688, 7.187, 10, "Government", 2, 0, 0 }, [3]={ 11327, 2334.6, 2443.7, 7.70, 2334.6, 2443.7, 15.70, 0, 0, -30, 2334.6, 2443.7, 5.70, 10, "Government", 1.3, 0, 0 }, [4]={ 2957, 2294, 2498.8, 5.1, 2294, 2498.8, 14.3, 0, 0, 90, 2294, 2498.8, 5.1, 10, "Government", 1.8, 0, 0 }, [5]={ 980, 3159, -1962.8, 12.5, 3159, -1947.8, 12.5, 0, 0, 90, 3159, -1967, 10, 10, "SAPD", 1, 0, 0 }, [6]={ 986, -1571.8, 662.1, 7.4, -1571.8, 654.6, 7.4, 0, 0, 90, -1571, 661.8, 6.8, 10, "Government", 1, 0, 0 }, [7]={ 985, -1641.4, 689, 7.4, -1641.4, 689, 7.4, 0, 0, 90, -1643, 682, 7.5, 10, "Government", 1, 0, 0 }, [8]={ 986, -1641.4, 681, 7.4, -1641.4, 673.1, 7.4, 0, 0, 90, -1643, 682, 7.5, 10, "Government", 1, 0, 0 }, [9]={ 985, -2990.75, 2358.6, 7.6, -2984.2, 2358.6, 7.6, 0, 0, 0, -2991, 2359, 7.2, 5, "Government", 0.83, 0, 0 }, [10]={ 985, 2237.5, 2453.3, 8.55, 2237.5, 2461.1, 8.55, 0, 0, 90, 2237, 2454, 10.6, 15, "Government", 1, 0, 0 }, [11]={ 986, 1543.55, -1627.1, 13.6, 1543.55, -1634.7, 13.6, 0, 0, 90, 1543, -1627, 13.1, 15, "Government", 0.93, 0, 0 }, [12]={ 985, -2228.5, 2373.3, 4.1, -2234.8, 2379.6, 4.1, 0, 0, 135, -2228, 2373, 4.9, 15, "Government", 1, 0, 0 }, [13]={ 985, 284.7, 1818.0, 17.0, 284.7, 1811.6, 17.0, 0, 0, 270, 284.7, 1818.0, 16.6, 5, "Government", 1, 0, 0 }, [14]={ 986, 284.7, 1826.0, 17.0, 284.7, 1831.2, 17.0, 0, 0, 270, 284.7, 1826.0, 16.6, 5, "Government", 1, 0, 0 }, [15]={ 985, 131, 1941.8, 17.8, 123, 1941.8, 17.8, 0, 0, 180, 131, 1941.4, 18.0, 5, "Government", 1, 0, 0 }, [16]={ 986, 139, 1941.8, 17.8, 147, 1941.8, 17.8, 0, 0, 180, 139, 1941.4, 18.0, 5, "Government", 1, 0, 0 }, [17]={ 986, -2995.7, 2252.7, 6.9, -2999.7, 2252.7, 6.9, 0, 0, 0, -2995.7, 2252.6, 7.0, 5, "Government", 1, 0, 0 }, [18]={ 986, -2954.8, 2136.5, 7.0, -2949.0, 2138, 7.0, 0, 0, 190, -2954, 2136.7, 7.0, 6, "Government", 1, 0, 0 }, [19]={ 986, -2996.1, 2305.1, 7.9, -2995.86, 2306.6, 7.9, 0, 0, 268.6, -2996, 2303.9, 7.0, 6, "Government", 1, 0, 0 }, [20]={ 985, -3085.2, 2314.7, 7.0, -3085.5, 2307.5, 7.0, 0, 0, 267, -3084.8,2314.6, 7.0, 6, "Government", 1, 0, 0 }, [21]={ 986, -2953.4, 2255.8, 6.7, -2953.4, 2249.1, 6.7, 0, 0, 90, -2953.4,2256.3, 7.0, 5, "Government", 1, 0, 0 }, [22]={ 986, -2944.7, 2254.1, 6.7, -2944.7, 2246.7, 6.7, 0, 0, 90, -2944.7,2254.3, 7.0, 5, "Government", 1, 0, 0 }, -- ObjectID closeX closeY closeZ openX openY openZ rotX rotY rotZ colX colY colZ colRad Group Scale Interior Dimension [23]={ 986, -2995.7, 2264.7, 6.9, -2999.7, 2264.7, 6.9, 0, 0, 0, -2992.7,2264.6, 7.0, 5, "Government", 1, 0, 0 }, [24]={ 986, -2990.7, 2348.7, 7.6, -2996.2, 2348.7, 7.6, 0, 0, 0, -2989.7,2348.7, 7.6, 5, "Government", 0.83, 0, 0 }, [25]={ 986, 380.8, -68.6, 1002.16, 380.8, -68.6, 1007.5, 0, 0, 90, 380.8, -69, 1000.0, 1.5, "Government", 1, 10, 10 }, } -- Global data members gates = { } cols = { } openSpeed = 2000 -- Add all gates function load_gates(name) for k=1, #gate_data do -- Create objects local gat = createObject( gate_data[k][1], gate_data[k][2], gate_data[k][3], gate_data[k][4], gate_data[k][8], gate_data[k][9], gate_data[k][10] ) local col = createColSphere( gate_data[k][11], gate_data[k][12], gate_data[k][13]+2, gate_data[k][14] ) setObjectScale( gat, gate_data[k][16] ) -- Assign arrays of object pointers gates[col] = gat cols[col] = k -- Set interior setElementInterior(gat, gate_data[k][17]) setElementInterior(col, gate_data[k][17]) -- Set dimension setElementDimension(gat, gate_data[k][18]) setElementDimension(col, gate_data[k][18]) -- Add event handlers addEventHandler("onColShapeHit", col, open_gate ) addEventHandler("onColShapeLeave", col, close_gate ) end end addEventHandler("onResourceStart", resourceRoot, load_gates) -- Gates open function open_gate(plr, matching_dimension) if not matching_dimension then return end local ID = cols[source] local px,py,pz = getElementPosition(plr) if plr and isElement(plr) and getElementType(plr) == "player" and ( getElementData(plr, "Group") == gate_data[ID][15] or getPlayerTeam(plr) == getTeamFromName(gate_data[ID][15]) or getPlayerTeam(plr) == getTeamFromName("Staff")) and pz + 5 > gate_data[ID][4] and pz - 5 < gate_data[ID][4] then -- Open the gate moveObject(gates[source], openSpeed, gate_data[ID][5], gate_data[ID][6], gate_data[ID][7] ) end end -- Gates close function close_gate(elem, matching_dimension) if not matching_dimension then return end local ID = cols[source] local elem_count = #getElementsWithinColShape(source, "player") elem_count = elem_count + #getElementsWithinColShape(source, "vehicle") if elem and isElement(elem) and elem_count == 0 then moveObject(gates[source], openSpeed, gate_data[ID][2], gate_data[ID][3], gate_data[ID][4]) end end addCommandHandler("gtwinfo", function(plr, cmd) outputChatBox("[GTW-RPG] "..getResourceName( getThisResource())..", by: "..getResourceInfo( getThisResource(), "author")..", v-"..getResourceInfo( getThisResource(), "version")..", is represented", plr) end)
[Patch] Fixed gates that didn't close
[Patch] Fixed gates that didn't close When passing a gate with a vehicle the gate didn't closed as it failed to count elements in it's col shape.
Lua
bsd-2-clause
404rq/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG
4ab1abf90c29be79410ea5dfd5b21a6a71f483ea
modules/admin-full/luasrc/model/cbi/admin_system/ipkg.lua
modules/admin-full/luasrc/model/cbi/admin_system/ipkg.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> 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 ipkgfile = "/etc/opkg.conf" f = SimpleForm("ipkgconf", translate("a_s_p_ipkg")) t = f:field(TextValue, "lines") t.rows = 10 function t.cfgvalue() return luci.fs.readfile(ipkgfile) or "" end f:append(Template("admin_system/ipkg")) function f.handle(self, state, data) if state == FORM_VALID then if (luci.fs.readfile(ipkgfile) or "") ~= data.lines then luci.fs.writefile(ipkgfile, data.lines) end end return true end return f
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> 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 ipkgfile = "/etc/opkg.conf" f = SimpleForm("ipkgconf", translate("a_s_p_ipkg")) t = f:field(TextValue, "lines") t.rows = 10 function t.cfgvalue() return luci.fs.readfile(ipkgfile) or "" end function t.write(self, section, data) return luci.fs.writefile(ipkgfile, data) end f:append(Template("admin_system/ipkg")) function f.handle(self, state, data) return true end return f
Fix saving of ipkg configuration file
Fix saving of ipkg configuration file git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4042 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
8879c55bb39b31a03de5d798a436d73b30a011d6
applications/luci-vnstat/luasrc/model/cbi/vnstat.lua
applications/luci-vnstat/luasrc/model/cbi/vnstat.lua
--[[ LuCI - Lua Configuration Interface Copyright 2010-2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local utl = require "luci.util" local sys = require "luci.sys" local fs = require "nixio.fs" local nw = require "luci.model.network" local dbdir, line for line in io.lines("/etc/vnstat.conf") do dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']") if dbdir then break end end dbdir = dbdir or "/var/lib/vnstat" m = Map("vnstat", translate("VnStat"), translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s).")) m.submit = translate("Restart VnStat") m.reset = false nw.init(luci.model.uci.cursor_state()) local ifaces = { } local enabled = { } local iface for iface in fs.dir(dbdir) do if iface:sub(1,1) ~= '.' then ifaces[iface] = iface enabled[iface] = iface 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" 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
--[[ LuCI - Lua Configuration Interface Copyright 2010-2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local utl = require "luci.util" local sys = require "luci.sys" local fs = require "nixio.fs" local nw = require "luci.model.network" local dbdir, line for line in io.lines("/etc/vnstat.conf") do dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']") if dbdir then break end end dbdir = dbdir or "/var/lib/vnstat" m = Map("vnstat", translate("VnStat"), translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s).")) m.submit = translate("Restart VnStat") m.reset = false nw.init(luci.model.uci.cursor_state()) local ifaces = { } local enabled = { } local iface if fs.access(dbdir) then for iface in fs.dir(dbdir) do if iface:sub(1,1) ~= '.' then ifaces[iface] = iface enabled[iface] = iface end end end for _, iface in ipairs(sys.net.devices()) do ifaces[iface] = iface end local s = m:section(TypedSection, "vnstat") s.anonymous = true s.addremove = false mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces")) mon_ifaces.template = "cbi/network_ifacelist" mon_ifaces.widget = "checkbox" mon_ifaces.cast = "table" 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
applications/luci-vnstat: fix crash if dbdir is defined but not existing yet
applications/luci-vnstat: fix crash if dbdir is defined but not existing yet
Lua
apache-2.0
LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,981213/luci-1,daofeng2015/luci,RedSnake64/openwrt-luci-packages,obsy/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,wongsyrone/luci-1,schidler/ionic-luci,bittorf/luci,nmav/luci,MinFu/luci,cshore-firmware/openwrt-luci,slayerrensky/luci,palmettos/test,david-xiao/luci,Hostle/luci,hnyman/luci,maxrio/luci981213,florian-shellfire/luci,tobiaswaldvogel/luci,Wedmer/luci,zhaoxx063/luci,nmav/luci,joaofvieira/luci,oneru/luci,tobiaswaldvogel/luci,dismantl/luci-0.12,slayerrensky/luci,ff94315/luci-1,kuoruan/luci,florian-shellfire/luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,nmav/luci,LuttyYang/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,taiha/luci,bright-things/ionic-luci,Kyklas/luci-proto-hso,fkooman/luci,nmav/luci,male-puppies/luci,jlopenwrtluci/luci,ollie27/openwrt_luci,wongsyrone/luci-1,openwrt/luci,keyidadi/luci,chris5560/openwrt-luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,daofeng2015/luci,rogerpueyo/luci,lcf258/openwrtcn,Wedmer/luci,opentechinstitute/luci,lbthomsen/openwrt-luci,keyidadi/luci,mumuqz/luci,david-xiao/luci,opentechinstitute/luci,nmav/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,nwf/openwrt-luci,jchuang1977/luci-1,ollie27/openwrt_luci,shangjiyu/luci-with-extra,jorgifumi/luci,jlopenwrtluci/luci,florian-shellfire/luci,david-xiao/luci,Wedmer/luci,sujeet14108/luci,urueedi/luci,RedSnake64/openwrt-luci-packages,Noltari/luci,deepak78/new-luci,oneru/luci,deepak78/new-luci,bright-things/ionic-luci,Sakura-Winkey/LuCI,taiha/luci,deepak78/new-luci,male-puppies/luci,ff94315/luci-1,nwf/openwrt-luci,bittorf/luci,openwrt-es/openwrt-luci,sujeet14108/luci,keyidadi/luci,mumuqz/luci,LuttyYang/luci,oneru/luci,LuttyYang/luci,NeoRaider/luci,openwrt-es/openwrt-luci,sujeet14108/luci,nwf/openwrt-luci,RedSnake64/openwrt-luci-packages,artynet/luci,artynet/luci,kuoruan/luci,tcatm/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,zhaoxx063/luci,fkooman/luci,maxrio/luci981213,lcf258/openwrtcn,jorgifumi/luci,thesabbir/luci,cappiewu/luci,tobiaswaldvogel/luci,urueedi/luci,lcf258/openwrtcn,ff94315/luci-1,jchuang1977/luci-1,openwrt-es/openwrt-luci,marcel-sch/luci,hnyman/luci,bittorf/luci,deepak78/new-luci,Kyklas/luci-proto-hso,NeoRaider/luci,rogerpueyo/luci,remakeelectric/luci,taiha/luci,Sakura-Winkey/LuCI,florian-shellfire/luci,urueedi/luci,Hostle/openwrt-luci-multi-user,oyido/luci,artynet/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,nmav/luci,jorgifumi/luci,artynet/luci,Sakura-Winkey/LuCI,981213/luci-1,forward619/luci,obsy/luci,palmettos/test,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,ollie27/openwrt_luci,cappiewu/luci,ollie27/openwrt_luci,Kyklas/luci-proto-hso,urueedi/luci,palmettos/cnLuCI,maxrio/luci981213,aa65535/luci,taiha/luci,cappiewu/luci,cappiewu/luci,jorgifumi/luci,fkooman/luci,ollie27/openwrt_luci,thess/OpenWrt-luci,openwrt/luci,slayerrensky/luci,openwrt/luci,Hostle/luci,nmav/luci,tcatm/luci,wongsyrone/luci-1,thesabbir/luci,cshore/luci,RuiChen1113/luci,male-puppies/luci,Hostle/luci,zhaoxx063/luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,NeoRaider/luci,Hostle/luci,MinFu/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,chris5560/openwrt-luci,chris5560/openwrt-luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,zhaoxx063/luci,kuoruan/lede-luci,daofeng2015/luci,RuiChen1113/luci,obsy/luci,fkooman/luci,forward619/luci,sujeet14108/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,chris5560/openwrt-luci,fkooman/luci,deepak78/new-luci,MinFu/luci,taiha/luci,db260179/openwrt-bpi-r1-luci,aa65535/luci,opentechinstitute/luci,slayerrensky/luci,nwf/openwrt-luci,opentechinstitute/luci,taiha/luci,sujeet14108/luci,palmettos/cnLuCI,keyidadi/luci,Noltari/luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,fkooman/luci,teslamint/luci,dismantl/luci-0.12,hnyman/luci,teslamint/luci,joaofvieira/luci,palmettos/test,schidler/ionic-luci,thess/OpenWrt-luci,Wedmer/luci,Noltari/luci,remakeelectric/luci,shangjiyu/luci-with-extra,maxrio/luci981213,shangjiyu/luci-with-extra,deepak78/new-luci,fkooman/luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,wongsyrone/luci-1,thess/OpenWrt-luci,bittorf/luci,thess/OpenWrt-luci,cappiewu/luci,wongsyrone/luci-1,cshore/luci,Wedmer/luci,harveyhu2012/luci,nmav/luci,kuoruan/luci,nwf/openwrt-luci,harveyhu2012/luci,RuiChen1113/luci,rogerpueyo/luci,aa65535/luci,urueedi/luci,marcel-sch/luci,kuoruan/lede-luci,aa65535/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,Hostle/luci,fkooman/luci,marcel-sch/luci,RuiChen1113/luci,ff94315/luci-1,bittorf/luci,jlopenwrtluci/luci,teslamint/luci,thesabbir/luci,male-puppies/luci,harveyhu2012/luci,maxrio/luci981213,forward619/luci,obsy/luci,rogerpueyo/luci,NeoRaider/luci,bright-things/ionic-luci,Hostle/openwrt-luci-multi-user,oneru/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,teslamint/luci,marcel-sch/luci,lbthomsen/openwrt-luci,artynet/luci,ollie27/openwrt_luci,RuiChen1113/luci,oneru/luci,bright-things/ionic-luci,taiha/luci,forward619/luci,openwrt/luci,daofeng2015/luci,marcel-sch/luci,marcel-sch/luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,kuoruan/luci,lbthomsen/openwrt-luci,daofeng2015/luci,Kyklas/luci-proto-hso,palmettos/test,oneru/luci,cappiewu/luci,cappiewu/luci,palmettos/cnLuCI,aa65535/luci,kuoruan/lede-luci,florian-shellfire/luci,jlopenwrtluci/luci,slayerrensky/luci,keyidadi/luci,chris5560/openwrt-luci,rogerpueyo/luci,thess/OpenWrt-luci,daofeng2015/luci,hnyman/luci,bittorf/luci,oneru/luci,RedSnake64/openwrt-luci-packages,dwmw2/luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,LuttyYang/luci,palmettos/test,slayerrensky/luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,thess/OpenWrt-luci,kuoruan/lede-luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,oyido/luci,MinFu/luci,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,bittorf/luci,dismantl/luci-0.12,cshore/luci,dismantl/luci-0.12,joaofvieira/luci,thesabbir/luci,david-xiao/luci,david-xiao/luci,joaofvieira/luci,RuiChen1113/luci,cshore/luci,zhaoxx063/luci,lbthomsen/openwrt-luci,male-puppies/luci,nmav/luci,Hostle/luci,dismantl/luci-0.12,Wedmer/luci,schidler/ionic-luci,opentechinstitute/luci,male-puppies/luci,oneru/luci,urueedi/luci,keyidadi/luci,openwrt-es/openwrt-luci,MinFu/luci,cshore/luci,nwf/openwrt-luci,taiha/luci,sujeet14108/luci,openwrt/luci,kuoruan/lede-luci,rogerpueyo/luci,bright-things/ionic-luci,remakeelectric/luci,thesabbir/luci,bright-things/ionic-luci,openwrt/luci,harveyhu2012/luci,obsy/luci,lcf258/openwrtcn,dwmw2/luci,teslamint/luci,lcf258/openwrtcn,oyido/luci,thess/OpenWrt-luci,sujeet14108/luci,RuiChen1113/luci,981213/luci-1,aircross/OpenWrt-Firefly-LuCI,oyido/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,thesabbir/luci,joaofvieira/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,remakeelectric/luci,lbthomsen/openwrt-luci,hnyman/luci,cshore/luci,kuoruan/lede-luci,zhaoxx063/luci,harveyhu2012/luci,LuttyYang/luci,aa65535/luci,dismantl/luci-0.12,tcatm/luci,LuttyYang/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,cshore/luci,oyido/luci,jlopenwrtluci/luci,Noltari/luci,shangjiyu/luci-with-extra,lcf258/openwrtcn,tobiaswaldvogel/luci,RedSnake64/openwrt-luci-packages,palmettos/test,openwrt/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,RuiChen1113/luci,oyido/luci,keyidadi/luci,oyido/luci,dwmw2/luci,Kyklas/luci-proto-hso,Hostle/openwrt-luci-multi-user,slayerrensky/luci,jchuang1977/luci-1,david-xiao/luci,nwf/openwrt-luci,ollie27/openwrt_luci,jchuang1977/luci-1,remakeelectric/luci,tobiaswaldvogel/luci,florian-shellfire/luci,mumuqz/luci,schidler/ionic-luci,keyidadi/luci,981213/luci-1,lcf258/openwrtcn,NeoRaider/luci,Kyklas/luci-proto-hso,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,hnyman/luci,harveyhu2012/luci,forward619/luci,aircross/OpenWrt-Firefly-LuCI,cshore-firmware/openwrt-luci,teslamint/luci,Noltari/luci,schidler/ionic-luci,marcel-sch/luci,mumuqz/luci,schidler/ionic-luci,Hostle/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,NeoRaider/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,male-puppies/luci,bright-things/ionic-luci,joaofvieira/luci,dismantl/luci-0.12,cshore-firmware/openwrt-luci,opentechinstitute/luci,Noltari/luci,LuttyYang/luci,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,maxrio/luci981213,981213/luci-1,mumuqz/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,teslamint/luci,MinFu/luci,tobiaswaldvogel/luci,urueedi/luci,forward619/luci,jchuang1977/luci-1,florian-shellfire/luci,cappiewu/luci,thess/OpenWrt-luci,dwmw2/luci,Noltari/luci,ff94315/luci-1,Wedmer/luci,artynet/luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,MinFu/luci,thesabbir/luci,kuoruan/luci,openwrt-es/openwrt-luci,openwrt/luci,ReclaimYourPrivacy/cloak-luci,981213/luci-1,sujeet14108/luci,remakeelectric/luci,obsy/luci,slayerrensky/luci,ff94315/luci-1,jlopenwrtluci/luci,artynet/luci,deepak78/new-luci,bittorf/luci,palmettos/cnLuCI,wongsyrone/luci-1,hnyman/luci,kuoruan/luci,aircross/OpenWrt-Firefly-LuCI,RedSnake64/openwrt-luci-packages,jorgifumi/luci,kuoruan/luci,aa65535/luci,mumuqz/luci,dwmw2/luci,palmettos/test,palmettos/cnLuCI,obsy/luci,ff94315/luci-1,chris5560/openwrt-luci,rogerpueyo/luci,forward619/luci,Sakura-Winkey/LuCI,Noltari/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,opentechinstitute/luci,ff94315/luci-1,schidler/ionic-luci,Hostle/luci,Wedmer/luci,palmettos/cnLuCI,NeoRaider/luci,ollie27/openwrt_luci,florian-shellfire/luci,dwmw2/luci,remakeelectric/luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,artynet/luci,tcatm/luci,remakeelectric/luci,palmettos/test,obsy/luci,jorgifumi/luci,tcatm/luci,maxrio/luci981213,mumuqz/luci,deepak78/new-luci,chris5560/openwrt-luci,urueedi/luci,lbthomsen/openwrt-luci,hnyman/luci,981213/luci-1,dwmw2/luci,artynet/luci,shangjiyu/luci-with-extra,wongsyrone/luci-1,teslamint/luci,cshore/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,oyido/luci,maxrio/luci981213,harveyhu2012/luci,marcel-sch/luci,palmettos/cnLuCI
41c66871d41fe159fe9ab7937d9bc74e4384731e
MMOCoreORB/bin/scripts/mobile/lok/serverobjects.lua
MMOCoreORB/bin/scripts/mobile/lok/serverobjects.lua
includeFile("lok/blood_razor_berzerker.lua") includeFile("lok/blood_razor_captain.lua") includeFile("lok/blood_razor_cutthroat.lua") includeFile("lok/blood_razor_destroyer.lua") includeFile("lok/blood_razor_elite_pirate.lua") includeFile("lok/blood_razor_guard.lua") includeFile("lok/blood_razor_officer.lua") includeFile("lok/blood_razor_scout.lua") includeFile("lok/blood_razor_strong_pirate.lua") includeFile("lok/blood_razor_weak_pirate.lua") includeFile("lok/canyon_corsair_captain.lua") includeFile("lok/canyon_corsair_cutthroat.lua") includeFile("lok/canyon_corsair_destroyer.lua") includeFile("lok/canyon_corsair_elite_pirate.lua") includeFile("lok/canyon_corsair_guard.lua") includeFile("lok/canyon_corsair_scout.lua") includeFile("lok/canyon_corsair_strong_pirate.lua") includeFile("lok/canyon_corsair_weak_pirate.lua") includeFile("lok/cas_vankoo.lua") includeFile("lok/crazed_gurk_destroyer.lua") includeFile("lok/deadly_vesp.lua") includeFile("lok/demolishing_snorbal_titan.lua") includeFile("lok/desert_vesp.lua") includeFile("lok/domesticated_gurnaset.lua") includeFile("lok/domesticated_snorbal.lua") includeFile("lok/droideka.lua") includeFile("lok/dune_kimogila.lua") includeFile("lok/elder_snorbal_female.lua") includeFile("lok/elder_snorbal_male.lua") includeFile("lok/elite_canyon_corsair.lua") includeFile("lok/enraged_dune_kimogila.lua") includeFile("lok/enraged_kimogila.lua") includeFile("lok/female_langlatch.lua") includeFile("lok/female_snorbal_calf.lua") includeFile("lok/feral_gurk.lua") includeFile("lok/ferocious_kusak.lua") includeFile("lok/flit_bloodsucker.lua") includeFile("lok/flit_harasser.lua") includeFile("lok/flit.lua") includeFile("lok/flit_youth.lua") includeFile("lok/giant_dune_kimogila.lua") includeFile("lok/giant_flit.lua") includeFile("lok/giant_kimogila.lua") includeFile("lok/giant_pharple.lua") includeFile("lok/giant_spined_snake.lua") includeFile("lok/gorge_vesp.lua") includeFile("lok/gurk_gatherer.lua") includeFile("lok/gurk.lua") includeFile("lok/gurk_tracker.lua") includeFile("lok/gurk_whelp.lua") includeFile("lok/gurnaset_be.lua") includeFile("lok/gurnaset_hatchling.lua") includeFile("lok/gurnaset.lua") includeFile("lok/imperial_deserter.lua") includeFile("lok/jinkins.lua") includeFile("lok/juvenile_langlatch.lua") includeFile("lok/kimogila_be.lua") includeFile("lok/kimogila_hatchling.lua") includeFile("lok/kimogila.lua") includeFile("lok/kole.lua") includeFile("lok/kusak_be.lua") includeFile("lok/kusak_hunter.lua") includeFile("lok/kusak.lua") includeFile("lok/kusak_mauler.lua") includeFile("lok/kusak_pup.lua") includeFile("lok/kusak_stalker.lua") includeFile("lok/langlatch_be.lua") includeFile("lok/langlatch_destroyer.lua") includeFile("lok/langlatch_hatchling.lua") includeFile("lok/langlatch_hunter.lua") includeFile("lok/langlatch_marauder.lua") includeFile("lok/lethargic_behemoth.lua") includeFile("lok/loathsome_mangler.lua") includeFile("lok/lowland_salt_mynock.lua") includeFile("lok/male_langlatch.lua") includeFile("lok/male_snorbal_calf.lua") includeFile("lok/marooned_pirate_captain.lua") includeFile("lok/marooned_pirate_engineer.lua") includeFile("lok/marooned_pirate_first_mate.lua") includeFile("lok/marooned_pirate.lua") includeFile("lok/mature_snorbal_female.lua") includeFile("lok/mature_snorbal_male.lua") includeFile("lok/mercenary_commander.lua") includeFile("lok/mercenary_destroyer.lua") includeFile("lok/mercenary_elite.lua") includeFile("lok/mercenary_messenger.lua") includeFile("lok/mercenary_warlord.lua") includeFile("lok/mercenary_weak.lua") includeFile("lok/mountain_vesp_medium.lua") includeFile("lok/nien_nunb.lua") includeFile("lok/nym_guard_elite.lua") includeFile("lok/nym_guard_strong.lua") includeFile("lok/nym_guard_weak.lua") includeFile("lok/nym.lua") includeFile("lok/nym_bodyguard.lua") includeFile("lok/nym_brawler.lua") includeFile("lok/nym_destroyer.lua") --includeFile("lok/nym_domesticated_gurk.lua") --includeFile("lok/nym_droideka.lua") includeFile("lok/nym_patrol_elite.lua") includeFile("lok/nym_pirate_elite.lua") includeFile("lok/nym_kusak_guardian.lua") includeFile("lok/nym_patrol_strong.lua") includeFile("lok/nym_patrol_weak.lua") includeFile("lok/nym_pirate_strong.lua") includeFile("lok/nym_pirate_weak.lua") includeFile("lok/nym_surveyor.lua") includeFile("lok/perlek.lua") includeFile("lok/perlek_ravager.lua") includeFile("lok/perlek_scavenger.lua") includeFile("lok/pharple.lua") includeFile("lok/reclusive_gurk_king.lua") includeFile("lok/riverside_sulfur_mynok.lua") includeFile("lok/runty_pharple.lua") includeFile("lok/salt_mynock.lua") includeFile("lok/sandy_spined_snake.lua") includeFile("lok/shaggy_gurk_youth.lua") includeFile("lok/sharptooth_langlatch.lua") includeFile("lok/snorbal_be.lua") includeFile("lok/snorbal.lua") includeFile("lok/snorbal_matriarch.lua") includeFile("lok/spined_snake.lua") includeFile("lok/spined_snake_recluse.lua") includeFile("lok/strong_mercenary.lua") includeFile("lok/sulfer_pool_mynock.lua") includeFile("lok/sulfur_lake_pirate.lua") includeFile("lok/weak_mercenary.lua") includeFile("lok/rifea_eicik.lua") includeFile("lok/rorha_wahe.lua") includeFile("lok/reggi_tirver.lua") includeFile("lok/vixur_webb.lua") includeFile("lok/ifoja_lico.lua") includeFile("lok/evathm.lua") includeFile("lok/bapibac.lua") includeFile("lok/lok_herald_01.lua") includeFile("lok/lok_herald_02.lua") includeFile("lok/melo.lua") includeFile("lok/idhak_ipath.lua")
includeFile("lok/blood_razor_berzerker.lua") includeFile("lok/blood_razor_captain.lua") includeFile("lok/blood_razor_cutthroat.lua") includeFile("lok/blood_razor_destroyer.lua") includeFile("lok/blood_razor_elite_pirate.lua") includeFile("lok/blood_razor_guard.lua") includeFile("lok/blood_razor_officer.lua") includeFile("lok/blood_razor_scout.lua") includeFile("lok/blood_razor_strong_pirate.lua") includeFile("lok/blood_razor_weak_pirate.lua") includeFile("lok/canyon_corsair_captain.lua") includeFile("lok/canyon_corsair_cutthroat.lua") includeFile("lok/canyon_corsair_destroyer.lua") includeFile("lok/canyon_corsair_elite_pirate.lua") includeFile("lok/canyon_corsair_guard.lua") includeFile("lok/canyon_corsair_scout.lua") includeFile("lok/canyon_corsair_strong_pirate.lua") includeFile("lok/canyon_corsair_weak_pirate.lua") includeFile("lok/cas_vankoo.lua") includeFile("lok/crazed_gurk_destroyer.lua") includeFile("lok/deadly_vesp.lua") includeFile("lok/demolishing_snorbal_titan.lua") includeFile("lok/desert_vesp.lua") includeFile("lok/domesticated_gurnaset.lua") includeFile("lok/domesticated_snorbal.lua") includeFile("lok/droideka.lua") includeFile("lok/dune_kimogila.lua") includeFile("lok/elder_snorbal_female.lua") includeFile("lok/elder_snorbal_male.lua") includeFile("lok/elite_canyon_corsair.lua") includeFile("lok/enraged_dune_kimogila.lua") includeFile("lok/enraged_kimogila.lua") includeFile("lok/female_langlatch.lua") includeFile("lok/female_snorbal_calf.lua") includeFile("lok/feral_gurk.lua") includeFile("lok/ferocious_kusak.lua") includeFile("lok/flit_bloodsucker.lua") includeFile("lok/flit_harasser.lua") includeFile("lok/flit.lua") includeFile("lok/flit_youth.lua") includeFile("lok/giant_dune_kimogila.lua") includeFile("lok/giant_flit.lua") includeFile("lok/giant_kimogila.lua") includeFile("lok/giant_pharple.lua") includeFile("lok/giant_spined_snake.lua") includeFile("lok/gorge_vesp.lua") includeFile("lok/gurk_gatherer.lua") includeFile("lok/gurk.lua") includeFile("lok/gurk_tracker.lua") includeFile("lok/gurk_whelp.lua") includeFile("lok/gurnaset_be.lua") includeFile("lok/gurnaset_hatchling.lua") includeFile("lok/gurnaset.lua") includeFile("lok/imperial_deserter.lua") includeFile("lok/jinkins.lua") includeFile("lok/juvenile_langlatch.lua") includeFile("lok/kimogila_be.lua") includeFile("lok/kimogila_hatchling.lua") includeFile("lok/kimogila.lua") includeFile("lok/kole.lua") includeFile("lok/kusak_be.lua") includeFile("lok/kusak_hunter.lua") includeFile("lok/kusak.lua") includeFile("lok/kusak_mauler.lua") includeFile("lok/kusak_pup.lua") includeFile("lok/kusak_stalker.lua") includeFile("lok/langlatch_be.lua") includeFile("lok/langlatch_destroyer.lua") includeFile("lok/langlatch_hatchling.lua") includeFile("lok/langlatch_hunter.lua") includeFile("lok/langlatch_marauder.lua") includeFile("lok/lethargic_behemoth.lua") includeFile("lok/loathsome_mangler.lua") includeFile("lok/lowland_salt_mynock.lua") includeFile("lok/male_langlatch.lua") includeFile("lok/male_snorbal_calf.lua") includeFile("lok/marooned_pirate_captain.lua") includeFile("lok/marooned_pirate_engineer.lua") includeFile("lok/marooned_pirate_first_mate.lua") includeFile("lok/marooned_pirate.lua") includeFile("lok/mature_snorbal_female.lua") includeFile("lok/mature_snorbal_male.lua") includeFile("lok/mercenary_commander.lua") includeFile("lok/mercenary_destroyer.lua") includeFile("lok/mercenary_elite.lua") includeFile("lok/mercenary_messenger.lua") includeFile("lok/mercenary_warlord.lua") includeFile("lok/mercenary_weak.lua") includeFile("lok/mountain_vesp_medium.lua") includeFile("lok/nien_nunb.lua") includeFile("lok/nym_guard_elite.lua") includeFile("lok/nym_guard_strong.lua") includeFile("lok/nym_guard_weak.lua") includeFile("lok/nym.lua") includeFile("lok/nym_bodyguard.lua") includeFile("lok/nym_brawler.lua") includeFile("lok/nym_destroyer.lua") --includeFile("lok/nym_domesticated_gurk.lua") --includeFile("lok/nym_droideka.lua") includeFile("lok/nym_patrol_elite.lua") includeFile("lok/nym_pirate_elite.lua") includeFile("lok/nym_kusak_guardian.lua") includeFile("lok/nym_patrol_strong.lua") includeFile("lok/nym_patrol_weak.lua") includeFile("lok/nym_pirate_strong.lua") includeFile("lok/nym_pirate_weak.lua") includeFile("lok/nym_surveyor.lua") includeFile("lok/perlek.lua") includeFile("lok/perlek_ravager.lua") includeFile("lok/perlek_scavenger.lua") includeFile("lok/pharple.lua") includeFile("lok/reclusive_gurk_king.lua") includeFile("lok/riverside_sulfur_mynok.lua") includeFile("lok/runty_pharple.lua") includeFile("lok/salt_mynock.lua") includeFile("lok/sandy_spined_snake.lua") includeFile("lok/shaggy_gurk_youth.lua") includeFile("lok/sharptooth_langlatch.lua") includeFile("lok/snorbal_be.lua") includeFile("lok/snorbal.lua") includeFile("lok/snorbal_matriarch.lua") includeFile("lok/spined_snake.lua") includeFile("lok/spined_snake_recluse.lua") includeFile("lok/strong_mercenary.lua") includeFile("lok/sulfer_pool_mynock.lua") includeFile("lok/sulfur_lake_pirate.lua") includeFile("lok/weak_mercenary.lua") includeFile("lok/rifea_eicik.lua") includeFile("lok/rorha_wahe.lua") includeFile("lok/reggi_tirver.lua") includeFile("lok/vixur_webb.lua") includeFile("lok/ifoja_lico.lua") includeFile("lok/evathm.lua") includeFile("lok/bapibac.lua") includeFile("lok/lok_herald_01.lua") includeFile("lok/lok_herald_02.lua") includeFile("lok/melo.lua") includeFile("lok/idhak_ipath.lua") includeFIle("lok/ciwi_mosregri.lua")
[fixed] mobile error
[fixed] mobile error git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4940 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
68b17adefbbc9e2fc0f58fdbad426cf32c188042
kong/plugins/liamp/aws-serializer.lua
kong/plugins/liamp/aws-serializer.lua
-- serializer to wrap the current request into the Amazon API gateway -- format as described here: -- https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format local public_utils = require "kong.tools.public" local EMPTY = {} local ngx_req_get_headers = ngx.req.get_headers local ngx_req_get_uri_args = ngx.req.get_uri_args local ngx_encode_base64 = ngx.encode_base64 local ngx_req_read_body = ngx.req.read_body return function(ctx) ctx = ctx or ngx.ctx local var = ngx.var -- prepare headers local headers = ngx_req_get_headers() local multiValueHeaders = {} for hname, hvalue in pairs(headers) do if type(hvalue) == "table" then -- multi value multiValueHeaders[hname] = hvalue headers[hname] = hvalue[1] else -- single value multiValueHeaders[hname] = { hvalue } end end -- prepare url-captures/path-parameters local pathParameters = {} for name, value in pairs(ctx.router_matches.uri_captures or EMPTY) do if type(name) == "string" then -- skip numerical indices, only named pathParameters[name] = value end end -- query parameters local queryStringParameters = ngx_req_get_uri_args() local multiValueQueryStringParameters = {} for qname, qvalue in pairs(queryStringParameters) do if type(qvalue) == "table" then -- multi value multiValueQueryStringParameters[qname] = qvalue queryStringParameters[qname] = qvalue[1] else -- single value multiValueQueryStringParameters[qname] = { qvalue } end end -- prepare body local isBase64Encoded = false local body do ngx_req_read_body() local _, err_code _, err_code, body = public_utils.get_body_info() if err_code == public_utils.req_body_errors.unknown_ct then -- don't know what this body MIME type is, base64 it just in case body = ngx_encode_base64(body) isBase64Encoded = true end end -- prepare path local path = var.request_uri:match("^([^%?]+)") -- strip any query args local request = { resource = ctx.router_matches.uri, path = path, httpMethod = var.request_method, headers = headers, multiValueHeaders = multiValueHeaders, pathParameters = pathParameters, queryStringParameters = queryStringParameters, multiValueQueryStringParameters = multiValueQueryStringParameters, body = body, isBase64Encoded = isBase64Encoded, } --print(require("pl.pretty").write(request)) --print(require("pl.pretty").write(ctx.router_matches)) return request end
-- serializer to wrap the current request into the Amazon API gateway -- format as described here: -- https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format local EMPTY = {} local ngx_req_get_headers = ngx.req.get_headers local ngx_req_get_uri_args = ngx.req.get_uri_args local ngx_encode_base64 = ngx.encode_base64 local ngx_req_read_body = ngx.req.read_body local ngx_req_get_body_data= ngx.req.get_body_data local ngx_req_get_body_file= ngx.req.get_body_file local ngx_log = ngx.log local ERR = ngx.ERR return function(ctx) ctx = ctx or ngx.ctx local var = ngx.var -- prepare headers local headers = ngx_req_get_headers() local multiValueHeaders = {} for hname, hvalue in pairs(headers) do if type(hvalue) == "table" then -- multi value multiValueHeaders[hname] = hvalue headers[hname] = hvalue[1] else -- single value multiValueHeaders[hname] = { hvalue } end end -- prepare url-captures/path-parameters local pathParameters = {} for name, value in pairs(ctx.router_matches.uri_captures or EMPTY) do if type(name) == "string" then -- skip numerical indices, only named pathParameters[name] = value end end -- query parameters local queryStringParameters = ngx_req_get_uri_args() local multiValueQueryStringParameters = {} for qname, qvalue in pairs(queryStringParameters) do if type(qvalue) == "table" then -- multi value multiValueQueryStringParameters[qname] = qvalue queryStringParameters[qname] = qvalue[1] else -- single value multiValueQueryStringParameters[qname] = { qvalue } end end -- prepare body local body, isBase64Encoded do ngx_req_read_body() body = ngx_req_get_body_data() if not body then if ngx_req_get_body_file() then ngx_log(ERR, "request body was buffered to disk, too large") end else if body ~= "" then body = ngx_encode_base64(body) isBase64Encoded = true else isBase64Encoded = false end end end -- prepare path local path = var.request_uri:match("^([^%?]+)") -- strip any query args local request = { resource = ctx.router_matches.uri, path = path, httpMethod = var.request_method, headers = headers, multiValueHeaders = multiValueHeaders, pathParameters = pathParameters, queryStringParameters = queryStringParameters, multiValueQueryStringParameters = multiValueQueryStringParameters, body = body, isBase64Encoded = isBase64Encoded, } --print(require("pl.pretty").write(request)) --print(require("pl.pretty").write(ctx.router_matches)) return request end
fix(aws-lambda) always send bodies at base64 encoded
fix(aws-lambda) always send bodies at base64 encoded Stop parsing body content, just pass them on.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong