repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
allwenandashi/ASHI
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
dmccuskey/lua-bytearray
dmc_lua/lua_bytearray.lua
40
9054
--====================================================================-- -- dmc_lua/bytearray.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014- 2015 David McCuskey 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. --]] --====================================================================-- --== DMC Lua Library: Lua Byte Array --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.4.0" --====================================================================-- --== Imports local Error = require 'lua_bytearray.exceptions' local Class = require 'lua_class' local has_pack, PackByteArray = pcall( require, 'lua_bytearray.pack_bytearray' ) --====================================================================-- --== Setup, Constants local ObjectBase = Class.ObjectBase local assert = assert local iwrite = io.write local mceil = math.ceil local sbyte = string.byte local schar = string.char local sfind = string.find local sformat = string.format local ssub = string.sub local tinsert = table.insert local type = type local Parents = { Class.Class } if has_pack then tinsert( Parents, PackByteArray ) end --====================================================================-- --== Support Functions local Utils = {} -- hexDump() -- pretty-print data in hex table -- function Utils.hexDump( buf ) for i=1,mceil(#buf/16) * 16 do if (i-1) % 16 == 0 then iwrite(sformat('%08X ', i-1)) end iwrite( i > #buf and ' ' or sformat('%02X ', buf:byte(i)) ) if i % 8 == 0 then iwrite(' ') end if i % 16 == 0 then iwrite( buf:sub(i-16+1, i):gsub('%c','.'), '\n' ) end end end --====================================================================-- --== Byte Array Class --====================================================================-- local ByteArray = newClass( Parents, { name="Byte Array" } ) --======================================================-- -- Start: Setup Lua Objects function ByteArray:__new__( params ) -- print( "ByteArray:__new__" ) params = params or {} self:superCall( '__new__', params ) --==-- self._endian = params.endian self._buf = "" -- buffer is string of bytes self._pos = 1 -- current position for reading end -- END: Setup Lua Objects --======================================================-- --====================================================================-- --== Static Methods function ByteArray.getBytes( buffer, index, length ) -- print( "ByteArray:getBytes", buffer, index, length ) assert( type(buffer)=='string', "buffer must be string" ) --==-- local idx_end index = index or 1 assert( index>=1 and index<=#buffer+1, "index out of range" ) assert( type(index)=='number', "start index must be a number" ) if length~=nil then idx_end = index + length - 1 end return ssub( buffer, index, idx_end ) end function ByteArray.putBytes( buffer, bytes, index ) -- print( "ByteArray:putBytes", buffer, bytes, #bytes, index ) assert( type(buffer)=='string', "buffer must be string" ) assert( type(bytes)=='string', "bytes must be string" ) --==-- if not index then return buffer .. bytes end assert( type(index)=='number', "index must be a number" ) assert( index>=1 and index<=#buffer+1, "index out of range" ) local buf_len, byte_len = #buffer, #bytes local result, buf_start, buf_end if index == 1 and byte_len >= buf_len then result = bytes elseif index == 1 and byte_len < buf_len then buf_end = ssub( buffer, byte_len+1 ) result = bytes .. buf_end elseif index <= buf_len and buf_len < (index + byte_len) then buf_start = ssub( buffer, 1, index-1 ) result = buf_start .. bytes else buf_start = ssub( buffer, 1, index-1 ) buf_end = ssub( buffer, index+byte_len ) result = buf_start .. bytes .. buf_end end return result end --====================================================================-- --== Public Methods function ByteArray.__getters:endian() return self._endian end function ByteArray.__setters:endian( value ) self._endian = value end function ByteArray.__getters:length() return #self._buf end function ByteArray.__getters:bytesAvailable() return #self._buf - (self._pos-1) end function ByteArray.__getters:position() return self._pos end function ByteArray.__setters:position( pos ) assert( type(pos)=='number', "position value must be integer" ) assert( pos >= 1 and pos <= self.length + 1 ) --==-- self._pos = pos return self end function ByteArray:toHex() Utils.hexDump( self._buf ) end function ByteArray:toString() return self._buf end function ByteArray:search( str ) assert( type(str)=='string', "search value must be string" ) --==-- return sfind( self._buf, str ) end function ByteArray:readBoolean() return (self:readByte() ~= 0) end function ByteArray:writeBoolean( boolean ) assert( type(boolean)=='boolean', "expected boolean type" ) --==-- if boolean then self:writeByte(1) else self:writeByte(0) end return self -- chaining end -- byte is number from 0<>255 function ByteArray:readByte() return sbyte( self:readChar() ) end function ByteArray:writeByte( byte ) assert( type(byte)=='number', "not valid byte" ) assert( byte>=0 and byte<=255, "not valid byte" ) --==-- self:writeChar( schar(byte) ) end function ByteArray:readChar() self:_checkAvailable(1) local char = self.getBytes( self._buf, self._pos, 1 ) self._pos = self._pos + 1 return char end -- should be single character function ByteArray:writeChar( char ) self._buf = self.putBytes( self._buf, char ) return self end -- Read byte string from ByteArray starting from current position, -- then update the position function ByteArray:readUTFBytes( len ) -- print( "ByteArray:readUTFBytes", len, self._pos ) assert( type(len)=='number', "need integer length" ) --==-- if len == 0 then return "" end self:_checkAvailable( len ) local bytes = self.getBytes( self._buf, self._pos, len ) self._pos = self._pos + len return bytes end ByteArray.readBuf = ByteArray.readUTFBytes --- Write a encoded char array into buf function ByteArray:writeUTFBytes( bytes, index ) assert( type(bytes)=='string', "must be string" ) --==-- self._buf = ByteArray.putBytes( self._buf, bytes, index ) return self -- chaining end ByteArray.writeBuf = ByteArray.writeUTFBytes -- reads bytes FROM us TO array -- ba array to read TO -- length for ba being read from -- offset for ba being written to -- function ByteArray:readBytes( ba, offset, length ) assert( ba and ba:isa(ByteArray), "Need a ByteArray instance" ) --==-- offset = offset ~= nil and offset or 1 length = length ~= nil and length or ba.bytesAvailable if length == 0 then return end assert( type(offset)=='number', "offset must be a number" ) assert( type(length)=='number', "offset must be a number" ) local bytes = self:readUTFBytes( length ) ba._buf = ByteArray.putBytes( ba._buf, bytes, offset ) return self -- chaining end -- write bytes TO us FROM array -- ba array to write FROM -- length for ba being read from -- offset for ba being written to -- function ByteArray:writeBytes( ba, offset, length ) assert( ba and ba:isa(ByteArray), "Need a ByteArray instance" ) --==-- offset = offset ~= nil and offset or 1 length = length ~= nil and length or ba.bytesAvailable if length == 0 then return end assert( type(offset)=='number', "offset must be a number" ) assert( type(length)=='number', "offset must be a number" ) local bytes = ba:readUTFBytes( length ) self._buf = ByteArray.putBytes( self._buf, bytes, offset ) return self -- chaining end --====================================================================-- --== Private Methods function ByteArray:_checkAvailable( len ) -- print( "ByteArray:_checkAvailable", len ) if len > self.bytesAvailable then error( Error.BufferError("Read surpasses buffer size") ) end end return ByteArray
mit
UnfortunateFruit/darkstar
scripts/globals/items/chunk_of_sweet_lizard.lua
35
1262
----------------------------------------- -- ID: 5738 -- Item: chunk_of_sweet_lizard -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 5 -- MP 5 -- Dexterity 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5738); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 5); target:addMod(MOD_MP, 5); target:addMod(MOD_DEX, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 5); target:delMod(MOD_MP, 5); target:delMod(MOD_DEX, 1); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Northern_San_dOria/npcs/Belgidiveau.lua
25
2335
----------------------------------- -- Area: Northern San d'Oria -- NPC: Belgidiveau -- Starts and Finishes Quest: Trouble at the Sluice -- @zone 231 -- @pos -98 0 69 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) troubleAtTheSluice = player:getQuestStatus(SANDORIA,TROUBLE_AT_THE_SLUICE); NeutralizerKI = player:hasKeyItem(NEUTRALIZER); if (troubleAtTheSluice == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3) then player:startEvent(0x0039); elseif (troubleAtTheSluice == QUEST_ACCEPTED and NeutralizerKI == false) then player:startEvent(0x0037); elseif (NeutralizerKI) then player:startEvent(0x0038); else player:startEvent(0x0249); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0039 and option == 0) then player:addQuest(SANDORIA,TROUBLE_AT_THE_SLUICE); player:setVar("troubleAtTheSluiceVar",1); elseif (csid == 0x0038) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16706); -- Heavy Axe else player:tradeComplete(); player:delKeyItem(NEUTRALIZER); player:addItem(16706); player:messageSpecial(ITEM_OBTAINED,16706); -- Heavy Axe player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,TROUBLE_AT_THE_SLUICE); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/chocobo_digging.lua
8
7395
-- chocobo_digging.lua require("scripts/globals/status"); require("scripts/globals/utils"); require("scripts/globals/settings"); ----------------------------------- -- DIG REQUIREMENTS ----------------------------------- DIGREQ_NONE = 0; DIGREQ_BURROW = 1; DIGREQ_BORE = 2; DIGREQ_MODIFIER = 4; DIGREQ_NIGHT = 8; local DIGABILITY_BURROW = 1; local DIGABILITY_BORE = 2; local function canDig(player) local DigCount = player:getVar('[DIG]DigCount'); local LastDigTime = player:getLocalVar('[DIG]LastDigTime'); local ZoneItemsDug = GetServerVariable('[DIG]ZONE'..player:getZoneID()..'_ITEMS'); local ZoneInTime = player:getLocalVar('[DIG]ZoneInTime'); local CurrentTime = os.time(os.date('!*t')); local SkillRank = player:getSkillRank(SKILL_DIG); -- base delay -5 for each rank local DigDelay = 16 - (SkillRank * 5); local AreaDigDelay = 60 - (SkillRank * 5); -- neither player nor zone have reached their dig limit if ((DigCount < 100 and ZoneItemsDug < 20) or DIG_FATIGUE == 0 ) then -- pesky delays if ((ZoneInTime <= AreaDigDelay + CurrentTime) and (LastDigTime + DigDelay <= CurrentTime)) then return true; end end return false; end; local function calculateSkillUp(player) -- 59 cause we're gonna use SKILL_DIG for burrow/bore local SkillRank = player:getSkillRank(SKILL_DIG); local MaxSkill = (SkillRank + 1) * 100; local RealSkill = player:getSkillLevel(SKILL_DIG); local SkillIncrement = 1; -- this probably needs correcting local SkillUpChance = math.random(0, 100); -- make sure our skill isn't capped if (RealSkill < MaxSkill) then -- can we skill up? if (SkillUpChance <= 15) then if ((SkillIncrement + RealSkill) > MaxSkill) then SkillIncrement = MaxSkill - RealSkill; end -- skill up! player:setSkillLevel(SKILL_DIG, RealSkill + SkillIncrement); -- gotta update the skill rank and push packet for i = 0, 10, 1 do if (SkillRank == i and RealSkill >= ((SkillRank * 100) + 100)) then player:setSkillRank(SKILL_DIG, SkillRank + 1); end end if ((RealSkill / 10) < ((RealSkill + SkillIncrement) / 10)) then -- todo: get this working correctly (apparently the lua binding updates RealSkills and WorkingSkills) player:setSkillLevel(SKILL_DIG, player:getSkillLevel(SKILL_DIG) + 0x20); end end end end; function updatePlayerDigCount(player, increment) local CurrentTime = os.time(os.date('!*t')); if (increment == 0) then player:setVar('[DIG]DigCount', 0); else local DigCount = player:getVar('[DIG]DigCount'); player:setVar('[DIG]DigCount', DigCount + increment); end player:setLocalVar('[DIG]LastDigTime', CurrentTime); end; function updateZoneDigCount(zone, increment) local ZoneDigCount = GetServerVariable('[DIG]ZONE'..zone..'_ITEMS'); -- 0 means we wanna wipe (probably only gonna happen onGameDay or something) if (increment == 0) then SetServerVariable('[DIG]ZONE'..zone..'ITEMS', 0); else SetServerVariable('[DIG]ZONE'..zone..'ITEMS', ZoneDigCount + increment); end end; function chocoboDig(player, itemMap, precheck, messageArray) -- make sure the player can dig before going any further -- (and also cause i need a return before core can go any further with this) if (precheck) then return canDig(player); else local DigCount = player:getVar('[DIG]DigCount'); local Chance = math.random(0, 100); if (Chance <= 15) then player:messageText(player, messageArray[2]); calculateSkillUp(player); else -- recalculate chance to compare with item abundance Chance = math.random(0, 100); -- select a random item local RandomItem = itemMap[math.random(1, #itemMap)]; local RItemAbundance = RandomItem[2]; local ItemID = 0; local weather = player:getWeather(); local moon = VanadielMoonPhase(); local day = VanadielDayElement(); -- item and DIG_ABUNDANCE_BONUS 3 digits, dont wanna get left out Chance = Chance * 100; -- We need to check for moon phase, too. 45-60% results in a much lower dig chance than the rest of the phases if (moon >= 45 and moon <=60) then Chance = Chance * .5; end if (Chance < (RItemAbundance + DIG_ABUNDANCE_BONUS)) then local RItemID = RandomItem[1]; local RItemReq = RandomItem[3]; -- rank 1 is burrow, rank 2 is bore (see DIGABILITY at the top of the file) local DigAbility = player:getSkillRank(SKILL_DIG); local Mod = player:getMod(MOD_EGGHELM); if ((RItemReq == DIGREQ_NONE) or (RItemReq == DIGREQ_BURROW and DigAbility == DIGABILITY_BURROW) or (RItemReq == DIGREQ_BORE and DigAbility == DIGABILITY_BORE) or (RItemReq == DIGREQ_MODIFIER and Mod == 1) or (RItemReq == DIGREQ_NIGHT and VanadielTOTD() == TIME_NIGHT)) then ItemID = RItemID; else ItemID = 0; end -- Let's see if the item should be obtained in this zone with this weather local crystalMap = { 0, -- fire crystal 8, -- fire cluster 5, -- water crystal 13, -- water cluster 3, -- earth crystal 11, -- earth cluster 2, -- wind crystal 10, -- wind cluster 1, -- ice crystal 9, -- ice cluster 4, -- lightning crystal 12, -- lightning cluster 6, -- light crystal 14, -- light cluster 7, -- dark crystal 15, -- dark cluster }; if (weather >= 4 and ItemID == 4096) then ItemID = ItemID + crystalMap[weather-3]; end local oreMap = { 0, -- fire ore 3, -- earth ore 5, -- water ore 2, -- wind ore 1, -- ice ore 4, -- lightning ore 6, -- light ore 7, -- dark ore }; -- If the item is an elemental ore, we need to check if the requirements are met if (ItemID == 1255 and weather > 1 and (moon >= 10 and moon <= 40) and SkillRank >= 7) then ItemID = ItemID + oreMap[day+1]; end -- make sure we have a valid item if (ItemID ~= 0) then -- make sure we have enough room for the item if(player:addItem(ItemID))then player:messageSpecial(ITEM_OBTAINED, ItemID); else player:messageSpecial(DIG_THROW_AWAY, ItemID); end else -- beat the dig chance, but not the item chance player:messageText(player, messageArray[2], false); end end calculateSkillUp(player); updatePlayerDigCount(player, 1); end return true; end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Windurst_Waters/npcs/Baren-Moren.lua
12
8393
----------------------------------- -- Area: Windurst Waters -- NPC: Baren-Moren -- Starts and Finishes Quest: Hat in Hand -- Working 100% -- @zone = 238 -- @pos = -66 -3 -148 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) featherstatus = player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP); if (featherstatus >= 1 and trade:hasItemQty(842,3) == true and trade:getGil() == 0 and trade:getItemCount() == 3) then player:startEvent(0x004f,1500); -- Quest Turn In end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- player:delQuest(WINDURST,A_FEATHER_IN_ONE_S_CAP); -- ================== FOR TESTING ONLY ===================== -- player:addFame(WINDURST,200); -- ================== FOR TESTING ONLY ===================== function testflag(set,flag) return (set % (2*flag) >= flag) end hatstatus = player:getQuestStatus(WINDURST,HAT_IN_HAND); featherstatus = player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP); pfame = player:getFameLevel(WINDURST); if (hatstatus == 0) then player:startEvent(0x0030); -- Quest Offered -- elseif ((hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) and player:getVar("QuestHatInHand_count") == 0) then -- player:startEvent(0x0033,80); -- Hat in Hand: During Quest - Objective Reminder elseif (hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) then -- Variable to track quest progress -- 1 = Machitata @pos 163 0 -22 -- 2 = Honoi-Gomoi @pos -195 -11 -120 -- 4 = Kenapa-Keppa @pos 27 -6 -199 -- 8 = Clais @pos -31 -3 11 -- 16 = Kyume-Romeh @pos -58 -4 23 -- 32 = Tosuka-Porika @pos -26 -6 103 -- 64 = Pechiru-Mashiru @pos = 162 -2 159 -- 128 = Bondada @pos = -66 -3 -148 count = player:getVar("QuestHatInHand_count"); if (count == 8) then -- 80 = HAT + FULL REWARD = 8 NPCS - Option 5 player:startEvent(0x0034,80); elseif (count >= 6) then -- 50 = HAT + GOOD REWARD >= 6-7 NPCS - Option 4 player:startEvent(0x0034,50); elseif (count >= 4) then -- 30 = PARTIAL REWARD - >= 4-5 NPCS - Option 3 player:startEvent(0x0034,30); elseif (count >= 2) then -- 20 = POOR REWARD >= 2-3 NPCS - Option 2 player:startEvent(0x0034,20); else -- 0/nill = NO REWARD >= 0-1 NPCS - Option 1 player:startEvent(0x0034); end elseif (featherstatus == 1 or player:getVar("QuestFeatherInOnesCap_var") == 1) then player:startEvent(0x004e,0,842); -- Quest Objective Reminder elseif (hatstatus == 2 and featherstatus == 0 and pfame >= 3 and player:needToZone() == false and player:getVar("QuestHatInHand_var2") == 0) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x004b,0,842); -- Quest "Feather In One's Cap" offered else player:startEvent(0x0031); -- Repeatable Quest "Hat In Hand" offered end elseif (featherstatus == 2 and player:needToZone() == false) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x0031); -- Repeatable Quest "Hat In Hand" offered else player:startEvent(0x004b,0,842); -- Repeatable Quest "A Feather In One's Cap" offered end elseif (player:needToZone() == false) then player:startEvent(0x0031); -- Repeatable Quest "Hat In Hand" offered else -- Will run through these if fame is not high enough for other quests rand = math.random(1,6); if (rand == 1) then player:startEvent(0x002a); -- Standard Conversation 1 elseif (rand == 2) then player:startEvent(0x002c); -- Standard Conversation 2 elseif (rand == 3) then player:startEvent(0x002d); -- Standard Conversation 3 elseif (rand == 4) then player:startEvent(0x002e); -- Standard Conversation 4 elseif (rand == 5) then player:startEvent(0x002f); -- Standard Conversation 5 elseif (rand == 6) then player:startEvent(0x03fe); -- Standard Conversation 6 end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x0030 and option == 1) then player:addQuest(WINDURST,HAT_IN_HAND); player:addKeyItem(NEW_MODEL_HAT); player:messageSpecial(KEYITEM_OBTAINED,NEW_MODEL_HAT); elseif (csid == 0x0031 and option == 1) then player:setVar("QuestHatInHand_var2",1); player:addKeyItem(NEW_MODEL_HAT); player:messageSpecial(KEYITEM_OBTAINED,NEW_MODEL_HAT); elseif (csid == 0x0034 and option >= 4 and player:getFreeSlotsCount(0) == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12543); elseif (csid == 0x0034 and option >= 1) then if (option == 5) then -- 80 = HAT + FULL REWARD = 8 NPCS - Option 5 player:addGil(GIL_RATE*500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*500); if (player:hasItem(12543) == false) then player:addItem(12543,1); player:messageSpecial(ITEM_OBTAINED,12543); end elseif (option == 4) then -- 50 = HAT + GOOD REWARD >= 6 NPCS - Option 4 player:addGil(GIL_RATE*400); player:messageSpecial(GIL_OBTAINED,GIL_RATE*400); if (player:hasItem(12543) == false) then player:addItem(12543,1); player:messageSpecial(ITEM_OBTAINED,12543); end elseif (option == 3) then -- 30 = PARTIAL REWARD - >= 4 NPCS - Option 3 player:addGil(GIL_RATE*300); player:messageSpecial(GIL_OBTAINED,GIL_RATE*300); elseif (option == 2) then -- 20 = POOR REWARD >= 2 NPCS - Option 2 player:addGil(GIL_RATE*150); player:messageSpecial(GIL_OBTAINED,GIL_RATE*150); -- else (option == 1) then -- 0/nill = NO REWARD >= 0 NPCS - Option 1 end if (hatstatus == 1) then player:addFame(WINDURST,75); else player:addFame(WINDURST,8); end player:completeQuest(WINDURST,HAT_IN_HAND); player:setVar("QuestHatInHand_count",0); player:setVar("QuestHatInHand_var",0); player:needToZone(true); player:delKeyItem(NEW_MODEL_HAT); player:setVar("QuestHatInHand_var2",0); elseif (csid == 0x004b and option == 1) then if (player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP) == QUEST_AVAILABLE) then player:addQuest(WINDURST,A_FEATHER_IN_ONE_S_CAP); elseif (player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP) == QUEST_COMPLETED) then player:setVar("QuestFeatherInOnesCap_var",1); end elseif (csid == 0x004f) then if (player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP) == QUEST_ACCEPTED) then player:completeQuest(WINDURST,A_FEATHER_IN_ONE_S_CAP); player:addFame(WINDURST,75); else player:addFame(WINDURST,8); player:setVar("QuestFeatherInOnesCap_var",0); end player:addGil(GIL_RATE*1500); player:tradeComplete(trade); player:needToZone(true); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Bastok_Mines/npcs/Conrad.lua
10
1871
----------------------------------- -- Area: Bastok Mines -- NPC: Conrad -- Outpost Teleporter NPC -- @pos 94.457 -0.375 -66.161 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Bastok_Mines/TextIDs"); guardnation = BASTOK; csid = 0x0245; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(guardnation == player:getNation()) then player:startEvent(csid,0,0,0,0,0,0,player:getMainLvl(),1073741823 - player:getNationTeleport(guardnation)); else player:startEvent(csid,0,0,0,0,0,256,0,0); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); loca = option - 1073741829; player:updateEvent(player:getGil(),OP_TeleFee(player,loca),player:getCP(),OP_TeleFee(player,loca),player:getCP()); end; ----------------------------------- --onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(option >= 5 and option <= 23) then if (player:delGil(OP_TeleFee(player,option-5))) then toOutpost(player,option); end elseif(option >= 1029 and option <= 1047) then local cpCost = OP_TeleFee(player,option-1029); --printf("CP Cost: %u",cpCost); if (player:getCP()>=cpCost) then player:delCP(cpCost); toOutpost(player,option-1024); end end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/spells/hojo_san.lua
11
1240
----------------------------------------- -- Spell: Hojo:San -- Description: Inflicts Slow on target. -- Edited from slow.lua ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Power for Hojo is a flat 30% reduction local power = 300; --Duration and Resistance calculation local duration = 420 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Calculates the resist chance from Resist Blind trait if(math.random(0,100) >= target:getMod(MOD_SLOWRES)) then -- Spell succeeds if a 1 or 1/2 resist check is achieved if(duration >= 210) then if(target:addStatusEffect(EFFECT_SLOW,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end else spell:setMsg(284); end return EFFECT_SLOW; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/jacknife.lua
18
1428
----------------------------------------- -- ID: 5123 -- Item: Jacknife -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 4 -- Defence 16% Cap 50 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5123); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -5); target:addMod(MOD_VIT, 4); target:addMod(MOD_FOOD_DEFP, 16); target:addMod(MOD_FOOD_DEF_CAP, 50); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -5); target:delMod(MOD_VIT, 4); target:delMod(MOD_FOOD_DEFP, 16); target:delMod(MOD_FOOD_DEF_CAP, 50); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Valley_of_Sorrows/Zone.lua
12
1749
----------------------------------- -- -- Zone: Valley_of_Sorrows (128) -- ----------------------------------- package.loaded["scripts/zones/Valley_of_Sorrows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Valley_of_Sorrows/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17301591,17301592}; SetFieldManual(manuals); -- Adamantoise SetRespawnTime(17301537, 900, 10800); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(45.25,-2.115,-140.562,0); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
jj918160/cocos2d-x-samples
samples/KillBug/src/cocos/framework/transition.lua
57
7512
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local transition = {} local ACTION_EASING = {} ACTION_EASING["BACKIN"] = {cc.EaseBackIn, 1} ACTION_EASING["BACKINOUT"] = {cc.EaseBackInOut, 1} ACTION_EASING["BACKOUT"] = {cc.EaseBackOut, 1} ACTION_EASING["BOUNCE"] = {cc.EaseBounce, 1} ACTION_EASING["BOUNCEIN"] = {cc.EaseBounceIn, 1} ACTION_EASING["BOUNCEINOUT"] = {cc.EaseBounceInOut, 1} ACTION_EASING["BOUNCEOUT"] = {cc.EaseBounceOut, 1} ACTION_EASING["ELASTIC"] = {cc.EaseElastic, 2, 0.3} ACTION_EASING["ELASTICIN"] = {cc.EaseElasticIn, 2, 0.3} ACTION_EASING["ELASTICINOUT"] = {cc.EaseElasticInOut, 2, 0.3} ACTION_EASING["ELASTICOUT"] = {cc.EaseElasticOut, 2, 0.3} ACTION_EASING["EXPONENTIALIN"] = {cc.EaseExponentialIn, 1} ACTION_EASING["EXPONENTIALINOUT"] = {cc.EaseExponentialInOut, 1} ACTION_EASING["EXPONENTIALOUT"] = {cc.EaseExponentialOut, 1} ACTION_EASING["IN"] = {cc.EaseIn, 2, 1} ACTION_EASING["INOUT"] = {cc.EaseInOut, 2, 1} ACTION_EASING["OUT"] = {cc.EaseOut, 2, 1} ACTION_EASING["RATEACTION"] = {cc.EaseRateAction, 2, 1} ACTION_EASING["SINEIN"] = {cc.EaseSineIn, 1} ACTION_EASING["SINEINOUT"] = {cc.EaseSineInOut, 1} ACTION_EASING["SINEOUT"] = {cc.EaseSineOut, 1} local actionManager = cc.Director:getInstance():getActionManager() function transition.newEasing(action, easingName, more) local key = string.upper(tostring(easingName)) local easing if ACTION_EASING[key] then local cls, count, default = unpack(ACTION_EASING[key]) if count == 2 then easing = cls:create(action, more or default) else easing = cls:create(action) end end return easing or action end function transition.create(action, args) args = checktable(args) if args.easing then if type(args.easing) == "table" then action = transition.newEasing(action, unpack(args.easing)) else action = transition.newEasing(action, args.easing) end end local actions = {} local delay = checknumber(args.delay) if delay > 0 then actions[#actions + 1] = cc.DelayTime:create(delay) end actions[#actions + 1] = action local onComplete = args.onComplete if type(onComplete) ~= "function" then onComplete = nil end if onComplete then actions[#actions + 1] = cc.CallFunc:create(onComplete) end if args.removeSelf then actions[#actions + 1] = cc.RemoveSelf:create() end if #actions > 1 then return transition.sequence(actions) else return actions[1] end end function transition.execute(target, action, args) assert(not tolua.isnull(target), "transition.execute() - target is not cc.Node") local action = transition.create(action, args) target:runAction(action) return action end function transition.moveTo(target, args) assert(not tolua.isnull(target), "transition.moveTo() - target is not cc.Node") local x = args.x or target:getPositionX() local y = args.y or target:getPositionY() local action = cc.MoveTo:create(args.time, cc.p(x, y)) return transition.execute(target, action, args) end function transition.moveBy(target, args) assert(not tolua.isnull(target), "transition.moveBy() - target is not cc.Node") local x = args.x or 0 local y = args.y or 0 local action = cc.MoveBy:create(args.time, cc.p(x, y)) return transition.execute(target, action, args) end function transition.fadeIn(target, args) assert(not tolua.isnull(target), "transition.fadeIn() - target is not cc.Node") local action = cc.FadeIn:create(args.time) return transition.execute(target, action, args) end function transition.fadeOut(target, args) assert(not tolua.isnull(target), "transition.fadeOut() - target is not cc.Node") local action = cc.FadeOut:create(args.time) return transition.execute(target, action, args) end function transition.fadeTo(target, args) assert(not tolua.isnull(target), "transition.fadeTo() - target is not cc.Node") local opacity = checkint(args.opacity) if opacity < 0 then opacity = 0 elseif opacity > 255 then opacity = 255 end local action = cc.FadeTo:create(args.time, opacity) return transition.execute(target, action, args) end function transition.scaleTo(target, args) assert(not tolua.isnull(target), "transition.scaleTo() - target is not cc.Node") local action if args.scale then action = cc.ScaleTo:create(checknumber(args.time), checknumber(args.scale)) elseif args.scaleX or args.scaleY then local scaleX, scaleY if args.scaleX then scaleX = checknumber(args.scaleX) else scaleX = target:getScaleX() end if args.scaleY then scaleY = checknumber(args.scaleY) else scaleY = target:getScaleY() end action = cc.ScaleTo:create(checknumber(args.time), scaleX, scaleY) end return transition.execute(target, action, args) end function transition.rotateTo(target, args) assert(not tolua.isnull(target), "transition.rotateTo() - target is not cc.Node") local rotation = args.rotation or target:getRotation() local action = cc.RotateTo:create(args.time, rotation) return transition.execute(target, action, args) end function transition.rotateBy(target, args) assert(not tolua.isnull(target), "transition.rotateTo() - target is not cc.Node") local rotation = args.rotation or 0 local action = cc.RotateBy:create(args.time, rotation) return transition.execute(target, action, args) end function transition.sequence(actions) if #actions < 1 then return end if #actions < 2 then return actions[1] end return cc.Sequence:create(actions) end function transition.removeAction(action) if not tolua.isnull(action) then actionManager:removeAction(action) end end function transition.stopTarget(target) if not tolua.isnull(target) then actionManager:removeAllActionsFromTarget(target) end end function transition.pauseTarget(target) if not tolua.isnull(target) then actionManager:pauseTarget(target) end end function transition.resumeTarget(target) if not tolua.isnull(target) then actionManager:resumeTarget(target) end end return transition
mit
UnfortunateFruit/darkstar
scripts/zones/Southern_San_dOria/npcs/Rosel.lua
19
2829
----------------------------------- -- Area: Southern San d'Oria -- NPC: Rosel -- Starts and Finishes Quest: Rosel the Armorer -- @zone 230 -- @pos ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED)then if(trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeRosel") == 0)then player:messageSpecial(8709); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeRosel",1); player:messageSpecial(FLYER_ACCEPTED); trade:complete(); elseif(player:getVar("tradeRosel") ==1)then player:messageSpecial(8710); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RoselTheArmorer = player:getQuestStatus(SANDORIA,ROSEL_THE_ARMORER); receiprForThePrince = player:hasKeyItem(RECEIPT_FOR_THE_PRINCE); if(player:getVar("RefuseRoselTheArmorerQuest") == 1 and RoselTheArmorer == QUEST_AVAILABLE) then player:startEvent(0x020c); elseif(RoselTheArmorer == QUEST_AVAILABLE) then player:startEvent(0x020b); player:setVar("RefuseRoselTheArmorerQuest",1); elseif(RoselTheArmorer == QUEST_ACCEPTED and receiprForThePrince) then player:startEvent(0x020c); elseif(RoselTheArmorer == QUEST_ACCEPTED and receiprForThePrince == false) then player:startEvent(0x020f); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); -- Rosel the Armorer, get quest and receipt for prince if((csid == 0x020b or csid == 0x020c) and option == 0) then player:addQuest(SANDORIA, ROSEL_THE_ARMORER); player:setVar("RefuseRoselTheArmorerQuest",0); player:addKeyItem(RECEIPT_FOR_THE_PRINCE); player:messageSpecial(KEYITEM_OBTAINED,RECEIPT_FOR_THE_PRINCE); -- Rosel the Armorer, finished quest, recieve 200gil elseif(csid == 0x020f) then npcUtil.completeQuest(player, SANDORIA, ROSEL_THE_ARMORER, { title= ENTRANCE_DENIED, gil= 200 }); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/spells/foe_lullaby_ii.lua
11
1232
----------------------------------------- -- Spell: Foe Lullaby ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local duration = 60; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local resm = applyResistance(caster,spell,target,dCHR,40,0); if(resm < 0.5) then spell:setMsg(85);--resist message return EFFECT_LULLABY; end if(target:hasImmunity(1) or 100 * math.random() < target:getMod(MOD_SLEEPRES)) then --No effect spell:setMsg(75); else local iBoost = caster:getMod(MOD_LULLABY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if(target:addStatusEffect(EFFECT_LULLABY,1,0,duration)) then spell:setMsg(237); else spell:setMsg(75); end end return EFFECT_LULLABY; end;
gpl-3.0
ruisebastiao/nodemcu-firmware
lua_examples/http_server.lua
53
3696
-- -- Simple NodeMCU web server (done is a not so nodeie fashion :-) -- -- Highly modified by Bruce Meacham, based on work by Scott Beasley 2015 -- Open and free to change and use. Enjoy. [Beasley/Meacham 2015] -- -- Meacham Update: I streamlined/improved the parsing to focus on simple HTTP GET request and their simple parameters -- Also added the code to drive a servo/light. Comment out as you see fit. -- -- Usage: -- Change SSID and SSID_PASSPHRASE for your wifi network -- Download to NodeMCU -- node.compile("http_server.lua") -- dofile("http_server.lc") -- When the server is esablished it will output the IP address. -- http://{ip address}/?s0=1200&light=1 -- s0 is the servo position (actually the PWM hertz), 500 - 2000 are all good values -- light chanel high(1)/low(0), some evaluation boards have LEDs pre-wired in a "pulled high" confguration, so '0' ground the emitter and turns it on backwards. -- -- Add to init.lua if you want it to autoboot. -- -- Your Wifi connection data local SSID = "YOUR WIFI SSID" local SSID_PASSWORD = "YOUR SSID PASSPHRASE" -- General setup local pinLight = 2 -- this is GPIO4 gpio.mode(pinLight,gpio.OUTPUT) gpio.write(pinLight,gpio.HIGH) servo = {} servo.pin = 4 --this is GPIO2 servo.value = 1500 servo.id = "servo" gpio.mode(servo.pin, gpio.OUTPUT) gpio.write(servo.pin, gpio.LOW) -- This alarm drives the servo tmr.alarm(0,10,1,function() -- 50Hz if servo.value then -- generate pulse gpio.write(servo.pin, gpio.HIGH) tmr.delay(servo.value) gpio.write(servo.pin, gpio.LOW) end end) local function connect (conn, data) local query_data conn:on ("receive", function (cn, req_data) params = get_http_req (req_data) cn:send("HTTP/1.1 200/OK\r\nServer: NodeLuau\r\nContent-Type: text/html\r\n\r\n") cn:send ("<h1>ESP8266 Servo &amp; Light Server</h1>\r\n") if (params["light"] ~= nil) then if ("0" == params["light"]) then gpio.write(pinLight, gpio.LOW) else gpio.write(pinLight, gpio.HIGH) end end if (params["s0"] ~= nil) then servo.value = tonumber(params["s0"]); end -- Close the connection for the request cn:close ( ) end) end -- Build and return a table of the http request data function get_http_req (instr) local t = {} local str = string.sub(instr, 0, 200) local v = string.gsub(split(str, ' ')[2], '+', ' ') parts = split(v, '?') local params = {} if (table.maxn(parts) > 1) then for idx,part in ipairs(split(parts[2], '&')) do parmPart = split(part, '=') params[parmPart[1]] = parmPart[2] end end return params end -- Source: http://lua-users.org/wiki/MakingLuaLikePhp -- Credit: http://richard.warburton.it/ function split(str, splitOn) if (splitOn=='') then return false end local pos,arr = 0,{} for st,sp in function() return string.find(str,splitOn,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) pos = sp + 1 end table.insert(arr,string.sub(str,pos)) return arr end -- Configure the ESP as a station (client) wifi.setmode (wifi.STATION) wifi.sta.config (SSID, SSID_PASSWORD) wifi.sta.autoconnect (1) -- Hang out until we get a wifi connection before the httpd server is started. tmr.alarm (1, 800, 1, function ( ) if wifi.sta.getip ( ) == nil then print ("Waiting for Wifi connection") else tmr.stop (1) print ("Config done, IP is " .. wifi.sta.getip ( )) end end) -- Create the httpd server svr = net.createServer (net.TCP, 30) -- Server listening on port 80, call connect function if a request is received svr:listen (80, connect)
mit
nesstea/darkstar
scripts/zones/Upper_Jeuno/TextIDs.lua
15
1699
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6543; -- Obtained: <item>. GIL_OBTAINED = 6544; -- Obtained <number> gil. KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem>. KEYITEM_LOST = 6547; -- Lost key item: NOT_HAVE_ENOUGH_GIL = 6548; -- You do not have enough gil. HOMEPOINT_SET = 6672; -- Home point set! NOTHING_OUT_OF_ORDINARY = 6557; -- There is nothing out of the ordinary here. -- Other Texts ITEM_DELIVERY_DIALOG = 8064; -- Delivering goods to residences everywhere! -- Conquest system CONQUEST = 7731; -- You've earned conquest points! -- NPC Texts KIRISOMANRISO_DIALOG = 8064; -- Delivering goods to residences everywhere! YOU_CAN_NOW_BECOME_A_BEASTMASTER = 7175; -- You can now become a beastmaster. UNLOCK_DANCER = 11818; -- You can now become a dancer! GUIDE_STONE = 6970; -- Up: Ru'Lude Gardens Down: Lower Jeuno -- Shop Texts GLYKE_SHOP_DIALOG = 6965; -- Can I help you? MEJUONE_SHOP_DIALOG = 6966; -- Welcome to the Chocobo Shop. COUMUNA_SHOP_DIALOG = 6967; -- Welcome to Viette's Finest Weapons. ANTONIA_SHOP_DIALOG = 6967; -- Welcome to Viette's Finest Weapons. DEADLYMINNOW_SHOP_DIALOG = 6968; -- Welcome to Durable Shields. KHECHALAHKO_SHOP_DIALOG = 6968; -- Welcome to Durable Shields. AREEBAH_SHOP_DIALOG = 6969; -- Welcome to M & P's Market. CHAMPALPIEU_SHOP_DIALOG = 6969; -- Welcome to M & P's Market. LEILLAINE_SHOP_DIALOG = 6995; -- Hello. Are you feeling all right? -- conquest Base CONQUEST_BASE = 0;
gpl-3.0
nesstea/darkstar
scripts/zones/Batallia_Downs_[S]/Zone.lua
13
1412
----------------------------------- -- -- Zone: Batallia_Downs_[S] (84) -- ----------------------------------- package.loaded["scripts/zones/Batallia_Downs_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Batallia_Downs_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-500.451,-39.71,504.894,39); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Windurst_Woods/npcs/Panoquieur_TK.lua
30
4701
----------------------------------- -- Area: Windurst Woods -- NPC: Panoquieur, T.K. -- @pos -60 0 -31 241 -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Windurst_Woods/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border local size = table.getn(SandInv); local inventory = SandInv; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else Menu1 = getArg1(guardnation,player); Menu2 = getExForceAvailable(guardnation,player); Menu3 = conquestRanking(); Menu4 = getSupplyAvailable(guardnation,player); Menu5 = player:getNationTeleport(guardnation); Menu6 = getArg6(player); Menu7 = player:getCP(); Menu8 = getRewardExForce(guardnation,player); player:startEvent(0x7ffb,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); if (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then CPVerify = 1 if (player:getCP() >= inventory[Item + 1]) then CPVerify = 0 end player:updateEvent(2,CPVerify,inventory[Item + 2]); break end end end end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); if (option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then if (player:getFreeSlotsCount() >= 1) then -- Logic to impose limits on exp bands if (option >= 32933 and option <= 32935) then if (checkConquestRing(player) > 0) then player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]); break else player:setVar("CONQUEST_RING_TIMER",getConquestTally()); end end if (player:getNation() == guardnation) then itemCP = inventory[Item + 1]; else if (inventory[Item + 1] <= 8000) then itemCP = inventory[Item + 1] * 2; else itemCP = inventory[Item + 1] + 8000; end end if (player:hasItem(inventory[Item + 2]) == false) then player:delCP(itemCP); player:addItem(inventory[Item + 2],1); player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end break end end elseif (option >= 65541 and option <= 65565) then -- player chose supply quest. local region = option - 65541; player:addKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region)); player:setVar("supplyQuest_started",vanaDay()); player:setVar("supplyQuest_region",region); player:setVar("supplyQuest_fresh",getConquestTally()); end end
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/spells/sandstorm.lua
31
1153
-------------------------------------- -- Spell: Sandstorm -- Changes the weather around target party member to "dusty." -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) target:delStatusEffectSilent(EFFECT_FIRESTORM); target:delStatusEffectSilent(EFFECT_SANDSTORM); target:delStatusEffectSilent(EFFECT_RAINSTORM); target:delStatusEffectSilent(EFFECT_WINDSTORM); target:delStatusEffectSilent(EFFECT_HAILSTORM); target:delStatusEffectSilent(EFFECT_THUNDERSTORM); target:delStatusEffectSilent(EFFECT_AURORASTORM); target:delStatusEffectSilent(EFFECT_VOIDSTORM); local merit = caster:getMerit(MERIT_STORMSURGE); local power = 0; if merit > 0 then power = merit + caster:getMod(MOD_STORMSURGE_EFFECT) + 2; end target:addStatusEffect(EFFECT_SANDSTORM,power,0,180); return EFFECT_SANDSTORM; end;
gpl-3.0
plajjan/snabbswitch
lib/ljsyscall/syscall/netbsd/version.lua
24
1319
-- detect netbsd version local abi = require "syscall.abi" local ffi = require "ffi" require "syscall.ffitypes" local version, major, minor local function inlibc_fn(k) return ffi.C[k] end -- NetBSD ABI version -- TODO if running rump on NetBSD the version detection is a bit flaky if the host and rump differ -- normally this is ok if you init netbsd first and have compat installed for rump, or do not use both... ffi.cdef[[ int sysctl(const int *, unsigned int, void *, size_t *, const void *, size_t); int __sysctl(const int *, unsigned int, void *, size_t *, const void *, size_t); int rump_getversion(void); ]] local sc = ffi.new("int[2]", 1, 3) -- kern.osrev local osrevision = ffi.new("int[1]") local lenp = ffi.new("unsigned long[1]", ffi.sizeof("int")) local major, minor local ok, res if abi.host == "netbsd" then ok, res = pcall(ffi.C.sysctl, sc, 2, osrevision, lenp, nil, 0) osrevision = osrevision[0] end if not ok or res == -1 then if pcall(inlibc_fn, "rump_getversion") then ok, osrevision = pcall(ffi.C.rump_getversion) end end if not ok then version = 7 else major = math.floor(osrevision / 100000000) minor = math.floor(osrevision / 1000000) - major * 100 version = major if minor == 99 then version = version + 1 end end return {version = version, major = major, minor = minor}
apache-2.0
niessner/Matterport
tasks/keypoint_match/2dmatch/train.lua
1
6467
require 'image' require 'cutorch' require 'cunn' require 'cudnn' require 'optim' -- Custom files require 'model' require 'sys' -- require 'qtwidget' -- for visualizing images dofile('util.lua') opt_string = [[ -h,--help print help -s,--save (default "logs") subdirectory to save logs -b,--batchSize (default 8) batch size -g,--gpu_index (default 0) GPU index (start from 0) --max_epoch (default 2) maximum number of epochs --basePath (default "/data/keypointmatch/") base path for train data --train_data (default "scenes_train.txt") txt file containing train --patchSize (default 64) patch size to extract (resized to 224) --matchFileSkip (default 10) only use every skip^th keypoint match in file --imWidth (default 640) image dimensions in data folder --imHeight (default 512) image dimensions in data folder --detectImWidth (default 1280) image dimensions for key detection --detectImHeight (default 1024) image dimensions for key detection --retrain (default "") initialize training with this model --resetModel (default false) ]] opt = lapp(opt_string) -- print help or chosen options if opt.help == true then print('Usage: th train.lua') print('Options:') print(opt_string) os.exit() else print(opt) end -- set gpu cutorch.setDevice(opt.gpu_index+1) -- Set RNG seed math.randomseed(0) torch.manualSeed(0) -- Load model and criterion local model,criterion if opt.retrain == "" then model,criterion = getModel() if opt.resetModel then print('reset model') recursiveModelReset(model) end else model = torch.load(opt.retrain) criterion = nn.HingeEmbeddingCriterion(1) end model = model:cuda() critrerion = criterion:cuda() model:zeroGradParameters() parameters, gradParameters = model:getParameters() --print(model) -- load training and testing files train_files = getDataFiles(paths.concat(opt.basePath,opt.train_data), opt.basePath) --filter out non-existent scenes print('#train files = ' .. #train_files) -- config logging testLogger = optim.Logger(paths.concat(opt.save, 'test.log')) testLogger:setNames{'epoch', 'iteration', 'current train loss', 'avg train loss'} do local optfile = assert(io.open(paths.concat(opt.save, 'options.txt'), 'w')) local cur = io.output() io.output(optfile) serialize(opt) serialize(train_files) io.output(cur) optfile:close() end local patchSize = opt.patchSize local saveInterval = 5000 local scaleX = opt.imWidth / opt.detectImWidth local scaleY = opt.imHeight / opt.detectImHeight ------------------------------------ -- Training routine -- function train() model:training() epoch = epoch or 1 -- if epoch not defined, assign it as 1 print('epoch ' .. epoch) --if epoch % opt.epoch_step == 0 then optimState.learningRate = optimState.learningRate/2 end --load in the train data (positive and negative matches) local poss, negs = loadMatchFiles(opt.basePath, train_files, patchSize/2, opt.matchFileSkip, opt.imWidth, opt.imHeight, scaleX, scaleY) print(#poss) --print(poss) --print(negs) collectgarbage() --pre-allocate memory local inputs_anc = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local inputs_pos = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local inputs_neg = torch.zeros(opt.batchSize, 3, 224, 224):cuda() local targets = torch.ones(opt.batchSize*2):cuda() targets[{{opt.batchSize+1, opt.batchSize*2}}]:fill(-1) local totalloss = 0 local indices = torch.randperm(#poss) local numIters = math.floor(#poss/opt.batchSize) for iter = 1,#poss,opt.batchSize do -- print progress bar local trainIter = (iter-1)/opt.batchSize+1 xlua.progress(trainIter, numIters) if iter + opt.batchSize > #poss then break end --don't use last batch collectgarbage() for k = iter,iter+opt.batchSize-1 do --create a mini batch local idx = indices[k] local sceneName = poss[idx][1] local imgPath = paths.concat(opt.basePath,sceneName,'images') local anc,pos,neg = getTrainingExampleTriplet(imgPath, poss[idx][2], poss[idx][3], negs[idx][3], patchSize) inputs_pos[{k-iter+1,{},{},{}}]:copy(pos) --match inputs_anc[{k-iter+1,{},{},{}}]:copy(anc) --anchor inputs_neg[{k-iter+1,{},{},{}}]:copy(neg) --non-match end -- a function that takes single input and return f(x) and df/dx local curLoss = -1 local feval = function(x) if x ~= parameters then parameters:copy(x) end gradParameters:zero() -- Forward and backward pass local inputs = {inputs_pos, inputs_anc, inputs_neg} local output = model:forward(inputs) local loss = criterion:forward(output, targets) local dLoss = criterion:backward(output, targets) model:backward(inputs,dLoss) curLoss = loss totalloss = totalloss + loss return loss,gradParameters end config = {learningRate = 0.001,momentum = 0.99} optim.sgd(feval, parameters, config) if testLogger then paths.mkdir(opt.save) testLogger:add{tostring(epoch), tostring(trainIter), curLoss, totalloss / trainIter} testLogger:style{'-','-','-','-'} end if trainIter > 0 and (trainIter % saveInterval == 0 or trainIter == numIters) then local filename = paths.concat(opt.save, 'model_' .. tostring(epoch) .. '-' .. tostring(trainIter) .. '.net') print('==> saving model to '..filename) torch.save(filename, model) --torch.save(filename, model:clearState()) end end epoch = epoch + 1 end ----------------------------------------- -- Start training -- for i = 1,opt.max_epoch do train() if epoch % 10 == 0 then local filename = paths.concat(opt.save, 'model_' ..tostring(epoch) .. '.net') print('==> saving model to '..filename) torch.save(filename, model:clearState()) end end
mit
UnfortunateFruit/darkstar
scripts/zones/Port_Bastok/npcs/Corann.lua
36
2068
----------------------------------- -- Area: Port Bastok -- NPC: Corann -- Start & Finishes Quest: The Quadav's Curse ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) TheQuadav = player:getQuestStatus(BASTOK,THE_QUADAV_S_CURSE); if (TheQuadav == QUEST_ACCEPTED) then count = trade:getItemCount(); QuadavBack = trade:hasItemQty(596,1); if (count == 1 and QuadavBack == true) then player:startEvent(0x0051); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TheQuadav = player:getQuestStatus(BASTOK,THE_QUADAV_S_CURSE); OutOfOneShell = player:getQuestStatus(BASTOK,OUT_OF_ONE_S_SHELL); if (OutOfOneShell == QUEST_COMPLETED) then player:startEvent(0x0058); elseif (TheQuadav == QUEST_COMPLETED) then player:startEvent(0x0057); elseif (TheQuadav == QUEST_AVAILABLE) then player:startEvent(0x0050); else player:startEvent(0x0026); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0050) then player:addQuest(BASTOK,THE_QUADAV_S_CURSE); elseif (csid == 0x0051) then player:tradeComplete(); player:completeQuest(BASTOK,THE_QUADAV_S_CURSE); player:addFame(BASTOK,BAS_FAME*120); player:addItem(12832); player:messageSpecial(ITEM_OBTAINED,12832); end end;
gpl-3.0
vonflynee/opencomputersserver
world/opencomputers/6d437cc7-8fe8-4147-8a29-4c8b62fcedc7/bin/dmesg.lua
15
1193
local event = require "event" local component = require "component" local keyboard = require "keyboard" local args = {...} local interactive = io.output() == io.stdout local color, isPal, evt if interactive then color, isPal = component.gpu.getForeground() end io.write("Press 'Ctrl-C' to exit\n") pcall(function() repeat if #args > 0 then evt = table.pack(event.pullMultiple("interrupted", table.unpack(args))) else evt = table.pack(event.pull()) end if interactive then component.gpu.setForeground(0xCC2200) end io.write("[" .. os.date("%T") .. "] ") if interactive then component.gpu.setForeground(0x44CC00) end io.write(tostring(evt[1]) .. string.rep(" ", math.max(10 - #tostring(evt[1]), 0) + 1)) if interactive then component.gpu.setForeground(0xB0B00F) end io.write(tostring(evt[2]) .. string.rep(" ", 37 - #tostring(evt[2]))) if interactive then component.gpu.setForeground(0xFFFFFF) end if evt.n > 2 then for i = 3, evt.n do io.write(" " .. tostring(evt[i])) end end io.write("\n") until evt[1] == "interrupted" end) if interactive then component.gpu.setForeground(color, isPal) end
mit
nesstea/darkstar
scripts/zones/Port_Windurst/npcs/Zoreen.lua
16
1411
----------------------------------- -- Area: Port Windurst -- NPC: Zoreen -- Regional Marchant NPC -- Only sells when Windurst controls Valdeaunia -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(VALDEAUNIA); if (RegionOwner ~= WINDURST) then player:showText(npc,ZOREEN_CLOSED_DIALOG); else player:showText(npc,ZOREEN_OPEN_DIALOG); stock = { 0x111E, 29, --Frost Turnip 0x027e, 170 --Sage } showShop(player,WINDURST,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
MetSystem/skynet
examples/share.lua
66
1702
local skynet = require "skynet" local sharedata = require "sharedata" local mode = ... if mode == "host" then skynet.start(function() skynet.error("new foobar") sharedata.new("foobar", { a=1, b= { "hello", "world" } }) skynet.fork(function() skynet.sleep(200) -- sleep 2s skynet.error("update foobar a = 2") sharedata.update("foobar", { a =2 }) skynet.sleep(200) -- sleep 2s skynet.error("update foobar a = 3") sharedata.update("foobar", { a = 3, b = { "change" } }) skynet.sleep(100) skynet.error("delete foobar") sharedata.delete "foobar" end) end) else skynet.start(function() skynet.newservice(SERVICE_NAME, "host") local obj = sharedata.query "foobar" local b = obj.b skynet.error(string.format("a=%d", obj.a)) for k,v in ipairs(b) do skynet.error(string.format("b[%d]=%s", k,v)) end -- test lua serialization local s = skynet.packstring(obj) local nobj = skynet.unpack(s) for k,v in pairs(nobj) do skynet.error(string.format("nobj[%s]=%s", k,v)) end for k,v in ipairs(nobj.b) do skynet.error(string.format("nobj.b[%d]=%s", k,v)) end for i = 1, 5 do skynet.sleep(100) skynet.error("second " ..i) for k,v in pairs(obj) do skynet.error(string.format("%s = %s", k , tostring(v))) end end local ok, err = pcall(function() local tmp = { b[1], b[2] } -- b is invalid , so pcall should failed end) if not ok then skynet.error(err) end -- obj. b is not the same with local b for k,v in ipairs(obj.b) do skynet.error(string.format("b[%d] = %s", k , tostring(v))) end collectgarbage() skynet.error("sleep") skynet.sleep(100) b = nil collectgarbage() skynet.error("sleep") skynet.sleep(100) skynet.exit() end) end
mit
nesstea/darkstar
scripts/globals/items/galkan_sausage.lua
18
2130
----------------------------------------- -- ID: 4395 -- Item: galkan_sausage -- Food Effect: 30Min, All Races ----------------------------------------- -- Multi-Race Effects -- Galka -- Strength 3 -- Intelligence -3 -- Attack % 25 -- Attack Cap 30 -- Ranged ATT % 25 -- Ranged ATT Cap 30 -- -- Other -- Strength 3 -- Intelligence -4 -- Attack 9 -- Ranged ATT 9 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4395); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) if (target:getRace() ~= 8) then target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -4); target:addMod(MOD_ATT, 9); target:addMod(MOD_RATT, 9); else target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 25); target:addMod(MOD_FOOD_ATT_CAP, 30); target:addMod(MOD_FOOD_RATTP, 25); target:addMod(MOD_FOOD_RATT_CAP, 30); end end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) if (target:getRace() ~= 8) then target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -4); target:addMod(MOD_ATT, 9); target:addMod(MOD_RATT, 9); else target:delMod(MOD_STR, 3); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 25); target:delMod(MOD_FOOD_ATT_CAP, 30); target:delMod(MOD_FOOD_RATTP, 25); target:delMod(MOD_FOOD_RATT_CAP, 30); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Al_Zahbi/npcs/Talruf.lua
13
1035
----------------------------------- -- Area: Al Zahbi -- NPC: Talruf -- Type: Standard NPC -- @zone: 48 -- @pos 100.878 -7 14.291 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00f3); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Samanj5/Assassin
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
Disslove-bot/Max3-BOT
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
Whit3Tig3R/BestSpammbot1
plugins/banhammer.lua
11
11337
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = '' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if member_id == our_id then return false end if get_cmd == 'kick' then if is_momod2(member_id, chat_id) then return send_large_msg(receiver, "you can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) then return send_large_msg(receiver, "you can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') return unbanall_user(member_id, chat_id) end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1]:lower() == 'id' then if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) else local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "group id : "..msg.to.id end end local receiver = get_receiver(msg) if matches[1]:lower() == 'kickme' then-- /kickme if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return nil end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(tonumber(matches[2]), msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'ban' local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end return 'User '..user_id..' banned' end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unban' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'kick' local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'banall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unbanall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
nesstea/darkstar
scripts/globals/items/prime_crab_stewpot.lua
18
1972
----------------------------------------- -- ID: 5545 -- Item: Prime Crab Stewpot -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 75 -- MP +15 -- Vitality +1 -- Agility +1 -- Mind +2 -- HP Recovered while healing +7 -- MP Recovered while healing +2 -- Defense 20% Cap 75 -- Evasion +6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5545); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 75); target:addMod(MOD_MP, 15); target:addMod(MOD_VIT, 1); target:addMod(MOD_AGI, 1); target:addMod(MOD_MND, 2); target:addMod(MOD_HPHEAL, 7); target:addMod(MOD_MPHEAL, 2); target:addMod(MOD_FOOD_DEFP, 20); target:addMod(MOD_FOOD_DEF_CAP, 75); target:addMod(MOD_EVA, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 75); target:delMod(MOD_MP, 15); target:delMod(MOD_VIT, 1); target:delMod(MOD_AGI, 1); target:delMod(MOD_MND, 2); target:delMod(MOD_HPHEAL, 7); target:delMod(MOD_MPHEAL, 2); target:delMod(MOD_FOOD_DEFP, 20); target:delMod(MOD_FOOD_DEF_CAP, 75); target:delMod(MOD_EVA, 6); end;
gpl-3.0
vonflynee/opencomputersserver
world/opencomputers/f6b12c72-550e-4c86-b7bc-3a72d250d375/lib/serialization.lua
15
3764
local serialization = {} -- Important: pretty formatting will allow presenting non-serializable values -- but may generate output that cannot be unserialized back. function serialization.serialize(value, pretty) local kw = {["and"]=true, ["break"]=true, ["do"]=true, ["else"]=true, ["elseif"]=true, ["end"]=true, ["false"]=true, ["for"]=true, ["function"]=true, ["goto"]=true, ["if"]=true, ["in"]=true, ["local"]=true, ["nil"]=true, ["not"]=true, ["or"]=true, ["repeat"]=true, ["return"]=true, ["then"]=true, ["true"]=true, ["until"]=true, ["while"]=true} local id = "^[%a_][%w_]*$" local ts = {} local function s(v, l) local t = type(v) if t == "nil" then return "nil" elseif t == "boolean" then return v and "true" or "false" elseif t == "number" then if v ~= v then return "0/0" elseif v == math.huge then return "math.huge" elseif v == -math.huge then return "-math.huge" else return tostring(v) end elseif t == "string" then return string.format("%q", v):gsub("\\\n","\\n") elseif t == "table" and pretty and getmetatable(v) and getmetatable(v).__tostring then return tostring(v) elseif t == "table" then if ts[v] then if pretty then return "recursion" else error("tables with cycles are not supported") end end ts[v] = true local i, r = 1, nil local f if pretty then local ks, sks, oks = {}, {}, {} for k in pairs(v) do if type(k) == "number" then table.insert(ks, k) elseif type(k) == "string" then table.insert(sks, k) else table.insert(oks, k) end end table.sort(ks) table.sort(sks) for _, k in ipairs(sks) do table.insert(ks, k) end for _, k in ipairs(oks) do table.insert(ks, k) end local n = 0 f = table.pack(function() n = n + 1 local k = ks[n] if k ~= nil then return k, v[k] else return nil end end) else f = table.pack(pairs(v)) end for k, v in table.unpack(f) do if r then r = r .. "," .. (pretty and ("\n" .. string.rep(" ", l)) or "") else r = "{" end local tk = type(k) if tk == "number" and k == i then i = i + 1 r = r .. s(v, l + 1) else if tk == "string" and not kw[k] and string.match(k, id) then r = r .. k else r = r .. "[" .. s(k, l + 1) .. "]" end r = r .. "=" .. s(v, l + 1) end end ts[v] = nil -- allow writing same table more than once return (r or "{") .. "}" else if pretty then return tostring(t) else error("unsupported type: " .. t) end end end local result = s(value, 1) local limit = type(pretty) == "number" and pretty or 10 if pretty then local truncate = 0 while limit > 0 and truncate do truncate = string.find(result, "\n", truncate + 1, true) limit = limit - 1 end if truncate then return result:sub(1, truncate) .. "..." end end return result end function serialization.unserialize(data) checkArg(1, data, "string") local result, reason = load("return " .. data, "=data", _, {math={huge=math.huge}}) if not result then return nil, reason end local ok, output = pcall(result) if not ok then return nil, output end return output end return serialization
mit
vonflynee/opencomputersserver
world/opencomputers/3f9e70c3-6961-48bd-bbb9-5c4b3888a254/lib/serialization.lua
15
3764
local serialization = {} -- Important: pretty formatting will allow presenting non-serializable values -- but may generate output that cannot be unserialized back. function serialization.serialize(value, pretty) local kw = {["and"]=true, ["break"]=true, ["do"]=true, ["else"]=true, ["elseif"]=true, ["end"]=true, ["false"]=true, ["for"]=true, ["function"]=true, ["goto"]=true, ["if"]=true, ["in"]=true, ["local"]=true, ["nil"]=true, ["not"]=true, ["or"]=true, ["repeat"]=true, ["return"]=true, ["then"]=true, ["true"]=true, ["until"]=true, ["while"]=true} local id = "^[%a_][%w_]*$" local ts = {} local function s(v, l) local t = type(v) if t == "nil" then return "nil" elseif t == "boolean" then return v and "true" or "false" elseif t == "number" then if v ~= v then return "0/0" elseif v == math.huge then return "math.huge" elseif v == -math.huge then return "-math.huge" else return tostring(v) end elseif t == "string" then return string.format("%q", v):gsub("\\\n","\\n") elseif t == "table" and pretty and getmetatable(v) and getmetatable(v).__tostring then return tostring(v) elseif t == "table" then if ts[v] then if pretty then return "recursion" else error("tables with cycles are not supported") end end ts[v] = true local i, r = 1, nil local f if pretty then local ks, sks, oks = {}, {}, {} for k in pairs(v) do if type(k) == "number" then table.insert(ks, k) elseif type(k) == "string" then table.insert(sks, k) else table.insert(oks, k) end end table.sort(ks) table.sort(sks) for _, k in ipairs(sks) do table.insert(ks, k) end for _, k in ipairs(oks) do table.insert(ks, k) end local n = 0 f = table.pack(function() n = n + 1 local k = ks[n] if k ~= nil then return k, v[k] else return nil end end) else f = table.pack(pairs(v)) end for k, v in table.unpack(f) do if r then r = r .. "," .. (pretty and ("\n" .. string.rep(" ", l)) or "") else r = "{" end local tk = type(k) if tk == "number" and k == i then i = i + 1 r = r .. s(v, l + 1) else if tk == "string" and not kw[k] and string.match(k, id) then r = r .. k else r = r .. "[" .. s(k, l + 1) .. "]" end r = r .. "=" .. s(v, l + 1) end end ts[v] = nil -- allow writing same table more than once return (r or "{") .. "}" else if pretty then return tostring(t) else error("unsupported type: " .. t) end end end local result = s(value, 1) local limit = type(pretty) == "number" and pretty or 10 if pretty then local truncate = 0 while limit > 0 and truncate do truncate = string.find(result, "\n", truncate + 1, true) limit = limit - 1 end if truncate then return result:sub(1, truncate) .. "..." end end return result end function serialization.unserialize(data) checkArg(1, data, "string") local result, reason = load("return " .. data, "=data", _, {math={huge=math.huge}}) if not result then return nil, reason end local ok, output = pcall(result) if not ok then return nil, output end return output end return serialization
mit
vonflynee/opencomputersserver
world/opencomputers/c0a0157a-e685-4d05-9dc9-9340cf29f413/lib/serialization.lua
15
3764
local serialization = {} -- Important: pretty formatting will allow presenting non-serializable values -- but may generate output that cannot be unserialized back. function serialization.serialize(value, pretty) local kw = {["and"]=true, ["break"]=true, ["do"]=true, ["else"]=true, ["elseif"]=true, ["end"]=true, ["false"]=true, ["for"]=true, ["function"]=true, ["goto"]=true, ["if"]=true, ["in"]=true, ["local"]=true, ["nil"]=true, ["not"]=true, ["or"]=true, ["repeat"]=true, ["return"]=true, ["then"]=true, ["true"]=true, ["until"]=true, ["while"]=true} local id = "^[%a_][%w_]*$" local ts = {} local function s(v, l) local t = type(v) if t == "nil" then return "nil" elseif t == "boolean" then return v and "true" or "false" elseif t == "number" then if v ~= v then return "0/0" elseif v == math.huge then return "math.huge" elseif v == -math.huge then return "-math.huge" else return tostring(v) end elseif t == "string" then return string.format("%q", v):gsub("\\\n","\\n") elseif t == "table" and pretty and getmetatable(v) and getmetatable(v).__tostring then return tostring(v) elseif t == "table" then if ts[v] then if pretty then return "recursion" else error("tables with cycles are not supported") end end ts[v] = true local i, r = 1, nil local f if pretty then local ks, sks, oks = {}, {}, {} for k in pairs(v) do if type(k) == "number" then table.insert(ks, k) elseif type(k) == "string" then table.insert(sks, k) else table.insert(oks, k) end end table.sort(ks) table.sort(sks) for _, k in ipairs(sks) do table.insert(ks, k) end for _, k in ipairs(oks) do table.insert(ks, k) end local n = 0 f = table.pack(function() n = n + 1 local k = ks[n] if k ~= nil then return k, v[k] else return nil end end) else f = table.pack(pairs(v)) end for k, v in table.unpack(f) do if r then r = r .. "," .. (pretty and ("\n" .. string.rep(" ", l)) or "") else r = "{" end local tk = type(k) if tk == "number" and k == i then i = i + 1 r = r .. s(v, l + 1) else if tk == "string" and not kw[k] and string.match(k, id) then r = r .. k else r = r .. "[" .. s(k, l + 1) .. "]" end r = r .. "=" .. s(v, l + 1) end end ts[v] = nil -- allow writing same table more than once return (r or "{") .. "}" else if pretty then return tostring(t) else error("unsupported type: " .. t) end end end local result = s(value, 1) local limit = type(pretty) == "number" and pretty or 10 if pretty then local truncate = 0 while limit > 0 and truncate do truncate = string.find(result, "\n", truncate + 1, true) limit = limit - 1 end if truncate then return result:sub(1, truncate) .. "..." end end return result end function serialization.unserialize(data) checkArg(1, data, "string") local result, reason = load("return " .. data, "=data", _, {math={huge=math.huge}}) if not result then return nil, reason end local ok, output = pcall(result) if not ok then return nil, output end return output end return serialization
mit
mrmost/mbc
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
LordError/LordError1
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
nesstea/darkstar
scripts/globals/items/plate_of_fatty_tuna_sushi.lua
17
1541
----------------------------------------- -- ID: 5153 -- Item: plate_of_fatty_tuna_sushi -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 20 -- Dexterity 3 -- Charisma 5 -- Accuracy % 16 -- Ranged ACC 16 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5153); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_CHR, 5); target:addMod(MOD_FOOD_ACCP, 16); target:addMod(MOD_RACC, 16); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_CHR, 5); target:delMod(MOD_FOOD_ACCP, 16); target:delMod(MOD_RACC, 16); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Promyvion-Dem/mobs/Memory_Receptacle.lua
7
7435
----------------------------------- -- Area: Promyvion-Dem -- MOB: Memory Receptacle -- Todo: clean up disgustingly bad formatting ----------------------------------- package.loaded["scripts/zones/Promyvion-Dem/TextIDs"] = nil; ----------------------------------- require( "scripts/zones/Promyvion-Dem/TextIDs" ); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 100); -- 10% Regain for now mob:SetAutoAttackEnabled(false); -- Recepticles only use TP moves. end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local Mem_Recep = mob:getID(); if (Mem_Recep == 16850971) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do -- Keep pets linked if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif (Mem_Recep == 16851025 or Mem_Recep == 16851032 or Mem_Recep == 16851039 or Mem_Recep == 16851046) then -- Floor 2 for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end elseif (Mem_Recep == 16851072 or Mem_Recep == 16851081 or Mem_Recep == 16851090 or Mem_Recep == 16851149 or Mem_Recep == 16851158 or -- Floor 3 Mem_Recep == 16851167) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 16) then GetMobByID(i):updateEnmity(target); end end end -- Summons a single stray every 30 seconds. if (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16850971) and mob:AnimationSub() == 2) then -- Floor 1 for i = Mem_Recep+1, Mem_Recep+3 do if (GetMobAction(i) == 0) then -- My Stray is deeaaaaaad! mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16851025 or Mem_Recep == 16851032 or Mem_Recep == 16851039 or -- Floor 2 Mem_Recep == 16851046) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+5 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle return; end end elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16851072 or Mem_Recep == 16851081 or Mem_Recep == 16851090 or -- Floor 3 Mem_Recep == 16851149 or Mem_Recep == 16851158 or Mem_Recep == 16851167) and mob:AnimationSub() == 2) then for i = Mem_Recep+1, Mem_Recep+7 do if (GetMobAction(i) == 0) then mob:AnimationSub(1); SpawnMob(i):updateEnmity(target); GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); return; end end else mob:AnimationSub(2); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local rand = 0; local mobID = mob:getID(); local difX = ally:getXPos()-mob:getXPos(); local difY = ally:getYPos()-mob:getYPos(); local difZ = ally:getZPos()-mob:getZPos(); local killeranimation = ally:getAnimation(); local Distance = math.sqrt( math.pow(difX,2) + math.pow(difY,2) + math.pow(difZ,2) ); --calcul de la distance entre les "killer" et le memory receptacle --print(mobID); mob:AnimationSub(0); -- Set ani. sub to default or the recepticles wont work properly if (VanadielMinute() % 2 == 1) then ally:setVar("MemoryReceptacle",2); rnd = 2; else ally:setVar("MemoryReceptacle",1); rnd = 1; end switch (mob:getID()) : caseof { [16850971] = function (x) GetNPCByID(16851268):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(30); end end, [16851025] = function (x) GetNPCByID(16851272):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd == 2) then ally:startEvent(35); else ally:startEvent(34); end end end, [16851032] = function (x) GetNPCByID(16851273):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd==2) then ally:startEvent(35); else ally:startEvent(34); end end end, [16851039] = function (x) GetNPCByID(16851274):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd==2) then ally:startEvent(35); else ally:startEvent(34); end end end, [16851046] = function (x) GetNPCByID(16851275):openDoor(180); if (Distance <4 and killeranimation == 0) then if (rnd==2) then ally:startEvent(35); else ally:startEvent(34); end end end, [16851072] = function (x) GetNPCByID(16851269):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(32); end end, [16851081] = function (x) GetNPCByID(16851270):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(32); end end, [16851090] = function (x) GetNPCByID(16851271):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(32); end end, [16851149] = function (x) GetNPCByID(16851276):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(32); end end, [16851158] = function (x) GetNPCByID(16851277):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(32); end end, [16851167] = function (x) GetNPCByID(16851278):openDoor(180); if (Distance <4 and killeranimation == 0) then ally:startEvent(32); end end, } end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ---------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (option==1) then player:setVar("MemoryReceptacle",0); end end;
gpl-3.0
nesstea/darkstar
scripts/globals/abilities/stay.lua
6
1383
----------------------------------- -- Ability: Stay -- Commands the Pet to stay in one place. -- Obtained: Beastmaster Level 15 -- Recast Time: 5 seconds -- Duration: Instant ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getPet() == nil) then return MSGBASIC_REQUIRES_A_PET,0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability,action) local pet = player:getPet(); if (not pet:hasPreventActionEffect()) then -- reduce tick speed based on level. but never less than 5 and never -- more than 10. This seems to mimic retail. There is no formula -- that I can find, but this seems close. local level = 0 if (player:getMainJob() == JOB_BST) then level = player:getMainLvl() elseif (player:getSubJob() == JOB_BST) then level = player:getSubLvl() end local tick = 10 - math.ceil(math.max(0, level / 20)) --printf('tick: %d', tick) pet:addStatusEffectEx(EFFECT_HEALING, 0, 0, tick, 0) pet:setAnimation(0) end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Abyssea-Attohwa/npcs/qm13.lua
17
1361
----------------------------------- -- Zone: Abyssea-Attohwa -- NPC: ??? -- Spawns: Smok ----------------------------------- require("scripts/globals/status"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(17658274) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(HOLLOW_DRAGON_EYE)) then player:startEvent(1022, HOLLOW_DRAGON_EYE); -- Ask if player wants to use KIs else player:startEvent(1023, HOLLOW_DRAGON_EYE); -- Do not ask, because player is missing at least 1. end end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1022 and option == 1) then SpawnMob(17658274):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(HOLLOW_DRAGON_EYE); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Spire_of_Vahzl/bcnms/desires_of_emptiness.lua
29
2295
----------------------------------- -- Area: Spire_of_VAHLZ -- Name: desires_of_emptiness ----------------------------------- package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Spire_of_Dem/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:addExp(1500); if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==8) then player:setVar("PromathiaStatus",9); player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0); else player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); -- Alreday finished this promy end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:addTitle(FROZEN_DEAD_BODY); player:setPos(-340 ,-100 ,137 ,67 ,111); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Middle_Delkfutts_Tower/TextIDs.lua
5
1147
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6542; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6545; -- Obtained: <item>. GIL_OBTAINED = 6546; -- Obtained <number> gil. KEYITEM_OBTAINED = 6548; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7199; -- You can't fish here. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7301; -- You unlock the chest! CHEST_FAIL = 7302; -- Fails to open the chest. CHEST_TRAP = 7303; -- The chest was trapped! CHEST_WEAK = 7304; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7305; -- The chest was a mimic! CHEST_MOOGLE = 7306; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7307; -- The chest was but an illusion... CHEST_LOCKED = 7308; -- The chest appears to be locked. -- Quest dialog NOTHING_OUT_OF_ORDINARY = 6559; -- There is nothing out of the ordinary here. SENSE_OF_FOREBODING = 6560; -- You are suddenly overcome with a sense of foreboding... -- conquest Base CONQUEST_BASE = 4;
gpl-3.0
nesstea/darkstar
scripts/zones/Windurst_Woods/npcs/Shih_Tayuun.lua
27
1188
----------------------------------- -- Area: Windurst Woods -- NPC: Shih Tayuun -- Guild Merchant NPC: Bonecrafting Guild -- @pos -3.064 -6.25 -131.374 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(514,8,23,3)) then player:showText(npc,SHIH_TAYUUN_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
focusworld/aabb
plugins/steam.lua
645
2117
-- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI do local BASE_URL = 'http://store.steampowered.com/api/appdetails/' local DESC_LENTH = 200 local function unescape(str) str = string.gsub( str, '&lt;', '<' ) str = string.gsub( str, '&gt;', '>' ) str = string.gsub( str, '&quot;', '"' ) str = string.gsub( str, '&apos;', "'" ) str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end ) str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end ) str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others return str end local function get_steam_data (appid) local url = BASE_URL url = url..'?appids='..appid url = url..'&cc=us' local res,code = http.request(url) if code ~= 200 then return nil end local data = json:decode(res)[appid].data return data end local function price_info (data) local price = '' -- If no data is empty if data then local initial = data.initial local final = data.final or data.initial local min = math.min(data.initial, data.final) price = tostring(min/100) if data.discount_percent and initial ~= final then price = price..data.currency..' ('..data.discount_percent..'% OFF)' end price = price..' (US)' end return price end local function send_steam_data(data, receiver) local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...' local title = data.name local price = price_info(data.price_overview) local text = title..' '..price..'\n'..description local image_url = data.header_image local cb_extra = { receiver = receiver, url = image_url } send_msg(receiver, text, send_photo_from_url_callback, cb_extra) end local function run(msg, matches) local appid = matches[1] local data = get_steam_data(appid) local receiver = get_receiver(msg) send_steam_data(data, receiver) end return { description = "Grabs Steam info for Steam links.", usage = "", patterns = { "http://store.steampowered.com/app/([0-9]+)", }, run = run } end
gpl-2.0
nesstea/darkstar
scripts/zones/Port_Bastok/npcs/Benita.lua
29
2144
----------------------------------- -- Area: Port Bastok -- NPC: Benita -- Starts Quest: The Wisdom Of Elders ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); BombAsh = trade:hasItemQty(928,1); if (count == 1 and BombAsh == true) then TheWisdom = player:getQuestStatus(BASTOK,THE_WISDOM_OF_ELDERS); TheWisdomVar = player:getVar("TheWisdomVar"); if (TheWisdom == 1 and TheWisdomVar == 2) then player:tradeComplete(); player:startEvent(0x00b0); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TheWisdom = player:getQuestStatus(BASTOK,THE_WISDOM_OF_ELDERS); pLevel = player:getMainLvl(); if (TheWisdom == 0 and pLevel >= 6) then player:startEvent(0x00ae); else rand = math.random(1,2); if (rand ==1) then player:startEvent(0x0066); else player:startEvent(0x0067); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00ae) then player:addQuest(BASTOK,THE_WISDOM_OF_ELDERS); player:setVar("TheWisdomVar",1); elseif (csid == 0x00b0) then player:completeQuest(BASTOK,THE_WISDOM_OF_ELDERS); player:addFame(BASTOK,120); player:addItem(12500); player:messageSpecial(ITEM_OBTAINED,12500); end end;
gpl-3.0
johnmccabe/dockercraft
world/Plugins/Core/console.lua
5
10580
-- console.lua -- Implements things related to console commands function HandleConsoleClear(Split) if (#Split == 1) then return true, "Usage: " .. Split[1] .. " <player>" end local InventoryCleared = false; local ClearInventory = function(Player) if (Player:GetName() == Split[2]) then Player:GetInventory():Clear() InventoryCleared = true end end cRoot:Get():FindAndDoWithPlayer(Split[2], ClearInventory); if (InventoryCleared) then return true, "You cleared the inventory of " .. Split[2] else return true, "Player not found" end end function HandleConsoleKick(Split) if (#Split < 2) then return true, "Usage: " .. Split[1] .. " <player> [reason ...]" end local Reason = cChatColor.Red .. "You have been kicked." if (#Split > 2) then Reason = table.concat(Split, " ", 3) end if (KickPlayer(Split[2], Reason)) then return true end return true, "Cannot find player " .. Split[2] end function HandleConsoleKill(Split) -- Check the params: if (#Split == 1) then return true, "Usage: " .. Split[1] .. " <player>" end -- Kill the player: local HasKilled = false; cRoot:Get():FindAndDoWithPlayer(Split[2], function(Player) if (Player:GetName() == Split[2]) then Player:TakeDamage(dtAdmin, nil, 1000, 1000, 0) HasKilled = true end end ); -- Report success or failure: if (HasKilled) then return true, "Player " .. Split[2] .. " is killed" else return true, "Player not found" end end function HandleConsoleList(Split) local PlayerTable = {} cRoot:Get():ForEachPlayer( function(a_Player) table.insert(PlayerTable, a_Player:GetName()) end ) table.sort(PlayerTable) local Out = "Players (" .. #PlayerTable .. "): " .. table.concat(PlayerTable, ", ") return true, Out end function HandleConsoleListGroups(a_Split) if (a_Split[3] ~= nil) then -- Too many params: return true, "Too many parameters. Usage: listgroups [rank]" end -- If no params are given, list all groups that the manager knows: local RankName = a_Split[2] if (RankName == nil) then -- Get all the groups: local Groups = cRankManager:GetAllGroups() -- Output the groups, concatenated to a string: local Out = "Available groups:\n" Out = Out .. table.concat(Groups, ", ") return true, Out end -- A rank name is given, list the groups in that rank: local Groups = cRankManager:GetRankGroups(RankName) local Out = "Groups in rank " .. RankName .. ":\n" .. table.concat(Groups, ", ") return true, Out end function HandleConsoleListRanks(Split) -- Get all the groups: local Groups = cRankManager:GetAllRanks() -- Output the groups, concatenated to a string: local Out = "Available ranks:\n" Out = Out .. table.concat(Groups, ", ") return true, Out end function HandleConsoleNumChunks(Split) -- List each world's chunk count into a table, sum the total chunk count: local Output = {} local Total = 0 cRoot:Get():ForEachWorld( function(a_World) table.insert(Output, a_World:GetName() .. ": " .. a_World:GetNumChunks() .. " chunks") Total = Total + a_World:GetNumChunks() end ) table.sort(Output) -- Return the complete report: return true, table.concat(Output, "\n") .. "\nTotal: " .. Total .. " chunks\n" end function HandleConsolePlayers(Split) local PlayersInWorlds = {} -- "WorldName" => [players array] local AddToTable = function(Player) local WorldName = Player:GetWorld():GetName() if (PlayersInWorlds[WorldName] == nil) then PlayersInWorlds[WorldName] = {} end table.insert(PlayersInWorlds[WorldName], Player:GetName() .. " @ " .. Player:GetIP()) end cRoot:Get():ForEachPlayer(AddToTable) local Out = "" for WorldName, Players in pairs(PlayersInWorlds) do Out = Out .. "World " .. WorldName .. ":\n" for i, PlayerName in ipairs(Players) do Out = Out .. " " .. PlayerName .. "\n" end end return true, Out end function HandleConsolePlugins(Split) -- Enumerate the plugins: local PluginTable = {} cPluginManager:Get():ForEachPlugin( function (a_CBPlugin) table.insert(PluginTable, { Name = a_CBPlugin:GetName(), Folder = a_CBPlugin:GetFolderName(), Status = a_CBPlugin:GetStatus(), LoadError = a_CBPlugin:GetLoadError() } ) end ) table.sort(PluginTable, function (a_Plugin1, a_Plugin2) return (string.lower(a_Plugin1.Folder) < string.lower(a_Plugin2.Folder)) end ) -- Prepare a translation table for the status: local StatusName = { [cPluginManager.psLoaded] = "Loaded ", [cPluginManager.psUnloaded] = "Unloaded", [cPluginManager.psError] = "Error ", [cPluginManager.psNotFound] = "NotFound", [cPluginManager.psDisabled] = "Disabled", } -- Generate the output: local Out = {} table.insert(Out, "There are ") table.insert(Out, #PluginTable) table.insert(Out, " plugins, ") table.insert(Out, cPluginManager:Get():GetNumLoadedPlugins()) table.insert(Out, " loaded:\n") for _, plg in ipairs(PluginTable) do table.insert(Out, " ") table.insert(Out, StatusName[plg.Status] or " ") table.insert(Out, " ") table.insert(Out, plg.Folder) if (plg.Name ~= plg.Folder) then table.insert(Out, " (API name ") table.insert(Out, plg.Name) table.insert(Out, ")") end if (plg.Status == cPluginManager.psError) then table.insert(Out, " ERROR: ") table.insert(Out, plg.LoadError or "<unknown>") end table.insert(Out, "\n") end return true, table.concat(Out, "") end function HandleConsoleRank(a_Split) -- Check parameters: if ((a_Split[2] == nil) or (a_Split[4] ~= nil)) then -- Not enough or too many parameters return true, "Usage: " .. Split[1] .. " <player> [rank]" end -- Translate the PlayerName to a UUID: local PlayerName = a_Split[2] local PlayerUUID if (cRoot:Get():GetServer():ShouldAuthenticate()) then -- The server is in online-mode, get the UUID from Mojang servers and check for validity: PlayerUUID = cMojangAPI:GetUUIDFromPlayerName(PlayerName) if ((PlayerUUID == nil) or (string.len(PlayerUUID) ~= 32)) then return true, "There is no such player: " .. PlayerName end else -- The server is in offline mode, generate an offline-mode UUID, no validity check is possible: PlayerUUID = cClientHandle:GenerateOfflineUUID(PlayerName) end -- View the player's rank, if requested: if (a_Split[3] == nil) then -- "/rank <PlayerName>" usage, display the rank: local CurrRank = cRankManager:GetPlayerRankName(PlayerUUID) if (CurrRank == "") then return true, "The player has no rank assigned to them." else return true, "The player's rank is " .. CurrRank end end -- Change the player's rank: local NewRank = a_Split[3] if not(cRankManager:RankExists(NewRank)) then return true, "The specified rank does not exist!" end cRankManager:SetPlayerRank(PlayerUUID, PlayerName, NewRank) -- Update all players in the game of the given name and let them know: cRoot:Get():ForEachPlayer( function(a_CBPlayer) if (a_CBPlayer:GetName() == PlayerName) then a_CBPlayer:SendMessageInfo("You were assigned the rank " .. NewRank .. " by the server console") a_CBPlayer:LoadRank() end end ) return true, "Player " .. PlayerName .. " is now in rank " .. NewRank end function HandleConsoleSaveAll(Split) cRoot:Get():SaveAllChunks() return true end function HandleConsoleSay(a_Split) cRoot:Get():BroadcastChat(cChatColor.Gold .. "[SERVER] " .. cChatColor.Yellow .. table.concat(a_Split, " ", 2)) return true end function HandleConsoleTeleport(Split) local TeleportToCoords = function(Player) if (Player:GetName() == Split[2]) then IsPlayerOnline = true Player:TeleportToCoords(Split[3], Split[4], Split[5]) end end local IsPlayerOnline = false; local FirstPlayerOnline = false; local GetPlayerCoords = function(Player) if (Player:GetName() == Split[3]) then PosX = Player:GetPosX() PosY = Player:GetPosY() PosZ = Player:GetPosZ() FirstPlayerOnline = true end end local TeleportToPlayer = function(Player) if (Player:GetName() == Split[2]) then Player:TeleportToCoords(PosX, PosY, PosZ) IsPlayerOnline = true end end if (#Split == 3) then cRoot:Get():FindAndDoWithPlayer(Split[3], GetPlayerCoords); if (FirstPlayerOnline) then cRoot:Get():FindAndDoWithPlayer(Split[2], TeleportToPlayer); if (IsPlayerOnline) then return true, "Teleported " .. Split[2] .." to " .. Split[3] end else return true, "Player " .. Split[3] .." not found" end elseif (#Split == 5) then cRoot:Get():FindAndDoWithPlayer(Split[2], TeleportToCoords); if (IsPlayerOnline) then return true, "You teleported " .. Split[2] .. " to [X:" .. Split[3] .. " Y:" .. Split[4] .. " Z:" .. Split[5] .. "]" else return true, "Player not found" end else return true, "Usage: '" .. Split[1] .. " <target player> <destination player>' or 'tp <target player> <x> <y> <z>'" end end function HandleConsoleUnload(Split) local UnloadChunks = function(World) World:QueueUnloadUnusedChunks() end local Out = "Num loaded chunks before: " .. cRoot:Get():GetTotalChunkCount() .. "\n" cRoot:Get():ForEachWorld(UnloadChunks) Out = Out .. "Num loaded chunks after: " .. cRoot:Get():GetTotalChunkCount() return true, Out end function HandleConsoleUnrank(a_Split) -- Check params: if ((a_Split[2] == nil) or (a_Split[3] ~= nil)) then -- Too few or too many parameters: return true, "Usage: " .. Split[1] .. " <player>" end -- Translate the PlayerName to a UUID: local PlayerName = a_Split[2] local PlayerUUID if (cRoot:Get():GetServer():ShouldAuthenticate()) then -- The server is in online-mode, get the UUID from Mojang servers and check for validity: PlayerUUID = cMojangAPI:GetUUIDFromPlayerName(PlayerName) if ((PlayerUUID == nil) or (string.len(PlayerUUID) ~= 32)) then return true, "There is no such player: " .. PlayerName end else -- The server is in offline mode, generate an offline-mode UUID, no validity check is possible: PlayerUUID = cClientHandle:GenerateOfflineUUID(PlayerName) end -- Unrank the player: cRankManager:RemovePlayerRank(PlayerUUID) -- Update all players in the game of the given name and let them know: cRoot:Get():ForEachPlayer( function(a_CBPlayer) if (a_CBPlayer:GetName() == PlayerName) then a_CBPlayer:SendMessageInfo("You were unranked by the server console") a_CBPlayer:LoadRank() end end ) return true, "Player " .. PlayerName .. " is now in the default rank." end
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/East_Ronfaure/npcs/Logging_Point.lua
29
1101
----------------------------------- -- Area: East Ronfaure -- NPC: Logging Point ----------------------------------- package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil; ------------------------------------- require("scripts/globals/logging"); require("scripts/zones/East_Ronfaure/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startLogging(player,player:getZoneID(),npc,trade,0x0385); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Dynamis_Lord.lua
13
1822
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Dynamis_Lord ----------------------------------- require("scripts/globals/status"); ----------------------------------- require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob,target) end; ----------------------------------- -- onMobRoam ----------------------------------- function onMobRoam(mob) --[[ if(mob:getExtraVar(1) <= os.time()) then DespawnMob(17330177); -- Despawn after 30min DespawnMob(17330183); DespawnMob(17330184); end ]] end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) SpawnMob(17330183):updateEnmity(target); -- Spawn Ying SpawnMob(17330184):updateEnmity(target); -- Spawn Yang end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) if(mob:getLocalVar("timeLimit") <= os.time()) then DespawnMob(17330177); -- Despawn after 30min DespawnMob(17330183); DespawnMob(17330184); end if(mob:getBattleTime() % 90 == 0) then if(GetMobAction(17330183) == 0) then SpawnMob(17330183):updateEnmity(target); -- Respawn Ying after 90sec end if(GetMobAction(17330184) == 0) then SpawnMob(17330184):updateEnmity(target); -- Respawn Yang after 90sec end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:addTitle(LIFTER_OF_SHADOWS); local npc = GetNPCByID(17330778); -- Spawn ??? npc:setPos(mob:getXPos(),mob:getYPos(),mob:getZPos()); npc:setStatus(0); end;
gpl-3.0
Mashape/kong
kong/templates/nginx_kong_stream.lua
1
2198
return [[ > if anonymous_reports then ${{SYSLOG_REPORTS}} > end log_format basic '$remote_addr [$time_local] ' '$protocol $status $bytes_sent $bytes_received ' '$session_time'; lua_package_path '${{LUA_PACKAGE_PATH}};;'; lua_package_cpath '${{LUA_PACKAGE_CPATH}};;'; lua_shared_dict stream_kong 5m; lua_shared_dict stream_kong_db_cache ${{MEM_CACHE_SIZE}}; > if database == "off" then lua_shared_dict stream_kong_db_cache_2 ${{MEM_CACHE_SIZE}}; > end lua_shared_dict stream_kong_db_cache_miss 12m; > if database == "off" then lua_shared_dict stream_kong_db_cache_miss_2 12m; > end lua_shared_dict stream_kong_locks 8m; lua_shared_dict stream_kong_process_events 5m; lua_shared_dict stream_kong_cluster_events 5m; lua_shared_dict stream_kong_healthchecks 5m; lua_shared_dict stream_kong_rate_limiting_counters 12m; > if database == "cassandra" then lua_shared_dict stream_kong_cassandra 5m; > end lua_shared_dict stream_prometheus_metrics 5m; # injected nginx_stream_* directives > for _, el in ipairs(nginx_stream_directives) do $(el.name) $(el.value); > end init_by_lua_block { -- shared dictionaries conflict between stream/http modules. use a prefix. local shared = ngx.shared ngx.shared = setmetatable({}, { __index = function(t, k) return shared["stream_"..k] end, }) Kong = require 'kong' Kong.init() } init_worker_by_lua_block { Kong.init_worker() } upstream kong_upstream { server 0.0.0.1:1; balancer_by_lua_block { Kong.balancer() } } server { > for i = 1, #stream_listeners do listen $(stream_listeners[i].listener); > end access_log ${{PROXY_ACCESS_LOG}} basic; error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}}; > for i = 1, #trusted_ips do set_real_ip_from $(trusted_ips[i]); > end # injected nginx_sproxy_* directives > for _, el in ipairs(nginx_sproxy_directives) do $(el.name) $(el.value); > end > if ssl_preread_enabled then ssl_preread on; > end preread_by_lua_block { Kong.preread() } proxy_pass kong_upstream; log_by_lua_block { Kong.log() } } ]]
apache-2.0
nesstea/darkstar
scripts/zones/Promyvion-Vahzl/npcs/_0mc.lua
13
1397
----------------------------------- -- Area: Promyvion vahzl -- NPC: Memory flux (1) ----------------------------------- package.loaded["scripts/zones/Promyvion-Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Promyvion-Vahzl/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==1) then SpawnMob(16867330,240):updateClaim(player); elseif (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==2) then player:startEvent(0x0033); else player:messageSpecial(OVERFLOWING_MEMORIES); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x0033) then player:setVar("PromathiaStatus",3); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Southern_San_dOria/npcs/Orechiniel.lua
32
1912
----------------------------------- -- Area: Southern San d'Oria -- NPC: Orechiniel -- Type: Leathercraft Adv. Synthesis Image Support ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,7); local SkillLevel = player:getSkillLevel(SKILL_LEATHERCRAFT); local Cost = getAdvImageSupportCost(player, SKILL_LEATHERCRAFT); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY) == false) then player:startEvent(0x028A,Cost,SkillLevel,0,239,player:getGil(),0,0,0); else player:startEvent(0x028A,Cost,SkillLevel,0,239,player:getGil(),28727,0,0); end else player:startEvent(0x028A); -- Standard Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local Cost = getAdvImageSupportCost(player, SKILL_LEATHERCRAFT); if (csid == 0x028A and option == 1) then player:delGil(Cost); player:messageSpecial(LEATHER_SUPPORT,0,5,0); player:addStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY,3,0,480); end end;
gpl-3.0
akdor1154/awesome
lib/menubar/utils.lua
1
9589
--------------------------------------------------------------------------- --- Utility module for menubar -- -- @author Antonio Terceiro -- @copyright 2009, 2011-2012 Antonio Terceiro, Alexander Yakushev -- @release @AWESOME_VERSION@ -- @module menubar.utils --------------------------------------------------------------------------- -- Grab environment local io = io local table = table local ipairs = ipairs local string = string local screen = screen local awful_util = require("awful.util") local theme = require("beautiful") local glib = require("lgi").GLib local wibox = require("wibox") local utils = {} -- NOTE: This icons/desktop files module was written according to the -- following freedesktop.org specifications: -- Icons: http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-0.11.html -- Desktop files: http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.0.html -- Options section --- Terminal which applications that need terminal would open in. utils.terminal = 'xterm' --- The default icon for applications that don't provide any icon in -- their .desktop files. local default_icon = nil --- Name of the WM for the OnlyShownIn entry in the .desktop file. utils.wm_name = "awesome" -- Private section local all_icon_sizes = { '128x128' , '96x96', '72x72', '64x64', '48x48', '36x36', '32x32', '24x24', '22x22', '16x16' } --- List of supported icon formats. local icon_formats = { "png", "xpm", "svg" } --- Check whether the icon format is supported. -- @param icon_file Filename of the icon. -- @return true if format is supported, false otherwise. local function is_format_supported(icon_file) for _, f in ipairs(icon_formats) do if icon_file:match('%.' .. f) then return true end end return false end local icon_lookup_path = nil --- Get a list of icon lookup paths. -- @treturn table A list of directories, without trailing slash. local function get_icon_lookup_path() if not icon_lookup_path then local add_if_readable = function(t, path) if awful_util.dir_readable(path) then table.insert(t, path) end end icon_lookup_path = {} local icon_theme_paths = {} local icon_theme = theme.icon_theme local paths = glib.get_system_data_dirs() table.insert(paths, 1, glib.get_user_data_dir()) table.insert(paths, 1, glib.build_filenamev({glib.get_home_dir(), '.icons'})) for _,dir in ipairs(paths) do local icons_dir = glib.build_filenamev({dir, 'icons'}) if awful_util.dir_readable(icons_dir) then if icon_theme then add_if_readable(icon_theme_paths, glib.build_filenamev({icons_dir, icon_theme})) end -- Fallback theme. add_if_readable(icon_theme_paths, glib.build_filenamev({icons_dir, 'hicolor'})) end end for _, icon_theme_directory in ipairs(icon_theme_paths) do for _, size in ipairs(all_icon_sizes) do add_if_readable(icon_lookup_path, glib.build_filenamev({icon_theme_directory, size, 'apps'})) end end for _,dir in ipairs(paths)do -- lowest priority fallbacks add_if_readable(icon_lookup_path, glib.build_filenamev({dir, 'pixmaps'})) add_if_readable(icon_lookup_path, glib.build_filenamev({dir, 'icons'})) end end return icon_lookup_path end --- Lookup an icon in different folders of the filesystem. -- @tparam string icon_file Short or full name of the icon. -- @treturn string|boolean Full name of the icon, or false on failure. function utils.lookup_icon_uncached(icon_file) if not icon_file or icon_file == "" then return false end if icon_file:sub(1, 1) == '/' and is_format_supported(icon_file) then -- If the path to the icon is absolute and its format is -- supported, do not perform a lookup. return awful_util.file_readable(icon_file) and icon_file or nil else for _, directory in ipairs(get_icon_lookup_path()) do if is_format_supported(icon_file) and awful_util.file_readable(directory .. "/" .. icon_file) then return directory .. "/" .. icon_file else -- Icon is probably specified without path and format, -- like 'firefox'. Try to add supported extensions to -- it and see if such file exists. for _, format in ipairs(icon_formats) do local possible_file = directory .. "/" .. icon_file .. "." .. format if awful_util.file_readable(possible_file) then return possible_file end end end end return false end end local lookup_icon_cache = {} --- Lookup an icon in different folders of the filesystem (cached). -- @param icon Short or full name of the icon. -- @return full name of the icon. function utils.lookup_icon(icon) if not lookup_icon_cache[icon] and lookup_icon_cache[icon] ~= false then lookup_icon_cache[icon] = utils.lookup_icon_uncached(icon) end return lookup_icon_cache[icon] or default_icon end --- Parse a .desktop file. -- @param file The .desktop file. -- @return A table with file entries. function utils.parse_desktop_file(file) local program = { show = true, file = file } local desktop_entry = false -- Parse the .desktop file. -- We are interested in [Desktop Entry] group only. for line in io.lines(file) do if line:find("^%s*#") then -- Skip comments. (function() end)() -- I haven't found a nice way to silence luacheck here elseif not desktop_entry and line == "[Desktop Entry]" then desktop_entry = true else if line:sub(1, 1) == "[" and line:sub(-1) == "]" then -- A declaration of new group - stop parsing break end -- Grab the values for key, value in line:gmatch("(%w+)%s*=%s*(.+)") do program[key] = value end end end -- In case [Desktop Entry] was not found if not desktop_entry then return nil end -- In case the (required) 'Name' entry was not found if not program.Name or program.Name == '' then return nil end -- Don't show program if NoDisplay attribute is false if program.NoDisplay and string.lower(program.NoDisplay) == "true" then program.show = false end -- Only show the program if there is no OnlyShowIn attribute -- or if it's equal to utils.wm_name if program.OnlyShowIn ~= nil and not program.OnlyShowIn:match(utils.wm_name) then program.show = false end -- Look up for a icon. if program.Icon then program.icon_path = utils.lookup_icon(program.Icon) end -- Split categories into a table. Categories are written in one -- line separated by semicolon. if program.Categories then program.categories = {} for category in program.Categories:gmatch('[^;]+') do table.insert(program.categories, category) end end if program.Exec then -- Substitute Exec special codes as specified in -- http://standards.freedesktop.org/desktop-entry-spec/1.1/ar01s06.html if program.Name == nil then program.Name = '['.. file:match("([^/]+)%.desktop$") ..']' end local cmdline = program.Exec:gsub('%%c', program.Name) cmdline = cmdline:gsub('%%[fuFU]', '') cmdline = cmdline:gsub('%%k', program.file) if program.icon_path then cmdline = cmdline:gsub('%%i', '--icon ' .. program.icon_path) else cmdline = cmdline:gsub('%%i', '') end if program.Terminal == "true" then cmdline = utils.terminal .. ' -e ' .. cmdline end program.cmdline = cmdline end return program end --- Parse a directory with .desktop files recursively. -- @tparam string dir The directory. -- @treturn table Paths of found .desktop files. function utils.parse_dir(dir) local programs = {} local files = io.popen('find '.. dir .." -name '*.desktop' 2>/dev/null") for file in files:lines() do local program = utils.parse_desktop_file(file) if program then table.insert(programs, program) end end return programs end --- Compute textbox width. -- @tparam wibox.widget.textbox textbox Textbox instance. -- @tparam number|screen s Screen -- @treturn int Text width. function utils.compute_textbox_width(textbox, s) s = screen[s or mouse.screen] local w, _ = textbox:get_preferred_size(s) return w end --- Compute text width. -- @tparam str text Text. -- @tparam number|screen s Screen -- @treturn int Text width. function utils.compute_text_width(text, s) return utils.compute_textbox_width(wibox.widget.textbox(awful_util.escape(text)), s) end return utils -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
johnmccabe/dockercraft
world/Plugins/APIDump/Hooks/OnBlockSpread.lua
23
1545
return { HOOK_BLOCK_SPREAD = { CalledWhen = "Called when a block spreads based on world conditions", DefaultFnName = "OnBlockSpread", -- also used as pagename Desc = [[ This hook is called when a block spreads.</p> <p> The spread carries with it the type of its source - whether it's a block spreads. It also carries the identification of the actual source. The exact type of the identification depends on the source kind: <table> <tr><th>Source</th><th>Notes</th></tr> <tr><td>ssFireSpread</td><td>Fire spreading</td></tr> <tr><td>ssGrassSpread</td><td>Grass spreading</td></tr> <tr><td>ssMushroomSpread</td><td>Mushroom spreading</td></tr> <tr><td>ssMycelSpread</td><td>Mycel spreading</td></tr> <tr><td>ssVineSpread</td><td>Vine spreading</td></tr> </table></p> ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the block resides" }, { Name = "BlockX", Type = "number", Notes = "X-coord of the block" }, { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" }, { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" }, { Name = "Source", Type = "eSpreadSource", Notes = "Source of the spread. See the table above." }, }, Returns = [[ If the function returns false or no value, the next plugin's callback is called, and finally Cuberite will process the spread. If the function returns true, no other callback is called for this event and the spread will not occur. ]], }, -- HOOK_BLOCK_SPREAD }
apache-2.0
nesstea/darkstar
scripts/zones/Lower_Jeuno/npcs/Akamafula.lua
13
1330
----------------------------------- -- Area: Lower Jeuno -- NPC: Akamafula -- Type: Tenshodo Merchant -- @pos 28.465 2.899 -46.699 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/keyitems"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then if (player:sendGuild(60417,1,23,1)) then player:showText(npc, AKAMAFULA_SHOP_DIALOG); end else -- player:startEvent(0x0096); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/West_Ronfaure/npcs/Molting_Moth_IM.lua
30
3047
----------------------------------- -- Area: West Ronfaure -- NPC: Molting Moth, I.M. -- Border Conquest Guards -- @pos -560.292 -0.961 -576.655 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Ronfaure/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = RONFAURE; local csid = 0x7ff8; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
DevCobra/Cobra.iraq
plugin/admin.lua
1
10192
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Function to add log supergroup local function logadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local GBan_log = 'GBan_log' if not data[tostring(GBan_log)] then data[tostring(GBan_log)] = {} save_data(_config.moderation.data, data) end data[tostring(GBan_log)][tostring(msg.to.id)] = msg.to.peer_id save_data(_config.moderation.data, data) local text = 'Log_SuperGroup has has been set!' reply_msg(msg.id,text,ok_cb,false) return end --Function to remove log supergroup local function logrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local GBan_log = 'GBan_log' if not data[tostring(GBan_log)] then data[tostring(GBan_log)] = nil save_data(_config.moderation.data, data) end data[tostring(GBan_log)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'Log_SuperGroup has has been removed!' reply_msg(msg.id,text,ok_cb,false) return end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairsByKeys(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function reload_plugins( ) plugins = {} return load_plugins() end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id local print_name = user_print_name(msg.from):gsub("?", "") local name_log = print_name:gsub("_", " ") if not is_admin1(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then local text = "Message From "..(msg.from.username or msg.from.last_name).."\n\nMessage : "..matches[3] send_large_msg("user#id"..matches[2],text) return "Message has been sent" end if matches[1] == "pmblock" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "pmunblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then if not is_sudo(msg) then-- Sudo only return end get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then if not is_sudo(msg) then-- Sudo only return end del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "addcontact" and is_sudo(msg) then phone = matches[2] first_name = matches[3] last_name = matches[4] add_contact(phone, first_name, last_name, ok_cb, false) return "User With Phone +"..matches[2].." has been added" end if matches[1] == "sendcontact" and is_sudo(msg) then phone = matches[2] first_name = matches[3] last_name = matches[4] send_contact(get_receiver(msg), phone, first_name, last_name, ok_cb, false) end if matches[1] == "mycontact" and is_sudo(msg) then if not msg.from.phone then return "I must Have Your Phone Number!" end phone = msg.from.phone first_name = (msg.from.first_name or msg.from.phone) last_name = (msg.from.last_name or msg.from.id) send_contact(get_receiver(msg), phone, first_name, last_name, ok_cb, false) end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent a group dialog list with both json and text format to your private messages" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end if matches[1] == "sync_gbans" then if not is_sudo(msg) then-- Sudo only return end local url = "http://seedteam.org/Teleseed/Global_bans.json" local SEED_gbans = http.request(url) local jdat = json:decode(SEED_gbans) for k,v in pairs(jdat) do redis:hset('user:'..v, 'print_name', k) banall_user(v) print(k, v.." Globally banned") end end if matches[1] == 'reload' then receiver = get_receiver(msg) reload_plugins(true) post_msg(receiver, "Reloaded!", ok_cb, false) return "Reloaded!" end --[[*For Debug* if matches[1] == "vardumpmsg" and is_admin1(msg) then local text = serpent.block(msg, {comment=false}) send_large_msg("channel#id"..msg.to.id, text) end]] if matches[1] == 'updateid' then local data = load_data(_config.moderation.data) local long_id = data[tostring(msg.to.id)]['long_id'] if not long_id then data[tostring(msg.to.id)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) return "Updated ID" end end if matches[1] == 'addlog' and not matches[2] then if is_log_group(msg) then return "Already a Log_SuperGroup" end print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup") logadd(msg) end if matches[1] == 'remlog' and not matches[2] then if not is_log_group(msg) then return "Not a Log_SuperGroup" end print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") removed") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup") logrem(msg) end return end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/](pm) (%d+) (.*)$", "^[#!/](import) (.*)$", "^[#!/](pmunblock) (%d+)$", "^[#!/](pmblock) (%d+)$", "^[#!/](markread) (on)$", "^[#!/](markread) (off)$", "^[#!/](setbotphoto)$", "^[#!/](contactlist)$", "^[#!/](dialoglist)$", "^[#!/](delcontact) (%d+)$", "^[#!/](addcontact) (.*) (.*) (.*)$", "^[#!/](sendcontact) (.*) (.*) (.*)$", "^[#!/](mycontact)$", "^[#/!](reload)$", "^[#/!](updateid)$", "^[#/!](sync_gbans)$", "^[#/!](addlog)$", "^[#/!](remlog)$", "%[(photo)%]", }, run = run, pre_process = pre_process } --By @G0vip :)
gpl-2.0
nesstea/darkstar
scripts/zones/Den_of_Rancor/npcs/_4g3.lua
27
2358
----------------------------------- -- Area: Den of Rancor -- NPC: Lantern (SW) -- @pos -59 45 24 160 ----------------------------------- package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Den_of_Rancor/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local Lantern_ID = 17433047 local LSW = GetNPCByID(Lantern_ID):getAnimation(); local LNW = GetNPCByID(Lantern_ID+1):getAnimation(); local LNE = GetNPCByID(Lantern_ID+2):getAnimation(); local LSE = GetNPCByID(Lantern_ID+3):getAnimation(); -- Trade Crimson Rancor Flame if (trade:hasItemQty(1139,1) and trade:getItemCount() == 1) then if (LSW == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit elseif (LSW == 9) then npc:openDoor(LANTERNS_STAY_LIT); local ALL = LNW+LNE+LSE; player:tradeComplete(); player:addItem(1138); -- Unlit Lantern if ALL == 27 then player:messageSpecial(LANTERN_OFFSET + 9); elseif ALL == 26 then player:messageSpecial(LANTERN_OFFSET + 10); elseif ALL == 25 then player:messageSpecial(LANTERN_OFFSET + 11); elseif ALL == 24 then player:messageSpecial(LANTERN_OFFSET + 12); GetNPCByID(Lantern_ID+3):closeDoor(1); GetNPCByID(Lantern_ID+2):closeDoor(1); GetNPCByID(Lantern_ID+1):closeDoor(1); GetNPCByID(Lantern_ID):closeDoor(1); GetNPCByID(Lantern_ID+4):openDoor(30); GetNPCByID(Lantern_ID+3):openDoor(30); GetNPCByID(Lantern_ID+2):openDoor(30); GetNPCByID(Lantern_ID+1):openDoor(30); GetNPCByID(Lantern_ID):openDoor(30); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local npca = npc:getAnimation() if (npca == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit else player:messageSpecial(LANTERN_OFFSET + 20); -- unlit end return 0; end;
gpl-3.0
Mashape/kong
spec/03-plugins/13-cors/01-access_spec.lua
1
34056
local helpers = require "spec.helpers" local cjson = require "cjson" local inspect = require "inspect" local tablex = require "pl.tablex" local CORS_DEFAULT_METHODS = "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS,TRACE,CONNECT" local function sortedpairs(t) local ks = tablex.keys(t) table.sort(ks) local i = 0 return function() i = i + 1 return ks[i], t[ks[i]] end end for _, strategy in helpers.each_strategy() do describe("Plugin: cors (access) [#" .. strategy .. "]", function() local proxy_client local regex_testcases = { { -- single entry, host only: ignore value, always return configured data origins = { "foo.test" }, tests = { ["http://evil.test"] = "foo.test", ["http://foo.test"] = "foo.test", ["http://foo.test.evil.test"] = "foo.test", ["http://something.foo.test"] = "foo.test", ["http://evilfoo.test"] = "foo.test", ["http://foo.test:80"] = "foo.test", ["http://foo.test:8000"] = "foo.test", ["https://foo.test:8000"] = "foo.test", ["http://foo.test:90"] = "foo.test", ["http://foobtest"] = "foo.test", ["https://bar.test:1234"] = "foo.test", }, }, { -- single entry, full domain (not regex): ignore value, always return configured data origins = { "https://bar.test:1234" }, tests = { ["http://evil.test"] = "https://bar.test:1234", ["http://foo.test"] = "https://bar.test:1234", ["http://foo.test.evil.test"] = "https://bar.test:1234", ["http://something.foo.test"] = "https://bar.test:1234", ["http://evilfoo.test"] = "https://bar.test:1234", ["http://foo.test:80"] = "https://bar.test:1234", ["http://foo.test:8000"] = "https://bar.test:1234", ["https://foo.test:8000"] = "https://bar.test:1234", ["http://foo.test:90"] = "https://bar.test:1234", ["http://foobtest"] = "https://bar.test:1234", ["https://bar.test:1234"] = "https://bar.test:1234", }, }, { -- single entry, simple regex without ":": anchored match on host only origins = { "foo\\.test" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = true, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = false, ["http://evilfoo.test"] = false, ["http://foo.test:80"] = "http://foo.test", ["http://foo.test:8000"] = true, ["https://foo.test:8000"] = true, ["http://foo.test:90"] = true, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- single entry, subdomain regex without ":": anchored match on host only origins = { "(.*[./])?foo\\.test" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = true, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = true, ["http://evilfoo.test"] = false, ["http://foo.test:80"] = "http://foo.test", ["http://foo.test:8000"] = true, ["https://foo.test:8000"] = true, ["http://foo.test:90"] = true, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- single entry, any-scheme subdomain regex with port: anchored match with scheme and port origins = { "(.*[./])?foo\\.test:8000" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = false, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = false, ["http://evilfoo.test"] = false, ["http://foo.test:80"] = false, ["http://foo.test:8000"] = true, ["https://foo.test:8000"] = true, ["http://foo.test:90"] = false, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- single entry, https subdomain regex with port: anchored match with scheme and port origins = { "https://(.*[.])?foo\\.test:8000" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = false, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = false, ["http://foo.test:80"] = false, ["http://foo.test:8000"] = false, ["https://foo.test:8000"] = true, ["http://foo.test:90"] = false, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- single entry, explicitly anchored https subdomain regex with port: anchored match with scheme and port origins = { "^http://(.*[.])?foo\\.test(:(80|90))?$" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = true, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = true, ["http://foo.test:80"] = "http://foo.test", ["http://foo.test:8000"] = false, ["https://foo.test:8000"] = false, ["http://foo.test:90"] = true, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- multiple entries, host only (not regex): match on full normalized domain (i.e. all fail) origins = { "foo.test", "bar.test" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = false, ["http://foo.test.evil.test"] = false, ["http://foo.test:80"] = false, ["http://foo.test:8000"] = false, ["http://foo.test:90"] = false, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- multiple entries, full domain (not regex): match on full normalized domain origins = { "http://foo.test", "https://bar.test:1234" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = true, ["http://foo.test.evil.test"] = false, ["http://foo.test:80"] = "http://foo.test", ["http://foo.test:8000"] = false, ["http://foo.test:90"] = false, ["http://foobtest"] = false, ["https://bar.test:1234"] = true, }, }, { -- multiple entries, simple regex without ":": anchored match on host only origins = { "bar.test", "foo\\.test" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = true, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = false, ["http://foo.test:80"] = "http://foo.test", ["http://foo.test:8000"] = true, ["http://foo.test:90"] = true, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- multiple entries, subdomain regex without ":": anchored match on host only origins = { "bar.test", "(.*\\.)?foo\\.test" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = true, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = true, ["http://foo.test:80"] = "http://foo.test", ["http://foo.test:8000"] = true, ["http://foo.test:90"] = true, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- multiple entries, any-scheme subdomain regex with ":": anchored match with scheme and port origins = { "bar.test", "(.*[./])?foo\\.test:8000" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = false, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = false, ["http://foo.test:80"] = false, ["http://foo.test:8000"] = true, ["https://foo.test:8000"] = true, ["http://foo.test:90"] = false, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, { -- multiple entries, https subdomain regex with ":": anchored match with scheme and port origins = { "bar.test", "https://(.*\\.)?foo\\.test:8000" }, tests = { ["http://evil.test"] = false, ["http://foo.test"] = false, ["http://foo.test.evil.test"] = false, ["http://something.foo.test"] = false, ["http://foo.test:80"] = false, ["http://foo.test:8000"] = false, ["https://foo.test:8000"] = true, ["http://foo.test:90"] = false, ["http://foobtest"] = false, ["https://bar.test:1234"] = false, }, }, } lazy_setup(function() local bp = helpers.get_db_utils(strategy, nil, { "error-generator-last" }) local route1 = bp.routes:insert({ hosts = { "cors1.com" }, }) local route2 = bp.routes:insert({ hosts = { "cors2.com" }, }) local route3 = bp.routes:insert({ hosts = { "cors3.com" }, }) local route4 = bp.routes:insert({ hosts = { "cors4.com" }, }) local route5 = bp.routes:insert({ hosts = { "cors5.com" }, }) local route6 = bp.routes:insert({ hosts = { "cors6.com" }, }) local route7 = bp.routes:insert({ hosts = { "cors7.com" }, }) local route8 = bp.routes:insert({ hosts = { "cors-empty-origins.com" }, }) local route9 = bp.routes:insert({ hosts = { "cors9.com" }, }) local route10 = bp.routes:insert({ hosts = { "cors10.com" }, }) local route11 = bp.routes:insert({ hosts = { "cors11.com" }, }) local mock_service = bp.services:insert { host = "127.0.0.2", port = 26865, } local route_timeout = bp.routes:insert { hosts = { "cors-timeout.com" }, service = mock_service, } local route_error = bp.routes:insert { hosts = { "cors-error.com" }, } bp.plugins:insert { name = "cors", route = { id = route1.id }, } bp.plugins:insert { name = "cors", route = { id = route2.id }, config = { origins = { "example.com" }, methods = { "GET" }, headers = { "origin", "type", "accepts" }, exposed_headers = { "x-auth-token" }, max_age = 23, credentials = true } } bp.plugins:insert { name = "cors", route = { id = route3.id }, config = { origins = { "example.com" }, methods = { "GET" }, headers = { "origin", "type", "accepts" }, exposed_headers = { "x-auth-token" }, max_age = 23, preflight_continue = true } } bp.plugins:insert { name = "cors", route = { id = route4.id }, } bp.plugins:insert { name = "key-auth", route = { id = route4.id } } bp.plugins:insert { name = "cors", route = { id = route5.id }, config = { origins = { "*" }, credentials = true } } bp.plugins:insert { name = "cors", route = { id = route6.id }, config = { origins = { "example.com", "example.org" }, methods = { "GET" }, headers = { "origin", "type", "accepts" }, exposed_headers = { "x-auth-token" }, max_age = 23, preflight_continue = true } } bp.plugins:insert { name = "cors", route = { id = route7.id }, config = { origins = { "*" }, credentials = false } } bp.plugins:insert { name = "cors", route = { id = route8.id }, config = { origins = {}, } } bp.plugins:insert { name = "cors", route = { id = route9.id }, config = { origins = { [[.*\.?example(?:-foo)?.com]] }, } } bp.plugins:insert { name = "cors", route = { id = route10.id }, config = { origins = { "http://my-site.com", "http://my-other-site.com" }, } } bp.plugins:insert { name = "cors", route = { id = route11.id }, config = { origins = { "http://my-site.com", "https://my-other-site.com:9000" }, } } bp.plugins:insert { name = "cors", route = { id = route_timeout.id }, config = { origins = { "example.com" }, methods = { "GET" }, headers = { "origin", "type", "accepts" }, exposed_headers = { "x-auth-token" }, max_age = 10, preflight_continue = true } } bp.plugins:insert { name = "cors", route = { id = route_error.id }, config = { origins = { "example.com" }, methods = { "GET" }, headers = { "origin", "type", "accepts" }, exposed_headers = { "x-auth-token" }, max_age = 10, preflight_continue = true } } bp.plugins:insert { name = "error-generator-last", route = { id = route_error.id }, config = { access = true, }, } for i, testcase in ipairs(regex_testcases) do local route = bp.routes:insert({ hosts = { "cors-regex-" .. i .. ".test" }, }) bp.plugins:insert { name = "cors", route = { id = route.id }, config = { origins = testcase.origins, } } end assert(helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", })) end) lazy_teardown(function() helpers.stop_kong() end) before_each(function() proxy_client = helpers.proxy_client() end) after_each(function() if proxy_client then proxy_client:close() end end) describe("HTTP method: OPTIONS", function() for i, testcase in ipairs(regex_testcases) do local host = "cors-regex-" .. i .. ".test" for origin, accept in sortedpairs(testcase.tests) do it("given " .. origin .. ", " .. inspect(testcase.origins) .. " will " .. (accept and "accept" or "reject"), function() local res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = host, ["Origin"] = origin, ["Access-Control-Request-Method"] = "GET", } }) assert.res_status(200, res) if accept then assert.equal(CORS_DEFAULT_METHODS, res.headers["Access-Control-Allow-Methods"]) assert.equal(accept == true and origin or accept, res.headers["Access-Control-Allow-Origin"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) else assert.is_nil(res.headers["Access-Control-Allow-Origin"]) end end) end end it("gives appropriate defaults", function() local res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = "cors1.com", ["Origin"] = "origin1.com", ["Access-Control-Request-Method"] = "GET", } }) assert.res_status(200, res) assert.equal("0", res.headers["Content-Length"]) assert.equal(CORS_DEFAULT_METHODS, res.headers["Access-Control-Allow-Methods"]) assert.equal("*", res.headers["Access-Control-Allow-Origin"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) assert.is_nil(res.headers["Vary"]) end) it("gives * wildcard when config.origins is empty", function() -- this test covers a regression introduced in 0.10.1, where -- the 'multiple_origins' migration would always insert a table -- (that might be empty) in the 'config.origins' field, and the -- * wildcard would only been sent when said table was **nil**, -- and not necessarily empty. local res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = "cors-empty-origins.com", ["Origin"] = "empty-origin.com", ["Access-Control-Request-Method"] = "GET", } }) assert.res_status(200, res) assert.equal("0", res.headers["Content-Length"]) assert.equal(CORS_DEFAULT_METHODS, res.headers["Access-Control-Allow-Methods"]) assert.equal("*", res.headers["Access-Control-Allow-Origin"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) assert.is_nil(res.headers["Vary"]) end) it("gives appropriate defaults when origin is explicitly set to *", function() local res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = "cors5.com", ["Origin"] = "origin5.com", ["Access-Control-Request-Method"] = "GET", } }) assert.res_status(200, res) assert.equal("0", res.headers["Content-Length"]) assert.equal(CORS_DEFAULT_METHODS, res.headers["Access-Control-Allow-Methods"]) assert.equal("origin5.com", res.headers["Access-Control-Allow-Origin"]) assert.equal("true", res.headers["Access-Control-Allow-Credentials"]) assert.equal("Origin", res.headers["Vary"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) end) it("accepts config options", function() local res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = "cors2.com", ["Origin"] = "origin5.com", ["Access-Control-Request-Method"] = "GET", } }) assert.res_status(200, res) assert.equal("0", res.headers["Content-Length"]) assert.equal("GET", res.headers["Access-Control-Allow-Methods"]) assert.equal("example.com", res.headers["Access-Control-Allow-Origin"]) assert.equal("23", res.headers["Access-Control-Max-Age"]) assert.equal("true", res.headers["Access-Control-Allow-Credentials"]) assert.equal("origin,type,accepts", res.headers["Access-Control-Allow-Headers"]) assert.equal("Origin", res.headers["Vary"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) end) it("preflight_continue enabled", function() local res = assert(proxy_client:send { method = "OPTIONS", path = "/status/201", headers = { ["Host"] = "cors3.com" } }) local body = assert.res_status(201, res) local json = cjson.decode(body) assert.equal(201, json.code) end) it("replies with request-headers if present in request", function() local res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = "cors5.com", ["Origin"] = "origin5.com", ["Access-Control-Request-Headers"] = "origin,accepts", ["Access-Control-Request-Method"] = "GET", } }) assert.res_status(200, res) assert.equal("0", res.headers["Content-Length"]) assert.equal("origin,accepts", res.headers["Access-Control-Allow-Headers"]) end) it("properly validates flat strings", function() -- Legitimate origins local res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = "cors10.com", ["Origin"] = "http://my-site.com" } }) assert.res_status(200, res) assert.equal("http://my-site.com", res.headers["Access-Control-Allow-Origin"]) -- Illegitimate origins res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = "cors10.com", ["Origin"] = "http://bad-guys.com" } }) assert.res_status(200, res) assert.is_nil(res.headers["Access-Control-Allow-Origin"]) -- Tricky illegitimate origins res = assert(proxy_client:send { method = "OPTIONS", headers = { ["Host"] = "cors10.com", ["Origin"] = "http://my-site.com.bad-guys.com" } }) assert.res_status(200, res) assert.is_nil(res.headers["Access-Control-Allow-Origin"]) end) end) describe("HTTP method: others", function() it("gives appropriate defaults", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors1.com" } }) assert.res_status(200, res) assert.equal("*", res.headers["Access-Control-Allow-Origin"]) assert.is_nil(res.headers["Access-Control-Allow-Methods"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) assert.is_nil(res.headers["Vary"]) end) it("proxies a non-preflight OPTIONS request", function() local res = assert(proxy_client:send { method = "OPTIONS", path = "/anything", headers = { ["Host"] = "cors1.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("OPTIONS", json.vars.request_method) assert.equal("*", res.headers["Access-Control-Allow-Origin"]) assert.is_nil(res.headers["Access-Control-Allow-Methods"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) assert.is_nil(res.headers["Vary"]) end) it("accepts config options", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors2.com" } }) assert.res_status(200, res) assert.equal("example.com", res.headers["Access-Control-Allow-Origin"]) assert.equal("x-auth-token", res.headers["Access-Control-Expose-Headers"]) assert.equal("true", res.headers["Access-Control-Allow-Credentials"]) assert.equal("Origin", res.headers["Vary"]) assert.is_nil(res.headers["Access-Control-Allow-Methods"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) end) it("works even when upstream timeouts", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors-timeout.com" } }) assert.res_status(502, res) assert.equal("example.com", res.headers["Access-Control-Allow-Origin"]) assert.equal("x-auth-token", res.headers["Access-Control-Expose-Headers"]) assert.equal("Origin", res.headers["Vary"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Allow-Methods"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) end) it("works even when a runtime error occurs", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors-error.com" } }) assert.res_status(500, res) assert.equal("example.com", res.headers["Access-Control-Allow-Origin"]) assert.equal("x-auth-token", res.headers["Access-Control-Expose-Headers"]) assert.equal("Origin", res.headers["Vary"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Allow-Methods"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) end) it("works with 404 responses", function() local res = assert(proxy_client:send { method = "GET", path = "/asdasdasd", headers = { ["Host"] = "cors1.com" } }) assert.res_status(404, res) assert.equal("*", res.headers["Access-Control-Allow-Origin"]) assert.is_nil(res.headers["Access-Control-Allow-Methods"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) assert.is_nil(res.headers["Vary"]) end) it("works with 40x responses returned by another plugin", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors4.com" } }) assert.res_status(401, res) assert.equal("*", res.headers["Access-Control-Allow-Origin"]) assert.is_nil(res.headers["Access-Control-Allow-Methods"]) assert.is_nil(res.headers["Access-Control-Allow-Headers"]) assert.is_nil(res.headers["Access-Control-Expose-Headers"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Access-Control-Max-Age"]) assert.is_nil(res.headers["Vary"]) end) it("sets CORS orgin based on origin host", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors6.com", ["Origin"] = "example.com" } }) assert.res_status(200, res) assert.equal("example.com", res.headers["Access-Control-Allow-Origin"]) assert.equal("Origin", res.headers["Vary"]) local domains = { ["example.com"] = true, ["www.example.com"] = true, ["example-foo.com"] = true, ["www.example-foo.com"] = true, ["www.example-fo0.com"] = false, } for domain in pairs(domains) do local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors9.com", ["Origin"] = domain } }) assert.res_status(200, res) assert.equal(domains[domain] and domain or nil, res.headers["Access-Control-Allow-Origin"]) assert.equal("Origin", res.headers["Vary"]) end end) it("does not automatically parse the host", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors6.com", ["Origin"] = "http://example.com" } }) assert.res_status(200, res) assert.is_nil(res.headers["Access-Control-Allow-Origin"]) -- With a different transport too local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors6.com", ["Origin"] = "https://example.com" } }) assert.res_status(200, res) assert.is_nil(res.headers["Access-Control-Allow-Origin"]) end) it("validates scheme and port", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors11.com", ["Origin"] = "http://my-site.com" } }) assert.res_status(200, res) assert.equals("http://my-site.com", res.headers["Access-Control-Allow-Origin"]) local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors11.com", ["Origin"] = "http://my-site.com:80" } }) assert.res_status(200, res) assert.equals("http://my-site.com", res.headers["Access-Control-Allow-Origin"]) local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors11.com", ["Origin"] = "http://my-site.com:8000" } }) assert.res_status(200, res) assert.is_nil(res.headers["Access-Control-Allow-Origin"]) res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors11.com", ["Origin"] = "https://my-site.com" } }) assert.res_status(200, res) assert.is_nil(res.headers["Access-Control-Allow-Origin"]) local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors11.com", ["Origin"] = "https://my-other-site.com:9000" } }) assert.res_status(200, res) assert.equals("https://my-other-site.com:9000", res.headers["Access-Control-Allow-Origin"]) local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors11.com", ["Origin"] = "https://my-other-site.com:9001" } }) assert.res_status(200, res) assert.is_nil(res.headers["Access-Control-Allow-Origin"]) end) it("does not sets CORS orgin if origin host is not in origin_domains list", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors6.com", ["Origin"] = "http://www.example.net" } }) assert.res_status(200, res) assert.is_nil(res.headers["Access-Control-Allow-Origin"]) end) it("responds with the requested Origin when config.credentials=true", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors5.com", ["Origin"] = "http://www.example.net" } }) assert.res_status(200, res) assert.equals("http://www.example.net", res.headers["Access-Control-Allow-Origin"]) assert.equals("true", res.headers["Access-Control-Allow-Credentials"]) assert.equal("Origin", res.headers["Vary"]) end) it("responds with the requested Origin (including port) when config.credentials=true", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors5.com", ["Origin"] = "http://www.example.net:3000" } }) assert.res_status(200, res) assert.equals("http://www.example.net:3000", res.headers["Access-Control-Allow-Origin"]) assert.equals("true", res.headers["Access-Control-Allow-Credentials"]) assert.equal("Origin", res.headers["Vary"]) end) it("responds with * when config.credentials=false", function() local res = assert(proxy_client:send { method = "GET", headers = { ["Host"] = "cors7.com", ["Origin"] = "http://www.example.net" } }) assert.res_status(200, res) assert.equals("*", res.headers["Access-Control-Allow-Origin"]) assert.is_nil(res.headers["Access-Control-Allow-Credentials"]) assert.is_nil(res.headers["Vary"]) end) end) end) end
apache-2.0
UnfortunateFruit/darkstar
scripts/zones/Metalworks/npcs/HomePoint#1.lua
12
1239
----------------------------------- -- Area: Metalworks -- NPC: HomePoint#1 -- @pos: 46 -14 -19 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Metalworks/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 16); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
nesstea/darkstar
scripts/zones/The_Eldieme_Necropolis_[S]/npcs/Layton.lua
13
2028
----------------------------------- -- Area: The Eldieme Necropolis (S) -- NPC: Layton -- Type: Standard Merchant NPC -- Note: Available during Campaign battles -- @pos 382.679 -39.999 3.541 175 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,LAYTON_SHOP_DIALOG); stock = {0x17A1,8060, -- Firestorm Schema 0x17A2,6318, -- Rainstorm Schema 0x17A3,9100, -- Thunderstorm Schema 0x17A4,8580, -- Hailstorm Schema 0x17A5,5200, -- Sandstorm Schema 0x17A6,6786, -- Windstorm Schema 0x17A7,11440, -- Aurorastorm Schema 0x17A8,10725, -- Voidstorm Schema 0x1799,7714, -- Pyrohelix Schema 0x179A,6786, -- Hydrohelix Schema 0x179B,8625, -- Ionohelix Schema 0x179C,7896, -- Cryohelix Schema 0x179D,6591, -- Geohelix Schema 0x179E,6981, -- Anemohelix Schema 0x179F,8940, -- Luminohelix Schema 0x17A0,8790} -- Noctohelix Schema showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ennis/autograph-pipelines
resources/scripts/pl/Map.lua
2
2761
--- A Map class. -- -- > Map = require 'pl.Map' -- > m = Map{one=1,two=2} -- > m:update {three=3,four=4,two=20} -- > = m == M{one=1,two=20,three=3,four=4} -- true -- -- Dependencies: `pl.utils`, `pl.class`, `pl.tablex`, `pl.pretty` -- @classmod pl.Map local tablex = require 'pl.tablex' local utils = require 'pl.utils' local stdmt = utils.stdmt local tmakeset,deepcompare,merge,keys,difference,tupdate = tablex.makeset,tablex.deepcompare,tablex.merge,tablex.keys,tablex.difference,tablex.update local pretty_write = require 'pl.pretty' . write local Map = stdmt.Map local Set = stdmt.Set local class = require 'pl.class' -- the Map class --------------------- class(nil,nil,Map) function Map:_init (t) local mt = getmetatable(t) if mt == Set or mt == Map then self:update(t) else return t -- otherwise assumed to be a map-like table end end local function makelist(t) return setmetatable(t, require('pl.List')) end --- list of keys. Map.keys = tablex.keys --- list of values. Map.values = tablex.values --- return an iterator over all key-value pairs. function Map:iter () return pairs(self) end --- return a List of all key-value pairs, sorted by the keys. function Map:items() local ls = makelist(tablex.pairmap (function (k,v) return makelist {k,v} end, self)) ls:sort(function(t1,t2) return t1[1] < t2[1] end) return ls end -- Will return the existing value, or if it doesn't exist it will set -- a default value and return it. function Map:setdefault(key, defaultval) return self[key] or self:set(key,defaultval) or defaultval end --- size of map. -- note: this is a relatively expensive operation! -- @class function -- @name Map:len Map.len = tablex.size --- put a value into the map. -- This will remove the key if the value is `nil` -- @param key the key -- @param val the value function Map:set (key,val) self[key] = val end --- get a value from the map. -- @param key the key -- @return the value, or nil if not found. function Map:get (key) return rawget(self,key) end local index_by = tablex.index_by --- get a list of values indexed by a list of keys. -- @param keys a list-like table of keys -- @return a new list function Map:getvalues (keys) return makelist(index_by(self,keys)) end --- update the map using key/value pairs from another table. -- @tab table -- @function Map:update Map.update = tablex.update --- equality between maps. -- @within metamethods -- @tparam Map m another map. function Map:__eq (m) -- note we explicitly ask deepcompare _not_ to use __eq! return deepcompare(self,m,true) end --- string representation of a map. -- @within metamethods function Map:__tostring () return pretty_write(self,'') end return Map
mit
Xileck/forgottenserver
data/actions/scripts/tools/fishing.lua
30
2222
local waterIds = {493, 4608, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4623, 4624, 4625, 7236, 10499, 15401, 15402} local lootTrash = {2234, 2238, 2376, 2509, 2667} local lootCommon = {2152, 2167, 2168, 2669, 7588, 7589} local lootRare = {2143, 2146, 2149, 7158, 7159} local lootVeryRare = {7632, 7633, 10220} local useWorms = true function onUse(player, item, fromPosition, target, toPosition, isHotkey) local targetId = target.itemid if not isInArray(waterIds, target.itemid) then return false end if targetId == 10499 then local owner = target:getAttribute(ITEM_ATTRIBUTE_CORPSEOWNER) if owner ~= 0 and owner ~= player:getId() then player:sendTextMessage(MESSAGE_STATUS_SMALL, "You are not the owner.") return true end toPosition:sendMagicEffect(CONST_ME_WATERSPLASH) target:remove() local rareChance = math.random(1, 100) if rareChance == 1 then player:addItem(lootVeryRare[math.random(#lootVeryRare)], 1) elseif rareChance <= 3 then player:addItem(lootRare[math.random(#lootRare)], 1) elseif rareChance <= 10 then player:addItem(lootCommon[math.random(#lootCommon)], 1) else player:addItem(lootTrash[math.random(#lootTrash)], 1) end return true end if targetId ~= 7236 then toPosition:sendMagicEffect(CONST_ME_LOSEENERGY) end if targetId == 493 or targetId == 15402 then return true end player:addSkillTries(SKILL_FISHING, 1) if math.random(1, 100) <= math.min(math.max(10 + (player:getEffectiveSkillLevel(SKILL_FISHING) - 10) * 0.597, 10), 50) then if useWorms and not player:removeItem("worm", 1) then return true end if targetId == 15401 then target:transform(targetId + 1) target:decay() if math.random(1, 100) >= 97 then player:addItem(15405, 1) return true end elseif targetId == 7236 then target:transform(targetId + 1) target:decay() local rareChance = math.random(1, 100) if rareChance == 1 then player:addItem(7158, 1) return true elseif rareChance <= 4 then player:addItem(2669, 1) return true elseif rareChance <= 10 then player:addItem(7159, 1) return true end end player:addItem("fish", 1) end return true end
gpl-2.0
mouhb/cjdns
contrib/lua/cjdns/router.lua
40
3083
-- Cjdns admin module for Lua -- Written by Philip Horger -- hacked up dumpTable, switchpinger, peerstats -- and other oddities by William Fleurant common = require 'cjdns/common' RouterFunctions = {} RouterFunctions.__index = RouterFunctions common.RouterFunctions = RouterFunctions function RouterFunctions.new(ai, config) properties = { ai = ai, config = config or ai.config } return setmetatable(properties, RouterFunctions) end function RouterFunctions:dumpTable(page) local response, err = self.ai:auth({ q = "NodeStore_dumpTable()", page = page, }) return response.routingTable end function RouterFunctions:lookup(address) local response, err = self.ai:auth({ q = "RouterModule_lookup", address = address }) if not response then return nil, err elseif response.error ~= "none" then return nil, response.error elseif response.result then return response.result else return nil, "bad response format" end end function RouterFunctions:availableFunctions(page) local response, err = self.ai:auth({q = "Admin_availableFunctions"}) print (err) print (response) end function RouterFunctions:switchpinger(path, data, timeout) local response, err = self.ai:auth({ q = "SwitchPinger_ping", path = path, data = 0, timeout = '' }) for k,v in pairs(response) do print(k,v) end return response end function RouterFunctions:peerStats(page) if page then page = page else page = 0 end while page do local response, err = self.ai:auth({ q = "InterfaceController_peerStats", page = page, }) for pubkey,switch in pairs(response.peers,response.peers) do print (response.peers[pubkey]['publicKey'], response.peers[pubkey]['switchLabel']) end if response.more then page = page + 1 else page = nil end end return response end function RouterFunctions:AuthorizedPasswords_list() local response, err = self.ai:auth({ q = "AuthorizedPasswords_list()" }) print("AuthorizedPasswords_list()") return reponse end function RouterFunctions:pingNode(path, timeout) local request = { q = "RouterModule_pingNode", path = path } if timeout then request.timeout = timeout end local response, err = self.ai:auth(request) if not response then return nil, err elseif response.error then return nil, response.error elseif response.result then if response.result == "timeout" then return nil, "timeout" else return response.ms end else return nil, "bad response format" end end function RouterFunctions:memory(page) local response, err = self.ai:call({q = "Admin_availableFunctions", page=page}) for key,value in pairs(response.availableFunctions) do print(key) end print(response) end
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/abilities/pets/lightning_breath.lua
25
1262
--------------------------------------------------- -- Lightning Breath --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill, master) ---------- Deep Breathing ---------- -- 0 for none -- 1 for first merit -- 0.25 for each merit after the first -- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*) local deep = 1; if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25; pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST); end local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_LIGHTNING); -- Works out to (hp/6) + 15, as desired dmgmod = (dmgmod * (1+gear))*deep; local dmg = MobFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end
gpl-3.0
vonflynee/opencomputersserver
world/opencomputers/3f9e70c3-6961-48bd-bbb9-5c4b3888a254/init.lua
14
5586
do _G._OSVERSION = "OpenOS 1.5" local component = component local computer = computer local unicode = unicode -- Runlevel information. local runlevel, shutdown = "S", computer.shutdown computer.runlevel = function() return runlevel end computer.shutdown = function(reboot) runlevel = reboot and 6 or 0 if os.sleep then computer.pushSignal("shutdown") os.sleep(0.1) -- Allow shutdown processing. end shutdown(reboot) end -- Low level dofile implementation to read filesystem libraries. local rom = {} function rom.invoke(method, ...) return component.invoke(computer.getBootAddress(), method, ...) end function rom.open(file) return rom.invoke("open", file) end function rom.read(handle) return rom.invoke("read", handle, math.huge) end function rom.close(handle) return rom.invoke("close", handle) end function rom.inits() return ipairs(rom.invoke("list", "boot")) end function rom.isDirectory(path) return rom.invoke("isDirectory", path) end local screen = component.list('screen')() for address in component.list('screen') do if #component.invoke(address, 'getKeyboards') > 0 then screen = address end end -- Report boot progress if possible. local gpu = component.list("gpu", true)() local w, h if gpu and screen then component.invoke(gpu, "bind", screen) w, h = component.invoke(gpu, "getResolution") component.invoke(gpu, "setResolution", w, h) component.invoke(gpu, "setBackground", 0x000000) component.invoke(gpu, "setForeground", 0xFFFFFF) component.invoke(gpu, "fill", 1, 1, w, h, " ") end local y = 1 local function status(msg) if gpu and screen then component.invoke(gpu, "set", 1, y, msg) if y == h then component.invoke(gpu, "copy", 1, 2, w, h - 1, 0, -1) component.invoke(gpu, "fill", 1, h, w, 1, " ") else y = y + 1 end end end status("Booting " .. _OSVERSION .. "...") -- Custom low-level loadfile/dofile implementation reading from our ROM. local function loadfile(file) status("> " .. file) local handle, reason = rom.open(file) if not handle then error(reason) end local buffer = "" repeat local data, reason = rom.read(handle) if not data and reason then error(reason) end buffer = buffer .. (data or "") until not data rom.close(handle) return load(buffer, "=" .. file) end local function dofile(file) local program, reason = loadfile(file) if program then local result = table.pack(pcall(program)) if result[1] then return table.unpack(result, 2, result.n) else error(result[2]) end else error(reason) end end status("Initializing package management...") -- Load file system related libraries we need to load other stuff moree -- comfortably. This is basically wrapper stuff for the file streams -- provided by the filesystem components. local package = dofile("/lib/package.lua") do -- Unclutter global namespace now that we have the package module. _G.component = nil _G.computer = nil _G.process = nil _G.unicode = nil -- Initialize the package module with some of our own APIs. package.preload["buffer"] = loadfile("/lib/buffer.lua") package.preload["component"] = function() return component end package.preload["computer"] = function() return computer end package.preload["filesystem"] = loadfile("/lib/filesystem.lua") package.preload["io"] = loadfile("/lib/io.lua") package.preload["unicode"] = function() return unicode end -- Inject the package and io modules into the global namespace, as in Lua. _G.package = package _G.io = require("io") end status("Initializing file system...") -- Mount the ROM and temporary file systems to allow working on the file -- system module from this point on. local filesystem = require("filesystem") filesystem.mount(computer.getBootAddress(), "/") status("Running boot scripts...") -- Run library startup scripts. These mostly initialize event handlers. local scripts = {} for _, file in rom.inits() do local path = "boot/" .. file if not rom.isDirectory(path) then table.insert(scripts, path) end end table.sort(scripts) for i = 1, #scripts do dofile(scripts[i]) end status("Initializing components...") local primaries = {} for c, t in component.list() do local s = component.slot(c) if not primaries[t] or (s >= 0 and s < primaries[t].slot) then primaries[t] = {address=c, slot=s} end computer.pushSignal("component_added", c, t) end for t, c in pairs(primaries) do component.setPrimary(t, c.address) end os.sleep(0.5) -- Allow signal processing by libraries. computer.pushSignal("init") -- so libs know components are initialized. status("Initializing system...") require("term").clear() os.sleep(0.1) -- Allow init processing. runlevel = 1 end local function motd() local f = io.open("/etc/motd") if not f then return end if f:read(2) == "#!" then f:close() os.execute("/etc/motd") else f:seek("set", 0) io.write(f:read("*a") .. "\n") f:close() end end while true do motd() local result, reason = os.execute(os.getenv("SHELL")) if not result then io.stderr:write((tostring(reason) or "unknown error") .. "\n") io.write("Press any key to continue.\n") os.sleep(0.5) require("event").pull("key") end require("term").clear() end
mit
vonflynee/opencomputersserver
world/opencomputers/689b9f29-1d36-4106-bf0e-c06a2ebfb1ef/usr/lib/raytracer.lua
1
5474
--[[ Very basic raytracer, passing results (i.e. hit "pixels") to a callback. Usage: local rt = require("raytracer").new() table.insert(rt.model, {0,0,0,16,16,16}) --rt.camera.position = {-20,20,0} --rt.camera.target = {8,8,8} --rt.camera.fov = 100 rt:render(width, height, function(hitX, hitY, box, normal) -- do stuff with the hit information, e.g. set pixel at hitX/hitY to boxes color end) Shapes must at least have their min/max coordinates given as the first six integer indexed entries of the table, as {minX,minY,minZ,maxX,maxY,maxZ}. The returned normal is a sequence with the x/y/z components of the normal. The camera can be configured as shown in the example above, i.e. it has a position, target and field of view (which is in degrees). MIT Licensed, Copyright Sangar 2015 ]] local M = {} -- vector math stuffs local function vadd(v1, v2) return {v1[1]+v2[1], v1[2]+v2[2], v1[3]+v2[3]} end local function vsub(v1, v2) return {v1[1]-v2[1], v1[2]-v2[2], v1[3]-v2[3]} end local function vmul(v1, v2) return {v1[1]*v2[1], v1[2]*v2[2], v1[3]*v2[3]} end local function vcross(v1, v2) return {v1[2]*v2[3]-v1[3]*v2[2], v1[3]*v2[1]-v1[1]*v2[3], v1[1]*v2[2]-v1[2]*v2[1]} end local function vmuls(v, s) return vmul(v, {s, s, s}) end local function vdot(v1, v2) return v1[1]*v2[1] + v1[2]*v2[2] + v1[3]*v2[3] end local function vnorm(v) return vdot(v, v) end local function vlen(v) return math.sqrt(vnorm(v)) end local function vnormalize(v) return vmuls(v, 1/vlen(v)) end -- collision stuffs -- http://tog.acm.org/resources/GraphicsGems/gems/RayBox.c -- adjusted version also returning the surface normal local function collideRayBox(box, origin, dir) local inside = true local quadrant = {0,0,0} local minB = {box[1],box[2],box[3]} local maxB = {box[4],box[5],box[6]} local maxT = {0,0,0} local candidatePlane = {0,0,0} local sign = 0 -- Find candidate planes; this loop can be avoided if -- rays cast all from the eye(assume perpsective view) for i=1,3 do if origin[i] < minB[i] then quadrant[i] = true candidatePlane[i] = minB[i] inside = false sign = -1 elseif origin[i] > maxB[i] then quadrant[i] = true candidatePlane[i] = maxB[i] inside = false sign = 1 else quadrant[i] = false end end -- Ray origin inside bounding box if inside then return nil end -- Calculate T distances to candidate planes for i=1,3 do if quadrant[i] and dir[i] ~= 0 then maxT[i] = (candidatePlane[i] - origin[i]) / dir[i] else maxT[i] = -1 end end -- Get largest of the maxT's for final choice of intersection local whichPlane = 1 for i=2,3 do if maxT[whichPlane] < maxT[i] then whichPlane = i end end -- Check final candidate actually inside box if maxT[whichPlane] < 0 then return nil end local coord,normal = {0,0,0},{0,0,0} for i=1,3 do if whichPlane ~= i then coord[i] = origin[i] + maxT[whichPlane] * dir[i] if coord[i] < minB[i] or coord[i] > maxB[i] then return nil end else coord[i] = candidatePlane[i] normal[i] = sign end end return coord, normal -- ray hits box end local function trace(model, origin, dir) local bestBox, bestNormal, bestDist = nil, nil, math.huge for _, box in ipairs(model) do local hit, normal = collideRayBox(box, origin, dir) if hit then local dist = vlen(vsub(hit, origin)) if dist < bestDist then bestBox = box bestNormal = normal bestDist = dist end end end return bestBox, bestNormal end -- public api function M.new() return setmetatable({model={},camera={position={-1,1,-1},target={0,0,0},fov=90}}, {__index=M}) end function M:render(w, h, f) if #self.model < 1 then return end -- overall model bounds, for quick empty space skipping local bounds = {self.model[1][1],self.model[1][2],self.model[1][3],self.model[1][4],self.model[1][5],self.model[1][6]} for _, shape in ipairs(self.model) do bounds[1] = math.min(bounds[1], shape[1]) bounds[2] = math.min(bounds[2], shape[2]) bounds[3] = math.min(bounds[3], shape[3]) bounds[4] = math.max(bounds[4], shape[4]) bounds[5] = math.max(bounds[5], shape[5]) bounds[6] = math.max(bounds[6], shape[6]) end bounds = {bounds} -- setup framework for ray generation local origin = self.camera.position local forward = vnormalize(vsub(self.camera.target, origin)) local plane = vadd(origin, forward) local side = vcross(forward, {0,1,0}) local up = vcross(forward, side) local lside = math.tan(self.camera.fov/2/180*math.pi) -- generate ray for each pixel, left-to-right, top-to-bottom local blanks = 0 for sy = 1, h do local ry = (sy/h - 0.5)*lside local py = vadd(plane, vmuls(up, ry)) for sx = 1, w do local rx = (sx/w - 0.5)*lside local px = vadd(py, vmuls(side, rx)) local dir = vnormalize(vsub(px, origin)) if trace(bounds, origin, dir) then local box, normal = trace(self.model, origin, dir) if box then blanks = 0 if f(sx, sy, box, normal) == false then return end else blanks = blanks + 1 end else blanks = blanks + 1 end if blanks > 50 then blanks = 0 os.sleep(0) -- avoid too long without yielding end end end end return M
mit
UnfortunateFruit/darkstar
scripts/zones/Northern_San_dOria/npcs/Letterare.lua
36
1428
----------------------------------- -- Area: Northern San d'Oria -- NPC: Letterare -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0294); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Eastern_Altepa_Desert/npcs/Variko-Njariko_WW.lua
13
3348
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: Variko-Njariko, W.W. -- Outpost Conquest Guards -- @pos -258.041 7.473 -254.527 114 ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = KUZOTZ; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
VurtualRuler98/kswep2-NWI
lua/ins_sounds/sounds_m1carbine.lua
1
1387
if (SERVER) then AddCSLuaFile() end --m1a1 sound.Add({ name="Weapon_m1a1.Single", volume = 1.0, pitch = {100,105}, sound = "weapons/m1a1/m1a1_fp.wav", level = 142, channel = CHAN_STATIC }) sound.Add({ name="Weapon_m1a1.SingleSilenced", volume = 1.0, pitch = {100,105}, sound = "weapons/m1a1/m1a1_suppressed_fp.wav", level = 118, channel = CHAN_STATIC }) sound.Add({ name="Weapon_m1a1.Magrelease", volume = 0.2, sound = "weapons/m1a1/handling/m1a1_magrelease.wav", level = 65, channel = CHAN_ITEM }) sound.Add({ name="Weapon_m1a1.MagHitrelease", volume = 0.3, sound = "weapons/m1a1/handling/m1a1_maghitrelease.wav", level = 65, channel = CHAN_ITEM }) sound.Add({ name="Weapon_m1a1.Magin", volume = 0.2, sound = "weapons/m1a1/handling/m1a1_magin.wav", level = 65, channel = CHAN_ITEM }) sound.Add({ name="Weapon_m1a1.Magout", volume = 0.2, sound = "weapons/m1a1/handling/m1a1_magout.wav", level = 65, channel = CHAN_ITEM }) sound.Add({ name="Weapon_m1a1.Boltback", volume = 0.3, sound = "weapons/m1a1/handling/m1a1_boltback.wav", level = 65, channel = CHAN_ITEM }) sound.Add({ name="Weapon_m1a1.Boltrelease", volume = 0.3, sound = "weapons/m1a1/handling/m1a1_boltrelease.wav", level = 65, channel = CHAN_ITEM }) sound.Add({ name="weapon_m1a1.Empty", volume=0.2, level=65, sound="weapons/m1a1/handling/m1a1_empty.wav", channel = CHAN_ITEM })
apache-2.0
ruisebastiao/nodemcu-firmware
lua_modules/si7021/si7021.lua
83
2184
-- *************************************************************************** -- SI7021 module for ESP8266 with nodeMCU -- Si7021 compatible tested 2015-1-22 -- -- Written by VIP6 -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** local moduleName = ... local M = {} _G[moduleName] = M --I2C slave address of Si70xx local Si7021_ADDR = 0x40 --Commands local CMD_MEASURE_HUMIDITY_HOLD = 0xE5 local CMD_MEASURE_HUMIDITY_NO_HOLD = 0xF5 local CMD_MEASURE_TEMPERATURE_HOLD = 0xE3 local CMD_MEASURE_TEMPERATURE_NO_HOLD = 0xF3 -- temperature and pressure local t,h local init = false -- i2c interface ID local id = 0 -- 16-bit two's complement -- value: 16-bit integer local function twoCompl(value) if value > 32767 then value = -(65535 - value + 1) end return value end -- read data from si7021 -- ADDR: slave address -- commands: Commands of si7021 -- length: bytes to read local function read_data(ADDR, commands, length) i2c.start(id) i2c.address(id, ADDR, i2c.TRANSMITTER) i2c.write(id, commands) i2c.stop(id) i2c.start(id) i2c.address(id, ADDR,i2c.RECEIVER) tmr.delay(20000) c = i2c.read(id, length) i2c.stop(id) return c end -- initialize module -- sda: SDA pin -- scl SCL pin function M.init(sda, scl) i2c.setup(id, sda, scl, i2c.SLOW) --print("i2c ok..") init = true end -- read humidity from si7021 local function read_humi() dataH = read_data(Si7021_ADDR, CMD_MEASURE_HUMIDITY_HOLD, 2) UH = string.byte(dataH, 1) * 256 + string.byte(dataH, 2) h = ((UH*12500+65536/2)/65536 - 600) return(h) end -- read temperature from si7021 local function read_temp() dataT = read_data(Si7021_ADDR, CMD_MEASURE_TEMPERATURE_HOLD, 2) UT = string.byte(dataT, 1) * 256 + string.byte(dataT, 2) t = ((UT*17572+65536/2)/65536 - 4685) return(t) end -- read temperature and humidity from si7021 function M.read() if (not init) then print("init() must be called before read.") else read_humi() read_temp() end end; -- get humidity function M.getHumidity() return h end -- get temperature function M.getTemperature() return t end return M
mit
alirezanile/LaSt-GaMfg
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
hussian/hell_iraq
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
ferisystem/ApiSeed
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
johnmccabe/dockercraft
world/Plugins/Core/web_weather.lua
6
2946
local function AddWorldButtons(inName) result = "<form method='POST'><input type='hidden' name='WorldName' value='" .. inName .. "'>" result = result .. "<input type='submit' name='SetTime' value='Dawn'>" result = result .. "<input type='submit' name='SetTime' value='Day'>" result = result .. "<input type='submit' name='SetTime' value='Dusk'>" result = result .. "<input type='submit' name='SetTime' value='Night'>" result = result .. "<input type='submit' name='SetTime' value='Midnight'>" result = result .. "<input type='submit' name='SetWeather' value='Sun'>" result = result .. "<input type='submit' name='SetWeather' value='Rain'>" result = result .. "<input type='submit' name='SetWeather' value='Storm'></form>" return result end function HandleRequest_Weather(Request) if (Request.PostParams["WorldName"] ~= nil) then -- World is selected! workWorldName = Request.PostParams["WorldName"] workWorld = cRoot:Get():GetWorld(workWorldName) if( Request.PostParams["SetTime"] ~= nil ) then -- Times used replicate vanilla: http://minecraft.gamepedia.com/Day-night_cycle#Commands if (Request.PostParams["SetTime"] == "Dawn") then workWorld:SetTimeOfDay(0) LOG("Time set to dawn in " .. workWorldName) elseif (Request.PostParams["SetTime"] == "Day") then workWorld:SetTimeOfDay(1000) LOG("Time set to day in " .. workWorldName) elseif (Request.PostParams["SetTime"] == "Dusk") then workWorld:SetTimeOfDay(12000) LOG("Time set to dusk in " .. workWorldName) elseif (Request.PostParams["SetTime"] == "Night") then workWorld:SetTimeOfDay(14000) LOG("Time set to night in " .. workWorldName) elseif (Request.PostParams["SetTime"] == "Midnight") then workWorld:SetTimeOfDay(18000) LOG("Time set to midnight in " .. workWorldName) end end if (Request.PostParams["SetWeather"] ~= nil) then if (Request.PostParams["SetWeather"] == "Sun") then workWorld:SetWeather(wSunny) LOG("Weather changed to sun in " .. workWorldName) elseif (Request.PostParams["SetWeather"] == "Rain") then workWorld:SetWeather(wRain) LOG("Weather changed to rain in " .. workWorldName) elseif (Request.PostParams["SetWeather"] == "Storm") then workWorld:SetWeather(wStorm) LOG("Weather changed to storm in " .. workWorldName) end end end return GenerateContent() end function GenerateContent() local content = "<h4>Operations:</h4><br>" local worldCount = 0 local AddWorldToTable = function( inWorld ) worldCount = worldCount + 1 content = content.."<tr><td style='width: 10px;'>"..worldCount..".</td><td>"..inWorld:GetName().."</td>" content = content.."<td>"..AddWorldButtons( inWorld:GetName() ).."</td></tr>" end content = content.."<table>" cRoot:Get():ForEachWorld( AddWorldToTable ) if( worldCount == 0 ) then content = content.."<tr><td>No worlds! O_O</td></tr>" end content = content.."</table>" return content end
apache-2.0
nesstea/darkstar
scripts/zones/Crawlers_Nest/TextIDs.lua
22
1594
--- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6569; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6574; -- Obtained: <item>. GIL_OBTAINED = 6575; -- Obtained <number> gil. KEYITEM_OBTAINED = 6577; -- Obtained key item: <keyitem>. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7247; -- You unlock the chest! CHEST_FAIL = 7248; -- Fails to open the chest. CHEST_TRAP = 7249; -- The chest was trapped! CHEST_WEAK = 7250; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7251; -- The chest was a mimic! CHEST_MOOGLE = 7252; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7253; -- The chest was but an illusion... CHEST_LOCKED = 7254; -- The chest appears to be locked. -- Quest Dialog SENSE_OF_FOREBODING = 6589; -- You are suddenly overcome with a sense of foreboding... NOTHING_WILL_HAPPEN_YET = 7261; -- It seems that nothing will happen yet. NOTHING_SEEMS_TO_HAPPEN = 7262; -- Nothing seems to happen. SOMEONE_HAS_BEEN_DIGGING_HERE = 7255; -- Someone has been digging here. EQUIPMENT_COMPLETELY_PURIFIED = 7256; -- Your equipment has not been completely purified. YOU_BURY_THE = 7258; -- You bury the -- conquest Base CONQUEST_BASE = 0; -- Strange Apparatus DEVICE_NOT_WORKING = 173; -- The device is not working. SYS_OVERLOAD = 182; -- arning! Sys...verload! Enterin...fety mode. ID eras...d YOU_LOST_THE = 187; -- You lost the #.
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/spells/bluemagic/jet_stream.lua
27
1767
----------------------------------------- -- Spell: Jet Stream -- Delivers a threefold attack. Accuracy varies with TP -- Spell cost: 47 MP -- Monster Type: Birds -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: DEX+2 -- Level: 38 -- Casting Time: 0.5 seconds -- Recast Time: 23 seconds -- Skillchain Element(s): Lightning (can open Liquefaction or Detonation; can close Impaction or Fusion) -- Combos: Rapid Shot ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ACC; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_IMPACTION; params.numhits = 3; params.multiplier = 1.125; params.tp150 = 1.2; params.tp300 = 1.4; params.azuretp = 1.5; params.duppercap = 39; --guesstimated acc % bonuses params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
kidanger/Drystal
tests/graphics/surface_manipulations.lua
1
2216
local drystal = require "drystal" local spritesheet = assert(drystal.fromjson(io.open('image.json'):read('*all'))) vert = [[ attribute vec2 position; attribute vec4 color; attribute vec2 texCoord; varying vec4 fColor; varying vec2 fTexCoord; uniform vec2 destinationSize; uniform vec2 sourceSize; #define pi ]]..math.pi..[[ uniform float tick; float rand(vec2 co){ return sin(dot(co.xy, vec2(12.9898,78.233))); } void main() { vec2 pos = (2. * position/destinationSize) - 1.; pos.x += rand(vec2(pos.x, tick/10.+100.)) * .01; pos.y += rand(vec2(pos.y, tick/10.)) * .01; gl_Position = vec4(pos, 0., 1.); fColor = color; fTexCoord = texCoord / sourceSize; } ]] local x = 0 local y = 0 local width = 0 local height = 0 local shader function drystal.init() drystal.resize(600, 400) image = assert(drystal.load_surface(spritesheet.meta.image)) image:draw_from() drystal.set_alpha(0) surf = drystal.new_surface(64, 32) surf:draw_on() drystal.set_color(255, 0, 0) drystal.set_alpha(105) drystal.draw_rect(32, 0, 40, 40) drystal.set_color(200, 200, 200) drystal.set_alpha(255) local sprite = spritesheet.frames['character.png'].frame drystal.draw_sprite(sprite, 0, 0) drystal.screen:draw_on() shader = assert(drystal.new_shader(vert)) end local tick = 0 function drystal.update(dt) tick = tick + dt end function drystal.draw() image:draw_from() drystal.set_alpha(255) drystal.set_color(10, 10, 30) drystal.draw_background() shader:use() shader:feed('tick', tick) drystal.set_color(255, 0, 0) drystal.set_alpha(105) drystal.draw_rect(16, 64, 40, 40) local sprite = spritesheet.frames['character.png'].frame drystal.set_color(200, 200, 200) drystal.set_alpha(255) drystal.draw_sprite_rotated(sprite, 16, 16, math.sin(tick)) drystal.use_default_shader() drystal.set_color(100, 0, 0) drystal.set_alpha(200) drystal.draw_sprite(sprite, 16+32, 16) drystal.set_color(255,255,255) drystal.set_alpha((math.sin(tick*5)/2+0.5)*255) surf:draw_from() drystal.draw_image(0, 0, 64, 32, 0, 256) end function drystal.key_press(key) if key == 'a' then drystal.stop() end end function drystal.key_release(key) end function drystal.mouse_motion(_x, _y) x = _x y = _y end
gpl-3.0
nesstea/darkstar
scripts/zones/South_Gustaberg/mobs/Tococo.lua
7
1075
----------------------------------- -- Area: South Gustaberg -- NM: Tococo ----------------------------------- require("scripts/globals/status"); ----------------------------------- ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) -- Guesstimating 1 in 3 chance to poison on melee. if ((math.random(1,100) >= 33) or (target:hasStatusEffect(EFFECT_POISON) == true)) then return 0,0,0; else local duration = math.random(5,15); target:addStatusEffect(EFFECT_POISON,5,3,duration); return SUBEFFECT_POISON,0,EFFECT_POISON; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(3600,4200)); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Mhaura/npcs/Ekokoko.lua
13
1624
----------------------------------- -- Area: Mhaura -- NPC: Ekokoko -- Gouvernor of Mhaura -- Involved in Quest: Riding on the Clouds -- @pos -78 -24 28 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 6) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_3",0); player:tradeComplete(); player:addKeyItem(SOMBER_STONE); player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (math.random() > 0.5) then player:startEvent(0x33); else player:startEvent(0x34); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nesstea/darkstar
scripts/zones/Kazham/npcs/Shey_Wayatih.lua
30
1379
----------------------------------- -- Area: Kazham -- NPC: Shey Wayatih -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 1 do vHour = vHour - 6; end if ( vHour == -5) then vHour = 1; elseif ( vHour == -4) then vHour = 2; elseif ( vHour == -3) then vHour = 3; elseif ( vHour == -2) then vHour = 4; elseif ( vHour == -1) then vHour = 5; end local seconds = math.floor(2.4 * ((vHour * 60) + vMin)); player:startEvent( 0x012F, seconds, 0, 0, 0, 0, 0, 0, 0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bowlofstew/Macaroni
Main/App/Source/main/lua/VersionInfoGenerator.lua
2
3070
-------------------------------------------------------------------------------- -- Copyright 2011 Tim Simpson -- -- 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. -------------------------------------------------------------------------------- require "Macaroni.IO.GeneratedFileWriter"; require "Macaroni.IO.Path"; require "About"; function aboutTextCString(version) local about = aboutText(version); local aboutT = string.gsub("~ " .. about, "\"", "\\\"") local aboutT = string.gsub(aboutT, "\n", "\\n\"\n\"~ "); return [[ "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" "]] .. aboutT .. [[\n" "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" ]]; end function formatTimeToString(date) return (date.year .. "-" .. date.month .. "-" .. date.day .. "-" .. date.hour .. ":" .. date.min .. ":" .. date.sec); end function localTime() return formatTimeToString( os.date("*t") ); end function utc() return formatTimeToString( os.date("!*t") ); end function GetMethod(name) if name == "Generate" then return { Run = function(args) createVersionNoH(args.path, args.projectVersion) createAboutTextH(args.path, args.projectVersion) createAboutTxt(args.path, args.projectVersion) end, }; end end function createAboutTxt(path, library) local version = library.Version; local file = path:NewPathForceSlash("LICENSE.txt"); local writer = file:CreateFile(); writer:Write(aboutText(version)); end function createAboutTextH(path, library) local version = library.Version; local file = path:NewPath("/Macaroni/AboutText.h"); local writer = file:CreateFile(); writer:Write(aboutTextCString(version)); end function createVersionNoH(path, library) local commaVersion = string.gsub(library.Version, "%.", [[\,]]); local version = library.Version; local file = path:NewPath("/Macaroni/VersionNo.h"); local writer = file:CreateFile(); writer:Write([[ #ifndef MACARONI_VERSION #define MACARONI_VERSION ]] .. commaVersion .. "\n" .. [[ #define MACARONI_VERSION_STRING "]] .. version .. "\"\n" .. [[ #define MACARONI_FILE_DESCRIPTION "Macaroni for C++" #define MACARONI_COPYRIGHT "(C) Tim Simpson, 2011" #define BUILD_TIMESTAMP_LOCAL "]] .. localTime() .. "\"\n" .. [[ #define BUILD_TIMESTAMP_UTC "]] .. utc() .. "\"\n" .. [[ #endif ]]); end
apache-2.0
UnfortunateFruit/darkstar
scripts/globals/weaponskills/uriel_blade.lua
29
1393
----------------------------------- -- Uriel Blade -- Sword weapon skill -- Skill Level: N/A -- Description: Delivers an area attack that deals light elemental damage. Damage varies with TP. Additional effect Flash. -- AoE range ??. -- Only available during Campaign Battle while wielding a Griffinclaw. -- Aligned with the Thunder Gorget & Breeze Gorget. -- Aligned with Thunder Belt & Breeze Belt. -- Modifiers: STR: 32% MND:32% -- 100%TP 200%TP 300%TP -- 4.50 6.00 7.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 4.5; params.ftp200 = 6; params.ftp300 = 7.5; params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.32; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_SWD; params.includemab = true; local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER if damage > 0 and (target:hasStatusEffect(EFFECT_FLASH) == false) then target:addStatusEffect(EFFECT_FLASH, 200, 0, 15); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/spells/enchanting_etude.lua
13
1761
----------------------------------------- -- Spell: Enchanting Etude -- Static CHR Boost, BRD 22 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 0; if (sLvl+iLvl <= 181) then power = 3; elseif((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then power = 4; elseif((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then power = 5; elseif((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then power = 6; elseif((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then power = 7; elseif((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then power = 8; elseif(sLvl+iLvl >= 450) then power = 9; end local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(), MOD_CHR, 1)) then spell:setMsg(75); end return EFFECT_ETUDE; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/juglan_jumble.lua
36
1363
----------------------------------------- -- ID: 5923 -- Item: Juglan Jumble -- Food Effect: 5 Min, All Races ----------------------------------------- -- HP Healing 5 -- MP Healing 8 -- Bird Killer 12 -- Resist Paralyze 12 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5923); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPHEAL, 5); target:addMod(MOD_MPHEAL, 8); target:addMod(MOD_BIRD_KILLER, 12); target:addMod(MOD_PARALYZERES, 12); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPHEAL, 5); target:delMod(MOD_MPHEAL, 8); target:delMod(MOD_BIRD_KILLER, 12); target:delMod(MOD_PARALYZERES, 12); end;
gpl-3.0
reonZ/project-arena
game/dota_addons/project_arenas/scripts/vscripts/abilities/royal_guard/royal_guard_cleave.lua
1
1738
require( 'custom_target_ability' ) local c_damage = 'damage' local c_cleave_damage = 'cleave_damage' local c_cleave_radius = 'cleave_radius' local c_anim_activity = ACT_DOTA_ATTACK local c_anim_frames = 30 local c_cast_sound = 'Hero_DragonKnight.PreAttack' local c_cleave_effect = 'particles/units/heroes/hero_sven/sven_spell_great_cleave.vpcf' --------------------------------------------------------------------------------------------------- royal_guard_cleave = class( {} ) royal_guard_cleave.target_team = DOTA_UNIT_TARGET_TEAM_ENEMY royal_guard_cleave.target_type = DOTA_UNIT_TARGET_ALL royal_guard_cleave.target_flag = DOTA_UNIT_TARGET_FLAG_NONE CustomTargetAbility( royal_guard_cleave ) function royal_guard_cleave:OnUpgrade() self.bCanMiss = true self.bCanCrit = true self.bCanBeEvaded = true self.bCanBeBlocked = true end function royal_guard_cleave:GetCastAnimation() return c_anim_activity end function royal_guard_cleave:GetPlaybackRateOverride() local fCastPoint = self:GetCastPoint() return AnimationRate( fCastPoint, c_anim_frames ) end function royal_guard_cleave:OnAbilityPhaseStart() local hCaster = self:GetCaster() EmitSoundOn( c_cast_sound, hCaster ) return true end function royal_guard_cleave:OnSpellStart() local iCleave = self:GetSpecialValueFor( c_cleave_damage ) local damage = { ability = self, target = self:GetCursorTarget(), damage = self:GetSpecialValueFor( c_damage ), radius = self:GetSpecialValueFor( c_cleave_radius ), cleave = self:GetSpecialValueFor( c_cleave_damage ), effect = c_cleave_effect } DealCleaveDamage( damage ) end ---------------------------------------------------------------------------------------------------
gpl-2.0
nesstea/darkstar
scripts/globals/items/akamochi.lua
35
2064
----------------------------------------- -- ID: 6260 -- Item: akamochi -- Food Effect: 30 Min, All Races ----------------------------------------- -- HP + 20 (Pet & Master) -- Vitality + 3 (Pet & Master) -- Attack + 16% Cap: 50 (Pet & Master) Pet Cap: 75 -- Accuracy + 10% Cap: 50 (Pet & Master) Pet Cap: 75 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD)) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,6260); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20) target:addMod(MOD_VIT, 3) target:addMod(MOD_FOOD_ATTP, 16) target:addMod(MOD_FOOD_ATT_CAP, 50) target:addMod(MOD_FOOD_ACCP, 10) target:addMod(MOD_FOOD_ACC_CAP, 50) target:addPetMod(MOD_HP, 20) target:addPetMod(MOD_VIT, 3) target:addPetMod(MOD_FOOD_ATTP, 16) target:addPetMod(MOD_FOOD_ATT_CAP, 75) target:addPetMod(MOD_FOOD_ACCP, 10) target:addPetMod(MOD_FOOD_ACC_CAP, 75) end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20) target:delMod(MOD_VIT, 3) target:delMod(MOD_FOOD_ATTP, 16) target:delMod(MOD_FOOD_ATT_CAP, 50) target:delMod(MOD_FOOD_ACCP, 10) target:delMod(MOD_FOOD_ACC_CAP, 50) target:delPetMod(MOD_HP, 20) target:delPetMod(MOD_VIT, 3) target:delPetMod(MOD_FOOD_ATTP, 16) target:delPetMod(MOD_FOOD_ATT_CAP, 75) target:delPetMod(MOD_FOOD_ACCP, 10) target:delPetMod(MOD_FOOD_ACC_CAP, 75) end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Southern_San_dOria/npcs/HomePoint#1.lua
12
1272
----------------------------------- -- Area: Southern San dOria -- NPC: HomePoint#1 -- @pos -85.468 1.000 -66.454 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
LordError/LordError1
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
nesstea/darkstar
scripts/zones/Waughroon_Shrine/npcs/Burning_Circle.lua
13
2263
----------------------------------- -- Area: Waughroon Shrine -- NPC: Burning Circle -- Waughroon Shrine Burning Circle -- @pos -345 104 -260 144 ------------------------------------- package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Waughroon_Shrine/TextIDs"); ---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad" ---- 1: Worms Turn ---- 2: Grimshell Shocktroopers ---- 3: On my Way ---- 4: Thief in Norg ---- 5: 3, 2, 1 ---- 6: Shattering Stars (RDM) ---- 7: Shattering Stars (THF) ---- 8: Shattering Stars (BST) ---- 9: Birds of the feather ---- 10: Crustacean Conundrum ---- 11: Grove Gardians ---- 12: The Hills are alive ---- 13: Royal Jelly ---- 14: The Final Bout ---- 15: Up in arms ---- 16: Copy Cat ---- 17: Operation Desert Swarm ---- 18: Prehistoric Pigeons ---- 19: The Palborough Project ---- 20: Shell Shocked ---- 21: Beyond infinity ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Mashape/kong
kong/plugins/acl/groups.lua
1
5454
local tablex = require "pl.tablex" local EMPTY = tablex.readonly {} local kong = kong local type = type local mt_cache = { __mode = "k" } local setmetatable = setmetatable local consumer_groups_cache = setmetatable({}, mt_cache) local consumer_in_groups_cache = setmetatable({}, mt_cache) local function load_groups_into_memory(consumer_pk) local groups = {} local len = 0 for row, err in kong.db.acls:each_for_consumer(consumer_pk) do if err then return nil, err end len = len + 1 groups[len] = row end return groups end --- Returns the database records with groups the consumer belongs to -- @param consumer_id (string) the consumer for which to fetch the groups it belongs to -- @return table with group records (empty table if none), or nil+error local function get_consumer_groups_raw(consumer_id) local cache_key = kong.db.acls:cache_key(consumer_id) local raw_groups, err = kong.cache:get(cache_key, nil, load_groups_into_memory, { id = consumer_id }) if err then return nil, err end -- use EMPTY to be able to use it as a cache key, since a new table would -- immediately be collected again and not allow for negative caching. return raw_groups or EMPTY end --- Returns a table with all group names a consumer belongs to. -- The table will have an array part to iterate over, and a hash part -- where each group name is indexed by itself. Eg. -- { -- [1] = "users", -- [2] = "admins", -- users = "users", -- admins = "admins", -- } -- If there are no groups defined, it will return an empty table -- @param consumer_id (string) the consumer for which to fetch the groups it belongs to -- @return table with groups (empty table if none) or nil+error local function get_consumer_groups(consumer_id) local raw_groups, err = get_consumer_groups_raw(consumer_id) if not raw_groups then return nil, err end local groups = consumer_groups_cache[raw_groups] if not groups then groups = {} consumer_groups_cache[raw_groups] = groups for i = 1, #raw_groups do local group = raw_groups[i].group groups[i] = group groups[group] = group end end return groups end --- checks whether a consumer-group-list is part of a given list of groups. -- @param groups_to_check (table) an array of group names. Note: since the -- results will be cached by this table, always use the same table for the -- same set of groups! -- @param consumer_groups (table) list of consumer groups (result from -- `get_consumer_groups`) -- @return (boolean) whether the consumer is part of any of the groups. local function consumer_in_groups(groups_to_check, consumer_groups) -- 1st level cache on "groups_to_check" local result1 = consumer_in_groups_cache[groups_to_check] if result1 == nil then result1 = setmetatable({}, mt_cache) consumer_in_groups_cache[groups_to_check] = result1 end -- 2nd level cache on "consumer_groups" local result2 = result1[consumer_groups] if result2 ~= nil then return result2 end -- not found, so validate and populate 2nd level cache result2 = false for i = 1, #groups_to_check do if consumer_groups[groups_to_check[i]] then result2 = true break end end result1[consumer_groups] = result2 return result2 end --- Gets the currently identified consumer for the request. -- Checks both consumer and if not found the credentials. -- @return consumer_id (string), or alternatively `nil` if no consumer was -- authenticated. local function get_current_consumer_id() return (kong.client.get_consumer() or EMPTY).id or (kong.client.get_credential() or EMPTY).consumer_id end --- Returns a table with all group names. -- The table will have an array part to iterate over, and a hash part -- where each group name is indexed by itself. Eg. -- { -- [1] = "users", -- [2] = "admins", -- users = "users", -- admins = "admins", -- } -- If there are no authenticated_groups defined, it will return nil -- @return table with groups or nil local function get_authenticated_groups() local authenticated_groups = kong.ctx.shared.authenticated_groups if type(authenticated_groups) ~= "table" then authenticated_groups = ngx.ctx.authenticated_groups if authenticated_groups == nil then return nil end if type(authenticated_groups) ~= "table" then kong.log.warn("invalid authenticated_groups, a table was expected") return nil end end local groups = {} for i = 1, #authenticated_groups do groups[i] = authenticated_groups[i] groups[authenticated_groups[i]] = authenticated_groups[i] end return groups end --- checks whether a group-list is part of a given list of groups. -- @param groups_to_check (table) an array of group names. -- @param groups (table) list of groups (result from -- `get_authenticated_groups`) -- @return (boolean) whether the authenticated group is part of any of the -- groups. local function group_in_groups(groups_to_check, groups) for i = 1, #groups_to_check do if groups[groups_to_check[i]] then return true end end end return { get_current_consumer_id = get_current_consumer_id, get_consumer_groups = get_consumer_groups, get_authenticated_groups = get_authenticated_groups, consumer_in_groups = consumer_in_groups, group_in_groups = group_in_groups, }
apache-2.0
amirmrbad/teleatom
plugins/spammer.lua
86
65983
local function run(msg) if msg.text == "[!/]killwili" then return "".. [[ kose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nv ]] end end return { description = "Spamms the group fastly", usage = "!fuck or Fuckgp or Fuck : send 10000 Spams to the group", patterns = { "^[!/]fuck$", "^fuckgp$", "^Fuck$", "^spam$", "^Fuckgp$", }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
akdor1154/awesome
lib/naughty/core.lua
1
24047
---------------------------------------------------------------------------- --- Notification library -- -- @author koniu &lt;gkusnierz@gmail.com&gt; -- @copyright 2008 koniu -- @release @AWESOME_VERSION@ -- @module naughty ---------------------------------------------------------------------------- -- Package environment local pairs = pairs local table = table local type = type local string = string local pcall = pcall local capi = { screen = screen, awesome = awesome } local timer = require("gears.timer") local button = require("awful.button") local screen = require("awful.screen") local util = require("awful.util") local bt = require("beautiful") local wibox = require("wibox") local surface = require("gears.surface") local cairo = require("lgi").cairo local dpi = require("beautiful").xresources.apply_dpi local function get_screen(s) return s and capi.screen[s] end local naughty = {} --[[-- Naughty configuration - a table containing common popup settings. @table naughty.config @tfield[opt=apply_dpi(4)] int padding Space between popups and edge of the workarea. @tfield[opt=apply_dpi(1)] int spacing Spacing between popups. @tfield[opt={"/usr/share/pixmaps/"}] table icon_dirs List of directories that will be checked by `getIcon()`. @tfield[opt={ "png", "gif" }] table icon_formats List of formats that will be checked by `getIcon()`. @tfield[opt] function notify_callback Callback used to modify or reject notifications, e.g. naughty.config.notify_callback = function(args) args.text = 'prefix: ' .. args.text return args end @tfield table presets Notification presets. See `config.presets`. @tfield table defaults Default values for the params to `notify()`. These can optionally be overridden by specifying a preset. See `config.defaults`. --]] -- naughty.config = { padding = dpi(4), spacing = dpi(1), icon_dirs = { "/usr/share/pixmaps/", }, icon_formats = { "png", "gif" }, notify_callback = nil, } --- Notification presets for `naughty.notify`. -- This holds presets for different purposes. A preset is a table of any -- parameters for `notify()`, overriding the default values -- (`naughty.config.defaults`). -- -- You have to pass a reference of a preset in your `notify()` as the `preset` -- argument. -- -- The presets `"low"`, `"normal"` and `"critical"` are used for notifications -- over DBUS. -- -- @table config.presets -- @tfield table low The preset for notifications with low urgency level. -- @tfield[opt=5] int low.timeout -- @tfield[opt=empty] table normal The default preset for every notification without a -- preset that will also be used for normal urgency level. -- @tfield table critical The preset for notifications with a critical urgency -- level. -- @tfield[opt="#ff0000"] string critical.bg -- @tfield[opt="#ffffff"] string critical.fg -- @tfield[opt=0] string critical.timeout naughty.config.presets = { low = { timeout = 5 }, normal = {}, critical = { bg = "#ff0000", fg = "#ffffff", timeout = 0, } } --- Defaults for `naughty.notify`. -- -- @table config.defaults -- @tfield[opt=5] int timeout -- @tfield[opt=""] string text -- @tfield[opt] int screen Defaults to `awful.screen.focused`. -- @tfield[opt=true] boolean ontop -- @tfield[opt=apply_dpi(5)] int margin -- @tfield[opt=apply_dpi(1)] int border_width -- @tfield[opt="top_right"] string position naughty.config.defaults = { timeout = 5, text = "", screen = nil, ontop = true, margin = dpi(5), border_width = dpi(1), position = "top_right" } naughty.notificationClosedReason = { silent = -1, expired = 1, dismissedByUser = 2, dismissedByCommand = 3, undefined = 4 } -- Counter for the notifications -- Required for later access via DBUS local counter = 1 -- True if notifying is suspended local suspended = false --- Index of notifications per screen and position. -- See config table for valid 'position' values. -- Each element is a table consisting of: -- -- @field box Wibox object containing the popup -- @field height Popup height -- @field width Popup width -- @field die Function to be executed on timeout -- @field id Unique notification id based on a counter -- @table notifications naughty.notifications = { suspended = { } } for s in capi.screen do naughty.notifications[get_screen(s)] = { top_left = {}, top_middle = {}, top_right = {}, bottom_left = {}, bottom_middle = {}, bottom_right = {}, } end --- Notification state function naughty.is_suspended() return suspended end --- Suspend notifications function naughty.suspend() suspended = true end --- Resume notifications function naughty.resume() suspended = false for _, v in pairs(naughty.notifications.suspended) do v.box.visible = true if v.timer then v.timer:start() end end naughty.notifications.suspended = { } end --- Toggle notification state function naughty.toggle() if suspended then naughty.resume() else naughty.suspend() end end --- Evaluate desired position of the notification by index - internal -- -- @param s Screen to use -- @param position top_right | top_left | bottom_right | bottom_left -- | top_middle | bottom_middle -- @param idx Index of the notification -- @param[opt] width Popup width. -- @param height Popup height -- @return Absolute position and index in { x = X, y = Y, idx = I } table local function get_offset(s, position, idx, width, height) s = get_screen(s) local ws = s.workarea local v = {} idx = idx or #naughty.notifications[s][position] + 1 width = width or naughty.notifications[s][position][idx].width -- calculate x if position:match("left") then v.x = ws.x + naughty.config.padding elseif position:match("middle") then v.x = (ws.width / 2) - (width / 2) else v.x = ws.x + ws.width - (width + naughty.config.padding) end -- calculate existing popups' height local existing = 0 for i = 1, idx-1, 1 do existing = existing + naughty.notifications[s][position][i].height + naughty.config.spacing end -- calculate y if position:match("top") then v.y = ws.y + naughty.config.padding + existing else v.y = ws.y + ws.height - (naughty.config.padding + height + existing) end -- Find old notification to replace in case there is not enough room. -- This tries to skip permanent notifications (without a timeout), -- e.g. critical ones. local find_old_to_replace = function() for i = 1, idx-1 do local n = naughty.notifications[s][position][i] if n.timeout > 0 then return n end end -- Fallback to first one. return naughty.notifications[s][position][1] end -- if positioned outside workarea, destroy oldest popup and recalculate if v.y + height > ws.y + ws.height or v.y < ws.y then naughty.destroy(find_old_to_replace()) idx = idx - 1 v = get_offset(s, position, idx, width, height) end if not v.idx then v.idx = idx end return v end --- Re-arrange notifications according to their position and index - internal -- -- @return None local function arrange(s) for p in pairs(naughty.notifications[s]) do for i,notification in pairs(naughty.notifications[s][p]) do local offset = get_offset(s, p, i, notification.width, notification.height) notification.box:geometry({ x = offset.x, y = offset.y }) notification.idx = offset.idx end end end --- Destroy notification by notification object -- -- @param notification Notification object to be destroyed -- @param reason One of the reasons from notificationClosedReason -- @return True if the popup was successfully destroyed, nil otherwise function naughty.destroy(notification, reason) if notification and notification.box.visible then if suspended then for k, v in pairs(naughty.notifications.suspended) do if v.box == notification.box then table.remove(naughty.notifications.suspended, k) break end end end local scr = notification.screen table.remove(naughty.notifications[scr][notification.position], notification.idx) if notification.timer then notification.timer:stop() end notification.box.visible = false arrange(scr) if notification.destroy_cb and reason ~= naughty.notificationClosedReason.silent then notification.destroy_cb(reason or naughty.notificationClosedReason.undefined) end return true end end --- Get notification by ID -- -- @param id ID of the notification -- @return notification object if it was found, nil otherwise function naughty.getById(id) -- iterate the notifications to get the notfications with the correct ID for s in pairs(naughty.notifications) do for p in pairs(naughty.notifications[s]) do for _, notification in pairs(naughty.notifications[s][p]) do if notification.id == id then return notification end end end end end --- Install expiration timer for notification object. -- @tparam notification notification Notification object. -- @tparam number timeout Time in seconds to be set as expiration timeout. local function set_timeout(notification, timeout) local die = function (reason) naughty.destroy(notification, reason) end if timeout > 0 then local timer_die = timer { timeout = timeout } timer_die:connect_signal("timeout", function() die(naughty.notificationClosedReason.expired) end) if not suspended then timer_die:start() end notification.timer = timer_die end notification.die = die end --- Set new notification timeout. -- @tparam notification notification Notification object, which timer is to be reset. -- @tparam number new_timeout Time in seconds after which notification disappears. -- @return None. function naughty.reset_timeout(notification, new_timeout) if notification.timer then notification.timer:stop() end local timeout = new_timeout or notification.timeout set_timeout(notification, timeout) notification.timeout = timeout notification.timer:start() end --- Escape and set title and text for notification object. -- @tparam notification notification Notification object. -- @tparam string title Title of notification. -- @tparam string text Main text of notification. -- @return None. local function set_text(notification, title, text) local escape_pattern = "[<>&]" local escape_subs = { ['<'] = "&lt;", ['>'] = "&gt;", ['&'] = "&amp;" } local textbox = notification.textbox local function setMarkup(pattern, replacements) return textbox:set_markup_silently(string.format('<b>%s</b>%s', title, text:gsub(pattern, replacements))) end local function setText() textbox:set_text(string.format('%s %s', title, text)) end -- Since the title cannot contain markup, it must be escaped first so that -- it is not interpreted by Pango later. title = title:gsub(escape_pattern, escape_subs) -- Try to set the text while only interpreting <br>. if not setMarkup("<br.->", "\n") then -- That failed, escape everything which might cause an error from pango if not setMarkup(escape_pattern, escape_subs) then -- Ok, just ignore all pango markup. If this fails, we got some invalid utf8 if not pcall(setText) then textbox:set_markup("<i>&lt;Invalid markup or UTF8, cannot display message&gt;</i>") end end end end --- Replace title and text of an existing notification. -- @tparam notification notification Notification object, which contents are to be replaced. -- @tparam string new_title New title of notification. If not specified, old title remains unchanged. -- @tparam string new_text New text of notification. If not specified, old text remains unchanged. -- @return None. function naughty.replace_text(notification, new_title, new_text) local title = new_title if title then title = title .. "\n" else title = "" end set_text(notification, title, new_text) end --- Create a notification. -- -- @tab args The argument table containing any of the arguments below. -- @string[opt=""] args.text Text of the notification. -- @string[opt] args.title Title of the notification. -- @int[opt=5] args.timeout Time in seconds after which popup expires. -- Set 0 for no timeout. -- @int[opt] args.hover_timeout Delay in seconds after which hovered popup disappears. -- @tparam[opt=focused] integer|screen args.screen Target screen for the notification. -- @string[opt="top_right"] args.position Corner of the workarea displaying the popups. -- Values: `"top_right"`, `"top_left"`, `"bottom_left"`, -- `"bottom_right"`, `"top_middle"`, `"bottom_middle"`. -- @bool[opt=true] args.ontop Boolean forcing popups to display on top. -- @int[opt=auto] args.height Popup height. -- @int[opt=auto] args.width Popup width. -- @string[opt=beautiful.font or awesome.font] args.font Notification font. -- @string[opt] args.icon Path to icon. -- @int[opt] args.icon_size Desired icon size in px. -- @string[opt=`beautiful.fg_focus` or `'#ffffff'`] args.fg Foreground color. -- @string[opt=`beautiful.bg_focus` or `'#535d6c'`] args.bg Background color. -- @int[opt=1] args.border_width Border width. -- @string[opt=`beautiful.border_focus` or `'#535d6c'`] args.border_color Border color. -- @tparam[opt] func args.run Function to run on left click. The notification -- object will be passed to it as an argument. -- You need to call e.g. -- `notification.die(naughty.notificationClosedReason.dismissedByUser)` from -- there to dismiss the notification yourself. -- @tparam[opt] func args.destroy Function to run when notification is destroyed. -- @tparam[opt] table args.preset Table with any of the above parameters. -- Note: Any parameters specified directly in args will override ones defined -- in the preset. -- @tparam[opt] int args.replaces_id Replace the notification with the given ID. -- @tparam[opt] func args.callback Function that will be called with all arguments. -- The notification will only be displayed if the function returns true. -- Note: this function is only relevant to notifications sent via dbus. -- @tparam[opt] table args.actions Mapping that maps a string to a callback when this -- action is selected. -- @usage naughty.notify({ title = "Achtung!", text = "You're idling", timeout = 0 }) -- @return The notification object function naughty.notify(args) if naughty.config.notify_callback then args = naughty.config.notify_callback(args) if not args then return end end -- gather variables together local preset = util.table.join(naughty.config.defaults or {}, args.preset or naughty.config.presets.normal or {}) local timeout = args.timeout or preset.timeout local icon = args.icon or preset.icon local icon_size = args.icon_size or preset.icon_size local text = args.text or preset.text local title = args.title or preset.title local s = get_screen(args.screen or preset.screen or screen.focused()) local ontop = args.ontop or preset.ontop local width = args.width or preset.width local height = args.height or preset.height local hover_timeout = args.hover_timeout or preset.hover_timeout local opacity = args.opacity or preset.opacity local margin = args.margin or preset.margin local border_width = args.border_width or preset.border_width local position = args.position or preset.position local actions = args.actions local destroy_cb = args.destroy -- beautiful local beautiful = bt.get() local font = args.font or preset.font or beautiful.font or capi.awesome.font local fg = args.fg or preset.fg or beautiful.fg_normal or '#ffffff' local bg = args.bg or preset.bg or beautiful.bg_normal or '#535d6c' local border_color = args.border_color or preset.border_color or beautiful.bg_focus or '#535d6c' local notification = { screen = s, destroy_cb = destroy_cb, timeout = timeout } -- replace notification if needed if args.replaces_id then local obj = naughty.getById(args.replaces_id) if obj then -- destroy this and ... naughty.destroy(obj, naughty.notificationClosedReason.silent) end -- ... may use its ID if args.replaces_id <= counter then notification.id = args.replaces_id else counter = counter + 1 notification.id = counter end else -- get a brand new ID counter = counter + 1 notification.id = counter end notification.position = position if title then title = title .. "\n" else title = "" end -- hook destroy set_timeout(notification, timeout) local die = notification.die local run = function () if args.run then args.run(notification) else die(naughty.notificationClosedReason.dismissedByUser) end end local hover_destroy = function () if hover_timeout == 0 then die(naughty.notificationClosedReason.expired) else if notification.timer then notification.timer:stop() end notification.timer = timer { timeout = hover_timeout } notification.timer:connect_signal("timeout", function() die(naughty.notificationClosedReason.expired) end) notification.timer:start() end end -- create textbox local textbox = wibox.widget.textbox() local marginbox = wibox.layout.margin() marginbox:set_margins(margin) marginbox:set_widget(textbox) textbox:set_valign("middle") textbox:set_font(font) notification.textbox = textbox set_text(notification, title, text) local actionslayout = wibox.layout.fixed.vertical() local actions_max_width = 0 local actions_total_height = 0 if actions then for action, callback in pairs(actions) do local actiontextbox = wibox.widget.textbox() local actionmarginbox = wibox.layout.margin() actionmarginbox:set_margins(margin) actionmarginbox:set_widget(actiontextbox) actiontextbox:set_valign("middle") actiontextbox:set_font(font) actiontextbox:set_markup(string.format('<b>%s</b>', action)) -- calculate the height and width local w, h = actiontextbox:get_preferred_size(s) local action_height = h + 2 * margin local action_width = w + 2 * margin actionmarginbox:buttons(util.table.join( button({ }, 1, callback), button({ }, 3, callback) )) actionslayout:add(actionmarginbox) actions_total_height = actions_total_height + action_height if actions_max_width < action_width then actions_max_width = action_width end end end -- create iconbox local iconbox = nil local iconmargin = nil local icon_w, icon_h = 0, 0 if icon then -- Is this really an URI instead of a path? if type(icon) == "string" and string.sub(icon, 1, 7) == "file://" then icon = string.sub(icon, 8) end -- try to guess icon if the provided one is non-existent/readable if type(icon) == "string" and not util.file_readable(icon) then icon = util.geticonpath(icon, naughty.config.icon_formats, naughty.config.icon_dirs, icon_size) or icon end -- is the icon file readable? icon = surface.load_uncached(icon) -- if we have an icon, use it if icon then iconbox = wibox.widget.imagebox() iconmargin = wibox.layout.margin(iconbox, margin, margin, margin, margin) if icon_size then local scaled = cairo.ImageSurface(cairo.Format.ARGB32, icon_size, icon_size) local cr = cairo.Context(scaled) cr:scale(icon_size / icon:get_height(), icon_size / icon:get_width()) cr:set_source_surface(icon, 0, 0) cr:paint() icon = scaled end iconbox:set_resize(false) iconbox:set_image(icon) icon_w = icon:get_width() icon_h = icon:get_height() end end -- create container wibox notification.box = wibox({ fg = fg, bg = bg, border_color = border_color, border_width = border_width, type = "notification" }) if hover_timeout then notification.box:connect_signal("mouse::enter", hover_destroy) end -- calculate the width if not width then local w, _ = textbox:get_preferred_size(s) width = w + (iconbox and icon_w + 2 * margin or 0) + 2 * margin end if width < actions_max_width then width = actions_max_width end -- calculate the height if not height then local w = width - (iconbox and icon_w + 2 * margin or 0) - 2 * margin local h = textbox:get_height_for_width(w, s) if iconbox and icon_h + 2 * margin > h + 2 * margin then height = icon_h + 2 * margin else height = h + 2 * margin end end height = height + actions_total_height -- crop to workarea size if too big local workarea = s.workarea if width > workarea.width - 2 * (border_width or 0) - 2 * (naughty.config.padding or 0) then width = workarea.width - 2 * (border_width or 0) - 2 * (naughty.config.padding or 0) end if height > workarea.height - 2 * (border_width or 0) - 2 * (naughty.config.padding or 0) then height = workarea.height - 2 * (border_width or 0) - 2 * (naughty.config.padding or 0) end -- set size in notification object notification.height = height + 2 * (border_width or 0) notification.width = width + 2 * (border_width or 0) -- position the wibox local offset = get_offset(s, notification.position, nil, notification.width, notification.height) notification.box.ontop = ontop notification.box:geometry({ width = width, height = height, x = offset.x, y = offset.y }) notification.box.opacity = opacity notification.box.visible = true notification.idx = offset.idx -- populate widgets local layout = wibox.layout.fixed.horizontal() if iconmargin then layout:add(iconmargin) end layout:add(marginbox) local completelayout = wibox.layout.fixed.vertical() completelayout:add(layout) completelayout:add(actionslayout) notification.box:set_widget(completelayout) -- Setup the mouse events layout:buttons(util.table.join(button({ }, 1, run), button({ }, 3, function() die(naughty.notificationClosedReason.dismissedByUser) end))) -- insert the notification to the table table.insert(naughty.notifications[s][notification.position], notification) if suspended then notification.box.visible = false table.insert(naughty.notifications.suspended, notification) end -- return the notification return notification end return naughty -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
UnfortunateFruit/darkstar
scripts/globals/abilities/animated_flourish.lua
28
2228
----------------------------------- -- Ability: Animated Flourish -- Provokes the target. Requires at least one, but uses two Finishing Moves. -- Obtained: Dancer Level 20 -- Finishing Moves Used: 1-2 -- Recast Time: 00:30 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then return 0,0; else return MSGBASIC_NO_FINISHINGMOVES,0; end; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_1); --Add extra enmity if 2 finishing moves are used elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_2); target:addEnmity(player, 0, 500); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3); player:addStatusEffect(EFFECT_FINISHING_MOVE_1,1,0,7200); target:addEnmity(player, 0, 500); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4); player:addStatusEffect(EFFECT_FINISHING_MOVE_2,1,0,7200); target:addEnmity(player, 0, 500); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_5); player:addStatusEffect(EFFECT_FINISHING_MOVE_3,1,0,7200); target:addEnmity(player, 0, 500); end; end;
gpl-3.0
ruisebastiao/nodemcu-firmware
lua_examples/u8glib/u8g_rotation.lua
43
2088
-- setup I2c and connect display function init_i2c_display() -- SDA and SCL can be assigned freely to available GPIOs local sda = 5 -- GPIO14 local scl = 6 -- GPIO12 local sla = 0x3c i2c.setup(0, sda, scl, i2c.SLOW) disp = u8g.ssd1306_128x64_i2c(sla) end -- setup SPI and connect display function init_spi_display() -- Hardware SPI CLK = GPIO14 -- Hardware SPI MOSI = GPIO13 -- Hardware SPI MISO = GPIO12 (not used) -- CS, D/C, and RES can be assigned freely to available GPIOs local cs = 8 -- GPIO15, pull-down 10k to GND local dc = 4 -- GPIO2 local res = 0 -- GPIO16 spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, spi.DATABITS_8, 0) disp = u8g.ssd1306_128x64_spi(cs, dc, res) end -- the draw() routine function draw() disp:setFont(u8g.font_6x10) disp:drawStr( 0+0, 20+0, "Hello!") disp:drawStr( 0+2, 20+16, "Hello!") disp:drawBox(0, 0, 3, 3) disp:drawBox(disp:getWidth()-6, 0, 6, 6) disp:drawBox(disp:getWidth()-9, disp:getHeight()-9, 9, 9) disp:drawBox(0, disp:getHeight()-12, 12, 12) end function rotate() if (next_rotation < tmr.now() / 1000) then if (dir == 0) then disp:undoRotation() elseif (dir == 1) then disp:setRot90() elseif (dir == 2) then disp:setRot180() elseif (dir == 3) then disp:setRot270() end dir = dir + 1 dir = bit.band(dir, 3) -- schedule next rotation step in 1000ms next_rotation = tmr.now() / 1000 + 1000 end end function rotation_test() print("--- Starting Rotation Test ---") dir = 0 next_rotation = 0 local loopcnt for loopcnt = 1, 100, 1 do rotate() disp:firstPage() repeat draw(draw_state) until disp:nextPage() == false tmr.delay(100000) tmr.wdclr() end print("--- Rotation Test done ---") end --init_i2c_display() init_spi_display() rotation_test()
mit
nesstea/darkstar
scripts/zones/Wajaom_Woodlands/npcs/qm1.lua
30
1349
----------------------------------- -- Area: Wajaom Woodlands -- NPC: ??? (Spawn Vulpangue(ZNM T1)) -- @pos -697 -7 -123 51 ----------------------------------- package.loaded["scripts/zones/Wajaom_Woodlands/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Wajaom_Woodlands/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 16986428; if (trade:hasItemQty(2580,1) and trade:getItemCount() == 1) then -- Trade Hellcage Butterfly if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ennis/autograph-pipelines
resources/glsl/blurCompute.lua
1
3478
require 'gl' local CS = [[ #version 450 #include "utils.glsl" // Adapted from: // http://callumhay.blogspot.com/2010/09/gaussian-blur-shader-glsl.html layout(binding = 0, FORMAT) readonly uniform image2D tex0; layout(binding = 1, FORMAT) writeonly uniform image2D tex1; layout(binding = 0, std140) uniform U0 { int blurSize; float sigma; float sstep_low; float sstep_high; }; layout(local_size_x = LOCAL_SIZE_X, local_size_y = LOCAL_SIZE_Y) in; vec4 linstep(float edge0, float edge1, vec4 x) { vec4 t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); return mix(vec4(0.0f), vec4(1.0f), t); } void main() { ivec2 texelCoords = ivec2(gl_GlobalInvocationID.xy); float numBlurPixelsPerSide = float(blurSize / 2); #ifdef BLUR_H ivec2 blurMultiplyVec = ivec2(1, 0); #else ivec2 blurMultiplyVec = ivec2(0, 1); #endif // Incremental Gaussian Coefficent Calculation (See GPU Gems 3 pp. 877 - 889) vec3 incrementalGaussian; incrementalGaussian.x = 1.0 / (sqrt(TWOPI) * sigma); incrementalGaussian.y = exp(-0.5 / (sigma * sigma)); incrementalGaussian.z = incrementalGaussian.y * incrementalGaussian.y; vec4 avgValue = vec4(0.0, 0.0, 0.0, 0.0); float coefficientSum = 0.0; // Take the central sample first... avgValue += imageLoad(tex0, texelCoords) * incrementalGaussian.x; coefficientSum += incrementalGaussian.x; incrementalGaussian.xy *= incrementalGaussian.yz; // Go through the remaining 8 vertical samples (4 on each side of the center) for (int i = 1; i <= numBlurPixelsPerSide; i++) { avgValue += imageLoad(tex0, texelCoords - i * blurMultiplyVec) * incrementalGaussian.x; avgValue += imageLoad(tex0, texelCoords + i * blurMultiplyVec) * incrementalGaussian.x; coefficientSum += 2.0 * incrementalGaussian.x; incrementalGaussian.xy *= incrementalGaussian.yz; } imageStore(tex1, texelCoords, linstep(sstep_low, sstep_high, avgValue / coefficientSum)); //imageStore(tex1, texelCoords, imageLoad(tex0, texelCoords)); memoryBarrierImage(); } ]] Shader('blurComputeH', { computeShaderFile = 'blurCompute.glsl', defines = { BLUR_H = true } }) Shader('blurComputeV', { computeShaderFile = 'blurCompute.glsl', defines = { BLUR_V = true } }) -- One file = one pass => NO -- One file = multiple passes -- One file = template for passes -- 1. Load shader file in context -- 2. call createShaderPass(shaderId, params) -- 2.1. call a function defined in the shader file that returns a complete state -- 3. get shader! -- From C++: -- shaderMan.load("resources/shaders/deferred") -- actually just does L.require("resources/shaders/deferred") -- shaderMan.getPass("deferred") -- calls autograph.createShaderPass('deferred', {}) and returns a table, then calls DrawPassBuilder::loadFromTable() -- Multi-compile: -- shaderMan.load("resources/shaders/blurCompute") -- blurHPass = shaderMan.getPass("blurComputeH", "FORMAT=rgba8") -- blurVPass = shaderMan.getPass("blurComputeV", "FORMAT=rgba8") -- From Lua: -- require 'shaders/blurCompute' -- blurH = loadShaderPass('blurCompute', 'BLUR_H') -- one source => multiple shader passes (one for each combination of keywords) -- one source => infinite number of shader passes (float constant parameters) -- the question boils down to: do we want to be able to run arbitrary code in shader templates -- VS only preprocessor keywords and simple text replacement => this one -- Lua: createShaderPass(shader, params)
mit
UnfortunateFruit/darkstar
scripts/zones/La_Theine_Plateau/npcs/Telepoint.lua
17
1631
----------------------------------- -- Area: La Theine Plateau -- NPC: Telepoint ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local item = trade:getItem(); if(trade:getItemCount() == 1 and item > 4095 and item < 4104) then if(player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then player:tradeComplete(); player:addItem(613); player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(HOLLA_GATE_CRYSTAL) == false) then player:addKeyItem(HOLLA_GATE_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,HOLLA_GATE_CRYSTAL); else player:messageSpecial(ALREADY_OBTAINED_TELE); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/effects/tabula_rasa.lua
37
3360
----------------------------------- -- -- -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local regen = effect:getSubPower(); local helix = effect:getPower(); if (target:hasStatusEffect(EFFECT_LIGHT_ARTS) or target:hasStatusEffect(EFFECT_ADDENDUM_WHITE)) then target:addMod(MOD_BLACK_MAGIC_COST, -30); target:addMod(MOD_BLACK_MAGIC_CAST, -30); target:addMod(MOD_BLACK_MAGIC_RECAST, -30); target:addMod(MOD_REGEN_EFFECT, math.ceil(regen/1.5)); target:addMod(MOD_REGEN_DURATION, math.ceil((regen*2)/1.5)); target:addMod(MOD_HELIX_EFFECT, helix); target:addMod(MOD_HELIX_DURATION, 108); elseif (target:hasStatusEffect(EFFECT_DARK_ARTS) or target:hasStatusEffect(EFFECT_ADDENDUM_BLACK)) then target:addMod(MOD_WHITE_MAGIC_COST, -30); target:addMod(MOD_WHITE_MAGIC_CAST, -30); target:addMod(MOD_WHITE_MAGIC_RECAST, -30); target:addMod(MOD_REGEN_EFFECT, regen); target:addMod(MOD_REGEN_DURATION, regen*2); target:addMod(MOD_HELIX_EFFECT, math.ceil(helix/1.5)); target:addMod(MOD_HELIX_DURATION, 36); else target:addMod(MOD_BLACK_MAGIC_COST, -10); target:addMod(MOD_BLACK_MAGIC_CAST, -10); target:addMod(MOD_BLACK_MAGIC_RECAST, -10); target:addMod(MOD_WHITE_MAGIC_COST, -10); target:addMod(MOD_WHITE_MAGIC_CAST, -10); target:addMod(MOD_WHITE_MAGIC_RECAST, -10); target:addMod(MOD_REGEN_EFFECT, regen); target:addMod(MOD_REGEN_DURATION, regen*2); target:addMod(MOD_HELIX_EFFECT, helix); target:addMod(MOD_HELIX_DURATION, 108); end end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local regen = effect:getSubPower(); local helix = effect:getPower(); if (target:hasStatusEffect(EFFECT_LIGHT_ARTS) or target:hasStatusEffect(EFFECT_ADDENDUM_WHITE)) then target:delMod(MOD_BLACK_MAGIC_COST, -30); target:delMod(MOD_BLACK_MAGIC_CAST, -30); target:delMod(MOD_BLACK_MAGIC_RECAST, -30); target:delMod(MOD_REGEN_EFFECT, math.ceil(regen/1.5)); target:delMod(MOD_REGEN_DURATION, math.ceil((regen*2)/1.5)); target:delMod(MOD_HELIX_EFFECT, helix); target:delMod(MOD_HELIX_DURATION, 108); elseif (target:hasStatusEffect(EFFECT_DARK_ARTS) or target:hasStatusEffect(EFFECT_ADDENDUM_BLACK)) then target:delMod(MOD_WHITE_MAGIC_COST, -30); target:delMod(MOD_WHITE_MAGIC_CAST, -30); target:delMod(MOD_WHITE_MAGIC_RECAST, -30); target:delMod(MOD_REGEN_EFFECT, regen); target:delMod(MOD_REGEN_DURATION, regen*2); target:delMod(MOD_HELIX_EFFECT, math.ceil(helix/1.5)); target:delMod(MOD_HELIX_DURATION, 36); else target:delMod(MOD_BLACK_MAGIC_COST, -10); target:delMod(MOD_BLACK_MAGIC_CAST, -10); target:delMod(MOD_BLACK_MAGIC_RECAST, -10); target:delMod(MOD_WHITE_MAGIC_COST, -10); target:delMod(MOD_WHITE_MAGIC_CAST, -10); target:delMod(MOD_WHITE_MAGIC_RECAST, -10); target:delMod(MOD_REGEN_EFFECT, regen); target:delMod(MOD_REGEN_DURATION, regen*2); target:delMod(MOD_HELIX_EFFECT, helix); target:delMod(MOD_HELIX_DURATION, 108); end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Spire_of_Holla/npcs/_0h3.lua
39
1336
----------------------------------- -- Area: Spire_of_Holla -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Holla/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
nesstea/darkstar
scripts/zones/Spire_of_Holla/npcs/_0h2.lua
39
1336
----------------------------------- -- Area: Spire_of_Holla -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Holla/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
NezzKryptic/Wire-Extras
lua/entities/gmod_wire_rfid_implanter/init.lua
3
3606
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include('shared.lua') ENT.WireDebugName = "RFID Implanter" local MODEL = Model("models/jaanus/wiretool/wiretool_beamcaster.mdl") function ENT:ShowOutput(a,b,c,d) self:SetOverlayText( "RFID Implanter\nA="..a..";B="..b..";C="..c..";D="..d ) end function ENT:Initialize() self:SetModel( MODEL ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, { "Fire", "A", "B", "C", "D", "Remove" }) self.Outputs = Wire_CreateOutputs(self, { "Out" }) self.A = 0; self.B = 0; self.C = 0; self.D = 0; self.NoColorChg = false; self:SetBeamLength(2048) self:ShowOutput(0,0,0,0) end function ENT:OnRemove() Wire_Remove(self) end function ENT:Setup(Range, col) self:SetBeamLength(Range) self.NoColorChg = col end function ENT:TriggerInput(iname, value) if ((iname == "Fire" or iname=="Remove") and value~=0) then local vStart = self:GetPos() local vForward = self:GetUp() local trace = {} trace.start = vStart trace.endpos = vStart + (vForward * self:GetBeamLength()) trace.filter = { self } local trace = util.TraceLine( trace ) if (!trace.Entity) then return false end if (!trace.Entity:IsValid() ) then return false end if (trace.Entity:IsWorld()) then return false end if ( CLIENT ) then return true end if(iname == "Fire") then -- Implant/Update RFID trace.Entity.__RFID_HASRFID = true; trace.Entity.__RFID_A = self.A; trace.Entity.__RFID_B = self.B; trace.Entity.__RFID_C = self.C; trace.Entity.__RFID_D = self.D; duplicator.StoreEntityModifier(trace.Entity, "WireRFID", {A = self.A, B = self.B, C = self.C, D = self.D}) else -- Remove RFID trace.Entity.__RFID_HASRFID = false; trace.Entity.__RFID_A = nil; trace.Entity.__RFID_B = nil; trace.Entity.__RFID_C = nil; trace.Entity.__RFID_D = nil; duplicator.ClearEntityModifier(trace.Entity, "WireRFID") end -- Generate spark effect local effectdata = EffectData() effectdata:SetOrigin( trace.HitPos ) effectdata:SetNormal( trace.HitNormal ) effectdata:SetMagnitude( 5 ) effectdata:SetScale( 1 ) effectdata:SetRadius( 10 ) util.Effect( "Sparks", effectdata ) elseif iname=="A" or iname=="B" or iname=="C" or iname=="D" then self[iname] = value; self:ShowOutput(self.A,self.B,self.C,self.D) end end duplicator.RegisterEntityModifier( "WireRFID", function( ply, ent, data ) ent.__RFID_HASRFID = true ent.__RFID_A = data.A ent.__RFID_B = data.B ent.__RFID_C = data.C ent.__RFID_D = data.D end ) function ENT:Think() self.BaseClass.Think(self) local vStart = self:GetPos() local vForward = self:GetUp() local trace = {} trace.start = vStart trace.endpos = vStart + (vForward * self:GetBeamLength()) trace.filter = { self } local trace = util.TraceLine( trace ) local ent = trace.Entity if (!trace.Entity or !trace.Entity:IsValid() or trace.Entity:IsWorld() or !trace.Entity:GetPhysicsObject()) then if(!self.NoColorChg and self:GetColor() != Color(255,255,255,255))then self:SetColor(Color(255, 255, 255, 255)) end return false end if(!self.NoColorChg and self:GetColor() != Color(0,255,0,255))then self:SetColor(Color(0, 255, 0, 255)) end self:NextThink(CurTime()+0.125) end function ENT:OnRestore() Wire_Restored(self) end
gpl-3.0