repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
wesnoth/wesnoth | data/campaigns/World_Conquest/lua/map/utility.lua | 7 | 1038 |
globals = {}
setmetatable(globals, {
["__index"] = function(t, k)
return rawget(_G, k)
end,
["__newindex"] = function(t, k, v)
_G[k] = v
end,
})
function wct_enemy(side, com, item, train, sup, l2, l3)
return {
commander=com,
have_item=item,
trained=train,
supply=sup,
recall_level2 = l2,
recall_level3 = l3,
}
end
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
function shuffle_special_locations(map, loc_ids)
local locs = {}
for i , v in ipairs(loc_ids) do
-- this tostring fixes a problem becasue map.special_locations
-- is actually a table with map at index 1 so map.special_locations[1]
-- would just return 1.
locs[i] = map.special_locations[tostring(v)]
end
assert(#locs == #loc_ids)
mathx.shuffle(locs)
for i , v in ipairs(loc_ids) do
map.special_locations[tostring(v)] = locs[i]
end
end
function shallow_copy(t)
local res = {}
for i, v in pairs(t) do
res[i] = v
end
return res
end
wesnoth.dofile("./generator/utilities.lua")
| gpl-2.0 |
Mutos/StarsOfCall-NAEV | dat/factions/equip/independent.lua | 1 | 2273 | -- ================================================================================================================================
--
-- Define functions to equip a generic ship from the SoC TC
-- - Faction : independent
--
-- ================================================================================================================================
-- ================================================================================================================================
-- Generic equipping routines
-- ================================================================================================================================
--
include("dat/factions/equip/generic.lua")
--
-- ================================================================================================================================
-- ================================================================================================================================
-- Actually equip the ship
-- ================================================================================================================================
--
function equip ( p )
-- Get ship info
local class = p:ship():class()
local shipBaseType = p:ship():baseType()
local shipName = p:ship():name()
-- print ( string.format("\nEquipping independent ship \"%s\"", shipName) )
-- Split by type
equip_generic( p )
-- Set faction
p:setFaction( "Independent" )
-- p:rename ("Independent " .. p:name() )
-- Debug -- printout
outfits = p:outfits ()
for _,o in ipairs(outfits) do
slotName, slotSize = o:slot()
-- print ( string.format("\t\t%s %s : %s", slotSize, slotName, o:name () ))
end
ws_name, ws = p:weapset( true )
-- print ( "\tWeapon Set (true) Name: " .. ws_name )
for _,w in ipairs(ws) do
-- print ( string.format ("\t\t%s", w.name ) )
end
for i = 0, 9 do
ws_name, ws = p:weapset( 1 )
-- print ( string.format ( "\tWeapon Set (%i) Name: %s", i, ws_name ) )
for _,w in ipairs(ws) do
-- print ( string.format ("\t\t%s", w.name ) )
end
end
end
--
-- ================================================================================================================================
| gpl-3.0 |
fegimanam/LNT | plugins/time.lua | 771 | 2865 | -- Implement a command !time [area] which uses
-- 2 Google APIs to get the desired result:
-- 1. Geocoding to get from area to a lat/long pair
-- 2. Timezone to get the local time in that lat/long location
-- Globals
-- If you have a google api key for the geocoding/timezone api
api_key = nil
base_api = "https://maps.googleapis.com/maps/api"
dateFormat = "%A %d %B - %H:%M:%S"
-- Need the utc time for the google api
function utctime()
return os.time(os.date("!*t"))
end
-- Use the geocoding api to get the lattitude and longitude with accuracy specifier
-- CHECKME: this seems to work without a key??
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Get the data
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
-- Use timezone api to get the time in the lat,
-- Note: this needs an API key
function get_time(lat,lng)
local api = base_api .. "/timezone/json?"
-- Get a timestamp (server time is relevant here)
local timestamp = utctime()
local parameters = "location=" ..
URL.escape(lat) .. "," ..
URL.escape(lng) ..
"×tamp="..URL.escape(timestamp)
if api_key ~=nil then
parameters = parameters .. "&key="..api_key
end
local res,code = https.request(api..parameters)
if code ~= 200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Construct what we want
-- The local time in the location is:
-- timestamp + rawOffset + dstOffset
local localTime = timestamp + data.rawOffset + data.dstOffset
return localTime, data.timeZoneId
end
return localTime
end
function getformattedLocalTime(area)
if area == nil then
return "The time in nowhere is never"
end
lat,lng,acc = get_latlong(area)
if lat == nil and lng == nil then
return 'It seems that in "'..area..'" they do not have a concept of time.'
end
local localTime, timeZoneId = get_time(lat,lng)
return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime)
end
function run(msg, matches)
return getformattedLocalTime(matches[1])
end
return {
description = "Displays the local time in an area",
usage = "!time [area]: Displays the local time in that area",
patterns = {"^!time (.*)$"},
run = run
}
| gpl-2.0 |
ivendrov/nn | SpatialDivisiveNormalization.lua | 39 | 5171 | local SpatialDivisiveNormalization, parent = torch.class('nn.SpatialDivisiveNormalization','nn.Module')
function SpatialDivisiveNormalization:__init(nInputPlane, kernel, threshold, thresval)
parent.__init(self)
-- get args
self.nInputPlane = nInputPlane or 1
self.kernel = kernel or torch.Tensor(9,9):fill(1)
self.threshold = threshold or 1e-4
self.thresval = thresval or threshold or 1e-4
local kdim = self.kernel:nDimension()
-- check args
if kdim ~= 2 and kdim ~= 1 then
error('<SpatialDivisiveNormalization> averaging kernel must be 2D or 1D')
end
if (self.kernel:size(1) % 2) == 0 or (kdim == 2 and (self.kernel:size(2) % 2) == 0) then
error('<SpatialDivisiveNormalization> averaging kernel must have ODD dimensions')
end
-- padding values
local padH = math.floor(self.kernel:size(1)/2)
local padW = padH
if kdim == 2 then
padW = math.floor(self.kernel:size(2)/2)
end
-- create convolutional mean estimator
self.meanestimator = nn.Sequential()
self.meanestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH))
if kdim == 2 then
self.meanestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, self.kernel:size(2), self.kernel:size(1)))
else
self.meanestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(self.nInputPlane), self.kernel:size(1), 1))
self.meanestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, 1, self.kernel:size(1)))
end
self.meanestimator:add(nn.Replicate(self.nInputPlane,1,3))
-- create convolutional std estimator
self.stdestimator = nn.Sequential()
self.stdestimator:add(nn.Square())
self.stdestimator:add(nn.SpatialZeroPadding(padW, padW, padH, padH))
if kdim == 2 then
self.stdestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, self.kernel:size(2), self.kernel:size(1)))
else
self.stdestimator:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(self.nInputPlane), self.kernel:size(1), 1))
self.stdestimator:add(nn.SpatialConvolution(self.nInputPlane, 1, 1, self.kernel:size(1)))
end
self.stdestimator:add(nn.Replicate(self.nInputPlane,1,3))
self.stdestimator:add(nn.Sqrt())
-- set kernel and bias
if kdim == 2 then
self.kernel:div(self.kernel:sum() * self.nInputPlane)
for i = 1,self.nInputPlane do
self.meanestimator.modules[2].weight[1][i] = self.kernel
self.stdestimator.modules[3].weight[1][i] = self.kernel
end
self.meanestimator.modules[2].bias:zero()
self.stdestimator.modules[3].bias:zero()
else
self.kernel:div(self.kernel:sum() * math.sqrt(self.nInputPlane))
for i = 1,self.nInputPlane do
self.meanestimator.modules[2].weight[i]:copy(self.kernel)
self.meanestimator.modules[3].weight[1][i]:copy(self.kernel)
self.stdestimator.modules[3].weight[i]:copy(self.kernel)
self.stdestimator.modules[4].weight[1][i]:copy(self.kernel)
end
self.meanestimator.modules[2].bias:zero()
self.meanestimator.modules[3].bias:zero()
self.stdestimator.modules[3].bias:zero()
self.stdestimator.modules[4].bias:zero()
end
-- other operation
self.normalizer = nn.CDivTable()
self.divider = nn.CDivTable()
self.thresholder = nn.Threshold(self.threshold, self.thresval)
-- coefficient array, to adjust side effects
self.coef = torch.Tensor(1,1,1)
end
function SpatialDivisiveNormalization:updateOutput(input)
self.localstds = self.stdestimator:updateOutput(input)
-- compute side coefficients
local dim = input:dim()
if self.localstds:dim() ~= self.coef:dim() or (input:size(dim) ~= self.coef:size(dim)) or (input:size(dim-1) ~= self.coef:size(dim-1)) then
self.ones = self.ones or input.new()
if dim == 4 then
-- batch mode
self.ones:resizeAs(input[1]):fill(1)
local coef = self.meanestimator:updateOutput(self.ones)
self._coef = self._coef or input.new()
self._coef:resizeAs(coef):copy(coef) -- make contiguous for view
self.coef = self._coef:view(1,table.unpack(self._coef:size():totable())):expandAs(self.localstds)
else
self.ones:resizeAs(input):fill(1)
self.coef = self.meanestimator:updateOutput(self.ones)
end
end
-- normalize std dev
self.adjustedstds = self.divider:updateOutput{self.localstds, self.coef}
self.thresholdedstds = self.thresholder:updateOutput(self.adjustedstds)
self.output = self.normalizer:updateOutput{input, self.thresholdedstds}
-- done
return self.output
end
function SpatialDivisiveNormalization:updateGradInput(input, gradOutput)
-- resize grad
self.gradInput:resizeAs(input):zero()
-- backprop through all modules
local gradnorm = self.normalizer:updateGradInput({input, self.thresholdedstds}, gradOutput)
local gradadj = self.thresholder:updateGradInput(self.adjustedstds, gradnorm[2])
local graddiv = self.divider:updateGradInput({self.localstds, self.coef}, gradadj)
self.gradInput:add(self.stdestimator:updateGradInput(input, graddiv[1]))
self.gradInput:add(gradnorm[1])
-- done
return self.gradInput
end
| bsd-3-clause |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armaser.lua | 1 | 2861 | return {
armaser = {
acceleration = 0.11999999731779,
activatewhenbuilt = true,
brakerate = 0.15000000596046,
buildcostenergy = 1326,
buildcostmetal = 73,
buildpic = "ARMASER.DDS",
buildtime = 4937,
canattack = false,
canmove = true,
category = "KBOT MOBILE ALL NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE",
corpse = "DEAD",
description = "Radar Jammer Kbot",
energyuse = 100,
explodeas = "BIG_UNITEX",
footprintx = 2,
footprintz = 2,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
maxdamage = 305,
maxslope = 32,
maxvelocity = 1.6100000143051,
maxwaterdepth = 112,
movementclass = "KBOT2",
name = "Eraser",
nochasecategory = "MOBILE",
objectname = "ARMASER",
onoffable = true,
radardistancejam = 450,
seismicsignature = 0,
selfdestructas = "BIG_UNIT",
sightdistance = 260,
smoothanim = true,
turnrate = 1045,
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "0.136978149414 4.50317382814e-05 -6.27960205078",
collisionvolumescales = "28.490814209 34.7166900635 16.3992004395",
collisionvolumetype = "Box",
damage = 183,
description = "Eraser Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 1,
footprintz = 1,
height = 40,
hitdensity = 100,
metal = 47,
object = "ARMASER_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 92,
description = "Eraser Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 1,
footprintz = 1,
height = 4,
hitdensity = 100,
metal = 19,
object = "1X1A",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "kbarmmov",
},
select = {
[1] = "radjam1",
},
},
weapondefs = {
bogus_ground_missile = {
areaofeffect = 48,
craterboost = 0,
cratermult = 0,
impulseboost = 0,
impulsefactor = 0,
metalpershot = 0,
name = "Missiles",
range = 800,
reloadtime = 0.5,
startvelocity = 450,
tolerance = 9000,
turnrate = 33000,
turret = true,
weaponacceleration = 101,
weapontimer = 0.10000000149012,
weapontype = "Cannon",
weaponvelocity = 650,
damage = {
default = 0,
},
},
},
weapons = {
[1] = {
badtargetcategory = "MOBILE",
def = "BOGUS_GROUND_MISSILE",
onlytargetcategory = "NOTSUB",
},
},
},
}
| gpl-2.0 |
LightenPan/skynet-yule | lualib/http/httpc.lua | 42 | 2906 | local socket = require "http.sockethelper"
local url = require "http.url"
local internal = require "http.internal"
local string = string
local table = table
local httpc = {}
local function request(fd, method, host, url, recvheader, header, content)
local read = socket.readfunc(fd)
local write = socket.writefunc(fd)
local header_content = ""
if header then
if not header.host then
header.host = host
end
for k,v in pairs(header) do
header_content = string.format("%s%s:%s\r\n", header_content, k, v)
end
else
header_content = string.format("host:%s\r\n",host)
end
if content then
local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n\r\n%s", method, url, header_content, #content, content)
write(data)
else
local request_header = string.format("%s %s HTTP/1.1\r\n%scontent-length:0\r\n\r\n", method, url, header_content)
write(request_header)
end
local tmpline = {}
local body = internal.recvheader(read, tmpline, "")
if not body then
error(socket.socket_error)
end
local statusline = tmpline[1]
local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
code = assert(tonumber(code))
local header = internal.parseheader(tmpline,2,recvheader or {})
if not header then
error("Invalid HTTP response header")
end
local length = header["content-length"]
if length then
length = tonumber(length)
end
local mode = header["transfer-encoding"]
if mode then
if mode ~= "identity" and mode ~= "chunked" then
error ("Unsupport transfer-encoding")
end
end
if mode == "chunked" then
body, header = internal.recvchunkedbody(read, nil, header, body)
if not body then
error("Invalid response body")
end
else
-- identity mode
if length then
if #body >= length then
body = body:sub(1,length)
else
local padding = read(length - #body)
body = body .. padding
end
else
body = nil
end
end
return code, body
end
function httpc.request(method, host, url, recvheader, header, content)
local hostname, port = host:match"([^:]+):?(%d*)$"
if port == "" then
port = 80
else
port = tonumber(port)
end
local fd = socket.connect(hostname, port)
local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content)
socket.close(fd)
if ok then
return statuscode, body
else
error(statuscode)
end
end
function httpc.get(...)
return httpc.request("GET", ...)
end
local function escape(s)
return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02X", string.byte(c))
end))
end
function httpc.post(host, url, form, recvheader)
local header = {
["content-type"] = "application/x-www-form-urlencoded"
}
local body = {}
for k,v in pairs(form) do
table.insert(body, string.format("%s=%s",escape(k),escape(v)))
end
return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&"))
end
return httpc
| mit |
Anarchid/Zero-K | units/planelightscout.lua | 4 | 1981 | return { planelightscout = {
unitname = [[planelightscout]],
name = [[Sparrow]],
description = [[Light Scout Plane]],
brakerate = 0.4,
buildCostMetal = 235,
builder = false,
buildPic = [[planelightscout.png]],
canFly = true,
canGuard = true,
canMove = true,
canPatrol = true,
canSubmerge = false,
category = [[UNARMED FIXEDWING]],
collide = false,
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[14 14 45]],
collisionVolumeType = [[cylZ]],
corpse = [[DEAD]],
cruiseAlt = 220,
customParams = {
bait_level_target = 2,
modelradius = [[8]],
refuelturnradius = [[130]],
},
explodeAs = [[GUNSHIPEX]],
floater = true,
footprintX = 2,
footprintZ = 2,
iconType = [[scoutplane]],
idleAutoHeal = 5,
idleTime = 1800,
maxAcc = 0.5,
maxDamage = 350,
maxAileron = 0.016,
maxElevator = 0.022,
maxRudder = 0.012,
maxVelocity = 7,
noAutoFire = false,
noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]],
objectName = [[planelightscout.s3o]],
script = [[planelightscout.lua]],
selfDestructAs = [[GUNSHIPEX]],
sightDistance = 950,
turnRadius = 50,
workerTime = 0,
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[planelightscout_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2b.s3o]],
},
},
} }
| gpl-2.0 |
wesnoth/wesnoth | data/lua/functional.lua | 4 | 6671 | -- This file implements equivalents of various higher-order WFL functions
local functional = {}
---Filter an array for elements matching a certain condition
---@generic T
---@param input T[]
---@param condition fun(val:T):boolean
---@return T[]
function functional.filter(input, condition)
local filtered_table = {}
for _,v in ipairs(input) do
if condition(v) then
table.insert(filtered_table, v)
end
end
return filtered_table
end
---Filter a map for elements matching a certain condition
---@generic K
---@generic V
---@param input table<K, V>
---@param condition fun(key:K, val:V):boolean
---@return table<K, V>
function functional.filter_map(input, condition)
local filtered_table = {}
for k,v in pairs(input) do
if condition(k, v) then
filtered_table[k] = v
end
end
return filtered_table
end
---Search an array for an element matching a certain condition
---@generic T
---@param input T[]
---@param condition fun(val:T):boolean
---@return T[]
function functional.find(input, condition)
for _,v in ipairs(input) do
if condition(v) then
return v
end
end
end
---Search a map for a key-value pair matching a certain condition
---@generic K
---@generic V
---@param input table<K, V>
---@param condition fun(key:K, val:V):boolean
---@return K
---@return V
function functional.find_map(input, condition)
for k,v in pairs(input) do
if condition(k,v) then
return k, v
end
end
end
---Find the element of an array with the largest value
---@generic T
---@param input T[]
---@param value fun(val:T):number
---@return T
---@return number
---@return integer
function functional.choose(input, value)
-- Equivalent of choose() function in Formula AI
-- Returns element of a table with the largest @value (a function)
-- Also returns the max value and the index
if value == nil then
value = function(v) return v end
elseif type(value) ~= 'function' then
local key = value
value = function(v) return v[key] end
end
local max_value, best_input, best_key = -math.huge, nil, nil
for k,v in ipairs(input) do
local v2 = value(v)
if v2 > max_value then
max_value, best_input, best_key = v2, v, k
end
end
return best_input, max_value, best_key
end
---Find the key-value pair in a map with the largest value
---@generic K
---@generic V
---@param input table<K, V>
---@param value fun(key:K, val:V):number
---@return {[1]:K, [2]:V}
---@return number
function functional.choose_map(input, value)
-- Equivalent of choose() function in Formula AI
-- Returns element of a table with the largest @value (a function)
-- Also returns the max value and the index
if value == nil then
value = function(k, v) return v end
elseif type(value) ~= 'function' then
local key = value
value = function(k, v) return v[key] end
end
local max_value, best_input, best_key = -math.huge, nil, nil
for k,v in pairs(input) do
local v2 = value(k, v)
if v2 > max_value then
max_value, best_input, best_key = v2, v, k
end
end
return {key = best_key, value = best_input}, max_value
end
---Map the elements of an array according to an operation
---@generic T1
---@generic T2
---@param input T1[]
---@param formula fun(val:T1):T2
---@return T2[]
function functional.map_array(input, formula)
local mapped_table = {}
for n,v in ipairs(input) do
table.insert(mapped_table, formula(v))
end
return mapped_table
end
---Map the values of a dictionary according to an operation
---@generic K
---@generic V1
---@generic V2
---@param input table<K, V1>
---@param formula fun(key:K,val:V1):V2
---@return table<K, V2>
function functional.map(input, formula)
local mapped_table = {}
for k,v in pairs(input) do
mapped_table[k] = formula(v, k)
end
return mapped_table
end
local known_operators = {
['+'] = function(a, b) return a + b end,
['-'] = function(a, b) return a - b end,
['*'] = function(a, b) return a * b end,
['/'] = function(a, b) return a / b end,
['%'] = function(a, b) return a % b end,
['^'] = function(a, b) return a ^ b end,
['//'] = function(a, b) return a // b end,
['&'] = function(a, b) return a & b end,
['|'] = function(a, b) return a | b end,
['~'] = function(a, b) return a ~ b end,
['<<'] = function(a, b) return a << b end,
['>>'] = function(a, b) return a >> b end,
['..'] = function(a, b) return a .. b end,
['=='] = function(a, b) return a == b end,
['~='] = function(a, b) return a ~= b end,
['<'] = function(a, b) return a < b end,
['>'] = function(a, b) return a > b end,
['<='] = function(a, b) return a <= b end,
['>='] = function(a, b) return a >= b end,
['and'] = function(a, b) return a and b end,
['or'] = function(a, b) return a or b end,
}
-- Reduce the elements of input array into a single value. operator is called as
--- 'operator(accumulator, element)' for every element in t. If a 3rd argument
--- is provided, even as nil, it will be used as the accumulator when
--- calling operator on the first element. If there is no 3rd argument, the
--- first operator call will be on the first two elements. If there is no 3rd
--- argument and the array is empty, return nil. operator may be a function or a
--- binary Lua operator as a string.
---@generic T
---@param input T[]
---@param operator string|fun(a:T, b:T):T
---@param identity? T
---@return T
function functional.reduce(input, operator, ...)
local f <const> = known_operators[operator] or operator
local function loop(init, i)
local value <const> = input[i]
if value == nil then
return init
end
return loop(f(init, value), i + 1)
end
if select('#', ...) == 0 then
return loop(input[1], 2)
end
return loop(select(1, ...), 1)
end
---Take elements of an array until the condition fails
---@generic T
---@param input T[]
---@param condition fun(val:T):boolean
---@return T[]
function functional.take_while(input, condition)
local truncated_table = {}
for _,v in ipairs(input) do
if not condition(v) then
break
end
table.insert(truncated_table, v)
end
return truncated_table
end
---Given an array of arrays, produce a new array of arrays where the first has every first element the second has every second element, etc
---@param input any[][]
---@return any[][]
function functional.zip(input)
-- Technically not a higher-order function, but whatever...
local output = {}
local _, n = functional.choose(input, function(list) return #list end)
for i = 1, n do
local elem = {}
for j, list in ipairs(input) do
elem[j] = list[i]
end
table.insert(output, elem)
end
return output
end
return functional
| gpl-2.0 |
bugobliterator/ardupilot | libraries/AP_Scripting/examples/param_get_set_test.lua | 15 | 2308 | -- This script is a test of param set and get
local count = 0
-- for fast param acess it is better to get a param object,
-- this saves the code searching for the param by name every time
local VM_I_Count = Parameter()
if not VM_I_Count:init('SCR_VM_I_COUNT') then
gcs:send_text(6, 'get SCR_VM_I_COUNT failed')
end
-- returns null if param cant be found
local fake_param = Parameter()
if not fake_param:init('FAKE_PARAM') then
gcs:send_text(6, 'get FAKE_PARAM failed')
end
function update() -- this is the loop which periodically runs
-- get and print all the scripting parameters
local value = param:get('SCR_ENABLE')
if value then
gcs:send_text(6, string.format('LUA: SCR_ENABLE: %i',value))
else
gcs:send_text(6, 'LUA: get SCR_ENABLE failed')
end
value = param:get('SCR_VM_I_COUNT')
if value then
gcs:send_text(6, string.format('LUA: SCR_VM_I_COUNT: %i',value))
else
gcs:send_text(6, 'LUA: get SCR_VM_I_COUNT failed')
end
value = param:get('SCR_HEAP_SIZE')
if value then
gcs:send_text(6, string.format('LUA: SCR_HEAP_SIZE: %i',value))
else
gcs:send_text(6, 'LUA: get SCR_HEAP_SIZE failed')
end
value = param:get('SCR_DEBUG_LVL')
if value then
gcs:send_text(6, string.format('LUA: SCR_DEBUG_LVL: %i',value))
else
gcs:send_text(6, 'LUA: get SCR_DEBUG_LVL failed')
end
-- increment the script heap size by one
local heap_size = param:get('SCR_HEAP_SIZE')
if heap_size then
if not(param:set('SCR_HEAP_SIZE',heap_size + 1)) then
gcs:send_text(6, 'LUA: param set failed')
end
else
gcs:send_text(6, 'LUA: get SCR_HEAP_SIZE failed')
end
-- increment the VM I count by one using direct accsess method
local VM_count = VM_I_Count:get()
if VM_count then
gcs:send_text(6, string.format('LUA: SCR_VM_I_COUNT: %i',VM_count))
if not VM_I_Count:set( VM_count + 1) then
gcs:send_text(6, string.format('LUA: failed to set SCR_VM_I_COUNT'))
end
else
gcs:send_text(6, 'LUA: read SCR_VM_I_COUNT failed')
end
count = count + 1;
-- self terminate after 30 loops
if count > 30 then
gcs:send_text(0, 'LUA: goodbye, world')
param:set('SCR_ENABLE',0)
end
return update, 1000 -- reschedules the loop
end
return update() -- run immediately before starting to reschedule
| gpl-3.0 |
Mutos/SoC-Test-001 | dat/missions/shadow/darkshadow.lua | 11 | 28246 | --[[
-- This is the third mission in the "shadow" series, featuring the return of SHITMAN.
--]]
include ("proximity.lua")
-- localization stuff, translators would work here
lang = naev.lang()
if lang == "es" then
else -- default english
title = {}
text = {}
Jorscene = {}
title[1] = "An urgent invitation"
text[1] = [[Suddenly, out of nowhere, one of the dormant panels in your cockpit springs to life. It shows you a face you've never seen before in your life, but you recognize the plain grey uniform as belonging to the Four Winds.
"Hello %s," the face says. "You must be wondering who I am and how it is I'm talking to you like this. Neither question is important. What is important is that Captain Rebina has urgent need of your services. You are to meet her on the Seiryuu, which is currently in orbit around %s in the %s system. Please don't ask any questions now. We expect to see you as quickly as you can make your way here."
The screen goes dead again. You decide to make a note of this in your log. Perhaps it would be a good idea to visit the Seiryuu once more, if only to find out how they got a private line to your ship!]]
title[2] = "Disclosure"
text[2] = [[You make your way through the now familiar corridors of the Seiryuu. You barely notice the strange environment anymore. It seems unimportant compared to the strange events that surround your every encounter with these Four Winds.
You step onto the bridge, where Captain Rebina is waiting for you. "Welcome back, %s," she says. "I'm pleased to see that you decided to respond to our communication. I doubt you would have come here if you weren't willing to continue to aid us. Your presence here confirms that you are a reliable partner, so I will treat you accordingly."
The captain motions you to take a seat at what looks like a holotable in the center of the bridge. "Before I tell you what I've called you here for, I feel I should explain to you in full who we are, what we do and what your part in all this is." She takes a seat opposite from yours, and leans on the holotable. "As I've said before, we are the Four Winds. Our organization is a very secretive one, as you've experienced firsthand. Very few outside our ranks know of our existence, and now you're one of those few."]]
text[3] = [["The Four Winds are old, %s. Very old indeed. The movement dates back to old Earth, before the Space Age, even. We have been with human civilization throughout the ages, at first only in the Eastern nations, later establishing a foothold worldwide. Our purpose was to guide humanity, prevent it from making mistakes it could not afford to make. We never came out in the open, we always worked behind the scenes, from the shadows. We were diplomats, scientists, journalists, politicians' spouses, sometimes even assassins. We used any means necessary to gather information and avert disaster, when we could.
"Of course, we didn't always succeed. We couldn't prevent the nuclear strikes on Japan, though we managed to prevent several others. We foiled the sabotage attempts on several of the colony ships launched during the First Growth, but sadly failed to do so in Maelstrom's case. We failed to stop the Faction Wars, though we managed to help the Empire gain the upper hand. Our most recent failure is the Incident - we should have seen it coming, but we were completely taken by surprise."]]
text[4] = [[Captain Rebina sits back in her chair and heaves a sigh. "I think that may have been when things started to change. We used to be committed to our purpose, but apparently things are different now. No doubt you remember what happened to the diplomatic exchange between the Empire and the Dvaered some time ago. Well, suffice to say that increasing the tension between the two is definitely not part of our mandate. In fact, it's completely at odds with what we stand for. And that was not just an isolated incident either. Things have been happening that suggest Four Winds involvement, things that bode ill."
She activates the holotable, and it displays four cruisers, all seemingly identical to the Seiryuu, though you notice subtle differences in the hull designs.
"These are our flagships. Including this ship, they are the Seiryuu, Suzaku, Byakko and Genbu. I'm given to understand that these names, as well as our collective name, have their roots in ancient Oriental mythology." The captain touches another control, and four portraits appear, superimposed over the ships. "These are the four captains of the flagships, which by extension makes them the highest level of authority within the Four Winds. You know me. The other three are called Giornio, Zurike and Farett."]]
text[5] = [["It is my belief that one or more of my fellow captains have abandoned their mission, and are misusing their resources for a different agenda. I have been unable to find out the details of Four Winds missions that I did not order myself, which is a bad sign. I am being stonewalled, and I don't like it. I want to know what's going on, %s, and you're going to help me do it."
The captain turns the holotable back off so she can have your undivided attention. "I have sent Jorek on a recon mission to the planet of %s in the %s system. He hasn't reported back to me so far, and that's bad news. Jorek is a reliable agent. If he fails to meet a deadline, then it means he is tied down by factors outside of his control, or worse. I want you to find him. Your position as an outsider will help you fly below the radar of potentially hostile Four Winds operatives. You must go to %s and contact Jorek if you can, or find out where he is if you can't."
Captain Rebina stands up, a signal that this briefing is over. You are seen to your ship by a grey-uniformed crewman. You sit in your cockpit for a few minutes before disengaging the docking clamp. What Captain Rebina has told you is a lot to take in. A shadowy organization that guides humanity behind the scenes? And parts of that organization going rogue? The road ahead could well be a bumpy one.]]
title[3] = "A tip from the barman"
text[6] = [[You meet the barman's stare. He hesitates for a moment, then speaks up.
"Hey... Are you %s by any chance?"
You tell him that yes, that's you, and ask how he knows your name.
"Well, your description was given to me by an old friend of mine. His name is Jarek. Do you know him?"
You tell him that you don't know anyone by the name of Jarek, but you do know a man named Jorek. The barman visibly relaxes when he hears that name.
"Ah, good. You're the real deal then. Can't be too careful in times like these, you know. Anyway, old Jorek was here, but he couldn't stay. He told me to keep an eye out for you, said you'd be coming to look for him." The barman glances around to make sure nobody is within earshot, even though the bar's music makes it difficult to overhear anyone who isn't standing right next to you. "I have a message for you. Go to the %s system and land on %s. Jorek will be waiting for you there. But you better be ready for some trouble. I don't know what kind of trouble it is, but Jorek is never in any kind of minor trouble. Don't say I didn't warn you."
You thank the barman, pay for your drink and prepare to head back to your ship, wondering whether your armaments will be enough to deal with whatever trouble Jorek is in.]]
title[4] = "Still an unpleasant man"
text[7] = [["Well hello there %s," Jorek says when you approach his table. "It's about damn time you showed up. I've been wastin' credits on this awful swill for days now."
Not at all surprised that Jorek is still as disagreeable as the last time you encountered him, you decide to ask him to explain the situation, beginning with how he knew that it was you who would be coming for him. Jorek laughs heartily at that.
"Ha! Of course it was going to be you. Who else would that lass Rebina send? She's tough as nails, that girl, but I know how her mind works. She's cornered, potential enemies behind every door in the organization. And you have done us a couple of favors already. In fact, you're the only one she can trust outside her own little circle of friends, and right now I'm not too sure how far she trusts those. Plus, she really has a keen nose when it comes to sniffin' out reliable people, and she knows it. Yeah, I knew she'd send you to find me."
That answers one question. But you still don't know why Jorek hasn't been reporting in like he should have.
"Yeah, right, about that. You know about the deal with the other branches getting too big for their britches? Good. Well, I've been lookin' into that, pokin' my nose into their business. Since I'm dealin' with my fellow Shadows here, I couldn't afford to give myself away. So that's that. But there's more."]]
text[8] = [["I dunno if you've seen them on your way here, but there's guys of ours hangin' around in the system. And when I say guys of ours, I mean guys of theirs, since they sure ain't our guys any more. They've been on my ass ever since I left Manis, so I think I know what they want. They want to get me and see what I know, or maybe they just want to blow me into space dust. Either way, I need you to help me get out of this rothole."
You ask Jorek why he didn't just lie low on some world until the coast was clear, instead of coming to this sink for the dregs of intergalactic society.
"It ain't that simple," Jorek sighs. "See, I got an inside man. A guy in their ranks who wants out. I need to get him back to the old girl so he can tell her what he knows firsthand. He's out there now, with the pack, so we need to pick him up on our way out. Now, there's two ways we can do this. We can either go in fast, grab the guy, get out fast before the wolves get us. Or we can try to fight our way through. Let me warn you though, these guys mean business, and they're not your average pirates. Unless you got a really tough ship, I recommend you run."
Jorek sits back in his chair. "Well, there you have it. I'll fill you in on the details once we're spaceborne. Show me to your ship, buddy, and let's get rollin'. I've had enough of this damn place."]]
title[5] = "An extra passenger"
text[9] = [[You board the Four Winds vessel, and as soon as the airlock opens a nervous looking man enters your ship. He eyes you warily, but when he sees that Jorek is with you his tension fades.
"Come on, %s," Jorek says. "Let's not waste any more time here. We got what we came for. Now let's give these damn vultures the slip, eh?"]]
title[6] = "Ambush!"
text[10] = [[Suddenly, your long range sensors pick up a ship jumping in behind you. Jorek checks the telemetry beside you. Suddenly, his eyes go wide and he groans. The Four Winds informant turns pale.
"Oh, damn it all," Jorek curses. "%s, that's the Genbu, Giornio's flagship. I never expected him to take an interest in me personally! Damn, this is bad. Listen, if you have anything to boost our speed, now would be the time. We got to get outta here as if all hell was hot on our heels, which it kinda is! If that thing catches us, we're toast. I really mean it, you don't wanna get into a fight against her, not on your own. Get your ass movin' to Sirius space. Giornio ain't gonna risk getting into a scrap with the Sirius military, so we'll be safe once we get there. Come on, what are you waitin' for? Step on it!"]]
title[7] = "A safe return"
text[11] = [[You find yourself back on the Seiryuu, in the company of Jorek and the Four Winds informant. The informant is escorted deeper into the ship by grey-uniformed crew members, while Jorek takes you up to the bridge for a meeting with Captain Rebina.
"Welcome back, Jorek, %s," Rebina greets you on your arrival. "I've already got a preliminary report on the situation, but let's have ourselves a proper debriefing. Have a seat."
Jorek and you sit down at the holotable in the middle of the bridge, and report on the events surrounding Jorek's retrieval. When you're done, Captain Rebina calls up a schematic view of the Genbu from the holotable.
"It would seem that Giornio and his comrades have a vested interest in keeping me away from the truth. It's a good thing you managed to get out of that ambush and bring me that informant. I do hope he'll be able to shed more light on the situation. I've got a bad premonition, a hunch that we're going to have to act soon if we're going to avert disaster, whatever that may be. I trust that you will be willing to aid us again when that time comes, %s. We're going to need all the help we can get. For now, you will find a modest amount of credits in your account. I will be in touch when things are clearer."
You return to your ship and undock from the Seiryuu. You reflect that you had to run for your life this time around, and by all accounts, things will only get worse with the Four Winds in the future. A lesser man might get nervous.]]
Jorscene[1] = [[Jorek> "That's my guy. We got to board his ship and get him off before we jump."]]
Jorscene[2] = [[Jorek> "Watch out for those patrols though. If they spot us, they'll be all over us."]]
Jorscene[3] = [[Jorek> "They're tougher than they look. Don't underestimate them."]]
joefailtitle = "You forgot the informant!"
joefailtext = [[Jorek is enraged. "Dammit, %s! I told you to pick up that informant on the way! Too late to go back now. I'll have to think of somethin' else. I'm disembarkin' at the next spaceport, don't bother taking me back to the Seiryuu."]]
patrolcomm = "All pilots, we've detected McArthy on that ship! Break and intercept!"
NPCtitle = "No Jorek"
NPCtext = [[You step into the bar, expecting to find Jorek McArthy sitting somewhere at a table. However, you don't see him anywhere. You decide to go for a drink to contemplate your next move. Then, you notice the barman is giving you a curious look.]]
NPCdesc = "The barman seems to be eyeing you in particular."
Jordesc = "There he is, Jorek McArthy, the man you've been chasing across half the galaxy. What he's doing on this piece of junk is unclear."
-- Mission info stuff
osd_title = {}
osd_msg = {}
osd2_msg = {}
osd_title = "Dark Shadow"
osd_msg[0] = "Look for Jorek on %s in the %s system" -- Note: indexing at 0 because it's a template. Shouldn't actually appear ingame.
osd2_msg[1] = "Fetch the Four Winds informant from his ship"
osd2_msg[2] = "Return Jorek and the informant to the Seiryuu in the %s system"
misn_desc1 = [[You have been summoned to the %s system, where the Seiryuu is supposedly waiting for you in orbit around %s.]]
misn_desc2 = [[You have been tasked by Captain Rebina of the Four Winds to assist Jorek McArthy.]]
misn_reward = "A sum of money."
end
function create()
var.push("darkshadow_active", true)
seirplanet, seirsys = planet.get("Edergast")
jorekplanet1, joreksys1 = planet.get("Manis")
jorekplanet2, joreksys2 = planet.get("The Wringer")
ambushsys = system.get("Herakin")
safesys = system.get("Eiderdown")
if not misn.claim ( {seirsys, joreksys2, ambushsys} ) then
abort()
end
tk.msg(title[1], text[1]:format(player.name(), seirplanet:name(), seirsys:name()))
firstmarker = misn.markerAdd(seirsys, "low")
accept() -- The player automatically accepts this mission.
end
-- This is the initial phase of the mission, when it still only shows up in the mission list. No OSD, reward or markers yet.
function accept()
misn.setReward("Unknown")
misn.setDesc(misn_desc1:format(seirsys:name(), seirplanet:name()))
misn.accept()
misn.osdDestroy() -- This is here because setDesc initializes the OSD.
stage = 1
hook.enter("enter")
end
-- This is the "real" start of the mission. Get yer mission variables here!
function accept2()
tick = {false, false, false, false, false}
tick["__save"] = true
osd_msg[1] = osd_msg[0]:format(jorekplanet1:name(), joreksys1:name())
misn.osdCreate(osd_title, osd_msg)
misn.setDesc(misn_desc2)
misn.setReward(misn_reward)
marker = misn.markerAdd(joreksys1, "low")
landhook = hook.land("land")
jumpouthook = hook.jumpout("jumpout")
end
-- Handle boarding of the Seiryuu
function seiryuuBoard()
seiryuu:setActiveBoard(false)
seiryuu:setHilight(false)
player.unboard()
if stage == 1 then -- Briefing
tk.msg(title[2], text[2]:format(player.name()))
tk.msg(title[2], text[3]:format(player.name()))
tk.msg(title[2], text[4])
tk.msg(title[2], text[5]:format(player.name(), jorekplanet1:name(), joreksys1:name(), jorekplanet1:name()))
accept2()
misn.markerRm(firstmarker)
stage = 2
elseif stage == 6 then -- Debriefing
tk.msg(title[7], text[11]:format(player.name(), player.name()))
player.pay(500000) -- 500K
seiryuu:control()
seiryuu:hyperspace()
var.pop("darkshadow_active")
misn.finish(true)
end
end
-- Board hook for joe
function joeBoard()
tk.msg(title[5], text[9]:format(player.name()))
misn.cargoAdd("Four Winds Informant", 0)
player.unboard()
misn.markerMove(marker, seirsys)
misn.osdActive(2)
stage = 5
end
-- Jumpout hook
function jumpout()
playerlastsys = system.cur() -- Keep track of which system the player came from
if not (patroller == nil) then
hook.rm(patroller)
end
if not (spinter == nil) then
hook.rm(spinter)
end
end
-- Enter hook
function enter()
if system.cur() == seirsys then
seiryuu = pilot.add("Seiryuu", nil, vec2.new(300, 300) + seirplanet:pos())[1]
seiryuu:setInvincible(true)
seiryuu:control()
if stage == 1 or stage == 6 then
seiryuu:setActiveBoard(true)
seiryuu:setHilight(true)
hook.pilot(seiryuu, "board", "seiryuuBoard")
else
seiryuu:setNoboard(true)
end
elseif system.cur() == joreksys2 and stage == 3 then
pilot.clear()
pilot.toggleSpawn(false)
spawnSquads(false)
elseif system.cur() == joreksys2 and stage == 4 then
pilot.clear()
pilot.toggleSpawn(false)
player.allowLand(false, "Landing permission denied. Our docking clamps are currently undergoing maintenance.")
-- Meet Joe, our informant.
joe = pilot.add("Four Winds Vendetta", nil, vec2.new(-500, -4000))[1]
joe:control()
joe:rename("Four Winds Informant")
joe:setHilight(true)
joe:setVisplayer()
joe:setInvincible(true)
joe:disable()
spawnSquads(true)
-- Make everyone visible for the cutscene
squadVis(true)
-- The cutscene itself
local delay = 0
zoomspeed = 2500
hook.timer(delay, "playerControl", true)
delay = delay + 2000
hook.timer(delay, "zoomTo", joe)
delay = delay + 4000
hook.timer(delay, "showText", Jorscene[1])
delay = delay + 4000
hook.timer(delay, "zoomTo", leader[1])
delay = delay + 1000
hook.timer(delay, "showText", Jorscene[2])
delay = delay + 2000
hook.timer(delay, "zoomTo", leader[2])
delay = delay + 3000
hook.timer(delay, "zoomTo", leader[3])
delay = delay + 2000
hook.timer(delay, "showText", Jorscene[3])
delay = delay + 3000
hook.timer(delay, "zoomTo", leader[4])
delay = delay + 4000
hook.timer(delay, "zoomTo", leader[5])
delay = delay + 4000
hook.timer(delay, "zoomTo", player.pilot())
hook.timer(delay, "playerControl", false)
-- Hide everyone again
delay = delay + 2000
hook.timer(delay, "squadVis", false)
delay = delay + 1
-- ...except the leadears.
hook.timer(delay, "leaderVis", true)
hook.pilot(joe, "board", "joeBoard")
poller = hook.timer(500, "patrolPoll")
elseif system.cur() == ambushsys and stage == 4 then
tk.msg(joefailtitle, joefailtext:format(player.name()))
abort()
elseif system.cur() == ambushsys and stage == 5 then
pilot.clear()
pilot.toggleSpawn(false)
hook.timer(500, "invProximity", { location = jump.pos(system.cur(), "Suna"), radius = 8000, funcname = "startAmbush" }) -- Starts an inverse proximity poll for distance from the jump point.
elseif system.cur() == safesys and stage == 5 then
stage = 6 -- stop spawning the Genbu
elseif genbuspawned and stage == 5 then
spawnGenbu(playerlastsys) -- The Genbu follows you around, and will probably insta-kill you.
continueAmbush()
end
end
function spawnSquads(highlight)
-- Start positions for the leaders
leaderstart = {}
leaderstart[1] = vec2.new(-2500, -1500)
leaderstart[2] = vec2.new(2500, 1000)
leaderstart[3] = vec2.new(-3500, -4500)
leaderstart[4] = vec2.new(2500, -2500)
leaderstart[5] = vec2.new(-2500, -6500)
-- Leaders will patrol between their start position and this one
leaderdest = {}
leaderdest[1] = vec2.new(2500, -1000)
leaderdest[2] = vec2.new(-500, 1500)
leaderdest[3] = vec2.new(-4500, -1500)
leaderdest[4] = vec2.new(2000, -6000)
leaderdest[5] = vec2.new(1000, -1500)
squads = {}
squads[1] = pilot.add("Four Winds Vendetta Quad", nil, leaderstart[1])
squads[2] = pilot.add("Four Winds Vendetta Quad", nil, leaderstart[2])
squads[3] = pilot.add("Four Winds Vendetta Quad", nil, leaderstart[3])
squads[4] = pilot.add("Four Winds Vendetta Quad", nil, leaderstart[4])
squads[5] = pilot.add("Four Winds Vendetta Quad", nil, leaderstart[5])
for _, squad in ipairs(squads) do
for _, k in ipairs(squad) do
hook.pilot(k, "attacked", "attacked")
k:rename("Four Winds Patrol")
k:control()
k:rmOutfit("all")
k:addOutfit("Cheater's Laser Cannon", 6) -- Equip these fellas with unfair weaponry
k:follow(squad[1]) -- Each ship in the squad follows the squad leader
end
squad[1]:taskClear() --...except the leader himself.
end
-- Shorthand notation for the leader pilots
leader = {}
leader[1] = squads[1][1]
leader[2] = squads[2][1]
leader[3] = squads[3][1]
leader[4] = squads[4][1]
leader[5] = squads[5][1]
leaderVis(highlight)
-- Kickstart the patrol sequence
for i, j in ipairs(leader) do
j:goto(leaderdest[i], false)
end
-- Set up the rest of the patrol sequence
for _, j in ipairs(leader) do
hook.pilot(j, "idle", "leaderIdle")
end
end
-- Makes the squads either visible or hides them
function squadVis(visible)
for _, squad in ipairs(squads) do
for _, k in ipairs(squad) do
k:setVisplayer(visible)
end
end
end
-- Makes the leaders visible or hides them, also highlights them (or not)
function leaderVis(visible)
for _, j in ipairs(leader) do
j:setVisplayer(visible)
j:setHilight(visible)
end
end
-- Hook for hostile actions against a squad member
function attacked()
for _, squad in ipairs(squads) do
for _, k in ipairs(squad) do
k:hookClear()
k:control()
k:attack(player.pilot())
end
end
end
-- Hook for the idle status of the leader of a squad.
-- Makes the squads patrol their routes.
function leaderIdle(pilot)
for i, j in ipairs(leader) do
if j == pilot then
if tick[i] then pilot:goto(leaderdest[i], false)
else pilot:goto(leaderstart[i], false)
end
tick[i] = not tick[i]
return
end
end
end
-- Check if any of the patrolling leaders can see the player, and if so intercept.
function patrolPoll()
for _, patroller in ipairs(leader) do
if vec2.dist(player.pilot():pos(), patroller:pos()) < 1200 then
patroller:broadcast(patrolcomm)
attacked()
return
end
end
poller = hook.timer(500, "patrolPoll")
end
-- Spawns the Genbu
function spawnGenbu(sys)
genbu = pilot.add("Genbu", nil, sys)[1]
genbu:rmOutfit("all")
genbu:addOutfit("Turbolaser", 3)
genbu:addOutfit("Cheater's Ragnarok Beam", 3) -- You can't win. Seriously.
genbu:control()
genbu:setHilight()
genbu:setVisplayer()
genbuspawned = true
end
-- The initial ambush cutscene
function startAmbush()
spawnGenbu(system.get("Anrique"))
local delay = 0
zoomspeed = 4500
hook.timer(delay, "playerControl", true)
hook.timer(delay, "zoomTo", genbu)
delay = delay + 5000
hook.timer(delay, "showMsg", {title[6], text[10]:format(player.name())})
delay = delay + 1000
hook.timer(delay, "zoomTo", player.pilot())
hook.timer(delay, "playerControl", false)
hook.timer(delay, "continueAmbush")
end
-- The continuation of the ambush, for timer purposes
function continueAmbush()
genbu:setHostile()
genbu:attack(player.pilot())
waves = 0
maxwaves = 5
spinter = hook.timer(5000, "spawnInterceptors")
end
-- Spawns a wing of Lancelots that intercept the player.
function spawnInterceptors()
inters = pilot.add("Four Winds Lancelot Trio", nil, genbu:pos())
for _, j in ipairs(inters) do
j:rmOutfit("all")
j:addOutfit("Cheater's Laser Cannon", 4) -- Equip these fellas with unfair weaponry
j:addOutfit("Engine Reroute", 1)
j:addOutfit("Improved Stabilizer", 1)
j:control()
j:attack(player.pilot())
end
if waves < maxwaves then
waves = waves + 1
spinter = hook.timer(25000, "spawnInterceptors")
end
end
-- Land hook
function land()
if planet.cur() == jorekplanet1 and stage == 2 then
-- Thank you player, but our SHITMAN is in another castle.
tk.msg(NPCtitle, NPCtext)
barmanNPC = misn.npcAdd("barman", "Barman", "neutral/barman", NPCdesc, 4)
elseif planet.cur() == jorekplanet2 and stage == 3 then
joreknpc = misn.npcAdd("jorek", "Jorek", "neutral/unique/jorek", Jordesc, 4)
end
end
-- NPC hook
function barman()
tk.msg(title[3], text[6]:format(player.name(), joreksys2:name(), jorekplanet2:name()))
osd_msg[1] = osd_msg[0]:format(jorekplanet2:name(), joreksys2:name())
misn.osdCreate(osd_title, osd_msg)
misn.markerMove(marker, joreksys2)
misn.npcRm(barmanNPC)
stage = 3
end
-- NPC hook
function jorek()
tk.msg(title[4], text[7]:format(player.name()))
tk.msg(title[4], text[8])
misn.npcRm(joreknpc)
misn.cargoAdd("Jorek", 0)
osd2_msg[2] = osd2_msg[2]:format(seirsys:name())
misn.osdCreate(osd_title, osd2_msg)
stage = 4
end
-- Capsule function for camera.set, for timer use
function zoomTo(target)
camera.set(target, true, zoomspeed)
end
-- Capsule function for player.msg, for timer use
function showText(text)
player.msg(text)
end
-- Capsule function for tk.msg, for timer use
function showMsg(content)
tk.msg(content[1], content[2])
end
-- Capsule function for player.pilot():control(), for timer use
-- Also saves the player's velocity.
function playerControl(status)
player.pilot():control(status)
player.cinematics(status)
if status then
pvel = player.pilot():vel()
player.pilot():setVel(vec2.new(0, 0))
else
player.pilot():setVel(pvel)
end
end
-- Poll for player proximity to a point in space. Will trigger when the player is NOT within the specified distance.
-- argument trigger: a table containing:
-- location: The target location
-- radius: The radius around the location
-- funcname: The name of the function to be called when the player is out of proximity.
function invProximity(trigger)
if vec2.dist(player.pos(), trigger.location) >= trigger.radius then
_G[trigger.funcname]()
else
hook.timer(500, "invProximity", trigger)
end
end
-- Handle the unsuccessful end of the mission.
function abort()
var.pop("darkshadow_active")
misn.finish(false)
end
| gpl-3.0 |
Whit3Tig3R/bestspammbot2 | plugins/rae.lua | 616 | 1312 | do
function getDulcinea( text )
-- Powered by https://github.com/javierhonduco/dulcinea
local api = "http://dulcinea.herokuapp.com/api/?query="
local query_url = api..text
local b, code = http.request(query_url)
if code ~= 200 then
return "Error: HTTP Connection"
end
dulcinea = json:decode(b)
if dulcinea.status == "error" then
return "Error: " .. dulcinea.message
end
while dulcinea.type == "multiple" do
text = dulcinea.response[1].id
b = http.request(api..text)
dulcinea = json:decode(b)
end
local text = ""
local responses = #dulcinea.response
if responses == 0 then
return "Error: 404 word not found"
end
if (responses > 5) then
responses = 5
end
for i = 1, responses, 1 do
text = text .. dulcinea.response[i].word .. "\n"
local meanings = #dulcinea.response[i].meanings
if (meanings > 5) then
meanings = 5
end
for j = 1, meanings, 1 do
local meaning = dulcinea.response[i].meanings[j].meaning
text = text .. meaning .. "\n\n"
end
end
return text
end
function run(msg, matches)
return getDulcinea(matches[1])
end
return {
description = "Spanish dictionary",
usage = "!rae [word]: Search that word in Spanish dictionary.",
patterns = {"^!rae (.*)$"},
run = run
}
end | gpl-2.0 |
PichotM/DarkRP | entities/entities/drug/cl_init.lua | 12 | 1493 | include("shared.lua")
function ENT:Initialize()
end
function ENT:Draw()
self:DrawModel()
local Pos = self:GetPos()
local Ang = self:GetAngles()
local owner = self:Getowning_ent()
owner = (IsValid(owner) and owner:Nick()) or DarkRP.getPhrase("unknown")
surface.SetFont("HUDNumber5")
local text = DarkRP.getPhrase("drugs")
local text2 = DarkRP.getPhrase("priceTag", DarkRP.formatMoney(self:Getprice()), "")
local TextWidth = surface.GetTextSize(text)
local TextWidth2 = surface.GetTextSize(text2)
Ang:RotateAroundAxis(Ang:Forward(), 90)
local TextAng = Ang
TextAng:RotateAroundAxis(TextAng:Right(), CurTime() * -180)
cam.Start3D2D(Pos + Ang:Right() * -15, TextAng, 0.1)
draw.WordBox(2, -TextWidth * 0.5 + 5, -30, text, "HUDNumber5", Color(140, 0, 0, 100), Color(255, 255, 255, 255))
draw.WordBox(2, -TextWidth2 * 0.5 + 5, 18, text2, "HUDNumber5", Color(140, 0, 0, 100), Color(255, 255, 255, 255))
cam.End3D2D()
end
function ENT:Think()
end
local function drugEffects(um)
local toggle = um:ReadBool()
LocalPlayer().isDrugged = toggle
if toggle then
hook.Add("RenderScreenspaceEffects", "drugged", function()
DrawSharpen(-1, 2)
DrawMaterialOverlay("models/props_lab/Tank_Glass001", 0)
DrawMotionBlur(0.13, 1, 0.00)
end)
else
hook.Remove("RenderScreenspaceEffects", "drugged")
end
end
usermessage.Hook("DrugEffects", drugEffects)
| mit |
Anarchid/Zero-K | units/napalmmissile.lua | 4 | 3419 | return { napalmmissile = {
unitname = [[napalmmissile]],
name = [[Inferno]],
description = [[Napalm Missile]],
buildCostMetal = 500,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 3,
buildingGroundDecalSizeY = 3,
buildingGroundDecalType = [[napalmmissile_aoplane.dds]],
buildPic = [[napalmmissile.png]],
category = [[SINK UNARMED]],
collisionVolumeOffsets = [[0 15 0]],
collisionVolumeScales = [[20 60 20]],
collisionVolumeType = [[CylY]],
customParams = {
mobilebuilding = [[1]],
},
explodeAs = [[WEAPON]],
footprintX = 1,
footprintZ = 1,
iconType = [[cruisemissilesmall]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 1000,
maxSlope = 18,
objectName = [[wep_napalm.s3o]],
script = [[cruisemissile.lua]],
selfDestructAs = [[WEAPON]],
sfxtypes = {
explosiongenerators = {
[[custom:RAIDMUZZLE]],
},
},
sightDistance = 0,
useBuildingGroundDecal = false,
yardMap = [[o]],
weapons = {
{
def = [[WEAPON]],
badTargetCategory = [[SWIM LAND SHIP HOVER]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]],
},
},
weaponDefs = {
WEAPON = {
name = [[Napalm Missile]],
cegTag = [[napalmtrail]],
areaOfEffect = 512,
craterAreaOfEffect = 64,
avoidFriendly = false,
collideFriendly = false,
craterBoost = 4,
craterMult = 3.5,
customParams = {
setunitsonfire = "1",
burntime = 90,
stats_hide_dps = 1, -- one use
stats_hide_reload = 1,
area_damage = 1,
area_damage_radius = 256,
area_damage_dps = 20,
area_damage_duration = 45,
light_color = [[1.35 0.5 0.36]],
light_radius = 550,
},
damage = {
default = 151,
},
edgeEffectiveness = 0.4,
explosionGenerator = [[custom:napalm_missile]],
fireStarter = 220,
flightTime = 100,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 1,
model = [[wep_napalm.s3o]],
noSelfDamage = true,
range = 3500,
reloadtime = 10,
smokeTrail = false,
soundHit = [[weapon/missile/nalpalm_missile_hit]],
soundStart = [[SiloLaunch]],
tolerance = 4000,
turnrate = 18000,
weaponAcceleration = 180,
weaponTimer = 3,
weaponType = [[StarburstLauncher]],
weaponVelocity = 1200,
},
},
featureDefs = {
},
} }
| gpl-2.0 |
fegimanam/ma | plugins/stats.lua | 866 | 4001 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'teleseed' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' then
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(chat_id)
else
return
end
end
if matches[2] == "teleseed" then -- Put everything you like :)
if not is_admin(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[!/]([Ss]tats)$",
"^[!/]([Ss]tatslist)$",
"^[!/]([Ss]tats) (group) (%d+)",
"^[!/]([Ss]tats) (teleseed)",-- Put everything you like :)
"^[!/]([Tt]eleseed)"-- Put everything you like :)
},
run = run
}
end
| gpl-2.0 |
erfan1292/1234 | plugins/fantasty_writter.lua | 3 | 28777 | local function run(msg, matches)
if #matches < 2 then
return "بعد از این دستور، با قید یک فاصله کلمه یا جمله ی مورد نظر را جهت زیبا نویسی وارد کنید"
end
if string.len(matches[2]) > 20 then
return "حداکثر حروف مجاز 20 کاراکتر انگلیسی و عدد است"
end
local font_base = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,9,8,7,6,5,4,3,2,1,.,_"
local font_hash = "z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,0,1,2,3,4,5,6,7,8,9,.,_"
local fonts = {
"ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_",
"⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_",
"α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_",
"α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"A̴,̴B̴,̴C̴,̴D̴,̴E̴,̴F̴,̴G̴,̴H̴,̴I̴,̴J̴,̴K̴,̴L̴,̴M̴,̴N̴,̴O̴,̴P̴,̴Q̴,̴R̴,̴S̴,̴T̴,̴U̴,̴V̴,̴W̴,̴X̴,̴Y̴,̴Z̴,̴a̴,̴b̴,̴c̴,̴d̴,̴e̴,̴f̴,̴g̴,̴h̴,̴i̴,̴j̴,̴k̴,̴l̴,̴m̴,̴n̴,̴o̴,̴p̴,̴q̴,̴r̴,̴s̴,̴t̴,̴u̴,̴v̴,̴w̴,̴x̴,̴y̴,̴z̴,̴0̴,̴9̴,̴8̴,̴7̴,̴6̴,̴5̴,̴4̴,̴3̴,̴2̴,̴1̴,̴.̴,̴_̴",
"ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_",
"⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_",
"α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,c,ɗ,є,f,g,н,ι,נ,к,Ɩ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,x,у,z,α,в,c,ɗ,є,f,g,н,ι,נ,к,Ɩ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,x,у,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,Ⴆ,ƈ,ԃ,ҽ,ϝ,ɠ,ԋ,ι,ʝ,ƙ,ʅ,ɱ,ɳ,σ,ρ,ϙ,ɾ,ʂ,ƚ,υ,ʋ,ɯ,x,ყ,ȥ,α,Ⴆ,ƈ,ԃ,ҽ,ϝ,ɠ,ԋ,ι,ʝ,ƙ,ʅ,ɱ,ɳ,σ,ρ,ϙ,ɾ,ʂ,ƚ,υ,ʋ,ɯ,x,ყ,ȥ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ą,ɓ,ƈ,đ,ε,∱,ɠ,ɧ,ï,ʆ,ҡ,ℓ,ɱ,ŋ,σ,þ,ҩ,ŗ,ş,ŧ,ų,√,щ,х,γ,ẕ,ą,ɓ,ƈ,đ,ε,∱,ɠ,ɧ,ï,ʆ,ҡ,ℓ,ɱ,ŋ,σ,þ,ҩ,ŗ,ş,ŧ,ų,√,щ,х,γ,ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_",
"მ,ჩ,ƈ,ძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,მ,ჩ,ƈ,ძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,0,Գ,Ց,Դ,6,5,Վ,Յ,Զ,1,.,_",
"ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,0,9,8,7,6,5,4,3,2,1,.,_",
"Δ,Ɓ,C,D,Σ,F,G,H,I,J,Ƙ,L,Μ,∏,Θ,Ƥ,Ⴓ,Γ,Ѕ,Ƭ,Ʊ,Ʋ,Ш,Ж,Ψ,Z,λ,ϐ,ς,d,ε,ғ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,ß,Ƈ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,Λ,ß,Ƈ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_",
"ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_",
"α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ค,๖,¢,໓,ē,f,ງ,h,i,ว,k,l,๓,ຖ,໐,p,๑,r,Ş,t,น,ง,ຟ,x,ฯ,ຊ,ค,๖,¢,໓,ē,f,ງ,h,i,ว,k,l,๓,ຖ,໐,p,๑,r,Ş,t,น,ง,ຟ,x,ฯ,ຊ,0,9,8,7,6,5,4,3,2,1,.,_",
"ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_",
"Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,0,9,8,7,6,5,4,3,2,1,.,_",
"Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,0,9,8,7,6,5,4,3,2,1,.,_",
"ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,M,X,ʎ,Z,ɐ,q,ɔ,p,ǝ,ɟ,ƃ,ɥ,ı,ɾ,ʞ,l,ա,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,Λ,M,X,ʎ,Z,ɐ,q,ɔ,p,ǝ,ɟ,ƃ,ɥ,ı,ɾ,ʞ,l,ա,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,‾",
"A̴,̴B̴,̴C̴,̴D̴,̴E̴,̴F̴,̴G̴,̴H̴,̴I̴,̴J̴,̴K̴,̴L̴,̴M̴,̴N̴,̴O̴,̴P̴,̴Q̴,̴R̴,̴S̴,̴T̴,̴U̴,̴V̴,̴W̴,̴X̴,̴Y̴,̴Z̴,̴a̴,̴b̴,̴c̴,̴d̴,̴e̴,̴f̴,̴g̴,̴h̴,̴i̴,̴j̴,̴k̴,̴l̴,̴m̴,̴n̴,̴o̴,̴p̴,̴q̴,̴r̴,̴s̴,̴t̴,̴u̴,̴v̴,̴w̴,̴x̴,̴y̴,̴z̴,̴0̴,̴9̴,̴8̴,̴7̴,̴6̴,̴5̴,̴4̴,̴3̴,̴2̴,̴1̴,̴.̴,̴_̴",
"A̱,̱Ḇ,̱C̱,̱Ḏ,̱E̱,̱F̱,̱G̱,̱H̱,̱I̱,̱J̱,̱Ḵ,̱Ḻ,̱M̱,̱Ṉ,̱O̱,̱P̱,̱Q̱,̱Ṟ,̱S̱,̱Ṯ,̱U̱,̱V̱,̱W̱,̱X̱,̱Y̱,̱Ẕ,̱a̱,̱ḇ,̱c̱,̱ḏ,̱e̱,̱f̱,̱g̱,̱ẖ,̱i̱,̱j̱,̱ḵ,̱ḻ,̱m̱,̱ṉ,̱o̱,̱p̱,̱q̱,̱ṟ,̱s̱,̱ṯ,̱u̱,̱v̱,̱w̱,̱x̱,̱y̱,̱ẕ,̱0̱,̱9̱,̱8̱,̱7̱,̱6̱,̱5̱,̱4̱,̱3̱,̱2̱,̱1̱,̱.̱,̱_̱",
"A̲,̲B̲,̲C̲,̲D̲,̲E̲,̲F̲,̲G̲,̲H̲,̲I̲,̲J̲,̲K̲,̲L̲,̲M̲,̲N̲,̲O̲,̲P̲,̲Q̲,̲R̲,̲S̲,̲T̲,̲U̲,̲V̲,̲W̲,̲X̲,̲Y̲,̲Z̲,̲a̲,̲b̲,̲c̲,̲d̲,̲e̲,̲f̲,̲g̲,̲h̲,̲i̲,̲j̲,̲k̲,̲l̲,̲m̲,̲n̲,̲o̲,̲p̲,̲q̲,̲r̲,̲s̲,̲t̲,̲u̲,̲v̲,̲w̲,̲x̲,̲y̲,̲z̲,̲0̲,̲9̲,̲8̲,̲7̲,̲6̲,̲5̲,̲4̲,̲3̲,̲2̲,̲1̲,̲.̲,̲_̲",
"Ā,̄B̄,̄C̄,̄D̄,̄Ē,̄F̄,̄Ḡ,̄H̄,̄Ī,̄J̄,̄K̄,̄L̄,̄M̄,̄N̄,̄Ō,̄P̄,̄Q̄,̄R̄,̄S̄,̄T̄,̄Ū,̄V̄,̄W̄,̄X̄,̄Ȳ,̄Z̄,̄ā,̄b̄,̄c̄,̄d̄,̄ē,̄f̄,̄ḡ,̄h̄,̄ī,̄j̄,̄k̄,̄l̄,̄m̄,̄n̄,̄ō,̄p̄,̄q̄,̄r̄,̄s̄,̄t̄,̄ū,̄v̄,̄w̄,̄x̄,̄ȳ,̄z̄,̄0̄,̄9̄,̄8̄,̄7̄,̄6̄,̄5̄,̄4̄,̄3̄,̄2̄,̄1̄,̄.̄,̄_̄",
"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_",
"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,9,8,7,6,5,4,3,2,1,.,_",
"@,♭,ḉ,ⓓ,℮,ƒ,ℊ,ⓗ,ⓘ,נ,ⓚ,ℓ,ⓜ,η,ø,℘,ⓠ,ⓡ,﹩,т,ⓤ,√,ω,ж,૪,ℨ,@,♭,ḉ,ⓓ,℮,ƒ,ℊ,ⓗ,ⓘ,נ,ⓚ,ℓ,ⓜ,η,ø,℘,ⓠ,ⓡ,﹩,т,ⓤ,√,ω,ж,૪,ℨ,0,➈,➑,➐,➅,➄,➃,➌,➁,➊,.,_",
"@,♭,¢,ⅾ,ε,ƒ,ℊ,ℌ,ї,נ,к,ℓ,м,п,ø,ρ,ⓠ,ґ,﹩,⊥,ü,√,ω,ϰ,૪,ℨ,@,♭,¢,ⅾ,ε,ƒ,ℊ,ℌ,ї,נ,к,ℓ,м,п,ø,ρ,ⓠ,ґ,﹩,⊥,ü,√,ω,ϰ,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,♭,ḉ,∂,ℯ,ƒ,ℊ,ℌ,ї,ʝ,ḱ,ℓ,м,η,ø,℘,ⓠ,я,﹩,⊥,ц,ṽ,ω,ჯ,૪,ẕ,α,♭,ḉ,∂,ℯ,ƒ,ℊ,ℌ,ї,ʝ,ḱ,ℓ,м,η,ø,℘,ⓠ,я,﹩,⊥,ц,ṽ,ω,ჯ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"@,ß,¢,ḓ,℮,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,м,п,◎,℘,ⓠ,я,﹩,т,ʊ,♥️,ẘ,✄,૪,ℨ,@,ß,¢,ḓ,℮,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,м,п,◎,℘,ⓠ,я,﹩,т,ʊ,♥️,ẘ,✄,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_",
"@,ß,¢,ḓ,℮,ƒ,ℊ,н,ḯ,נ,к,ℓμ,п,☺️,℘,ⓠ,я,﹩,⊥,υ,ṽ,ω,✄,૪,ℨ,@,ß,¢,ḓ,℮,ƒ,ℊ,н,ḯ,נ,к,ℓμ,п,☺️,℘,ⓠ,я,﹩,⊥,υ,ṽ,ω,✄,૪,ℨ,0,9,8,7,6,5,4,3,2,1,.,_",
"@,ß,ḉ,ḓ,є,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,ღ,η,◎,℘,ⓠ,я,﹩,⊥,ʊ,♥️,ω,ϰ,૪,ẕ,@,ß,ḉ,ḓ,є,ƒ,ℊ,ℌ,ї,נ,ḱ,ʟ,ღ,η,◎,℘,ⓠ,я,﹩,⊥,ʊ,♥️,ω,ϰ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"@,ß,ḉ,∂,ε,ƒ,ℊ,ℌ,ї,נ,ḱ,ł,ღ,и,ø,℘,ⓠ,я,﹩,т,υ,√,ω,ჯ,૪,ẕ,@,ß,ḉ,∂,ε,ƒ,ℊ,ℌ,ї,נ,ḱ,ł,ღ,и,ø,℘,ⓠ,я,﹩,т,υ,√,ω,ჯ,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,♭,¢,∂,ε,ƒ,❡,н,ḯ,ʝ,ḱ,ʟ,μ,п,ø,ρ,ⓠ,ґ,﹩,т,υ,ṽ,ω,ж,૪,ẕ,α,♭,¢,∂,ε,ƒ,❡,н,ḯ,ʝ,ḱ,ʟ,μ,п,ø,ρ,ⓠ,ґ,﹩,т,υ,ṽ,ω,ж,૪,ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,♭,ḉ,∂,℮,ⓕ,ⓖ,н,ḯ,ʝ,ḱ,ℓ,м,п,ø,ⓟ,ⓠ,я,ⓢ,ⓣ,ⓤ,♥️,ⓦ,✄,ⓨ,ⓩ,α,♭,ḉ,∂,℮,ⓕ,ⓖ,н,ḯ,ʝ,ḱ,ℓ,м,п,ø,ⓟ,ⓠ,я,ⓢ,ⓣ,ⓤ,♥️,ⓦ,✄,ⓨ,ⓩ,0,➒,➑,➐,➏,➄,➍,➂,➁,➀,.,_",
"@,♭,ḉ,ḓ,є,ƒ,ⓖ,ℌ,ⓘ,נ,к,ⓛ,м,ⓝ,ø,℘,ⓠ,я,﹩,ⓣ,ʊ,√,ω,ჯ,૪,ⓩ,@,♭,ḉ,ḓ,є,ƒ,ⓖ,ℌ,ⓘ,נ,к,ⓛ,м,ⓝ,ø,℘,ⓠ,я,﹩,ⓣ,ʊ,√,ω,ჯ,૪,ⓩ,0,➒,➇,➆,➅,➄,➍,➌,➋,➀,.,_",
"α,♭,ⓒ,∂,є,ⓕ,ⓖ,ℌ,ḯ,ⓙ,ḱ,ł,ⓜ,и,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,⊥,ʊ,ⓥ,ⓦ,ж,ⓨ,ⓩ,α,♭,ⓒ,∂,є,ⓕ,ⓖ,ℌ,ḯ,ⓙ,ḱ,ł,ⓜ,и,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,⊥,ʊ,ⓥ,ⓦ,ж,ⓨ,ⓩ,0,➒,➑,➆,➅,➎,➍,➌,➁,➀,.,_",
"ⓐ,ß,ḉ,∂,℮,ⓕ,❡,ⓗ,ї,נ,ḱ,ł,μ,η,ø,ρ,ⓠ,я,﹩,ⓣ,ц,√,ⓦ,✖️,૪,ℨ,ⓐ,ß,ḉ,∂,℮,ⓕ,❡,ⓗ,ї,נ,ḱ,ł,μ,η,ø,ρ,ⓠ,я,﹩,ⓣ,ц,√,ⓦ,✖️,૪,ℨ,0,➒,➑,➐,➅,➄,➍,➂,➁,➊,.,_",
"α,ß,ⓒ,ⅾ,ℯ,ƒ,ℊ,ⓗ,ї,ʝ,к,ʟ,ⓜ,η,ⓞ,℘,ⓠ,ґ,﹩,т,υ,ⓥ,ⓦ,ж,ⓨ,ẕ,α,ß,ⓒ,ⅾ,ℯ,ƒ,ℊ,ⓗ,ї,ʝ,к,ʟ,ⓜ,η,ⓞ,℘,ⓠ,ґ,﹩,т,υ,ⓥ,ⓦ,ж,ⓨ,ẕ,0,➈,➇,➐,➅,➎,➍,➌,➁,➊,.,_",
"@,♭,ḉ,ⅾ,є,ⓕ,❡,н,ḯ,נ,ⓚ,ⓛ,м,ⓝ,☺️,ⓟ,ⓠ,я,ⓢ,⊥,υ,♥️,ẘ,ϰ,૪,ⓩ,@,♭,ḉ,ⅾ,є,ⓕ,❡,н,ḯ,נ,ⓚ,ⓛ,м,ⓝ,☺️,ⓟ,ⓠ,я,ⓢ,⊥,υ,♥️,ẘ,ϰ,૪,ⓩ,0,➒,➑,➆,➅,➄,➃,➂,➁,➀,.,_",
"ⓐ,♭,ḉ,ⅾ,є,ƒ,ℊ,ℌ,ḯ,ʝ,ḱ,ł,μ,η,ø,ⓟ,ⓠ,ґ,ⓢ,т,ⓤ,√,ⓦ,✖️,ⓨ,ẕ,ⓐ,♭,ḉ,ⅾ,є,ƒ,ℊ,ℌ,ḯ,ʝ,ḱ,ł,μ,η,ø,ⓟ,ⓠ,ґ,ⓢ,т,ⓤ,√,ⓦ,✖️,ⓨ,ẕ,0,➈,➇,➐,➅,➄,➃,➂,➁,➀,.,_",
"ձ,ъƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_",
"λ,ϐ,ς,d,ε,ғ,ϑ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,λ,ϐ,ς,d,ε,ғ,ϑ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"მ,ჩ,ƈძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,მ,ჩ,ƈძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,0,Գ,Ց,Դ,6,5,Վ,Յ,Զ,1,.,_",
"ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"λ,ß,Ȼ,ɖ,ε,ʃ,Ģ,ħ,ί,ĵ,κ,ι,ɱ,ɴ,Θ,ρ,ƣ,ર,Ș,τ,Ʋ,ν,ώ,Χ,ϓ,Հ,λ,ß,Ȼ,ɖ,ε,ʃ,Ģ,ħ,ί,ĵ,κ,ι,ɱ,ɴ,Θ,ρ,ƣ,ર,Ș,τ,Ʋ,ν,ώ,Χ,ϓ,Հ,0,9,8,7,6,5,4,3,2,1,.,_",
"ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,0,9,8,7,6,5,4,3,2,1,.,_",
"Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,Ϧ,ㄈ,Ð,Ɛ,F,Ɠ,н,ɪ,フ,Қ,Ł,௱,Л,Ø,þ,Ҩ,尺,ら,Ť,Ц,Ɣ,Ɯ,χ,Ϥ,Ẕ,Λ,Ϧ,ㄈ,Ð,Ɛ,F,Ɠ,н,ɪ,フ,Қ,Ł,௱,Л,Ø,þ,Ҩ,尺,ら,Ť,Ц,Ɣ,Ɯ,χ,Ϥ,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"Ǟ,в,ट,D,ę,բ,g,৸,i,j,κ,l,ɱ,П,Φ,Р,q,Я,s,Ʈ,Ц,v,Щ,ж,ყ,ւ,Ǟ,в,ट,D,ę,բ,g,৸,i,j,κ,l,ɱ,П,Φ,Р,q,Я,s,Ʈ,Ц,v,Щ,ж,ყ,ւ,0,9,8,7,6,5,4,3,2,1,.,_",
"ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,0,9,8,7,6,5,4,3,2,1,.,_",
"ª,ß,¢,ð,€,f,g,h,¡,j,k,|,m,ñ,¤,Þ,q,®,$,t,µ,v,w,×,ÿ,z,ª,ß,¢,ð,€,f,g,h,¡,j,k,|,m,ñ,¤,Þ,q,®,$,t,µ,v,w,×,ÿ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_",
"ɑ,ʙ,c,ᴅ,є,ɻ,მ,ʜ,ι,ɿ,ĸ,г,w,и,o,ƅϭ,ʁ,ƨ,⊥,n,ʌ,ʍ,x,⑃,z,ɑ,ʙ,c,ᴅ,є,ɻ,მ,ʜ,ι,ɿ,ĸ,г,w,и,o,ƅϭ,ʁ,ƨ,⊥,n,ʌ,ʍ,x,⑃,z,0,9,8,7,6,5,4,3,2,1,.,_",
"4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,ßƇ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,Λ,ßƇ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,c,ɔ,ε,ғ,ɢ,н,ı,נ,κ,ʟ,м,п,σ,ρ,ǫ,я,ƨ,т,υ,ν,ш,х,ч,z,α,в,c,ɔ,ε,ғ,ɢ,н,ı,נ,κ,ʟ,м,п,σ,ρ,ǫ,я,ƨ,т,υ,ν,ш,х,ч,z,0,9,8,7,6,5,4,3,2,1,.,_",
"【a】,【b】,【c】,【d】,【e】,【f】,【g】,【h】,【i】,【j】,【k】,【l】,【m】,【n】,【o】,【p】,【q】,【r】,【s】,【t】,【u】,【v】,【w】,【x】,【y】,【z】,【a】,【b】,【c】,【d】,【e】,【f】,【g】,【h】,【i】,【j】,【k】,【l】,【m】,【n】,【o】,【p】,【q】,【r】,【s】,【t】,【u】,【v】,【w】,【x】,【y】,【z】,【0】,【9】,【8】,【7】,【6】,【5】,【4】,【3】,【2】,【1】,.,_",
"[̲̲̅̅a̲̅,̲̅b̲̲̅,̅c̲̅,̲̅d̲̲̅,̅e̲̲̅,̅f̲̲̅,̅g̲̅,̲̅h̲̲̅,̅i̲̲̅,̅j̲̲̅,̅k̲̅,̲̅l̲̲̅,̅m̲̅,̲̅n̲̅,̲̅o̲̲̅,̅p̲̅,̲̅q̲̅,̲̅r̲̲̅,̅s̲̅,̲̅t̲̲̅,̅u̲̅,̲̅v̲̅,̲̅w̲̅,̲̅x̲̅,̲̅y̲̅,̲̅z̲̅,[̲̲̅̅a̲̅,̲̅b̲̲̅,̅c̲̅,̲̅d̲̲̅,̅e̲̲̅,̅f̲̲̅,̅g̲̅,̲̅h̲̲̅,̅i̲̲̅,̅j̲̲̅,̅k̲̅,̲̅l̲̲̅,̅m̲̅,̲̅n̲̅,̲̅o̲̲̅,̅p̲̅,̲̅q̲̅,̲̅r̲̲̅,̅s̲̅,̲̅t̲̲̅,̅u̲̅,̲̅v̲̅,̲̅w̲̅,̲̅x̲̅,̲̅y̲̅,̲̅z̲̅,̲̅0̲̅,̲̅9̲̲̅,̅8̲̅,̲̅7̲̅,̲̅6̲̅,̲̅5̲̅,̲̅4̲̅,̲̅3̲̲̅,̅2̲̲̅,̅1̲̲̅̅],.,_",
"[̺͆a̺͆͆,̺b̺͆͆,̺c̺͆,̺͆d̺͆,̺͆e̺͆,̺͆f̺͆͆,̺g̺͆,̺͆h̺͆,̺͆i̺͆,̺͆j̺͆,̺͆k̺͆,̺l̺͆͆,̺m̺͆͆,̺n̺͆͆,̺o̺͆,̺͆p̺͆͆,̺q̺͆͆,̺r̺͆͆,̺s̺͆͆,̺t̺͆͆,̺u̺͆͆,̺v̺͆͆,̺w̺͆,̺͆x̺͆,̺͆y̺͆,̺͆z̺,[̺͆a̺͆͆,̺b̺͆͆,̺c̺͆,̺͆d̺͆,̺͆e̺͆,̺͆f̺͆͆,̺g̺͆,̺͆h̺͆,̺͆i̺͆,̺͆j̺͆,̺͆k̺͆,̺l̺͆͆,̺m̺͆͆,̺n̺͆͆,̺o̺͆,̺͆p̺͆͆,̺q̺͆͆,̺r̺͆͆,̺s̺͆͆,̺t̺͆͆,̺u̺͆͆,̺v̺͆͆,̺w̺͆,̺͆x̺͆,̺͆y̺͆,̺͆z̺,̺͆͆0̺͆,̺͆9̺͆,̺͆8̺̺͆͆7̺͆,̺͆6̺͆,̺͆5̺͆,̺͆4̺͆,̺͆3̺͆,̺͆2̺͆,̺͆1̺͆],.,_",
"̛̭̰̃ã̛̰̭,̛̭̰̃b̛̰̭̃̃,̛̭̰c̛̛̰̭̃̃,̭̰d̛̰̭̃,̛̭̰̃ḛ̛̭̃̃,̛̭̰f̛̰̭̃̃,̛̭̰g̛̰̭̃̃,̛̭̰h̛̰̭̃,̛̭̰̃ḭ̛̛̭̃̃,̭̰j̛̰̭̃̃,̛̭̰k̛̰̭̃̃,̛̭̰l̛̰̭,̛̭̰̃m̛̰̭̃̃,̛̭̰ñ̛̛̰̭̃,̭̰ỡ̰̭̃,̛̭̰p̛̰̭̃,̛̭̰̃q̛̰̭̃̃,̛̭̰r̛̛̰̭̃̃,̭̰s̛̰̭,̛̭̰̃̃t̛̰̭̃,̛̭̰̃ữ̰̭̃,̛̭̰ṽ̛̰̭̃,̛̭̰w̛̛̰̭̃̃,̭̰x̛̰̭̃,̛̭̰̃ỹ̛̰̭̃,̛̭̰z̛̰̭̃̃,̛̛̭̰ã̛̰̭,̛̭̰̃b̛̰̭̃̃,̛̭̰c̛̛̰̭̃̃,̭̰d̛̰̭̃,̛̭̰̃ḛ̛̭̃̃,̛̭̰f̛̰̭̃̃,̛̭̰g̛̰̭̃̃,̛̭̰h̛̰̭̃,̛̭̰̃ḭ̛̛̭̃̃,̭̰j̛̰̭̃̃,̛̭̰k̛̰̭̃̃,̛̭̰l̛̰̭,̛̭̰̃m̛̰̭̃̃,̛̭̰ñ̛̛̰̭̃,̭̰ỡ̰̭̃,̛̭̰p̛̰̭̃,̛̭̰̃q̛̰̭̃̃,̛̭̰r̛̛̰̭̃̃,̭̰s̛̰̭,̛̭̰̃̃t̛̰̭̃,̛̭̰̃ữ̰̭̃,̛̭̰ṽ̛̰̭̃,̛̭̰w̛̛̰̭̃̃,̭̰x̛̰̭̃,̛̭̰̃ỹ̛̰̭̃,̛̭̰z̛̰̭̃̃,̛̭̰0̛̛̰̭̃̃,̭̰9̛̰̭̃̃,̛̭̰8̛̛̰̭̃̃,̭̰7̛̰̭̃̃,̛̭̰6̛̰̭̃̃,̛̭̰5̛̰̭̃,̛̭̰̃4̛̰̭̃,̛̭̰̃3̛̰̭̃̃,̛̭̰2̛̰̭̃̃,̛̭̰1̛̰̭̃,.,_",
"a,ะb,ะc,ะd,ะe,ะf,ะg,ะh,ะi,ะj,ะk,ะl,ะm,ะn,ะo,ะp,ะq,ะr,ะs,ะt,ะu,ะv,ะw,ะx,ะy,ะz,a,ะb,ะc,ะd,ะe,ะf,ะg,ะh,ะi,ะj,ะk,ะl,ะm,ะn,ะo,ะp,ะq,ะr,ะs,ะt,ะu,ะv,ะw,ะx,ะy,ะz,ะ0,ะ9,ะ8,ะ7,ะ6,ะ5,ะ4,ะ3,ะ2,ะ1ะ,.,_",
"̑ȃ,̑b̑,̑c̑,̑d̑,̑ȇ,̑f̑,̑g̑,̑h̑,̑ȋ,̑j̑,̑k̑,̑l̑,̑m̑,̑n̑,̑ȏ,̑p̑,̑q̑,̑ȓ,̑s̑,̑t̑,̑ȗ,̑v̑,̑w̑,̑x̑,̑y̑,̑z̑,̑ȃ,̑b̑,̑c̑,̑d̑,̑ȇ,̑f̑,̑g̑,̑h̑,̑ȋ,̑j̑,̑k̑,̑l̑,̑m̑,̑n̑,̑ȏ,̑p̑,̑q̑,̑ȓ,̑s̑,̑t̑,̑ȗ,̑v̑,̑w̑,̑x̑,̑y̑,̑z̑,̑0̑,̑9̑,̑8̑,̑7̑,̑6̑,̑5̑,̑4̑,̑3̑,̑2̑,̑1̑,.,_",
"~a,͜͝b,͜͝c,͜͝d,͜͝e,͜͝f,͜͝g,͜͝h,͜͝i,͜͝j,͜͝k,͜͝l,͜͝m,͜͝n,͜͝o,͜͝p,͜͝q,͜͝r,͜͝s,͜͝t,͜͝u,͜͝v,͜͝w,͜͝x,͜͝y,͜͝z,~a,͜͝b,͜͝c,͜͝d,͜͝e,͜͝f,͜͝g,͜͝h,͜͝i,͜͝j,͜͝k,͜͝l,͜͝m,͜͝n,͜͝o,͜͝p,͜͝q,͜͝r,͜͝s,͜͝t,͜͝u,͜͝v,͜͝w,͜͝x,͜͝y,͜͝z,͜͝0,͜͝9,͜͝8,͜͝7,͜͝6,͜͝5,͜͝4,͜͝3,͜͝2͜,͝1͜͝~,.,_",
"̤̈ä̤,̤̈b̤̈,̤̈c̤̈̈,̤d̤̈,̤̈ë̤,̤̈f̤̈,̤̈g̤̈̈,̤ḧ̤̈,̤ï̤̈,̤j̤̈,̤̈k̤̈̈,̤l̤̈,̤̈m̤̈,̤̈n̤̈,̤̈ö̤,̤̈p̤̈,̤̈q̤̈,̤̈r̤̈,̤̈s̤̈̈,̤ẗ̤̈,̤ṳ̈,̤̈v̤̈,̤̈ẅ̤,̤̈ẍ̤,̤̈ÿ̤,̤̈z̤̈,̤̈ä̤,̤̈b̤̈,̤̈c̤̈̈,̤d̤̈,̤̈ë̤,̤̈f̤̈,̤̈g̤̈̈,̤ḧ̤̈,̤ï̤̈,̤j̤̈,̤̈k̤̈̈,̤l̤̈,̤̈m̤̈,̤̈n̤̈,̤̈ö̤,̤̈p̤̈,̤̈q̤̈,̤̈r̤̈,̤̈s̤̈̈,̤ẗ̤̈,̤ṳ̈,̤̈v̤̈,̤̈ẅ̤,̤̈ẍ̤,̤̈ÿ̤,̤̈z̤̈,̤̈0̤̈,̤̈9̤̈,̤̈8̤̈,̤̈7̤̈,̤̈6̤̈,̤̈5̤̈,̤̈4̤̈,̤̈3̤̈,̤̈2̤̈̈,̤1̤̈,.,_",
"≋̮̑ȃ̮,̮̑b̮̑,̮̑c̮̑,̮̑d̮̑,̮̑ȇ̮,̮̑f̮̑,̮̑g̮̑,̮̑ḫ̑,̮̑ȋ̮,̮̑j̮̑,̮̑k̮̑,̮̑l̮̑,̮̑m̮̑,̮̑n̮̑,̮̑ȏ̮,̮̑p̮̑,̮̑q̮̑,̮̑r̮,̮̑̑s̮,̮̑̑t̮,̮̑̑u̮,̮̑̑v̮̑,̮̑w̮̑,̮̑x̮̑,̮̑y̮̑,̮̑z̮̑,≋̮̑ȃ̮,̮̑b̮̑,̮̑c̮̑,̮̑d̮̑,̮̑ȇ̮,̮̑f̮̑,̮̑g̮̑,̮̑ḫ̑,̮̑ȋ̮,̮̑j̮̑,̮̑k̮̑,̮̑l̮̑,̮̑m̮̑,̮̑n̮̑,̮̑ȏ̮,̮̑p̮̑,̮̑q̮̑,̮̑r̮,̮̑̑s̮,̮̑̑t̮,̮̑̑u̮,̮̑̑v̮̑,̮̑w̮̑,̮̑x̮̑,̮̑y̮̑,̮̑z̮̑,̮̑0̮̑,̮̑9̮̑,̮̑8̮̑,̮̑7̮̑,̮̑6̮̑,̮̑5̮̑,̮̑4̮̑,̮̑3̮̑,̮̑2̮̑,̮̑1̮̑≋,.,_",
"a̮,̮b̮̮,c̮̮,d̮̮,e̮̮,f̮̮,g̮̮,ḫ̮,i̮,j̮̮,k̮̮,l̮,̮m̮,̮n̮̮,o̮,̮p̮̮,q̮̮,r̮̮,s̮,̮t̮̮,u̮̮,v̮̮,w̮̮,x̮̮,y̮̮,z̮̮,a̮,̮b̮̮,c̮̮,d̮̮,e̮̮,f̮̮,g̮̮,ḫ̮i,̮̮,j̮̮,k̮̮,l̮,̮m̮,̮n̮̮,o̮,̮p̮̮,q̮̮,r̮̮,s̮,̮t̮̮,u̮̮,v̮̮,w̮̮,x̮̮,y̮̮,z̮̮,0̮̮,9̮̮,8̮̮,7̮̮,6̮̮,5̮̮,4̮̮,3̮̮,2̮̮,1̮,.,_",
"A̲,̲B̲,̲C̲,̲D̲,̲E̲,̲F̲,̲G̲,̲H̲,̲I̲,̲J̲,̲K̲,̲L̲,̲M̲,̲N̲,̲O̲,̲P̲,̲Q̲,̲R̲,̲S̲,̲T̲,̲U̲,̲V̲,̲W̲,̲X̲,̲Y̲,̲Z̲,̲a̲,̲b̲,̲c̲,̲d̲,̲e̲,̲f̲,̲g̲,̲h̲,̲i̲,̲j̲,̲k̲,̲l̲,̲m̲,̲n̲,̲o̲,̲p̲,̲q̲,̲r̲,̲s̲,̲t̲,̲u̲,̲v̲,̲w̲,̲x̲,̲y̲,̲z̲,̲0̲,̲9̲,̲8̲,̲7̲,̲6̲,̲5̲,̲4̲,̲3̲,̲2̲,̲1̲,̲.̲,̲_̲",
"Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local result = {}
i=0
for k=1,#fonts do
i=i+1
local tar_font = fonts[i]:split(",")
local text = matches[2]
local text = text:gsub("A",tar_font[1])
local text = text:gsub("B",tar_font[2])
local text = text:gsub("C",tar_font[3])
local text = text:gsub("D",tar_font[4])
local text = text:gsub("E",tar_font[5])
local text = text:gsub("F",tar_font[6])
local text = text:gsub("G",tar_font[7])
local text = text:gsub("H",tar_font[8])
local text = text:gsub("I",tar_font[9])
local text = text:gsub("J",tar_font[10])
local text = text:gsub("K",tar_font[11])
local text = text:gsub("L",tar_font[12])
local text = text:gsub("M",tar_font[13])
local text = text:gsub("N",tar_font[14])
local text = text:gsub("O",tar_font[15])
local text = text:gsub("P",tar_font[16])
local text = text:gsub("Q",tar_font[17])
local text = text:gsub("R",tar_font[18])
local text = text:gsub("S",tar_font[19])
local text = text:gsub("T",tar_font[20])
local text = text:gsub("U",tar_font[21])
local text = text:gsub("V",tar_font[22])
local text = text:gsub("W",tar_font[23])
local text = text:gsub("X",tar_font[24])
local text = text:gsub("Y",tar_font[25])
local text = text:gsub("Z",tar_font[26])
local text = text:gsub("a",tar_font[27])
local text = text:gsub("b",tar_font[28])
local text = text:gsub("c",tar_font[29])
local text = text:gsub("d",tar_font[30])
local text = text:gsub("e",tar_font[31])
local text = text:gsub("f",tar_font[32])
local text = text:gsub("g",tar_font[33])
local text = text:gsub("h",tar_font[34])
local text = text:gsub("i",tar_font[35])
local text = text:gsub("j",tar_font[36])
local text = text:gsub("k",tar_font[37])
local text = text:gsub("l",tar_font[38])
local text = text:gsub("m",tar_font[39])
local text = text:gsub("n",tar_font[40])
local text = text:gsub("o",tar_font[41])
local text = text:gsub("p",tar_font[42])
local text = text:gsub("q",tar_font[43])
local text = text:gsub("r",tar_font[44])
local text = text:gsub("s",tar_font[45])
local text = text:gsub("t",tar_font[46])
local text = text:gsub("u",tar_font[47])
local text = text:gsub("v",tar_font[48])
local text = text:gsub("w",tar_font[49])
local text = text:gsub("x",tar_font[50])
local text = text:gsub("y",tar_font[51])
local text = text:gsub("z",tar_font[52])
local text = text:gsub("0",tar_font[53])
local text = text:gsub("9",tar_font[54])
local text = text:gsub("8",tar_font[55])
local text = text:gsub("7",tar_font[56])
local text = text:gsub("6",tar_font[57])
local text = text:gsub("5",tar_font[58])
local text = text:gsub("4",tar_font[59])
local text = text:gsub("3",tar_font[60])
local text = text:gsub("2",tar_font[61])
local text = text:gsub("1",tar_font[62])
table.insert(result, text)
end
local result_text = "کلمه ی اولیه: "..matches[2].."\nطراحی با "..tostring(#fonts).." فونت:\n\n"
a=0
for v=1,#result do
a=a+1
result_text = result_text..a.."- "..result[a].."\n\n"
end
return result_text.."sezar.bot"
end
return {
description = "Fantasy Writer",
usagehtm = '<tr><td align="center">write متن</td><td align="right">با استفاده از این پلاگین میتوانید متون خود را با فونت های متنوع و زیبایی طراحی کنید. حد اکثر کاراکتر های مجاز 20 عدد میباشد و فقط میتوانید از حروف انگلیسی و اعداد استفاده کنید</td></tr>',
usage = {"!write [text] : زیبا نویسی",},
patterns = {
"^[#!/](بنویس) (.*)",
"^[#!/](بنویس)$",
"^[#!/]([Ww]rite) (.*)",
"^[#!/]([Ww]rite)$",
},
run = run
}
| gpl-2.0 |
wesnoth/wesnoth | data/campaigns/World_Conquest/lua/map/generator/utilities.lua | 6 | 6320 |
function flatten1(list)
local res = {}
assert(type(list) == "table")
for i1, v1 in ipairs(list) do
assert(type(v1) == "table")
for i2, v2 in ipairs(v1) do
res[#res + 1] = v2
end
end
return res
end
function dr_height(height, terrain)
return {
height = height,
terrain = terrain,
}
end
-- dr_convert(nil, nil, nil, nil, "aaaa", "aaaa"),
function dr_convert(min, max, mint, maxt, from, to)
return { {
min_height=min,
max_height=max,
min_temperature=mint,
max_temperature=maxt,
from=from,
to=to,
} }
end
function dr_temperature(from, mint, maxt, to)
return { {
min_temperature=mint,
max_temperature=maxt,
from=from,
to=to,
} }
end
function dr_village(t)
return { t }
end
function wct_fix_river_into_ocean(t, height)
-- generator uses Ww for rivers
-- best way to difference ocean from river in postgeneration is use different terrain for ocean
-- this macro fix water of different color into ocean
-- as rivers are generated until map border
return {
{
max_height=0,
from="Ww",
to="Wo" ..t ,
},
{
max_height=height,
from="Ww",
to="Ww" .. t,
}
}
end
function dr_road(from, to, cost)
return { {
terrain = from,
cost = cost,
convert_to = to
} }
end
function dr_bridge(from, bridge, road, cost)
return { {
terrain = from,
cost = cost,
convert_to_bridge = bridge .. "|," .. bridge .. "/," .. bridge .. "\\",
convert_to = road,
} }
end
function dr_road_over_bridges(bridge, cost)
return flatten1 {
dr_road(bridge .. "|", bridge .. "|", cost),
dr_road(bridge .. "/", bridge .. "/", cost),
dr_road(bridge .. "\\", bridge .. "\\", cost),
}
end
function wct_generator_settings_arguments(length, villages, castle, iterations, hill_size, players, island)
local width = length
if width % 2 == 1 then
width = width + 1
end
return {
border_size=0,
map_width=width,
map_height=length,
iterations=iterations,
hill_size=hill_size,
villages=villages,
nplayers=players,
island_size=island,
castle_size=castle,
temperature_iterations=iterations,
link_castles=true,
}
end
function wct_generator_village(GG, GS, DS, UU, UH, GSFP, HH, MM, AA, AAFPA, SS, WW)
return flatten1 {
dr_village {
terrain="Gg",
convert_to="Gg^Vh",
rating=GG,
adjacent_liked="Gg, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp",
},
dr_village {
terrain="Gs",
convert_to="Gs^Vht",
rating=GS,
adjacent_liked="Gg, Gs, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp",
},
dr_village {
terrain="Ds",
convert_to="Dd^Vda",
rating=DS,
adjacent_liked="Gg, Gs, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp",
},
dr_village {
terrain="Uu",
convert_to="Uu^Vud",
rating=UU,
adjacent_liked="Re,Hh,Mm,Uu,Uh,Xu",
},
dr_village {
terrain="Uh",
convert_to="Uu^Vu",
rating=UH,
adjacent_liked="Re,Hh,Mm,Uu,Uh,Xu",
},
dr_village {
terrain="Hh",
convert_to="Hh^Vhh",
rating=HH,
adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp",
},
dr_village {
terrain="Mm",
convert_to="Mm^Vhh",
rating=MM,
adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp",
},
-- villages in forest are Elvish
dr_village {
terrain="Gs^Fp",
convert_to="Gg^Ve",
rating=GSFP,
adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp, Gs^Fp, Gs^Fp",
},
dr_village {
terrain="Aa^Fpa",
convert_to="Aa^Vea",
rating=AAFPA,
adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp",
},
dr_village {
terrain="Aa",
convert_to="Aa^Vha",
rating=AA,
adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp",
},
dr_village {
terrain="Ss",
convert_to="Ss^Vhs",
rating=SS,
adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bw|, Ww^Bw/, Ww^Bw\\, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp",
},
-- mermen villages - give them low chance of appearing
dr_village {
terrain="Ww",
convert_to="Ww^Vm",
rating=WW,
adjacent_liked="Ww, Ww",
},
}
end
function wct_generator_road_cost_classic()
return flatten1 {
dr_road("Gg", "Re", 10),
dr_road("Gs^Fp", "Re", 20),
dr_road("Hh", "Re", 30),
dr_road("Mm", "Re", 40),
dr_road("Mm^Xm", "Re", 75),
dr_bridge("Ql", "Ql^Bs", "Re", 100),
dr_bridge("Qxu", "Qxu^Bs", "Re", 100),
dr_road("Uu", "Re", 10),
dr_road("Uh", "Re", 40),
dr_road("Xu", "Re", 90),
-- road going through snow is covered over by the snow
-- (in classic WC people were too lazy to clean it :P)
dr_road("Aa", "Aa", 20),
dr_road("Re", "Re", 2),
dr_road_over_bridges("Ww^Bw", 2),
dr_road("Ch", "Ch", 2),
dr_road("Ce", "Ce", 2),
}
end
function default_generate_map(data)
local max_island = 10
local max_coastal = 5
data.village = flatten1(data.village or {})
data.road_cost = flatten1(data.road_cost or {})
data.convert = flatten1(data.convert or {})
local cfg = wc2_convert.lon_to_wml(data, "mg_main")
local w, h = cfg.map_width, cfg.map_height
local orig_island_size = cfg.island_size
local orig_nvillages = cfg.villages
cfg.island_size = 0;
cfg.nvillages = (orig_nvillages * w * h) // 1000;
cfg.island_off_center = 0;
if orig_island_size >= max_coastal then
-- Islands look good with much fewer iterations than normal, and fewer lakes
cfg.iterations = cfg.iterations // 10
cfg.max_lakes = (cfg.max_lakes or 0) // 9
-- The radius of the island should be up to half the width of the map
local island_radius = 50 + ((max_island - orig_island_size) * 50) // (max_island - max_coastal)
cfg.island_size = (island_radius * (w/2)) // 100;
elseif orig_island_size > 0 then
-- The radius of the island should be up to twice the width of the map
local island_radius = 40 + ((max_coastal - orig_island_size) * 40) // max_coastal;
cfg.island_size = (island_radius * w * 2) // 100;
cfg.island_off_center = math.min(w, h);
end
for i = 1, 20 do
local status, map = pcall(function()
cfg.seed = mathx.random(5000) + 7
return wesnoth.map.generate(w, h, cfg)
end)
if status then
return map
end
end
cfg.seed = mathx.random(5000) + 7
return wesnoth.map.generate(w, h, cfg)
end
| gpl-2.0 |
Sannis/tarantool | test/app/csv.test.lua | 6 | 3607 | #!/usr/bin/env tarantool
local function table2str(t)
local res = ""
for k, line in pairs(t) do
local s = ""
for k2, field in pairs(line) do
s = s .. '|' .. field .. '|\t'
end
res = res .. s .. '\n'
end
return res
end
local function myread(self, bytes)
self.i = self.i + bytes
return self.v:sub(self.i - bytes + 1, self.i)
end
local csv = require('csv')
local fio = require('fio')
local tap = require('tap')
local test1_ans = '|a|\t|b|\t\n|1|\t|ha\n"ha"\nha|\t\n|3|\t|4|\t\n'
local test2_ans = '||\t||\t||\t\n||\t||\t\n||\t\n'
local test3_ans = '||\t||\t\n|kp"v|\t\n'
local test4_ans = '|123|\t|5|\t|92|\t|0|\t|0|\t\n|1|\t|12 34|\t|56|\t' ..
'|quote , |\t|66|\t\n|ok|\t\n'
local test5_ans = "|1|\t\n|23|\t|456|\t|abcac|\t|'multiword field 4'|\t\n" ..
"|none|\t|none|\t|0|\t\n||\t||\t||\t\n|aba|\t|adda|\t|f" ..
"3|\t|0|\t\n|local res = internal.pwrite(self.fh|\t|dat" ..
"a|\t|len|\t|offset)|\t\n|iflag = bit.bor(iflag|\t|fio." ..
"c.flag[ flag ])|\t\n||\t||\t||\t\n"
local test6_ans = "|23|\t|456|\t|abcac|\t|'multiword field 4'|\t\n|none|" ..
"\t|none|\t|0|\t\n||\t||\t||\t\n|aba|\t|adda|\t|f3|\t|" ..
"0|\t\n|local res = internal.pwrite(self.fh|\t|data|\t" ..
"|len|\t|offset)|\t\n|iflag = bit.bor(iflag|\t|fio.c.f" ..
"lag[ flag ])|\t\n||\t||\t||\t\n"
test = tap.test("csv")
test:plan(8)
readable = {}
readable.read = myread
readable.v = "a,b\n1,\"ha\n\"\"ha\"\"\nha\"\n3,4\n"
readable.i = 0
test:is(table2str(csv.load(readable)), test1_ans, "obj test1")
readable.v = ", ,\n , \n\n"
readable.i = 0
test:is(table2str(csv.load(readable, {chunk_size = 1} )), test2_ans, "obj test2")
readable.v = ", \r\nkp\"\"v"
readable.i = 0
test:is(table2str(csv.load(readable, {chunk_size = 3})), test3_ans, "obj test3")
tmpdir = fio.tempdir()
file1 = fio.pathjoin(tmpdir, 'file.1')
file2 = fio.pathjoin(tmpdir, 'file.2')
file3 = fio.pathjoin(tmpdir, 'file.3')
local f = fio.open(file1, { 'O_WRONLY', 'O_TRUNC', 'O_CREAT' }, 0777)
f:write("123 , 5 , 92 , 0, 0\n" ..
"1, 12 34, 56, \"quote , \", 66\nok")
f:close()
f = fio.open(file1, {'O_RDONLY'})
test:is(table2str(csv.load(f, {chunk_size = 10})), test4_ans, "fio test1")
f:close()
f = fio.open(file2, { 'O_WRONLY', 'O_TRUNC', 'O_CREAT' }, 0777)
f:write("1\n23,456,abcac,\'multiword field 4\'\n" ..
"none,none,0\n" ..
",,\n" ..
"aba,adda,f3,0\n" ..
"local res = internal.pwrite(self.fh, data, len, offset)\n" ..
"iflag = bit.bor(iflag, fio.c.flag[ flag ])\n" ..
",,"
)
f:close()
f = fio.open(file2, {'O_RDONLY'})
--symbol by symbol reading
test:is(table2str(csv.load(f, {chunk_size = 1})), test5_ans, "fio test2")
f:close()
f = fio.open(file2, {'O_RDONLY'})
opts = {chunk_size = 7, skip_head_lines = 1}
--7 symbols per chunk
test:is(table2str(csv.load(f, opts)), test6_ans, "fio test3")
f:close()
t = {
{'quote" d', ',and, comma', 'both " of " t,h,e,m'},
{'"""', ',","'},
{'mul\nti\nli\r\nne\n\n', 'field'},
{""},
{'"'},
{"\n"}
}
f = require("fio").open(file3, { "O_WRONLY", "O_TRUNC" , "O_CREAT"}, 0x1FF)
csv.dump(t, {}, f)
f:close()
f = fio.open(file3, {'O_RDONLY'})
t2 = csv.load(f, {chunk_size = 5})
f:close()
test:is(table2str(t), table2str(t2), "test roundtrip")
test:is(table2str(t), table2str(csv.load(csv.dump(t))), "test load(dump(t))")
fio.unlink(file1)
fio.unlink(file2)
fio.unlink(file3)
fio.rmdir(tmpdir)
| bsd-2-clause |
helingping/Urho3D | bin/Data/LuaScripts/03_Sprites.lua | 24 | 3509 | -- Moving sprites example.
-- This sample demonstrates:
-- - Adding Sprite elements to the UI
-- - Storing custom data (sprite velocity) inside UI elements
-- - Handling frame update events in which the sprites are moved
require "LuaScripts/Utilities/Sample"
local numSprites = 100
local sprites = {}
-- Custom variable identifier for storing sprite velocity within the UI element
local VAR_VELOCITY = StringHash("Velocity")
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the sprites to the user interface
CreateSprites()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_FREE)
-- Hook up to the frame update events
SubscribeToEvents()
end
function CreateSprites()
local decalTex = cache:GetResource("Texture2D", "Textures/UrhoDecal.dds")
local width = graphics.width
local height = graphics.height
for i = 1, numSprites do
-- Create a new sprite, set it to use the texture
local sprite = Sprite:new()
sprite.texture = decalTex
sprite:SetFullImageRect()
-- The UI root element is as big as the rendering window, set random position within it
sprite.position = Vector2(Random(width), Random(height))
-- Set sprite size & hotspot in its center
sprite:SetSize(128, 128)
sprite.hotSpot = IntVector2(64, 64)
-- Set random rotation in degrees and random scale
sprite.rotation = Random(360.0)
sprite.scale = Vector2(1.0, 1.0) * (Random(1.0) + 0.5)
-- Set random color and additive blending mode
sprite:SetColor(Color(Random(0.5) + 0.5, Random(0.5) + 0.5, Random(0.5) + 0.5, 1.0))
sprite.blendMode = BLEND_ADD
-- Add as a child of the root UI element
ui.root:AddChild(sprite)
-- Store sprite's velocity as a custom variable
sprite:SetVar(VAR_VELOCITY, Variant(Vector2(Random(200.0) - 100.0, Random(200.0) - 100.0)))
table.insert(sprites, sprite)
end
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
end
function MoveSprites(timeStep)
local width = graphics.width
local height = graphics.height
for i = 1, numSprites do
local sprite = sprites[i]
sprite.rotation = sprite.rotation + timeStep * 30
local newPos = sprite.position
newPos = newPos + sprite:GetVar(VAR_VELOCITY):GetVector2() * timeStep
if newPos.x >= width then
newPos.x = newPos.x - width
elseif newPos.x < 0 then
newPos.x = newPos.x + width
end
if newPos.y >= height then
newPos.y = newPos.y - height
elseif newPos.y < 0 then
newPos.y = newPos.y + height
end
sprite.position = newPos
end
end
function HandleUpdate(eventType, eventData)
local timeStep = eventData["TimeStep"]:GetFloat()
MoveSprites(timeStep)
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
" <attribute name=\"Is Visible\" value=\"false\" />" ..
" </add>" ..
"</patch>"
end
| mit |
Bew78LesellB/awesome | spec/wibox/test_utils.lua | 6 | 4137 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2014 Uli Schlachter
---------------------------------------------------------------------------
local object = require("gears.object")
local matrix_equals = require("gears.matrix").equals
local base = require("wibox.widget.base")
local say = require("say")
local assert = require("luassert")
local no_parent = base.no_parent_I_know_what_I_am_doing
-- {{{ Own widget-based assertions
local function widget_fit(state, arguments)
if #arguments ~= 3 then
error("Have " .. #arguments .. " arguments, but need 3")
end
local widget = arguments[1]
local given = arguments[2]
local expected = arguments[3]
local w, h = base.fit_widget(no_parent, { "fake context" }, widget, given[1], given[2])
local fits = expected[1] == w and expected[2] == h
if state.mod == fits then
return true
end
-- For proper error message, mess with the arguments
arguments[1] = given[1]
arguments[2] = given[2]
arguments[3] = expected[1]
arguments[4] = expected[2]
arguments[5] = w
arguments[6] = h
return false
end
say:set("assertion.widget_fit.positive", "Offering (%s, %s) to widget and expected (%s, %s), but got (%s, %s)")
assert:register("assertion", "widget_fit", widget_fit, "assertion.widget_fit.positive", "assertion.widget_fit.positive")
local function widget_layout(state, arguments)
if #arguments ~= 3 then
error("Have " .. #arguments .. " arguments, but need 3")
end
local widget = arguments[1]
local given = arguments[2]
local expected = arguments[3]
local children = widget.layout and widget:layout({ "fake context" }, given[1], given[2]) or {}
local fits = true
if #children ~= #expected then
fits = false
else
for i = 1, #children do
local child, exp = children[i], expected[i]
if child._widget ~= exp._widget or
child._width ~= exp._width or
child._height ~= exp._height or
not matrix_equals(child._matrix, exp._matrix) then
fits = false
break
end
end
end
if state.mod == fits then
return true
end
-- For proper error message, mess with the arguments
arguments[1] = expected
arguments[2] = children
arguments[3] = given[1]
arguments[4] = given[2]
return false
end
say:set("assertion.widget_layout.positive", "Expected:\n%s\nbut got:\n%s\nwhen offering (%s, %s) to widget")
assert:register("assertion",
"widget_layout",
widget_layout,
"assertion.widget_layout.positive",
"assertion.widget_layout.positive")
-- }}}
local function test_container(container)
local w1 = base.empty_widget()
assert.is.same({}, container:get_children())
container:set_widget(w1)
assert.is.same({ w1 }, container:get_children())
container:set_widget(nil)
assert.is.same({}, container:get_children())
container:set_widget(w1)
assert.is.same({ w1 }, container:get_children())
if container.reset then
container:reset()
assert.is.same({}, container:get_children())
end
end
return {
widget_stub = function(width, height)
local w = object()
w._private = {}
w.is_widget = true
w._private.visible = true
w._private.opacity = 1
if width or height then
w.fit = function()
return width or 10, height or 10
end
end
w._private.widget_caches = {}
w:connect_signal("widget::layout_changed", function()
-- TODO: This is not completely correct, since our parent's caches
-- are not cleared. For the time being, tests just have to handle
-- this clearing-part themselves.
w._private.widget_caches = {}
end)
return w
end,
test_container = test_container,
}
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
helingping/Urho3D | Source/ThirdParty/toluapp/src/bin/lua/custom.lua | 25 | 1388 |
function extract_code(fn,s)
local code = ""
if fn then
code = '\n$#include "'..fn..'"\n'
end
s= "\n" .. s .. "\n" -- add blank lines as sentinels
local _,e,c,t = strfind(s, "\n([^\n]-)SCRIPT_([%w_]*)[^\n]*\n")
while e do
t = strlower(t)
if t == "bind_begin" then
_,e,c = strfind(s,"(.-)\n[^\n]*SCRIPT_BIND_END[^\n]*\n",e)
if not e then
tolua_error("Unbalanced 'SCRIPT_BIND_BEGIN' directive in header file")
end
end
if t == "bind_class" or t == "bind_block" then
local b
_,e,c,b = string.find(s, "([^{]-)(%b{})", e)
c = c..'{\n'..extract_code(nil, b)..'\n};\n'
end
code = code .. c .. "\n"
_,e,c,t = strfind(s, "\n([^\n]-)SCRIPT_([%w_]*)[^\n]*\n",e)
end
return code
end
function preprocess_hook(p)
end
function preparse_hook(p)
end
function include_file_hook(p, filename)
do return end
--print("FILENAME is "..filename)
p.code = string.gsub(p.code, "\n%s*SigC::Signal", "\n\ttolua_readonly SigC::Signal")
p.code = string.gsub(p.code, "#ifdef __cplusplus\nextern \"C\" {\n#endif", "")
p.code = string.gsub(p.code, "#ifdef __cplusplus\n};?\n#endif", "")
p.code = string.gsub(p.code, "DECLSPEC", "")
p.code = string.gsub(p.code, "SDLCALL", "")
p.code = string.gsub(p.code, "DLLINTERFACE", "")
p.code = string.gsub(p.code, "#define[^\n]*_[hH]_?%s*\n", "\n")
--print("code is "..p.code)
end
| mit |
CyberSecurityBot/Cyber-Security-pro | plugins/onservice.lua | 2 | 1704 | --[[
|------------------------------------------------- |--------- ______-----------------_______---|
| ______ __ ______ _____ _____ __ | _____ | ____| __ __ / _____/ |
| |__ __| | | |__ __| / \ | \ | | | |__ | | |____ | | | | / /____ |
| | | | | | | / /_\ \ | |\ \ | | | / / | ____| | | | | \____ / |
| | | | | | | / _____ \ | | \ \| | | / /_ | |____ | |___| | ___/ / |
| |__| |__| |__| /__/ \__\|__| \_____| | |_____| |______| \_______/ /______/ |
|--------------------------------------------------|-------------------------------------------|
| This Project Powered by : Pouya Poorrahman CopyRight 2016 Jove Version 5.3 Anti Spam Cli Bot |
|----------------------------------------------------------------------------------------------|
]]
do
-- Will leave the group if be added
local function run(msg, matches)
local bot_id = our_id
local receiver = get_receiver(msg)
if matches[1] == 'leave' and is_admin1(msg) then
chat_del_user("chat#id"..msg.to.id, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
elseif msg.service and msg.action.type == "chat_add_user" and msg.action.user.id == tonumber(bot_id) and not is_admin1(msg) then
send_large_msg(receiver, '<i>✨این گروه من نیست<ژوپیتر ورژن 5.3✨</i>', ok_cb, false)
chat_del_user(receiver, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
end
end
return {
patterns = {
"^[#!/](leave)$",
"^(leave)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| agpl-3.0 |
iamgreaser/iceball | pkg/iceball/lib/font.lua | 4 | 2269 | --[[
Copyright (c) 2014 Team Sparkle
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.
]]
function glyphmap_linear(start, stop, default)
local l = {}
local i
local offs = 0
for i=start,stop do
l[i] = offs
offs = offs + 1
end
l.gcount = (stop-start)+1
l.default = default
return l
end
function font_mono_new(settings)
local this = {
img = common.img_load(settings.fname, "png"),
glyphmap = settings.glyphmap,
}
this.iwidth, this.iheight = common.img_get_dims(this.img)
function this.render(x, y, s, c, destimg)
c = c or 0xFFFFFFFF
local w = this.iwidth / this.glyphmap.gcount
local h = this.iheight
local i
for i=1,#s do
local offs = this.glyphmap[s:byte(i)]
offs = offs or this.glyphmap.default
offs = offs or 0
offs = offs * w
if destimg then
client.img_blit_to(destimg, this.img, x, y, w, h, offs, 0, c)
else
client.img_blit(this.img, x, y, w, h, offs, 0, c)
end
x = x + w
end
end
function this.string_width(s)
return (this.iwidth / this.glyphmap.gcount) * string.len(s)
end
function this.string_height(s)
return this.iheight
end
return this
end
font_dejavu_bold = {
[18] = font_mono_new {
fname = "pkg/iceball/gfx/dejavu-18-bold.png",
glyphmap = glyphmap_linear(32, 126, ("?"):byte()-32),
},
}
| gpl-3.0 |
Anarchid/Zero-K | LuaUI/Widgets/dbg_ceg_spawner.lua | 8 | 3055 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "CEG Spawner",
desc = "v0.031 Spawn CEGs",
author = "CarRepairer",
date = "2010-11-07",
license = "GPLv2",
layer = 5,
enabled = false, -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--Set to true to sort CEGs into alphabetic submenus. This cannot be added to epicmenu options because it's used to actually change those options.
local ALPHA = true
local echo = Spring.Echo
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
options_order = { 'reload', 'xdir', 'ydir', 'zdir', 'radius', }
options_path = 'Settings/Toolbox/CEG Spawner'
options = {
reload = {
name = 'Reload CEGs',
type = 'button',
OnChange = function() Spring.SendCommands('reloadcegs') end,
},
xdir = {
name = 'X (-1,1)',
type = 'number',
min = -1, max = 1, step = 0.1,
value = 0,
},
ydir = {
name = 'Y (-1,1)',
type = 'number',
min = -1, max = 1, step = 0.1,
value = 0,
},
zdir = {
name = 'Z (-1,1)',
type = 'number',
min = -1, max = 1, step = 0.1,
value = 0,
},
radius = {
name = 'Radius (0 - 100)',
type = 'number',
min = 0, max = 100, step = 1,
value = 20,
},
}
local vsx, vsy = widgetHandler:GetViewSizes()
local cx,cy = vsx * 0.5,vsy * 0.5
function OnChangeFunc(self)
if not Spring.IsCheatingEnabled() then
echo "Cannot do this unless Cheating is enabled."
return
end
cx,cy = vsx * 0.5,vsy * 0.5
local ttype,pos = Spring.TraceScreenRay(cx, cy, true)
if ttype == 'ground' then
Spring.SendLuaRulesMsg( '*' .. self.cegname
.. '|' .. pos[1]
.. '|' .. pos[2]
.. '|' .. pos[3]
.. '|' .. options.xdir.value
.. '|' .. options.ydir.value
.. '|' .. options.zdir.value
.. '|' .. options.radius.value
)
else
echo "Cannot do this with a unit in the center of the screen."
end
end
local function AddCEGButton(cegname)
options_order[#options_order+1] = cegname
options[cegname] = {
type = 'button',
name = cegname,
cegname = cegname,
OnChange = OnChangeFunc,
}
if ALPHA then
options[cegname].path = options_path..'/' .. cegname:sub(1,1):upper()
--echo ( options[cegname].path )
end
end
local function SetupOptions()
local explosionDefs = VFS.Include("gamedata/explosions.lua")
local explosions2 = {}
for k,v in pairs(explosionDefs) do
--echo(k,v)
explosions2[#explosions2+1] = k
end
table.sort(explosions2)
for i,v in ipairs(explosions2) do
AddCEGButton(v)
end
end
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
cx = vsx * 0.5
cy = vsy * 0.5
end
function widget:Initialize()
SetupOptions()
end
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/corsd.lua | 1 | 2404 | return {
corsd = {
activatewhenbuilt = true,
buildangle = 4096,
buildcostenergy = 6363,
buildcostmetal = 698,
buildinggrounddecaldecayspeed = 30,
buildinggrounddecalsizex = 6,
buildinggrounddecalsizey = 6,
buildinggrounddecaltype = "corsd_aoplane.dds",
buildpic = "CORSD.DDS",
buildtime = 11955,
category = "ALL NOTLAND NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE",
collisionvolumeoffsets = "0 -1 0",
collisionvolumescales = "65 10 60",
collisionvolumetest = 1,
collisionvolumetype = "Box",
corpse = "DEAD",
description = "Intrusion Countermeasure System",
energyuse = 125,
explodeas = "LARGE_BUILDINGEX",
footprintx = 4,
footprintz = 4,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
levelground = false,
maxdamage = 2500,
maxslope = 36,
maxwaterdepth = 0,
name = "Nemesis",
objectname = "CORSD",
onoffable = true,
seismicdistance = 2000,
seismicsignature = 0,
selfdestructas = "LARGE_BUILDING",
sightdistance = 225,
usebuildinggrounddecal = true,
yardmap = "oooooooooooooooo",
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "-1.15772247314 -1.86200052979 2.43579101563",
collisionvolumescales = "68.8967437744 12.3805389404 66.8254699707",
collisionvolumetype = "Box",
damage = 1500,
description = "Nemesis Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 4,
footprintz = 4,
height = 15,
hitdensity = 100,
metal = 584,
object = "CORSD_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 750,
description = "Nemesis Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 4,
footprintz = 4,
height = 4,
hitdensity = 100,
metal = 234,
object = "4X4A",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
activate = "targon2",
canceldestruct = "cancel2",
deactivate = "targoff2",
underattack = "warning1",
working = "targsel2",
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
select = {
[1] = "targsel2",
},
},
},
}
| gpl-2.0 |
LightenPan/skynet-yule | lualib/snax.lua | 59 | 3683 | local skynet = require "skynet"
local snax_interface = require "snax.interface"
local snax = {}
local typeclass = {}
local interface_g = skynet.getenv("snax_interface_g")
local G = interface_g and require (interface_g) or { require = function() end }
interface_g = nil
skynet.register_protocol {
name = "snax",
id = skynet.PTYPE_SNAX,
pack = skynet.pack,
unpack = skynet.unpack,
}
function snax.interface(name)
if typeclass[name] then
return typeclass[name]
end
local si = snax_interface(name, G)
local ret = {
name = name,
accept = {},
response = {},
system = {},
}
for _,v in ipairs(si) do
local id, group, name, f = table.unpack(v)
ret[group][name] = id
end
typeclass[name] = ret
return ret
end
local meta = { __tostring = function(v) return string.format("[%s:%x]", v.type, v.handle) end}
local skynet_send = skynet.send
local skynet_call = skynet.call
local function gen_post(type, handle)
return setmetatable({} , {
__index = function( t, k )
local id = type.accept[k]
if not id then
error(string.format("post %s:%s no exist", type.name, k))
end
return function(...)
skynet_send(handle, "snax", id, ...)
end
end })
end
local function gen_req(type, handle)
return setmetatable({} , {
__index = function( t, k )
local id = type.response[k]
if not id then
error(string.format("request %s:%s no exist", type.name, k))
end
return function(...)
return skynet_call(handle, "snax", id, ...)
end
end })
end
local function wrapper(handle, name, type)
return setmetatable ({
post = gen_post(type, handle),
req = gen_req(type, handle),
type = name,
handle = handle,
}, meta)
end
local handle_cache = setmetatable( {} , { __mode = "kv" } )
function snax.rawnewservice(name, ...)
local t = snax.interface(name)
local handle = skynet.newservice("snaxd", name)
assert(handle_cache[handle] == nil)
if t.system.init then
skynet.call(handle, "snax", t.system.init, ...)
end
return handle
end
function snax.bind(handle, type)
local ret = handle_cache[handle]
if ret then
assert(ret.type == type)
return ret
end
local t = snax.interface(type)
ret = wrapper(handle, type, t)
handle_cache[handle] = ret
return ret
end
function snax.newservice(name, ...)
local handle = snax.rawnewservice(name, ...)
return snax.bind(handle, name)
end
local function service_name(global, name, ...)
if global == true then
return name
else
return global
end
end
function snax.uniqueservice(name, ...)
local handle = assert(skynet.call(".service", "lua", "LAUNCH", "snaxd", name, ...))
return snax.bind(handle, name)
end
function snax.globalservice(name, ...)
local handle = assert(skynet.call(".service", "lua", "GLAUNCH", "snaxd", name, ...))
return snax.bind(handle, name)
end
function snax.queryservice(name)
local handle = assert(skynet.call(".service", "lua", "QUERY", "snaxd", name))
return snax.bind(handle, name)
end
function snax.queryglobal(name)
local handle = assert(skynet.call(".service", "lua", "GQUERY", "snaxd", name))
return snax.bind(handle, name)
end
function snax.kill(obj, ...)
local t = snax.interface(obj.type)
skynet_call(obj.handle, "snax", t.system.exit, ...)
end
function snax.self()
return snax.bind(skynet.self(), SERVICE_NAME)
end
function snax.exit(...)
snax.kill(snax.self(), ...)
end
local function test_result(ok, ...)
if ok then
return ...
else
error(...)
end
end
function snax.hotfix(obj, source, ...)
local t = snax.interface(obj.type)
return test_result(skynet_call(obj.handle, "snax", t.system.hotfix, source, ...))
end
function snax.printf(fmt, ...)
skynet.error(string.format(fmt, ...))
end
return snax
| mit |
ivendrov/nn | Euclidean.lua | 24 | 5711 | local Euclidean, parent = torch.class('nn.Euclidean', 'nn.Module')
function Euclidean:__init(inputSize,outputSize)
parent.__init(self)
self.weight = torch.Tensor(inputSize,outputSize)
self.gradWeight = torch.Tensor(inputSize,outputSize)
-- state
self.gradInput:resize(inputSize)
self.output:resize(outputSize)
self.fastBackward = true
self:reset()
end
function Euclidean:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(1))
end
if nn.oldSeed then
for i=1,self.weight:size(2) do
self.weight:select(2, i):apply(function()
return torch.uniform(-stdv, stdv)
end)
end
else
self.weight:uniform(-stdv, stdv)
end
end
local function view(res, src, ...)
local args = {...}
if src:isContiguous() then
res:view(src, table.unpack(args))
else
res:reshape(src, table.unpack(args))
end
end
function Euclidean:updateOutput(input)
-- lazy initialize buffers
self._input = self._input or input.new()
self._weight = self._weight or self.weight.new()
self._expand = self._expand or self.output.new()
self._expand2 = self._expand2 or self.output.new()
self._repeat = self._repeat or self.output.new()
self._repeat2 = self._repeat2 or self.output.new()
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
-- y_j = || w_j - x || = || x - w_j ||
if input:dim() == 1 then
view(self._input, input, inputSize, 1)
self._expand:expandAs(self._input, self.weight)
self._repeat:resizeAs(self._expand):copy(self._expand)
self._repeat:add(-1, self.weight)
self.output:norm(self._repeat, 2, 1)
self.output:resize(outputSize)
elseif input:dim() == 2 then
local batchSize = input:size(1)
view(self._input, input, batchSize, inputSize, 1)
self._expand:expand(self._input, batchSize, inputSize, outputSize)
-- make the expanded tensor contiguous (requires lots of memory)
self._repeat:resizeAs(self._expand):copy(self._expand)
self._weight:view(self.weight, 1, inputSize, outputSize)
self._expand2:expandAs(self._weight, self._repeat)
if torch.type(input) == 'torch.CudaTensor' then
-- requires lots of memory, but minimizes cudaMallocs and loops
self._repeat2:resizeAs(self._expand2):copy(self._expand2)
self._repeat:add(-1, self._repeat2)
else
self._repeat:add(-1, self._expand2)
end
self.output:norm(self._repeat, 2, 2)
self.output:resize(batchSize, outputSize)
else
error"1D or 2D input expected"
end
return self.output
end
function Euclidean:updateGradInput(input, gradOutput)
if not self.gradInput then
return
end
self._div = self._div or input.new()
self._output = self._output or self.output.new()
self._gradOutput = self._gradOutput or input.new()
self._expand3 = self._expand3 or input.new()
if not self.fastBackward then
self:updateOutput(input)
end
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
--[[
dy_j -2 * (w_j - x) x - w_j
---- = --------------- = -------
dx 2 || w_j - x || y_j
--]]
-- to prevent div by zero (NaN) bugs
self._output:resizeAs(self.output):copy(self.output):add(0.0000001)
view(self._gradOutput, gradOutput, gradOutput:size())
self._div:cdiv(gradOutput, self._output)
if input:dim() == 1 then
self._div:resize(1, outputSize)
self._expand3:expandAs(self._div, self.weight)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat2:resizeAs(self._expand3):copy(self._expand3)
self._repeat2:cmul(self._repeat)
else
self._repeat2:cmul(self._repeat, self._expand3)
end
self.gradInput:sum(self._repeat2, 2)
self.gradInput:resizeAs(input)
elseif input:dim() == 2 then
local batchSize = input:size(1)
self._div:resize(batchSize, 1, outputSize)
self._expand3:expand(self._div, batchSize, inputSize, outputSize)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat2:resizeAs(self._expand3):copy(self._expand3)
self._repeat2:cmul(self._repeat)
else
self._repeat2:cmul(self._repeat, self._expand3)
end
self.gradInput:sum(self._repeat2, 3)
self.gradInput:resizeAs(input)
else
error"1D or 2D input expected"
end
return self.gradInput
end
function Euclidean:accGradParameters(input, gradOutput, scale)
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
scale = scale or 1
--[[
dy_j 2 * (w_j - x) w_j - x
---- = --------------- = -------
dw_j 2 || w_j - x || y_j
--]]
-- assumes a preceding call to updateGradInput
if input:dim() == 1 then
self.gradWeight:add(-scale, self._repeat2)
elseif input:dim() == 2 then
self._sum = self._sum or input.new()
self._sum:sum(self._repeat2, 1)
self._sum:resize(inputSize, outputSize)
self.gradWeight:add(-scale, self._sum)
else
error"1D or 2D input expected"
end
end
function Euclidean:type(type, tensorCache)
if type then
-- prevent premature memory allocations
self._input = nil
self._output = nil
self._gradOutput = nil
self._weight = nil
self._div = nil
self._sum = nil
self._expand = nil
self._expand2 = nil
self._expand3 = nil
self._repeat = nil
self._repeat2 = nil
end
return parent.type(self, type, tensorCache)
end
| bsd-3-clause |
Whit3Tig3R/bestspammbot2 | plugins/id.lua | 226 | 4260 | local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'IDs for chat '..chatname
..' ('..chat_id..')\n'
..'There are '..result.members_num..' members'
..'\n---------\n'
for k,v in pairs(result.members) do
text = text .. v.print_name .. " (user#id" .. v.id .. ")\n"
end
send_large_msg(receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "!id" then
local text = user_print_name(msg.from) .. ' (user#id' .. msg.from.id .. ')'
if is_chat_msg(msg) then
text = text .. "\nYou are in group " .. user_print_name(msg.to) .. " (chat#id" .. msg.to.id .. ")"
end
return text
elseif matches[1] == "chat" then
-- !ids? (chat) (%d+)
if matches[2] and is_sudo(msg) then
local chat = 'chat#id'..matches[2]
chat_info(chat, returnids, {receiver=receiver})
else
if not is_chat_msg(msg) then
return "You are not in a group."
end
local chat = get_receiver(msg)
chat_info(chat, returnids, {receiver=receiver})
end
elseif matches[1] == "member" and matches[2] == "@" then
local nick = matches[3]
local chat = get_receiver(msg)
if not is_chat_msg(msg) then
return "You are not in a group."
end
chat_info(chat, function (extra, success, result)
local receiver = extra.receiver
local nick = extra.nick
local found
for k,user in pairs(result.members) do
if user.username == nick then
found = user
end
end
if not found then
send_msg(receiver, "User not found on this chat.", ok_cb, false)
else
local text = "ID: "..found.id
send_msg(receiver, text, ok_cb, false)
end
end, {receiver=chat, nick=nick})
elseif matches[1] == "members" and matches[2] == "name" then
local text = matches[3]
local chat = get_receiver(msg)
if not is_chat_msg(msg) then
return "You are not in a group."
end
chat_info(chat, function (extra, success, result)
local members = result.members
local receiver = extra.receiver
local text = extra.text
local founds = {}
for k,member in pairs(members) do
local fields = {'first_name', 'print_name', 'username'}
for k,field in pairs(fields) do
if member[field] and type(member[field]) == "string" then
if member[field]:match(text) then
local id = tostring(member.id)
founds[id] = member
end
end
end
end
if next(founds) == nil then -- Empty table
send_msg(receiver, "User not found on this chat.", ok_cb, false)
else
local text = ""
for k,user in pairs(founds) do
local first_name = user.first_name or ""
local print_name = user.print_name or ""
local user_name = user.user_name or ""
local id = user.id or "" -- This would be funny
text = text.."First name: "..first_name.."\n"
.."Print name: "..print_name.."\n"
.."User name: "..user_name.."\n"
.."ID: "..id
end
send_msg(receiver, text, ok_cb, false)
end
end, {receiver=chat, text=text})
end
end
return {
description = "Know your id or the id of a chat members.",
usage = {
"!id: Return your ID and the chat id if you are in one.",
"!ids chat: Return the IDs of the current chat members.",
"!ids chat <chat_id>: Return the IDs of the <chat_id> members.",
"!id member @<user_name>: Return the member @<user_name> ID from the current chat",
"!id members name <text>: Search for users with <text> on first_name, print_name or username on current chat"
},
patterns = {
"^!id$",
"^!ids? (chat) (%d+)$",
"^!ids? (chat)$",
"^!id (member) (@)(.+)",
"^!id (members) (name) (.+)"
},
run = run
}
| gpl-2.0 |
amircheshme/megatron | plugins/id.lua | 226 | 4260 | local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'IDs for chat '..chatname
..' ('..chat_id..')\n'
..'There are '..result.members_num..' members'
..'\n---------\n'
for k,v in pairs(result.members) do
text = text .. v.print_name .. " (user#id" .. v.id .. ")\n"
end
send_large_msg(receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "!id" then
local text = user_print_name(msg.from) .. ' (user#id' .. msg.from.id .. ')'
if is_chat_msg(msg) then
text = text .. "\nYou are in group " .. user_print_name(msg.to) .. " (chat#id" .. msg.to.id .. ")"
end
return text
elseif matches[1] == "chat" then
-- !ids? (chat) (%d+)
if matches[2] and is_sudo(msg) then
local chat = 'chat#id'..matches[2]
chat_info(chat, returnids, {receiver=receiver})
else
if not is_chat_msg(msg) then
return "You are not in a group."
end
local chat = get_receiver(msg)
chat_info(chat, returnids, {receiver=receiver})
end
elseif matches[1] == "member" and matches[2] == "@" then
local nick = matches[3]
local chat = get_receiver(msg)
if not is_chat_msg(msg) then
return "You are not in a group."
end
chat_info(chat, function (extra, success, result)
local receiver = extra.receiver
local nick = extra.nick
local found
for k,user in pairs(result.members) do
if user.username == nick then
found = user
end
end
if not found then
send_msg(receiver, "User not found on this chat.", ok_cb, false)
else
local text = "ID: "..found.id
send_msg(receiver, text, ok_cb, false)
end
end, {receiver=chat, nick=nick})
elseif matches[1] == "members" and matches[2] == "name" then
local text = matches[3]
local chat = get_receiver(msg)
if not is_chat_msg(msg) then
return "You are not in a group."
end
chat_info(chat, function (extra, success, result)
local members = result.members
local receiver = extra.receiver
local text = extra.text
local founds = {}
for k,member in pairs(members) do
local fields = {'first_name', 'print_name', 'username'}
for k,field in pairs(fields) do
if member[field] and type(member[field]) == "string" then
if member[field]:match(text) then
local id = tostring(member.id)
founds[id] = member
end
end
end
end
if next(founds) == nil then -- Empty table
send_msg(receiver, "User not found on this chat.", ok_cb, false)
else
local text = ""
for k,user in pairs(founds) do
local first_name = user.first_name or ""
local print_name = user.print_name or ""
local user_name = user.user_name or ""
local id = user.id or "" -- This would be funny
text = text.."First name: "..first_name.."\n"
.."Print name: "..print_name.."\n"
.."User name: "..user_name.."\n"
.."ID: "..id
end
send_msg(receiver, text, ok_cb, false)
end
end, {receiver=chat, text=text})
end
end
return {
description = "Know your id or the id of a chat members.",
usage = {
"!id: Return your ID and the chat id if you are in one.",
"!ids chat: Return the IDs of the current chat members.",
"!ids chat <chat_id>: Return the IDs of the <chat_id> members.",
"!id member @<user_name>: Return the member @<user_name> ID from the current chat",
"!id members name <text>: Search for users with <text> on first_name, print_name or username on current chat"
},
patterns = {
"^!id$",
"^!ids? (chat) (%d+)$",
"^!ids? (chat)$",
"^!id (member) (@)(.+)",
"^!id (members) (name) (.+)"
},
run = run
}
| gpl-2.0 |
jerizm/kong | kong/templates/nginx_kong.lua | 1 | 3760 | return [[
resolver ${{DNS_RESOLVER}} ipv6=off;
charset UTF-8;
error_log logs/error.log ${{LOG_LEVEL}};
access_log logs/access.log;
> if anonymous_reports then
${{SYSLOG_REPORTS}}
> end
> if nginx_optimizations then
>-- send_timeout 60s; # default value
>-- keepalive_timeout 75s; # default value
>-- client_body_timeout 60s; # default value
>-- client_header_timeout 60s; # default value
>-- tcp_nopush on; # disabled until benchmarked
>-- proxy_buffer_size 128k; # disabled until benchmarked
>-- proxy_buffers 4 256k; # disabled until benchmarked
>-- proxy_busy_buffers_size 256k; # disabled until benchmarked
>-- reset_timedout_connection on; # disabled until benchmarked
> end
client_max_body_size 0;
proxy_ssl_server_name on;
underscores_in_headers on;
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
lua_package_path '${{LUA_PACKAGE_PATH}};;';
lua_package_cpath '${{LUA_PACKAGE_CPATH}};;';
lua_code_cache ${{LUA_CODE_CACHE}};
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict cache ${{MEM_CACHE_SIZE}};
lua_shared_dict reports_locks 100k;
lua_shared_dict cluster_locks 100k;
lua_shared_dict cluster_autojoin_locks 100k;
lua_shared_dict cache_locks 100k;
lua_shared_dict cassandra 1m;
lua_shared_dict cassandra_prepared 5m;
lua_socket_log_errors off;
> if lua_ssl_trusted_certificate then
lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}';
lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}};
> end
init_by_lua_block {
require 'resty.core'
kong = require 'kong'
kong.init()
}
init_worker_by_lua_block {
kong.init_worker()
}
server {
server_name kong;
listen ${{PROXY_LISTEN}};
error_page 404 408 411 412 413 414 417 /kong_error_handler;
error_page 500 502 503 504 /kong_error_handler;
> if ssl then
listen ${{PROXY_LISTEN_SSL}} ssl;
ssl_certificate ${{SSL_CERT}};
ssl_certificate_key ${{SSL_CERT_KEY}};
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_certificate_by_lua_block {
kong.ssl_certificate()
}
> end
location / {
set $upstream_host nil;
set $upstream_url nil;
access_by_lua_block {
kong.access()
}
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $upstream_host;
proxy_pass_header Server;
proxy_pass $upstream_url;
header_filter_by_lua_block {
kong.header_filter()
}
body_filter_by_lua_block {
kong.body_filter()
}
log_by_lua_block {
kong.log()
}
}
location = /kong_error_handler {
internal;
content_by_lua_block {
require('kong.core.error_handlers')(ngx)
}
}
}
server {
server_name kong_admin;
listen ${{ADMIN_LISTEN}};
client_max_body_size 10m;
client_body_buffer_size 10m;
location / {
default_type application/json;
content_by_lua_block {
ngx.header['Access-Control-Allow-Origin'] = '*'
if ngx.req.get_method() == 'OPTIONS' then
ngx.header['Access-Control-Allow-Methods'] = 'GET,HEAD,PUT,PATCH,POST,DELETE'
ngx.header['Access-Control-Allow-Headers'] = 'Content-Type'
ngx.exit(204)
end
ngx.log(ngx.DEBUG, 'Loading Admin API endpoints')
require('lapis').serve('kong.api')
}
}
location /nginx_status {
internal;
access_log off;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
}
]] | apache-2.0 |
mnemnion/grym | lib/pl/seq.lua | 1 | 14544 | --- Manipulating iterators as sequences.
-- See @{07-functional.md.Sequences|The Guide}
--
-- Dependencies: `pl.utils`, `pl.types`, `debug`
-- @module pl.seq
local next,assert,pairs,tonumber,type,setmetatable = next,assert,pairs,tonumber,type,setmetatable
local strfind,format = string.find,string.format
local mrandom = math.random
local tsort,tappend = table.sort,table.insert
local io = io
local utils = require 'pl.utils'
local callable = require 'pl.types'.is_callable
local function_arg = utils.function_arg
local assert_arg = utils.assert_arg
local debug = require 'debug'
local seq = {}
-- given a number, return a function(y) which returns true if y > x
-- @param x a number
function seq.greater_than(x)
return function(v)
return tonumber(v) > x
end
end
-- given a number, returns a function(y) which returns true if y < x
-- @param x a number
function seq.less_than(x)
return function(v)
return tonumber(v) < x
end
end
-- given any value, return a function(y) which returns true if y == x
-- @param x a value
function seq.equal_to(x)
if type(x) == "number" then
return function(v)
return tonumber(v) == x
end
else
return function(v)
return v == x
end
end
end
--- given a string, return a function(y) which matches y against the string.
-- @param s a string
function seq.matching(s)
return function(v)
return strfind(v,s)
end
end
local nexti
--- sequence adaptor for a table. Note that if any generic function is
-- passed a table, it will automatically use seq.list()
-- @param t a list-like table
-- @usage sum(list(t)) is the sum of all elements of t
-- @usage for x in list(t) do...end
function seq.list(t)
assert_arg(1,t,'table')
if not nexti then
nexti = ipairs{}
end
local key,value = 0
return function()
key,value = nexti(t,key)
return value
end
end
--- return the keys of the table.
-- @param t an arbitrary table
-- @return iterator over keys
function seq.keys(t)
assert_arg(1,t,'table')
local key,value
return function()
key,value = next(t,key)
return key
end
end
local list = seq.list
local function default_iter(iter)
if type(iter) == 'table' then return list(iter)
else return iter end
end
seq.iter = default_iter
--- create an iterator over a numerical range. Like the standard Python function xrange.
-- @param start a number
-- @param finish a number greater than start
function seq.range(start,finish)
local i = start - 1
return function()
i = i + 1
if i > finish then return nil
else return i end
end
end
-- count the number of elements in the sequence which satisfy the predicate
-- @param iter a sequence
-- @param condn a predicate function (must return either true or false)
-- @param optional argument to be passed to predicate as second argument.
-- @return count
function seq.count(iter,condn,arg)
local i = 0
seq.foreach(iter,function(val)
if condn(val,arg) then i = i + 1 end
end)
return i
end
--- return the minimum and the maximum value of the sequence.
-- @param iter a sequence
-- @return minimum value
-- @return maximum value
function seq.minmax(iter)
local vmin,vmax = 1e70,-1e70
for v in default_iter(iter) do
v = tonumber(v)
if v < vmin then vmin = v end
if v > vmax then vmax = v end
end
return vmin,vmax
end
--- return the sum and element count of the sequence.
-- @param iter a sequence
-- @param fn an optional function to apply to the values
function seq.sum(iter,fn)
local s = 0
local i = 0
for v in default_iter(iter) do
if fn then v = fn(v) end
s = s + v
i = i + 1
end
return s,i
end
--- create a table from the sequence. (This will make the result a List.)
-- @param iter a sequence
-- @return a List
-- @usage copy(list(ls)) is equal to ls
-- @usage copy(list {1,2,3}) == List{1,2,3}
function seq.copy(iter)
local res,k = {},1
for v in default_iter(iter) do
res[k] = v
k = k + 1
end
setmetatable(res, require('pl.List'))
return res
end
--- create a table of pairs from the double-valued sequence.
-- @param iter a double-valued sequence
-- @param i1 used to capture extra iterator values
-- @param i2 as with pairs & ipairs
-- @usage copy2(ipairs{10,20,30}) == {{1,10},{2,20},{3,30}}
-- @return a list-like table
function seq.copy2 (iter,i1,i2)
local res,k = {},1
for v1,v2 in iter,i1,i2 do
res[k] = {v1,v2}
k = k + 1
end
return res
end
--- create a table of 'tuples' from a multi-valued sequence.
-- A generalization of copy2 above
-- @param iter a multiple-valued sequence
-- @return a list-like table
function seq.copy_tuples (iter)
iter = default_iter(iter)
local res = {}
local row = {iter()}
while #row > 0 do
tappend(res,row)
row = {iter()}
end
return res
end
--- return an iterator of random numbers.
-- @param n the length of the sequence
-- @param l same as the first optional argument to math.random
-- @param u same as the second optional argument to math.random
-- @return a sequence
function seq.random(n,l,u)
local rand
assert(type(n) == 'number')
if u then
rand = function() return mrandom(l,u) end
elseif l then
rand = function() return mrandom(l) end
else
rand = mrandom
end
return function()
if n == 0 then return nil
else
n = n - 1
return rand()
end
end
end
--- return an iterator to the sorted elements of a sequence.
-- @param iter a sequence
-- @param comp an optional comparison function (comp(x,y) is true if x < y)
function seq.sort(iter,comp)
local t = seq.copy(iter)
tsort(t,comp)
return list(t)
end
--- return an iterator which returns elements of two sequences.
-- @param iter1 a sequence
-- @param iter2 a sequence
-- @usage for x,y in seq.zip(ls1,ls2) do....end
function seq.zip(iter1,iter2)
iter1 = default_iter(iter1)
iter2 = default_iter(iter2)
return function()
return iter1(),iter2()
end
end
--- Makes a table where the key/values are the values and value counts of the sequence.
-- This version works with 'hashable' values like strings and numbers.
-- `pl.tablex.count_map` is more general.
-- @param iter a sequence
-- @return a map-like table
-- @return a table
-- @see pl.tablex.count_map
function seq.count_map(iter)
local t = {}
local v
for s in default_iter(iter) do
v = t[s]
if v then t[s] = v + 1
else t[s] = 1 end
end
return setmetatable(t, require('pl.Map'))
end
-- given a sequence, return all the unique values in that sequence.
-- @param iter a sequence
-- @param returns_table true if we return a table, not a sequence
-- @return a sequence or a table; defaults to a sequence.
function seq.unique(iter,returns_table)
local t = seq.count_map(iter)
local res,k = {},1
for key in pairs(t) do res[k] = key; k = k + 1 end
table.sort(res)
if returns_table then
return res
else
return list(res)
end
end
--- print out a sequence iter with a separator.
-- @param iter a sequence
-- @param sep the separator (default space)
-- @param nfields maximum number of values per line (default 7)
-- @param fmt optional format function for each value
function seq.printall(iter,sep,nfields,fmt)
local write = io.write
if not sep then sep = ' ' end
if not nfields then
if sep == '\n' then nfields = 1e30
else nfields = 7 end
end
if fmt then
local fstr = fmt
fmt = function(v) return format(fstr,v) end
end
local k = 1
for v in default_iter(iter) do
if fmt then v = fmt(v) end
if k < nfields then
write(v,sep)
k = k + 1
else
write(v,'\n')
k = 1
end
end
write '\n'
end
-- return an iterator running over every element of two sequences (concatenation).
-- @param iter1 a sequence
-- @param iter2 a sequence
function seq.splice(iter1,iter2)
iter1 = default_iter(iter1)
iter2 = default_iter(iter2)
local iter = iter1
return function()
local ret = iter()
if ret == nil then
if iter == iter1 then
iter = iter2
return iter()
else return nil end
else
return ret
end
end
end
--- return a sequence where every element of a sequence has been transformed
-- by a function. If you don't supply an argument, then the function will
-- receive both values of a double-valued sequence, otherwise behaves rather like
-- tablex.map.
-- @param fn a function to apply to elements; may take two arguments
-- @param iter a sequence of one or two values
-- @param arg optional argument to pass to function.
function seq.map(fn,iter,arg)
fn = function_arg(1,fn)
iter = default_iter(iter)
return function()
local v1,v2 = iter()
if v1 == nil then return nil end
return fn(v1,arg or v2) or false
end
end
--- filter a sequence using a predicate function.
-- @param iter a sequence of one or two values
-- @param pred a boolean function; may take two arguments
-- @param arg optional argument to pass to function.
function seq.filter (iter,pred,arg)
pred = function_arg(2,pred)
return function ()
local v1,v2
while true do
v1,v2 = iter()
if v1 == nil then return nil end
if pred(v1,arg or v2) then return v1,v2 end
end
end
end
--- 'reduce' a sequence using a binary function.
-- @func fn a function of two arguments
-- @param iter a sequence
-- @param initval optional initial value
-- @usage seq.reduce(operator.add,seq.list{1,2,3,4}) == 10
-- @usage seq.reduce('-',{1,2,3,4,5}) == -13
function seq.reduce (fn,iter,initval)
fn = function_arg(1,fn)
iter = default_iter(iter)
local val = initval or iter()
if val == nil then return nil end
for v in iter do
val = fn(val,v)
end
return val
end
--- take the first n values from the sequence.
-- @param iter a sequence of one or two values
-- @param n number of items to take
-- @return a sequence of at most n items
function seq.take (iter,n)
iter = default_iter(iter)
return function()
if n < 1 then return end
local val1,val2 = iter()
if not val1 then return end
n = n - 1
return val1,val2
end
end
--- skip the first n values of a sequence
-- @param iter a sequence of one or more values
-- @param n number of items to skip
function seq.skip (iter,n)
n = n or 1
for i = 1,n do
if iter() == nil then return list{} end
end
return iter
end
--- a sequence with a sequence count and the original value.
-- enum(copy(ls)) is a roundabout way of saying ipairs(ls).
-- @param iter a single or double valued sequence
-- @return sequence of (i,v), i = 1..n and v is from iter.
function seq.enum (iter)
local i = 0
iter = default_iter(iter)
return function ()
local val1,val2 = iter()
if not val1 then return end
i = i + 1
return i,val1,val2
end
end
--- map using a named method over a sequence.
-- @param iter a sequence
-- @param name the method name
-- @param arg1 optional first extra argument
-- @param arg2 optional second extra argument
function seq.mapmethod (iter,name,arg1,arg2)
iter = default_iter(iter)
return function()
local val = iter()
if not val then return end
local fn = val[name]
if not fn then error(type(val).." does not have method "..name) end
return fn(val,arg1,arg2)
end
end
--- a sequence of (last,current) values from another sequence.
-- This will return S(i-1),S(i) if given S(i)
-- @param iter a sequence
function seq.last (iter)
iter = default_iter(iter)
local val, l = iter(), nil
if val == nil then return list{} end
return function ()
val,l = iter(),val
if val == nil then return nil end
return val,l
end
end
--- call the function on each element of the sequence.
-- @param iter a sequence with up to 3 values
-- @param fn a function
function seq.foreach(iter,fn)
fn = function_arg(2,fn)
for i1,i2,i3 in default_iter(iter) do fn(i1,i2,i3) end
end
---------------------- Sequence Adapters ---------------------
local SMT
local function SW (iter,...)
if callable(iter) then
return setmetatable({iter=iter},SMT)
else
return iter,...
end
end
-- can't directly look these up in seq because of the wrong argument order...
local map,reduce,mapmethod = seq.map, seq.reduce, seq.mapmethod
local overrides = {
map = function(self,fun,arg)
return map(fun,self,arg)
end,
reduce = function(self,fun,initval)
return reduce(fun,self,initval)
end
}
SMT = {
__index = function (tbl,key)
local fn = overrides[key] or seq[key]
if fn then
return function(sw,...) return SW(fn(sw.iter,...)) end
else
return function(sw,...) return SW(mapmethod(sw.iter,key,...)) end
end
end,
__call = function (sw)
return sw.iter()
end,
}
setmetatable(seq,{
__call = function(tbl,iter,extra)
if not callable(iter) then
if type(iter) == 'table' then iter = seq.list(iter)
else return iter
end
end
if extra then
return setmetatable({iter=function()
return iter(extra)
end},SMT)
else
return setmetatable({iter=iter},SMT)
end
end
})
--- create a wrapped iterator over all lines in the file.
-- @param f either a filename, file-like object, or 'STDIN' (for standard input)
-- @param ... for Lua 5.2 only, optional format specifiers, as in `io.read`.
-- @return a sequence wrapper
function seq.lines (f,...)
local n = select('#',...)
local iter,obj
if f == 'STDIN' then
f = io.stdin
elseif type(f) == 'string' then
iter,obj = io.lines(f,...)
elseif not f.read then
error("Pass either a string or a file-like object",2)
end
if not iter then
iter,obj = f:lines(...)
end
if obj then -- LuaJIT version returns a function operating on a file
local lines,file = iter,obj
iter = function() return lines(file) end
end
return SW(iter)
end
function seq.import ()
debug.setmetatable(function() end,{
__index = function(tbl,key)
local s = overrides[key] or seq[key]
if s then return s
else
return function(s,...) return seq.mapmethod(s,key,...) end
end
end
})
end
return seq
| mit |
gberger/PES-3 | src/models/conference.lua | 1 | 2011 | --[[
Módulo responsável representar o conferência (model) do padrão de design MVC
]]
local utils = require "utils"
local path = require "pl.path"
local ATTRIBUTES = {"id", "abbreviation", "name", "location", "month", "year", "editors", "creation_date"}
--[[
Responsabilidade: Retorna dados da conferência baseado numa lista de atributos
Pré-Condição: * Deve receber os dados de conferência
Pós-Condição: * Retorna dados de conferência baseado numa lista de atributos
]]
local function to_data(values)
local data = {}
for _,attribute in ipairs(ATTRIBUTES) do
data[attribute] = values[attribute]
end
return data
end
local M = {
new = function(self, values)
local conference = to_data(values)
conference.creation_date = conference.creation_date or os.date()
setmetatable(conference, {__index = self.metatable})
return conference
end,
--[[
Responsabilidade: Retorna conferências a partir de uma lista de dados de conferência
Pré-Condição: * Deve receber objetos contendo dados de conferência
Pós-Condição: * Retorna todas as conferências criadas a partir dos dados
]]
build_all = function(self, conferences_data)
local conferences = {}
for i,values in ipairs(conferences_data) do
conferences[#conferences+1] = self:new(values)
end
return conferences
end,
--[[
Responsabilidade: Retorna lista de dados de conferências a partir de uma lista de conferências
Pré-Condição: * Deve receber uma lista de conferências
Pós-Condição: * Retorna todos os dados de conferências convertidos a partir das conferências
]]
data_of_all = function(self, conferences)
return utils.map(conferences, function(conference) return conference:data() end)
end,
}
M.metatable = {
--[[
Responsabilidade: Retorna somente os dados de conferência
Pré-Condição: * -
Pós-Condição: * Retorna somente os dados de conferência
]]
data = function(self)
return to_data(self)
end
}
return M
| mit |
Whit3Tig3R/bestspammbot2 | plugins/minecraft.lua | 624 | 2605 | local usage = {
"!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565",
"!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.",
}
local ltn12 = require "ltn12"
local function mineSearch(ip, port, receiver) --25565
local responseText = ""
local api = "https://api.syfaro.net/server/status"
local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true"
local http = require("socket.http")
local respbody = {}
local body, code, headers, status = http.request{
url = api..parameters,
method = "GET",
redirect = true,
sink = ltn12.sink.table(respbody)
}
local body = table.concat(respbody)
if (status == nil) then return "ERROR: status = nil" end
if code ~=200 then return "ERROR: "..code..". Status: "..status end
local jsonData = json:decode(body)
responseText = responseText..ip..":"..port.." ->\n"
if (jsonData.motd ~= nil) then
local tempMotd = ""
tempMotd = jsonData.motd:gsub('%§.', '')
if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end
end
if (jsonData.online ~= nil) then
responseText = responseText.." Online: "..tostring(jsonData.online).."\n"
end
if (jsonData.players ~= nil) then
if (jsonData.players.max ~= nil) then
responseText = responseText.." Max Players: "..jsonData.players.max.."\n"
end
if (jsonData.players.now ~= nil) then
responseText = responseText.." Players online: "..jsonData.players.now.."\n"
end
if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then
responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n"
end
end
if (jsonData.favicon ~= nil and false) then
--send_photo(receiver, jsonData.favicon) --(decode base64 and send)
end
return responseText
end
local function parseText(chat, text)
if (text == nil or text == "!mine") then
return usage
end
ip, port = string.match(text, "^!mine (.-) (.*)$")
if (ip ~= nil and port ~= nil) then
return mineSearch(ip, port, chat)
end
local ip = string.match(text, "^!mine (.*)$")
if (ip ~= nil) then
return mineSearch(ip, "25565", chat)
end
return "ERROR: no input ip?"
end
local function run(msg, matches)
local chat_id = tostring(msg.to.id)
local result = parseText(chat_id, msg.text)
return result
end
return {
description = "Searches Minecraft server and sends info",
usage = usage,
patterns = {
"^!mine (.*)$"
},
run = run
} | gpl-2.0 |
flavorzyb/cocos2d-x | samples/Lua/TestLua/Resources/luaScript/RenderTextureTest/RenderTextureTest.lua | 7 | 18244 | -- Test #1 by Jason Booth (slipster216)
-- Test #3 by David Deaco (ddeaco)
--/**
-- * Impelmentation of RenderTextureSave
--*/
local function RenderTextureSave()
local ret = createTestLayer("Touch the screen",
"Press 'Save Image' to create an snapshot of the render texture")
local s = CCDirector:sharedDirector():getWinSize()
local m_pTarget = nil
local m_pBrush = nil
local m_pTarget = nil
local counter = 0
local function clearImage(tag, pSender)
m_pTarget:clear(math.random(), math.random(), math.random(), math.random())
end
local function saveImage(tag, pSender)
local png = string.format("image-%d.png", counter)
local jpg = string.format("image-%d.jpg", counter)
m_pTarget:saveToFile(png, kCCImageFormatPNG)
m_pTarget:saveToFile(jpg, kCCImageFormatJPEG)
local pImage = m_pTarget:newCCImage()
local tex = CCTextureCache:sharedTextureCache():addUIImage(pImage, png)
pImage:release()
local sprite = CCSprite:createWithTexture(tex)
sprite:setScale(0.3)
ret:addChild(sprite)
sprite:setPosition(ccp(40, 40))
sprite:setRotation(counter * 3)
cclog("Image saved %s and %s", png, jpg)
counter = counter + 1
end
local function onNodeEvent(event)
if event == "exit" then
m_pBrush:release()
m_pTarget:release()
CCTextureCache:sharedTextureCache():removeUnusedTextures()
end
end
ret:registerScriptHandler(onNodeEvent)
-- create a render texture, this is what we are going to draw into
m_pTarget = CCRenderTexture:create(s.width, s.height, kCCTexture2DPixelFormat_RGBA8888)
m_pTarget:retain()
m_pTarget:setPosition(ccp(s.width / 2, s.height / 2))
-- note that the render texture is a CCNode, and contains a sprite of its texture for convience,
-- so we can just parent it to the scene like any other CCNode
ret:addChild(m_pTarget, -1)
-- create a brush image to draw into the texture with
m_pBrush = CCSprite:create("Images/fire.png")
m_pBrush:retain()
m_pBrush:setColor(ccc3(255, 0, 0))
m_pBrush:setOpacity(20)
local prev = {x = 0, y = 0}
local function onTouchEvent(eventType, x, y)
if eventType == "began" then
prev.x = x
prev.y = y
return true
elseif eventType == "moved" then
local diffX = x - prev.x
local diffY = y - prev.y
local startP = ccp(x, y)
local endP = ccp(prev.x, prev.y)
-- begin drawing to the render texture
m_pTarget:begin()
-- for extra points, we'll draw this smoothly from the last position and vary the sprite's
-- scale/rotation/offset
local distance = ccpDistance(startP, endP)
if distance > 1 then
local d = distance
local i = 0
for i = 0, d-1 do
local difx = endP.x - startP.x
local dify = endP.y - startP.y
local delta = i / distance
m_pBrush:setPosition(ccp(startP.x + (difx * delta), startP.y + (dify * delta)))
m_pBrush:setRotation(math.random(0, 359))
local r = math.random(0, 49) / 50.0 + 0.25
m_pBrush:setScale(r)
-- Use CCRANDOM_0_1() will cause error when loading libtests.so on android, I don't know why.
m_pBrush:setColor(ccc3(math.random(0, 126) + 128, 255, 255))
-- Call visit to draw the brush, don't call draw..
m_pBrush:visit()
end
end
-- finish drawing and return context back to the screen
m_pTarget:endToLua()
end
prev.x = x
prev.y = y
end
ret:setTouchEnabled(true)
ret:registerScriptTouchHandler(onTouchEvent)
-- Save Image menu
CCMenuItemFont:setFontSize(16)
local item1 = CCMenuItemFont:create("Save Image")
item1:registerScriptTapHandler(saveImage)
local item2 = CCMenuItemFont:create("Clear")
item2:registerScriptTapHandler(clearImage)
local arr = CCArray:create()
arr:addObject(item1)
arr:addObject(item2)
local menu = CCMenu:createWithArray(arr)
ret:addChild(menu)
menu:alignItemsVertically()
menu:setPosition(ccp(VisibleRect:rightTop().x - 80, VisibleRect:rightTop().y - 30))
return ret
end
--/**
-- * Impelmentation of RenderTextureIssue937
--*/
-- local function RenderTextureIssue937()
-- /*
-- * 1 2
-- * A: A1 A2
-- *
-- * B: B1 B2
-- *
-- * A1: premulti sprite
-- * A2: premulti render
-- *
-- * B1: non-premulti sprite
-- * B2: non-premulti render
-- */
-- local background = CCLayerColor:create(ccc4(200,200,200,255))
-- addChild(background)
-- local spr_premulti = CCSprite:create("Images/fire.png")
-- spr_premulti:setPosition(ccp(16,48))
-- local spr_nonpremulti = CCSprite:create("Images/fire.png")
-- spr_nonpremulti:setPosition(ccp(16,16))
-- /* A2 & B2 setup */
-- local rend = CCRenderTexture:create(32, 64, kCCTexture2DPixelFormat_RGBA8888)
-- if (NULL == rend)
-- return
-- end
-- -- It's possible to modify the RenderTexture blending function by
-- -- [[rend sprite] setBlendFunc:(ccBlendFunc) GL_ONE, GL_ONE_MINUS_SRC_ALPHAend]
-- rend:begin()
-- spr_premulti:visit()
-- spr_nonpremulti:visit()
-- rend:end()
-- local s = CCDirector:sharedDirector():getWinSize()
-- --/* A1: setup */
-- spr_premulti:setPosition(ccp(s.width/2-16, s.height/2+16))
-- --/* B1: setup */
-- spr_nonpremulti:setPosition(ccp(s.width/2-16, s.height/2-16))
-- rend:setPosition(ccp(s.width/2+16, s.height/2))
-- addChild(spr_nonpremulti)
-- addChild(spr_premulti)
-- addChild(rend)
-- end
-- local function title()
-- return "Testing issue #937"
-- end
-- local function subtitle()
-- return "All images should be equal..."
-- end
-- local function runThisTest()
-- local pLayer = nextTestCase()
-- addChild(pLayer)
-- CCDirector:sharedDirector():replaceScene(this)
-- end
-- --/**
-- -- * Impelmentation of RenderTextureZbuffer
-- --*/
-- local function RenderTextureZbuffer()
-- this:setTouchEnabled(true)
-- local size = CCDirector:sharedDirector():getWinSize()
-- local label = CCLabelTTF:create("vertexZ = 50", "Marker Felt", 64)
-- label:setPosition(ccp(size.width / 2, size.height * 0.25))
-- this:addChild(label)
-- local label2 = CCLabelTTF:create("vertexZ = 0", "Marker Felt", 64)
-- label2:setPosition(ccp(size.width / 2, size.height * 0.5))
-- this:addChild(label2)
-- local label3 = CCLabelTTF:create("vertexZ = -50", "Marker Felt", 64)
-- label3:setPosition(ccp(size.width / 2, size.height * 0.75))
-- this:addChild(label3)
-- label:setVertexZ(50)
-- label2:setVertexZ(0)
-- label3:setVertexZ(-50)
-- CCSpriteFrameCache:sharedSpriteFrameCache():addSpriteFramesWithFile("Images/bugs/circle.plist")
-- mgr = CCSpriteBatchNode:create("Images/bugs/circle.png", 9)
-- this:addChild(mgr)
-- sp1 = CCSprite:createWithSpriteFrameName("circle.png")
-- sp2 = CCSprite:createWithSpriteFrameName("circle.png")
-- sp3 = CCSprite:createWithSpriteFrameName("circle.png")
-- sp4 = CCSprite:createWithSpriteFrameName("circle.png")
-- sp5 = CCSprite:createWithSpriteFrameName("circle.png")
-- sp6 = CCSprite:createWithSpriteFrameName("circle.png")
-- sp7 = CCSprite:createWithSpriteFrameName("circle.png")
-- sp8 = CCSprite:createWithSpriteFrameName("circle.png")
-- sp9 = CCSprite:createWithSpriteFrameName("circle.png")
-- mgr:addChild(sp1, 9)
-- mgr:addChild(sp2, 8)
-- mgr:addChild(sp3, 7)
-- mgr:addChild(sp4, 6)
-- mgr:addChild(sp5, 5)
-- mgr:addChild(sp6, 4)
-- mgr:addChild(sp7, 3)
-- mgr:addChild(sp8, 2)
-- mgr:addChild(sp9, 1)
-- sp1:setVertexZ(400)
-- sp2:setVertexZ(300)
-- sp3:setVertexZ(200)
-- sp4:setVertexZ(100)
-- sp5:setVertexZ(0)
-- sp6:setVertexZ(-100)
-- sp7:setVertexZ(-200)
-- sp8:setVertexZ(-300)
-- sp9:setVertexZ(-400)
-- sp9:setScale(2)
-- sp9:setColor(ccYELLOW)
-- end
-- local function title()
-- return "Testing Z Buffer in Render Texture"
-- end
-- local function subtitle()
-- return "Touch screen. It should be green"
-- end
-- local function ccTouchesBegan(cocos2d:CCSet *touches, cocos2d:CCEvent *event)
-- CCSetIterator iter
-- CCTouch *touch
-- for (iter = touches:begin() iter != touches:end() ++iter)
-- touch = (CCTouch *)(*iter)
-- local location = touch:getLocation()
-- sp1:setPosition(location)
-- sp2:setPosition(location)
-- sp3:setPosition(location)
-- sp4:setPosition(location)
-- sp5:setPosition(location)
-- sp6:setPosition(location)
-- sp7:setPosition(location)
-- sp8:setPosition(location)
-- sp9:setPosition(location)
-- end
-- end
-- local function ccTouchesMoved(CCSet* touches, CCEvent* event)
-- CCSetIterator iter
-- CCTouch *touch
-- for (iter = touches:begin() iter != touches:end() ++iter)
-- touch = (CCTouch *)(*iter)
-- local location = touch:getLocation()
-- sp1:setPosition(location)
-- sp2:setPosition(location)
-- sp3:setPosition(location)
-- sp4:setPosition(location)
-- sp5:setPosition(location)
-- sp6:setPosition(location)
-- sp7:setPosition(location)
-- sp8:setPosition(location)
-- sp9:setPosition(location)
-- end
-- end
-- local function ccTouchesEnded(CCSet* touches, CCEvent* event)
-- this:renderScreenShot()
-- end
-- local function renderScreenShot()
-- local texture = CCRenderTexture:create(512, 512)
-- if (NULL == texture)
-- return
-- end
-- texture:setAnchorPoint(ccp(0, 0))
-- texture:begin()
-- this:visit()
-- texture:end()
-- local sprite = CCSprite:createWithTexture(texture:getSprite():getTexture())
-- sprite:setPosition(ccp(256, 256))
-- sprite:setOpacity(182)
-- sprite:setFlipY(1)
-- this:addChild(sprite, 999999)
-- sprite:setColor(ccGREEN)
-- sprite:runAction(CCSequence:create(CCFadeTo:create(2, 0),
-- CCHide:create(),
-- NULL))
-- end
-- -- RenderTextureTestDepthStencil
-- local function RenderTextureTestDepthStencil()
-- local s = CCDirector:sharedDirector():getWinSize()
-- local sprite = CCSprite:create("Images/fire.png")
-- sprite:setPosition(ccp(s.width * 0.25, 0))
-- sprite:setScale(10)
-- local rend = CCRenderTexture:create(s.width, s.height, kCCTexture2DPixelFormat_RGBA4444, GL_DEPTH24_STENCIL8)
-- glStencilMask(0xFF)
-- rend:beginWithClear(0, 0, 0, 0, 0, 0)
-- --! mark sprite quad into stencil buffer
-- glEnable(GL_STENCIL_TEST)
-- glStencilFunc(GL_ALWAYS, 1, 0xFF)
-- glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
-- glColorMask(0, 0, 0, 1)
-- sprite:visit()
-- --! move sprite half width and height, and draw only where not marked
-- sprite:setPosition(ccpAdd(sprite:getPosition(), ccpMult(ccp(sprite:getContentSize().width * sprite:getScale(), sprite:getContentSize().height * sprite:getScale()), 0.5)))
-- glStencilFunc(GL_NOTEQUAL, 1, 0xFF)
-- glColorMask(1, 1, 1, 1)
-- sprite:visit()
-- rend:end()
-- glDisable(GL_STENCIL_TEST)
-- rend:setPosition(ccp(s.width * 0.5, s.height * 0.5))
-- this:addChild(rend)
-- end
-- local function title()
-- return "Testing depthStencil attachment"
-- end
-- local function subtitle()
-- return "Circle should be missing 1/4 of its region"
-- end
-- -- RenderTextureTest
-- local function RenderTextureTargetNode()
-- /*
-- * 1 2
-- * A: A1 A2
-- *
-- * B: B1 B2
-- *
-- * A1: premulti sprite
-- * A2: premulti render
-- *
-- * B1: non-premulti sprite
-- * B2: non-premulti render
-- */
-- local background = CCLayerColor:create(ccc4(40,40,40,255))
-- addChild(background)
-- -- sprite 1
-- sprite1 = CCSprite:create("Images/fire.png")
-- -- sprite 2
-- sprite2 = CCSprite:create("Images/fire_rgba8888.pvr")
-- local s = CCDirector:sharedDirector():getWinSize()
-- /* Create the render texture */
-- local renderTexture = CCRenderTexture:create(s.width, s.height, kCCTexture2DPixelFormat_RGBA4444)
-- this:renderTexture = renderTexture
-- renderTexture:setPosition(ccp(s.width/2, s.height/2))
-- -- [renderTexture setPosition:ccp(s.width, s.height)]
-- -- renderTexture.scale = 2
-- /* add the sprites to the render texture */
-- renderTexture:addChild(sprite1)
-- renderTexture:addChild(sprite2)
-- renderTexture:setClearColor(ccc4f(0, 0, 0, 0))
-- renderTexture:setClearFlags(GL_COLOR_BUFFER_BIT)
-- /* add the render texture to the scene */
-- addChild(renderTexture)
-- renderTexture:setAutoDraw(true)
-- scheduleUpdate()
-- -- Toggle clear on / off
-- local item = CCMenuItemFont:create("Clear On/Off", this, menu_selector(RenderTextureTargetNode:touched))
-- local menu = CCMenu:create(item, NULL)
-- addChild(menu)
-- menu:setPosition(ccp(s.width/2, s.height/2))
-- end
-- local function touched(CCObject* sender)
-- if (renderTexture:getClearFlags() == 0)
-- renderTexture:setClearFlags(GL_COLOR_BUFFER_BIT)
-- end
-- else
-- renderTexture:setClearFlags(0)
-- renderTexture:setClearColor(ccc4f( CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 1))
-- end
-- end
-- local function update(float dt)
-- static float time = 0
-- float r = 80
-- sprite1:setPosition(ccp(cosf(time * 2) * r, sinf(time * 2) * r))
-- sprite2:setPosition(ccp(sinf(time * 2) * r, cosf(time * 2) * r))
-- time += dt
-- end
-- local function title()
-- return "Testing Render Target Node"
-- end
-- local function subtitle()
-- return "Sprites should be equal and move with each frame"
-- end
-- -- SpriteRenderTextureBug
-- local function SimpleSprite() : rt(NULL) {}
-- local function SimpleSprite* SpriteRenderTextureBug:SimpleSprite:create(const char* filename, const CCRect &rect)
-- SimpleSprite *sprite = new SimpleSprite()
-- if (sprite && sprite:initWithFile(filename, rect))
-- sprite:autorelease()
-- end
-- else
-- CC_SAFE_DELETE(sprite)
-- end
-- return sprite
-- end
-- local function SimpleSprite:draw()
-- if (rt == NULL)
-- local s = CCDirector:sharedDirector():getWinSize()
-- rt = new CCRenderTexture()
-- rt:initWithWidthAndHeight(s.width, s.height, kCCTexture2DPixelFormat_RGBA8888)
-- end
-- rt:beginWithClear(0.0, 0.0, 0.0, 1.0)
-- rt:end()
-- CC_NODE_DRAW_SETUP()
-- ccBlendFunc blend = getBlendFunc()
-- ccGLBlendFunc(blend.src, blend.dst)
-- ccGLBindTexture2D(getTexture():getName())
-- --
-- -- Attributes
-- --
-- ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex)
-- #define kQuadSize sizeof(m_sQuad.bl)
-- long offset = (long)&m_sQuad
-- -- vertex
-- int diff = offsetof( ccV3F_C4B_T2F, vertices)
-- glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff))
-- -- texCoods
-- diff = offsetof( ccV3F_C4B_T2F, texCoords)
-- glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff))
-- -- color
-- diff = offsetof( ccV3F_C4B_T2F, colors)
-- glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff))
-- glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)
-- end
-- local function SpriteRenderTextureBug()
-- setTouchEnabled(true)
-- local s = CCDirector:sharedDirector():getWinSize()
-- addNewSpriteWithCoords(ccp(s.width/2, s.height/2))
-- end
-- local function SimpleSprite* SpriteRenderTextureBug:addNewSpriteWithCoords(const CCPoint& p)
-- int idx = CCRANDOM_0_1() * 1400 / 100
-- int x = (idx%5) * 85
-- int y = (idx/5) * 121
-- SpriteRenderTextureBug:SimpleSprite *sprite = SpriteRenderTextureBug:SimpleSprite:create("Images/grossini_dance_atlas.png",
-- CCRectMake(x,y,85,121))
-- addChild(sprite)
-- sprite:setPosition(p)
-- local action = NULL
-- float rd = CCRANDOM_0_1()
-- if (rd < 0.20)
-- action = CCScaleBy:create(3, 2)
-- else if (rd < 0.40)
-- action = CCRotateBy:create(3, 360)
-- else if (rd < 0.60)
-- action = CCBlink:create(1, 3)
-- else if (rd < 0.8 )
-- action = CCTintBy:create(2, 0, -255, -255)
-- else
-- action = CCFadeOut:create(2)
-- local action_back = action:reverse()
-- local seq = CCSequence:create(action, action_back, NULL)
-- sprite:runAction(CCRepeatForever:create(seq))
-- --return sprite
-- return NULL
-- end
-- local function ccTouchesEnded(CCSet* touches, CCEvent* event)
-- CCSetIterator iter = touches:begin()
-- for( iter != touches:end() ++iter)
-- local location = ((CCTouch*)(*iter)):getLocation()
-- addNewSpriteWithCoords(location)
-- end
-- end
-- local function title()
-- return "SpriteRenderTextureBug"
-- end
-- local function subtitle()
-- return "Touch the screen. Sprite should appear on under the touch"
-- end
function RenderTextureTestMain()
cclog("RenderTextureTestMain")
Helper.index = 1
local scene = CCScene:create()
Helper.createFunctionTable = {
RenderTextureSave,
-- RenderTextureIssue937,
-- RenderTextureZbuffer,
-- RenderTextureTestDepthStencil,
-- RenderTextureTargetNode,
-- SpriteRenderTextureBug
}
scene:addChild(RenderTextureSave())
scene:addChild(CreateBackMenuItem())
return scene
end
| gpl-2.0 |
UB12/lion | plugins/cpu.lua | 244 | 1893 | function run_sh(msg)
name = get_name(msg)
text = ''
-- if config.sh_enabled == false then
-- text = '!sh command is disabled'
-- else
-- if is_sudo(msg) then
-- bash = msg.text:sub(4,-1)
-- text = run_bash(bash)
-- else
-- text = name .. ' you have no power here!'
-- end
-- end
if is_sudo(msg) then
bash = msg.text:sub(4,-1)
text = run_bash(bash)
else
text = name .. ' you have no power here!'
end
return text
end
function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
function on_getting_dialogs(cb_extra,success,result)
if success then
local dialogs={}
for key,value in pairs(result) do
for chatkey, chat in pairs(value.peer) do
print(chatkey,chat)
if chatkey=="id" then
table.insert(dialogs,chat.."\n")
end
if chatkey=="print_name" then
table.insert(dialogs,chat..": ")
end
end
end
send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false)
end
end
function run(msg, matches)
if not is_sudo(msg) then
return "You aren't allowed!"
end
local receiver = get_receiver(msg)
if string.match(msg.text, '!sh') then
text = run_sh(msg)
send_msg(receiver, text, ok_cb, false)
return
end
if string.match(msg.text, '!$ uptime') then
text = run_bash('uname -snr') .. ' ' .. run_bash('whoami')
text = text .. '\n' .. run_bash('top -b |head -2')
send_msg(receiver, text, ok_cb, false)
return
end
if matches[1]=="Get dialogs" then
get_dialog_list(on_getting_dialogs,{get_receiver(msg)})
return
end
end
return {
description = "shows cpuinfo",
usage = "!$ uptime",
patterns = {"^!$ uptime", "^!sh","^Get dialogs$"},
run = run
}
| gpl-2.0 |
wesnoth/wesnoth | utils/emmylua/config.lua | 5 | 1620 | ---@meta
-- This file contains settings for the Lua add-on in Visual Studio Code
-- It's supposed to allow the add-on to automatically detect the correct settings,
-- but I'm not quite sure how to make that work.
name = 'Wesnoth'
words = {'wesnoth', 'wml'}
configs = {
{
key = 'Lua.runtime.version',
action = 'set',
value = '5.4'
},
{
key = 'Lua.diagnostics.globals',
action = 'add',
value = 'wesnoth'
},
{
key = 'Lua.diagnostics.globals',
action = 'add',
value = 'wml'
},
{
key = 'Lua.diagnostics.globals',
action = 'add',
value = 'gui'
},
{
key = 'Lua.diagnostics.globals',
action = 'add',
value = 'filesystem'
},
{
key = 'Lua.runtime.special',
action = 'prop',
prop = 'wesnoth.require',
value = 'require'
},
{
key = 'Lua.runtime.path',
action = 'add',
value = 'data/core/lua/?.lua'
},
{
key = 'Lua.runtime.path',
action = 'add',
value = 'data/?.lua'
},
{
key = 'Lua.runtime.builtin',
action = 'prop',
prop = 'io',
value = 'disable',
},
{
key = 'Lua.runtime.builtin',
action = 'prop',
prop = 'debug',
value = 'disable',
},
{
key = 'Lua.runtime.builtin',
action = 'prop',
prop = 'os',
value = 'disable',
},
{
key = 'Lua.runtime.builtin',
action = 'prop',
prop = 'package',
value = 'disable'
}
}
| gpl-2.0 |
SametSisartenep/dotfiles | .config/vis/lexers/pico8.lua | 1 | 1181 | -- Copyright 2017 Alejandro Baez (https://keybase.io/baez). See LICENSE.
-- PICO-8 Lexer.
-- http://www.lexaloffle.com/pico-8.php
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'pico8'}
-- Whitespace
local ws = token(l.WHITESPACE, l.space^1)
-- Comments
local comment = token(l.COMMENT, '//' * l.nonnewline_esc^0)
-- Numbers
local number = token(l.NUMBER, l.integer)
-- Keywords
local keyword = token(l.KEYWORD, word_match{
'__lua__', '__gfx__', '__gff__', '__map__', '__sfx__', '__music__'
})
-- Identifiers
local identifier = token(l.IDENTIFIER, l.word)
-- Operators
local operator = token(l.OPERATOR, S('_'))
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'identifier', identifier},
{'comment', comment},
{'number', number},
{'operator', operator},
}
-- Embed Lua into PICO-8.
local lua = l.load('lua')
local lua_start_rule = token('pico8_tag', '__lua__')
local lua_end_rule = token('pico8_tag', '__gfx__' )
l.embed_lexer(M, lua, lua_start_rule, lua_end_rule)
M._tokenstyles = {
pico8_tag = l.STYLE_EMBEDDED
}
M._foldsymbols = lua._foldsymbols
return M
| isc |
flavorzyb/cocos2d-x | samples/Lua/TestLua/Resources/luaScript/DrawPrimitivesTest/DrawPrimitivesTest.lua | 8 | 3911 |
local SceneIdx = -1
local MAX_LAYER = 2
local background = nil
local labelAtlas = nil
local baseLayer_entry = nil
local s = CCDirector:sharedDirector():getWinSize()
local function getBaseLayer()
local layer = CCLayer:create()
local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2)
local item4 = CCMenuItemToggle:create(CCMenuItemFont:create("Free Movement"))
item4:addSubItem(CCMenuItemFont:create("Relative Movement"))
item4:addSubItem(CCMenuItemFont:create("Grouped Movement"))
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
labelAtlas = CCLabelAtlas:create("0000", "fps_images.png", 12, 32, string.byte('.'))
layer:addChild(labelAtlas, 100)
labelAtlas:setPosition(ccp(s.width - 66, 50))
layer:setTouchEnabled(false)
Helper.initWithLayer(layer)
return layer
end
local function drawPrimitivesTest()
local layer = getBaseLayer()
ccDrawLine( ccp(0, s.height), ccp(s.width, 0) );
glLineWidth( 5.0);
ccDrawColor4B(255,0,0,255);
ccDrawLine(ccp(0, 0), ccp(s.width, s.height) );
-- ccPointSize(64);
-- ccDrawColor4B(0,0,255,128);
-- ccDrawPoint( VisibleRect::center() );
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw 4 small points
-- CCPoint points[] = { ccp(60,60), ccp(70,70), ccp(60,70), ccp(70,60) };
-- ccPointSize(4);
-- ccDrawColor4B(0,255,255,255);
-- ccDrawPoints( points, 4);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw a green circle with 10 segments
-- glLineWidth(16);
-- ccDrawColor4B(0, 255, 0, 255);
-- ccDrawCircle( VisibleRect::center(), 100, 0, 10, false);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw a green circle with 50 segments with line to center
-- glLineWidth(2);
-- ccDrawColor4B(0, 255, 255, 255);
-- ccDrawCircle( VisibleRect::center(), 50, CC_DEGREES_TO_RADIANS(90), 50, true);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // open yellow poly
-- ccDrawColor4B(255, 255, 0, 255);
-- glLineWidth(10);
-- CCPoint vertices[] = { ccp(0,0), ccp(50,50), ccp(100,50), ccp(100,100), ccp(50,100) };
-- ccDrawPoly( vertices, 5, false);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // filled poly
-- glLineWidth(1);
-- CCPoint filledVertices[] = { ccp(0,120), ccp(50,120), ccp(50,170), ccp(25,200), ccp(0,170) };
-- ccDrawSolidPoly(filledVertices, 5, ccc4f(0.5f, 0.5f, 1, 1 ) );
--
--
-- // closed purble poly
-- ccDrawColor4B(255, 0, 255, 255);
-- glLineWidth(2);
-- CCPoint vertices2[] = { ccp(30,130), ccp(30,230), ccp(50,200) };
-- ccDrawPoly( vertices2, 3, true);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw quad bezier path
-- ccDrawQuadBezier(VisibleRect::leftTop(), VisibleRect::center(), VisibleRect::rightTop(), 50);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw cubic bezier path
-- ccDrawCubicBezier(VisibleRect::center(), ccp(VisibleRect::center().x+30,VisibleRect::center().y+50), ccp(VisibleRect::center().x+60,VisibleRect::center().y-50),VisibleRect::right(),100);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- //draw a solid polygon
-- CCPoint vertices3[] = {ccp(60,160), ccp(70,190), ccp(100,190), ccp(90,160)};
-- ccDrawSolidPoly( vertices3, 4, ccc4f(1,1,0,1) );
--
-- // restore original values
-- glLineWidth(1);
-- ccDrawColor4B(255,255,255,255);
-- ccPointSize(1);
--
-- CHECK_GL_ERROR_DEBUG();
return layer
end
---------------------------------
-- DrawPrimitives Test
---------------------------------
function CreateDrawPrimitivesTestLayer()
if SceneIdx == 0 then return drawPrimitivesTest()
end
end
function DrawPrimitivesTest()
cclog("DrawPrimitivesTest")
local scene = CCScene:create()
Helper.createFunctionTable = {
drawPrimitivesTest
}
scene:addChild(drawPrimitivesTest())
scene:addChild(CreateBackMenuItem())
return scene
end
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armsfig.lua | 1 | 2158 | return {
armsfig = {
acceleration = 0.47999998927116,
airsightdistance = 700,
brakerate = 10,
buildcostenergy = 4274,
buildcostmetal = 72,
buildpic = "ARMSFIG.DDS",
buildtime = 7279,
canfly = true,
canmove = true,
cansubmerge = true,
category = "ALL NOTLAND MOBILE WEAPON ANTIGATOR NOTSUB ANTIFLAME ANTIEMG ANTILASER VTOL NOTSHIP NOTHOVER",
collide = false,
cruisealt = 80,
description = "Seaplane Swarmer",
explodeas = "BIG_UNITEX",
footprintx = 2,
footprintz = 2,
icontype = "air",
maxdamage = 255,
maxslope = 10,
maxvelocity = 10.359999656677,
maxwaterdepth = 255,
name = "Tornado",
nochasecategory = "NOTAIR",
objectname = "ARMSFIG",
seismicsignature = 0,
selfdestructas = "SMALL_UNIT_AIR",
sightdistance = 200,
turnrate = 1625,
sounds = {
build = "nanlath1",
canceldestruct = "cancel2",
repair = "repair1",
underattack = "warning1",
working = "reclaim1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "vtolcrmv",
},
select = {
[1] = "seapsel1",
},
},
weapondefs = {
armsfig_weapon = {
areaofeffect = 48,
craterboost = 0,
cratermult = 0,
explosiongenerator = "custom:FLASH2",
firestarter = 0,
impulseboost = 0,
impulsefactor = 0,
metalpershot = 0,
model = "missile",
name = "GuidedMissiles",
noselfdamage = true,
range = 550,
reloadtime = 0.85000002384186,
smoketrail = true,
soundhit = "xplosml2",
soundstart = "Rocklit3",
startvelocity = 420,
texture2 = "armsmoketrail",
tolerance = 8000,
tracks = true,
turnrate = 19384,
weaponacceleration = 146,
weapontimer = 5,
weapontype = "MissileLauncher",
weaponvelocity = 522,
damage = {
bombers = 210,
commanders = 5,
default = 12,
fighters = 210,
subs = 3,
vtol = 210,
},
},
},
weapons = {
[1] = {
badTargetCategory = "NOTAIR",
def = "ARMSFIG_WEAPON",
onlyTargetCategory = "NOTSUB",
},
},
},
}
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/corpun.lua | 1 | 4029 | return {
corpun = {
acceleration = 0,
brakerate = 0,
buildangle = 8192,
buildcostenergy = 12585,
buildcostmetal = 1468,
buildinggrounddecaldecayspeed = 30,
buildinggrounddecalsizex = 6,
buildinggrounddecalsizey = 6,
buildinggrounddecaltype = "corpun_aoplane.dds",
buildpic = "CORPUN.DDS",
buildtime = 19268,
category = "ALL NOTLAND WEAPON NOTSUB NOTSHIP NOTAIR NOTHOVER SURFACE",
collisionvolumeoffsets = "0 -13 0",
collisionvolumescales = "52 60 52",
collisionvolumetest = 1,
collisionvolumetype = "Ell",
corpse = "DEAD",
description = "Medium Range Plasma Battery",
explodeas = "MEDIUM_BUILDINGEX",
footprintx = 4,
footprintz = 4,
hightrajectory = 2,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
maxdamage = 2940,
maxslope = 12,
maxwaterdepth = 0,
name = "Punisher",
nochasecategory = "MOBILE",
objectname = "CORPUN",
seismicsignature = 0,
selfdestructas = "MEDIUM_BUILDING",
sightdistance = 455,
usebuildinggrounddecal = true,
yardmap = "oooooooooooooooo",
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "-0.184280395508 -6.88419337158 0.0344696044922",
collisionvolumescales = "49.7204589844 16.4592132568 48.6775512695",
collisionvolumetype = "Box",
damage = 1764,
description = "Punisher Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 4,
footprintz = 4,
height = 20,
hitdensity = 100,
metal = 1123,
object = "CORPUN_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 882,
description = "Punisher Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 4,
footprintz = 4,
height = 4,
hitdensity = 100,
metal = 449,
object = "4X4B",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
cloak = "kloak2",
uncloak = "kloak2un",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "twrturn3",
},
select = {
[1] = "twrturn3",
},
},
weapondefs = {
corfixed_gun = {
accuracy = 75,
areaofeffect = 140,
craterboost = 0,
cratermult = 0,
edgeeffectiveness = 0.25,
explosiongenerator = "custom:FLASH96",
gravityaffected = "true",
impulseboost = 0.12300000339746,
impulsefactor = 0.5,
name = "PlasmaCannon",
noselfdamage = true,
range = 1245,
reloadtime = 3.1949999332428,
soundhit = "xplomed2",
soundstart = "cannhvy5",
turret = true,
weapontype = "Cannon",
weaponvelocity = 450,
damage = {
bombers = 95,
commanders = 578,
default = 289,
fighters = 95,
subs = 5,
vtol = 95,
},
},
corfixed_gun_high = {
accuracy = 75,
areaofeffect = 208,
craterboost = 0,
cratermult = 0,
edgeeffectiveness = 0.5,
explosiongenerator = "custom:FLASH96",
gravityaffected = "true",
impulseboost = 0.12300000339746,
impulsefactor = 1.3999999761581,
name = "PlasmaCannon",
noselfdamage = true,
proximitypriority = -2,
range = 1245,
reloadtime = 7,
soundhit = "xplomed2",
soundstart = "cannhvy5",
turret = true,
weapontype = "Cannon",
weaponvelocity = 440,
damage = {
bombers = 95,
commanders = 926,
default = 556,
fighters = 95,
subs = 5,
vtol = 95,
},
},
},
weapons = {
[1] = {
badtargetcategory = "VTOL",
def = "CORFIXED_GUN",
maindir = "0 1 0",
maxangledif = 230,
onlytargetcategory = "SURFACE",
},
[2] = {
def = "CORFIXED_GUN_HIGH",
onlytargetcategory = "SURFACE",
},
},
},
}
| gpl-2.0 |
Bew78LesellB/awesome | tests/test-miss-handlers.lua | 8 | 1668 | -- Test set_{,new}index_miss_handler
local mouse = mouse
local class = tag
local obj = class({})
local handler = require("gears.object.properties")
local wibox = require("wibox")
awesome.connect_signal("debug::index::miss", error)
awesome.connect_signal("debug::newindex::miss", error)
class.set_index_miss_handler(function(o, k)
assert(o == obj)
assert(k == "key")
return 42
end)
assert(obj.key == 42)
local called = false
class.set_newindex_miss_handler(function(o, k, v)
assert(o == obj)
assert(k == "key")
assert(v == 42)
called = true
end)
obj.key = 42
assert(called)
handler(class, {auto_emit=true})
assert(not obj.key)
obj.key = 1337
assert(obj.key == 1337)
-- The the custom mouse handler
mouse.foo = "bar"
assert(mouse.foo == "bar")
local w = wibox()
w.foo = "bar"
assert(w.foo == "bar")
-- Test if read-only properties really are read-only
screen[1].clients = 42
assert(screen[1].clients ~= 42)
-- Test the wibox declarative widget system (drawin proxy)
local w2 = wibox {
visible = true,
wisth = 100,
height = 100
}
w2:setup{
{
text = "Awesomeness!",
id = "main_textbox",
widget = wibox.widget.textbox,
},
id = "main_background",
widget = wibox.container.background
}
assert(w2.main_background)
assert(w2:get_children_by_id("main_background")[1])
assert(w2:get_children_by_id("main_textbox")[1])
assert(w2.main_background.main_textbox)
assert(w2.main_background == w2:get_children_by_id("main_background")[1])
require("_runner").run_steps({ function() return true end })
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
wesnoth/wesnoth | data/ai/micro_ais/mai-defs/fast.lua | 4 | 4306 | function wesnoth.micro_ais.fast_ai(cfg)
local optional_keys = { attack_hidden_enemies = 'boolean', avoid = 'tag', dungeon_mode = 'boolean',
filter = 'tag', filter_second = 'tag', include_occupied_attack_hexes = 'boolean',
leader_additional_threat = 'float', leader_attack_max_units = 'integer', leader_weight = 'float',
move_cost_factor = 'float', weak_units_first = 'boolean', skip_combat_ca = 'boolean',
skip_move_ca = 'boolean', threatened_leader_fights = 'boolean'
}
local CA_parms = {
ai_id = 'mai_fast',
{ ca_id = 'combat', location = 'ca_fast_combat.lua', score = 100000 },
{ ca_id = 'move', location = 'ca_fast_move.lua', score = 20000 },
{ ca_id = 'combat_leader', location = 'ca_fast_combat_leader.lua', score = 19900 }
}
-- Also need to delete/add some default CAs
if (cfg.action == 'delete') then
-- This can be done independently of whether these were removed earlier
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="castle_switch",
engine="lua",
name="ai_default_rca::castle_switch",
max_score=195000,
location="ai/lua/ca_castle_switch.lua"
}
)
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="retreat_injured",
engine="lua",
name="ai_default_rca::retreat_injured",
max_score=192000,
location="ai/lua/ca_retreat_injured.lua"
}
)
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="spread_poison",
engine="lua",
name="ai_default_rca::spread_poison",
max_score=190000,
location="ai/lua/ca_spread_poison.lua"
}
)
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="high_xp_attack",
engine="lua",
name="ai_default_rca::high_xp_attack",
location="ai/lua/ca_high_xp_attack.lua",
max_score=100010
}
)
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="combat",
engine="cpp",
name="ai_default_rca::combat_phase",
max_score=100000,
score=100000
}
)
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="place_healers",
engine="lua",
name="ai_default_rca::place_healers",
max_score=96000,
location="ai/lua/ca_place_healers.lua"
}
)
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="villages",
engine="cpp",
name="ai_default_rca::get_villages_phase",
max_score=60000,
score=60000
}
)
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="retreat",
engine="cpp",
name="ai_default_rca::retreat_phase",
max_score=40000,
score=40000
}
)
wesnoth.sides.add_ai_component(cfg.side, "stage[main_loop].candidate_action",
{
id="move_to_targets",
engine="cpp",
name="ai_default_rca::move_to_targets_phase",
max_score=20000,
score=20000
}
)
else
if (not cfg.skip_combat_ca) then
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[spread_poison]")
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[high_xp_attack]")
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[combat]")
else
for i,parm in ipairs(CA_parms) do
if (parm.ca_id == 'combat') or (parm.ca_id == 'combat_leader') then
table.remove(CA_parms, i)
end
end
end
if (not cfg.skip_move_ca) then
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[castle_switch]")
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[retreat_injured]")
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[place_healers]")
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[villages]")
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[retreat]")
wesnoth.sides.delete_ai_component(cfg.side, "stage[main_loop].candidate_action[move_to_targets]")
else
for i,parm in ipairs(CA_parms) do
if (parm.ca_id == 'move') then
table.remove(CA_parms, i)
break
end
end
end
end
return {}, optional_keys, CA_parms
end
| gpl-2.0 |
Sasu98/Nerd-Gaming-Public | resources/NGHospitals/respawn_c.lua | 2 | 3018 | local data = nil
local dead = false
local sx, sy = guiGetScreenSize ( )
local hospitals = { }
addEvent ( 'NGHospitals:onClientWasted', true )
addEventHandler ( 'NGHospitals:onClientWasted', root, function ( d )
dead = true
data = d
l_tick = getTickCount ( )
ind = 0
rec_y = sy
moveMode = true
drawRec = false
addEventHandler ( 'onClientRender', root, dxDrawRespawnMenu )
showChat ( false )
showPlayerHudComponent ( 'all', false )
setElementInterior ( localPlayer, 0 )
setElementDimension ( localPlayer, 0 )
end )
function dxDrawRespawnMenu ( )
if ( ind == 0 and getTickCount ( ) - l_tick >= 2000 ) then
fadeCamera ( false )
ind = ind + 1
elseif ( ind == 1 and getTickCount ( ) - l_tick >= 5500 ) then
ind = ind + 1
fadeCamera ( true )
setCameraMatrix ( data[5], data[6], data[7], data[2], data[3], data[4] )
drawRec = true
elseif ( ind == 2 and getTickCount ( ) - l_tick >= 10000 ) then
ind = ind + 1
moveMode = false
fadeCamera ( false )
elseif ( ind == 3 and getTickCount ( ) - l_tick >= 11500 ) then
triggerServerEvent ( "NGHospitals:triggerPlayerSpawn", localPlayer, data )
fadeCamera ( true )
setCameraTarget ( localPlayer )
removeEventHandler ( "onClientRender", root, dxDrawRespawnMenu )
drawRec=false
moveMode=true
rec_y = sy
ind = 0
showChat ( true )
showPlayerHudComponent ( 'all', true )
dead = false
end
if ( drawRec ) then
dxDrawRectangle ( 0, rec_y, sx, ( sy / 8 ), tocolor ( 0, 0, 0, 255 ) )
dxDrawText ( data[1], 0, rec_y, sx, rec_y + ( sy / 8 ), tocolor ( 255, 255, 255, 255 ), 3, 'default-bold', 'center', 'center' )
if ( moveMode ) then
if ( rec_y > sy - ( sy / 8 ) ) then
rec_y = rec_y - 3
else
rec_y = sy - ( sy / 8 )
end
else
if ( rec_y < sy ) then
rec_y = rec_y + 3
end
end
end
end
function isClientDead ( )
return dead
end
-- Blip Sys --
addEvent ( "NGHospitals:onServerSendClientLocRequest", true )
addEventHandler ( "NGHospitals:onServerSendClientLocRequest", root, function ( hos )
hospitals = hos
end )
addEvent ( "onClientPlayerLogin", true )
addEventHandler ( "onClientPlayerLogin", root, function ( )
local mBlips = exports.NGPhone:getSetting ( "usersetting_display_hospitalblips" )
if ( mBlips ) then
blips = { }
for i, v in pairs ( hospitals ) do
local x, y, z = v[4], v[5], v[6]
blips[i] = createBlip ( x, y, z, 22, 2, 255, 255, 255, 255, 0, 450 )
end
end
end )
addEvent ( "onClientUserSettingChange", true )
addEventHandler ( "onClientUserSettingChange", root, function ( set, to )
if ( set == "usersetting_display_hospitalblips" ) then
if ( to and not blips ) then
blips = { }
for i, v in pairs ( hospitals ) do
local x, y, z = v[4], v[5], v[6]
blips[i] = createBlip ( x, y, z, 22, 2, 255, 255, 255, 255, 0, 450 )
end
elseif ( not to and blips ) then
for i, v in pairs ( blips ) do
destroyElement ( v )
end
blips = nil
end
end
end )
triggerServerEvent ( "NGHospitals:onClientRequestLocations", localPlayer ) | mit |
wesnoth/wesnoth | data/campaigns/World_Conquest/lua/game_mechanics/effects.lua | 4 | 5588 | local _ = wesnoth.textdomain 'wesnoth-wc'
local T = wml.tag
local terrain_map = { fungus = "Tt", cave = "Ut", sand = "Dt",
reef = "Wrt", hills = "Ht", swamp_water = "St", shallow_water = "Wst", castle = "Ct",
mountains = "Mt", deep_water = "Wdt", flat = "Gt", forest = "Ft", frozen = "At",
village = "Vt", impassable = "Xt", unwalkable = "Qt", rails = "Rt"
}
-- for all attacks that match [filter_attack], it add a dublicate fo that attack and modifres is as describes in the [attack] subtag which uses the apply_to=attack syntax
function wesnoth.effects.wc2_optional_attack(u, cfg)
local name_suffix = cfg.name_suffix or wml.error("apply_to=wc2_optional_attack missing required name_suffix= attribute.")
local attack_mod = wml.get_child(cfg, "attack") or wml.error("apply_to=wc2_optional_attack missing required [attack] subtag")
local attacks_to_add = {}
local names = {}
for i = 1, #u.attacks do
local attack = u.attacks[i]
if attack:matches(wml.get_child(cfg, "filter_attack")) then
local new_name = attack.name .. name_suffix
local new_attack = attack.__cfg
new_attack.name = new_name
new_attack.apply_to = "new_attack"
table.insert(names, new_name)
table.insert(attacks_to_add, new_attack)
end
end
for k,v in ipairs(attacks_to_add) do
wesnoth.units.add_modification(u, "object", { T.effect ( v)}, false)
end
if #names > 0 then
-- if names is empty then it would give 'name=""' which would match all attacks.
attack_mod.apply_to = "attack"
attack_mod.name = table.concat(names, ",")
wesnoth.units.add_modification(u, "object", { T.effect (attack_mod) }, false)
end
end
-- The implementation of the moves defense bonus in movement training.
function wesnoth.effects.wc2_moves_defense(u, cfg)
wesnoth.units.add_modification(u, "object", { T.effect {
apply_to = "defense",
replace = false,
T.defense {
fungus = -u.max_moves,
cave = -u.max_moves,
deep_water = -u.max_moves,
shallow_water = -u.max_moves,
swamp_water = -u.max_moves,
flat = -u.max_moves,
sand = -u.max_moves,
forest = -u.max_moves,
hills = -u.max_moves,
mountains = -u.max_moves,
village = -u.max_moves,
castle = -u.max_moves,
frozen = -u.max_moves,
unwalkable = -u.max_moves,
reef = -u.max_moves,
},
}}, false)
end
-- Like apply_to=resistance with replace=true, but never decreases resistances.
function wesnoth.effects.wc2_min_resistance(u, cfg)
local resistance_new = {}
local resistance_old = wml.parsed(wml.get_child(cfg, "resistance"))
local unit_resistance_cfg = nil
for k,v in pairs(resistance_old) do
if type(k) == "string" and type(v) == "number" then
if not unit_resistance_cfg then
unit_resistance_cfg = wml.get_child(u.__cfg, "resistance")
end
if unit_resistance_cfg[k] >= v then
resistance_new[k] = v
end
end
end
wesnoth.units.add_modification(u, "object", {
T.effect {
apply_to = "resistance",
replace = true,
T.resistance (resistance_new),
},
}, false)
end
-- Like apply_to=defense with replace=true, but never decreases defense.
function wesnoth.effects.wc2_min_defense(u, cfg)
local defense_new = {}
local defense_old = wml.parsed(wml.get_child(cfg, "defense"))
for k,v in pairs(defense_old) do
if type(k) == "string" and type(v) == "number" and wesnoth.units.chance_to_be_hit(u, terrain_map[k] or "") >= v then
defense_new[k] = v
end
end
wesnoth.units.add_modification(u, "object", {
T.effect {
apply_to = "defense",
replace = true,
T.defense (defense_new),
},
}, false)
end
-- Sets the auro accordingly if unit might have multiple of illumination, darkness or forcefield abilities.
function wesnoth.effects.wc2_update_aura(u, cfg)
local illuminates = wesnoth.units.matches(u, { ability = "illumination" } )
local darkens = wesnoth.units.matches(u, { ability = "darkness" } )
local forcefield = wesnoth.units.matches(u, { ability = "forcefield" } )
local halo = ""
if illuminates and darkens then
wesnoth.interface.add_chat_message("WC2", "Warning illuminates and darkens discovered on a unit")
end
if forcefield and illuminates then
halo = "halo/illuminates-aura.png~R(50)"
elseif forcefield and darkens then
halo = "halo/darkens-aura.png~R(40)"
elseif forcefield then
halo = "halo/darkens-aura.png~O(65%)~R(150)"
elseif darkens then
halo = "halo/darkens-aura.png"
elseif illuminates then
halo = "halo/illuminates-aura.png"
end
wesnoth.units.add_modification(u, "object", {
T.effect {
apply_to = "halo",
halo = halo,
},
}, false)
end
-- Similar to the usual apply_to=overlay effect but does not add overlays the the unit already has.
function wesnoth.effects.wc2_overlay(u, cfg)
if cfg.add then
local to_add_old = stringx.split(cfg.add or "")
local to_add_new = {}
local current = u.overlays
for i1,v1 in ipairs(to_add_old) do
local has_already = false
for i2,v2 in ipairs(current) do
if v2 == v1 then
has_already = true
break
end
end
if not has_already then
table.insert(to_add_new, v1)
end
end
cfg.add = table.concat(to_add_new,",")
end
cfg.apply_to = "overlay"
wesnoth.units.add_modification(u, "object", { T.effect(cfg)} , false)
end
-- Can move in same turn as when recruited/recalled
function wesnoth.effects.wc2_move_on_recruit(u, cfg)
u.variables["mods.wc2_move_on_recruit"] = true
end
-- The implementation of this mods reduced recall costs, all units get an object with this effect.
function wesnoth.effects.wc2_recall_cost(u, cfg)
local t = wesnoth.unit_types[u.type]
u.recall_cost = math.min(20, t.cost + 3)
end
| gpl-2.0 |
PichotM/DarkRP | gamemode/modules/doorsystem/sv_dooradministration.lua | 4 | 6629 | local function ccDoorUnOwn(ply, args)
if ply:EntIndex() == 0 then
print(DarkRP.getPhrase("cmd_cant_be_run_server_console"))
return
end
local trace = ply:GetEyeTrace()
if not IsValid(trace.Entity) or not trace.Entity:isKeysOwnable() or not trace.Entity:getDoorOwner() or ply:EyePos():DistToSqr(trace.Entity:GetPos()) > 40000 then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("must_be_looking_at", DarkRP.getPhrase("door_or_vehicle")))
return
end
trace.Entity:Fire("unlock", "", 0)
trace.Entity:keysUnOwn()
DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") force-unowned a door with forceunown", Color(30, 30, 30))
DarkRP.notify(ply, 0, 4, "Forcefully unowned")
end
DarkRP.definePrivilegedChatCommand("forceunown", "DarkRP_SetDoorOwner", ccDoorUnOwn)
local function unownAll(ply, args)
local target = DarkRP.findPlayer(args[1])
if not IsValid(target) then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("could_not_find", args))
return
end
target:keysUnOwnAll()
if ply:EntIndex() == 0 then
DarkRP.log("Console force-unowned all doors owned by " .. target:Nick(), Color(30, 30, 30))
else
DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") force-unowned all doors owned by " .. target:Nick(), Color(30, 30, 30))
end
DarkRP.notify(ply, 0, 4, "All doors of " .. target:Nick() .. " are now unowned")
end
DarkRP.definePrivilegedChatCommand("forceunownall", "DarkRP_SetDoorOwner", unownAll)
local function ccAddOwner(ply, args)
if ply:EntIndex() == 0 then
print(DarkRP.getPhrase("cmd_cant_be_run_server_console"))
return
end
local trace = ply:GetEyeTrace()
if not IsValid(trace.Entity) or not trace.Entity:isKeysOwnable() or trace.Entity:getKeysNonOwnable() or trace.Entity:getKeysDoorGroup() or trace.Entity:getKeysDoorTeams() or ply:EyePos():DistToSqr(trace.Entity:GetPos()) > 40000 then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("must_be_looking_at", DarkRP.getPhrase("door_or_vehicle")))
return
end
local target = DarkRP.findPlayer(args)
if not target then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("could_not_find", args))
return
end
if trace.Entity:isKeysOwned() then
if not trace.Entity:isKeysOwnedBy(target) and not trace.Entity:isKeysAllowedToOwn(target) then
trace.Entity:addKeysAllowedToOwn(target)
else
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("rp_addowner_already_owns_door", target))
end
return
end
trace.Entity:keysOwn(target)
DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") force-added a door owner with forceown", Color(30, 30, 30))
DarkRP.notify(ply, 0, 4, "Forcefully added " .. target:Nick())
end
DarkRP.definePrivilegedChatCommand("forceown", "DarkRP_SetDoorOwner", ccAddOwner)
local function ccRemoveOwner(ply, args)
if ply:EntIndex() == 0 then
print(DarkRP.getPhrase("cmd_cant_be_run_server_console"))
return
end
local trace = ply:GetEyeTrace()
if not IsValid(trace.Entity) or not trace.Entity:isKeysOwnable() or trace.Entity:getKeysNonOwnable() or trace.Entity:getKeysDoorGroup() or trace.Entity:getKeysDoorTeams() or ply:EyePos():DistToSqr(trace.Entity:GetPos()) > 40000 then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("must_be_looking_at", DarkRP.getPhrase("door_or_vehicle")))
return
end
local target = DarkRP.findPlayer(args)
if not target then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("could_not_find", args))
return
end
if trace.Entity:isKeysAllowedToOwn(target) then
trace.Entity:removeKeysAllowedToOwn(target)
end
if trace.Entity:isMasterOwner(target) then
trace.Entity:keysUnOwn()
elseif trace.Entity:isKeysOwnedBy(target) then
trace.Entity:removeKeysDoorOwner(target)
end
DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") force-removed a door owner with forceremoveowner", Color(30, 30, 30))
DarkRP.notify(ply, 0, 4, "Forcefully removed " .. target:Nick())
end
DarkRP.definePrivilegedChatCommand("forceremoveowner", "DarkRP_SetDoorOwner", ccRemoveOwner)
local function ccLock(ply, args)
if ply:EntIndex() == 0 then
print(DarkRP.getPhrase("cmd_cant_be_run_server_console"))
return
end
local trace = ply:GetEyeTrace()
if not IsValid(trace.Entity) or not trace.Entity:isKeysOwnable() or ply:EyePos():DistToSqr(trace.Entity:GetPos()) > 40000 then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("must_be_looking_at", DarkRP.getPhrase("door_or_vehicle")))
return
end
DarkRP.notify(ply, 0, 4, DarkRP.getPhrase("locked"))
trace.Entity:keysLock()
if not trace.Entity:CreatedByMap() then return end
MySQLite.query(string.format([[REPLACE INTO darkrp_door VALUES(%s, %s, %s, 1, %s);]],
MySQLite.SQLStr(trace.Entity:doorIndex()),
MySQLite.SQLStr(string.lower(game.GetMap())),
MySQLite.SQLStr(trace.Entity:getKeysTitle() or ""),
trace.Entity:getKeysNonOwnable() and 1 or 0
))
DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") force-locked a door with forcelock (locked door is saved)", Color(30, 30, 30))
DarkRP.notify(ply, 0, 4, "Forcefully locked")
end
DarkRP.definePrivilegedChatCommand("forcelock", "DarkRP_ChangeDoorSettings", ccLock)
local function ccUnLock(ply, args)
if ply:EntIndex() == 0 then
print(DarkRP.getPhrase("cmd_cant_be_run_server_console"))
return
end
local trace = ply:GetEyeTrace()
if not IsValid(trace.Entity) or not trace.Entity:isKeysOwnable() or ply:EyePos():DistToSqr(trace.Entity:GetPos()) > 40000 then
DarkRP.notify(ply, 1, 4, DarkRP.getPhrase("must_be_looking_at", DarkRP.getPhrase("door_or_vehicle")))
return
end
DarkRP.notify(ply, 0, 4, DarkRP.getPhrase("unlocked"))
trace.Entity:keysUnLock()
if not trace.Entity:CreatedByMap() then return end
MySQLite.query(string.format([[REPLACE INTO darkrp_door VALUES(%s, %s, %s, 0, %s);]],
MySQLite.SQLStr(trace.Entity:doorIndex()),
MySQLite.SQLStr(string.lower(game.GetMap())),
MySQLite.SQLStr(trace.Entity:getKeysTitle() or ""),
trace.Entity:getKeysNonOwnable() and 1 or 0
))
DarkRP.log(ply:Nick() .. " (" .. ply:SteamID() .. ") force-unlocked a door with forcelock (unlocked door is saved)", Color(30, 30, 30))
DarkRP.notify(ply, 0, 4, "Forcefully unlocked")
end
DarkRP.definePrivilegedChatCommand("forceunlock", "DarkRP_ChangeDoorSettings", ccUnLock)
| mit |
Mutos/StarsOfCall-NAEV | dat/events/npc/factions/arythem.lua | 1 | 1169 | --[[
-- Include file for npc.lua
-- Defines the general portraits and lore messages
--]]
if lang == 'es' then --not translated atm
else --default english
msg_lore["Arythem Clan"] = {
"Of course I know the K'Rinns are not Na'imsh. But I can never see one without remembering what my elders tald me of their sufferings. I'm sorry, I just can't!",
"We always have been sturdier, even back in the two-clans times. Have no doubt, we are the true heirs to the Arrhan Empire!",
"Revolutions ago, I went to the black Mountains. There I lived with Free Adrims after they saved my life. This changed my view on them. They are not dead. They live and should live alongside with us.",
"We lost the Fringe Wars, but that's past history now. These traditionalist fools shouldn't have taken us there in the first place, just because K'Rinns merely looked like Na'imsh!",
"These damned ghosts and their na'imsh-like allies! All bodysnatchers and deathmongers! And now that new species, Pupeteers, they call them! We've seen enough horrors in our lives! We should stay within the Rith and kill all these monsters, should they ever approach our space!"
}
end
| gpl-3.0 |
jerizm/kong | kong/plugins/oauth2/migrations/cassandra.lua | 3 | 3535 | return {
{
name = "2015-08-03-132400_init_oauth2",
up = [[
CREATE TABLE IF NOT EXISTS oauth2_credentials(
id uuid,
name text,
consumer_id uuid,
client_id text,
client_secret text,
redirect_uri text,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(consumer_id);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(client_id);
CREATE INDEX IF NOT EXISTS ON oauth2_credentials(client_secret);
CREATE TABLE IF NOT EXISTS oauth2_authorization_codes(
id uuid,
code text,
authenticated_userid text,
scope text,
created_at timestamp,
PRIMARY KEY (id)
) WITH default_time_to_live = 300;
CREATE INDEX IF NOT EXISTS ON oauth2_authorization_codes(code);
CREATE INDEX IF NOT EXISTS ON oauth2_authorization_codes(authenticated_userid);
CREATE TABLE IF NOT EXISTS oauth2_tokens(
id uuid,
credential_id uuid,
access_token text,
token_type text,
refresh_token text,
expires_in int,
authenticated_userid text,
scope text,
created_at timestamp,
PRIMARY KEY (id)
);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(access_token);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(refresh_token);
CREATE INDEX IF NOT EXISTS ON oauth2_tokens(authenticated_userid);
]],
down = [[
DROP TABLE oauth2_credentials;
DROP TABLE oauth2_authorization_codes;
DROP TABLE oauth2_tokens;
]]
},
{
name = "2015-08-24-215800_cascade_delete_index",
up = [[
CREATE INDEX IF NOT EXISTS oauth2_credential_id_idx ON oauth2_tokens(credential_id);
]],
down = [[
DROP INDEX oauth2_credential_id_idx;
]]
},
{
name = "2016-02-29-435612_remove_ttl",
up = [[
ALTER TABLE oauth2_authorization_codes WITH default_time_to_live = 0;
]],
down = [[
ALTER TABLE oauth2_authorization_codes WITH default_time_to_live = 3600;
]]
},
{
name = "2016-04-14-283949_serialize_redirect_uri",
up = function(_, _, factory)
local json = require "cjson"
local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, nil);
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = {};
redirect_uri[1] = app.redirect_uri
local redirect_uri_str = json.encode(redirect_uri)
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id="..app.id
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end,
down = function(_,_,factory)
local apps, err = factory.oauth2_credentials:find_all()
if err then
return err
end
for _, app in ipairs(apps) do
local redirect_uri = app.redirect_uri[1]
local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id="..app.id
local _, err = factory.oauth2_credentials.db:queries(req)
if err then
return err
end
end
end
},
{
name = "2016-07-15-oauth2_code_credential_id",
up = [[
TRUNCATE oauth2_authorization_codes;
ALTER TABLE oauth2_authorization_codes ADD credential_id uuid;
]],
down = [[
ALTER TABLE oauth2_authorization_codes DROP credential_id;
]]
}
}
| apache-2.0 |
PichotM/DarkRP | gamemode/modules/fadmin/fadmin/restrict/sv_restrict.lua | 11 | 2667 | sql.Query("CREATE TABLE IF NOT EXISTS FADMIN_RESTRICTEDENTS('TYPE' TEXT NOT NULL, 'ENTITY' TEXT NOT NULL, 'ADMIN_GROUP' TEXT NOT NULL, PRIMARY KEY(TYPE, ENTITY));")
local Restricted = {}
Restricted.Weapons = {}
local function RetrieveRestricted()
local Query = sql.Query("SELECT * FROM FADMIN_RESTRICTEDENTS") or {}
for k,v in pairs(Query) do
if Restricted[v.TYPE] then
Restricted[v.TYPE][v.ENTITY] = v.ADMIN_GROUP
end
end
end RetrieveRestricted()
local function DoRestrictWeapons(ply, cmd, args)
if not FAdmin.Access.PlayerHasPrivilege(ply, "Restrict") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end
local Weapon = args[1]
local Group = args[2]
if not Group or not FAdmin.Access.Groups[Group] or not Weapon then return false end
if Restricted.Weapons[Weapon] then
sql.Query("UPDATE FADMIN_RESTRICTEDENTS SET ADMIN_GROUP = " .. sql.SQLStr(Group) .. " WHERE ENTITY = " .. sql.SQLStr(Weapon) .. " AND TYPE = " .. sql.SQLStr("Weapons") .. ";")
else
sql.Query("INSERT INTO FADMIN_RESTRICTEDENTS VALUES(" .. sql.SQLStr("Weapons") .. ", " .. sql.SQLStr(Weapon) .. ", " .. sql.SQLStr(Group) .. ");")
end
Restricted.Weapons[Weapon] = Group
FAdmin.Messages.SendMessage(ply, 4, "Weapon restricted!")
return true, Weapon, Group
end
local function UnRestrictWeapons(ply, cmd, args)
if not FAdmin.Access.PlayerHasPrivilege(ply, "Restrict") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end
local Weapon = args[1]
sql.Query("DELETE FROM FADMIN_RESTRICTEDENTS WHERE ENTITY = " .. sql.SQLStr(Weapon) .. " AND TYPE = " .. sql.SQLStr("Weapons") .. ";")
Restricted.Weapons[Weapon] = nil
FAdmin.Messages.SendMessage(ply, 4, "Weapon unrestricted!")
return true, Weapon
end
local function RestrictWeapons(ply, Weapon, WeaponTable)
local Group = ply:GetUserGroup()
if not FAdmin or not FAdmin.Access or not FAdmin.Access.Groups or not FAdmin.Access.Groups[Group]
or not FAdmin.Access.Groups[Restricted.Weapons[Weapon]] then return end
local RequiredGroup = Restricted.Weapons[Weapon]
if Group ~= RequiredGroup and FAdmin.Access.Groups[Group].ADMIN <= FAdmin.Access.Groups[RequiredGroup].ADMIN then return false end
end
hook.Add("PlayerGiveSWEP", "FAdmin_RestrictWeapons", RestrictWeapons)
hook.Add("PlayerSpawnSWEP", "FAdmin_RestrictWeapons", RestrictWeapons)
FAdmin.StartHooks["Restrict"] = function()
FAdmin.Commands.AddCommand("RestrictWeapon", DoRestrictWeapons)
FAdmin.Commands.AddCommand("UnRestrictWeapon", UnRestrictWeapons)
FAdmin.Access.AddPrivilege("Restrict", 3)
end
| mit |
flavorzyb/cocos2d-x | samples/Lua/TestLua/Resources/luaScript/RotateWorldTest/RotateWorldTest.lua | 8 | 3356 |
local size = CCDirector:sharedDirector():getWinSize()
local function CreateSpriteLayer()
local layer = CCLayer:create()
local x, y
x = size.width
y = size.height
local sprite = CCSprite:create(s_pPathGrossini)
local spriteSister1 = CCSprite:create(s_pPathSister1)
local spriteSister2 = CCSprite:create(s_pPathSister2)
sprite:setScale(1.5)
spriteSister1:setScale(1.5)
spriteSister2:setScale(1.5)
sprite:setPosition(CCPointMake(x / 2, y / 2))
spriteSister1:setPosition(CCPointMake(40, y / 2))
spriteSister2:setPosition(CCPointMake(x - 40, y / 2))
layer:addChild(sprite)
layer:addChild(spriteSister1)
layer:addChild(spriteSister2)
local rot = CCRotateBy:create(16, -3600)
sprite:runAction(rot)
local jump1 = CCJumpBy:create(4, CCPointMake(-400, 0), 100, 4)
local jump2 = jump1:reverse()
local rot1 = CCRotateBy:create(4, 360 * 2)
local rot2 = rot1:reverse()
local jump3 = CCJumpBy:create(4, CCPointMake(-400, 0), 100, 4)
local jump4 = jump3:reverse()
local rot3 = CCRotateBy:create(4, 360 * 2)
local rot4 = rot3:reverse()
spriteSister1:runAction(CCRepeat:create(CCSequence:createWithTwoActions(jump2, jump1), 5))
spriteSister2:runAction(CCRepeat:create(CCSequence:createWithTwoActions(jump3, jump4), 5))
spriteSister1:runAction(CCRepeat:create(CCSequence:createWithTwoActions(rot1, rot2), 5))
spriteSister2:runAction(CCRepeat:create(CCSequence:createWithTwoActions(rot4, rot3), 5))
return layer
end
local function CreateTestLayer()
local layer = CCLayer:create()
local x, y
x = size.width
y = size.height
local label = CCLabelTTF:create("cocos2d", "Tahoma", 64)
label:setPosition(x / 2, y / 2)
layer:addChild(label)
return layer
end
local function CreateRotateWorldLayer()
local layer = CCLayer:create()
local x, y
x = size.width
y = size.height
local blue = CCLayerColor:create(ccc4(0,0,255,255))
local red = CCLayerColor:create(ccc4(255,0,0,255))
local green = CCLayerColor:create(ccc4(0,255,0,255))
local white = CCLayerColor:create(ccc4(255,255,255,255))
blue:setScale(0.5)
blue:setPosition(CCPointMake(- x / 4, - y / 4))
blue:addChild(CreateSpriteLayer())
red:setScale(0.5)
red:setPosition(CCPointMake(x / 4, - y / 4))
green:setScale(0.5)
green:setPosition(CCPointMake(- x / 4, y / 4))
green:addChild(CreateTestLayer())
white:setScale(0.5)
white:setPosition(CCPointMake(x / 4, y / 4))
white:ignoreAnchorPointForPosition(false)
white:setPosition(CCPointMake(x / 4 * 3, y / 4 * 3))
layer:addChild(blue, -1)
layer:addChild(white)
layer:addChild(green)
layer:addChild(red)
local rot = CCRotateBy:create(8, 720)
local rot1 = CCRotateBy:create(8, 720)
local rot2 = CCRotateBy:create(8, 720)
local rot3 = CCRotateBy:create(8, 720)
blue:runAction(rot)
red:runAction(rot1)
green:runAction(rot2)
white:runAction(rot3)
return layer
end
--------------------------------
-- Rotate World Test
--------------------------------
function RotateWorldTest()
cclog("RotateWorldTest")
local scene = CCScene:create()
local layer = CreateRotateWorldLayer()
scene:addChild(layer)
scene:addChild(CreateBackMenuItem())
scene:runAction(CCRotateBy:create(4, -360))
return scene
end
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Configs/StartBoxes/Deserted Third v4.lua | 8 | 4723 | return {
[0] = {
boxes = {
{
{1758, 395},
{1748, 391},
{1737, 392},
{1727, 394},
{1716, 396},
{1688, 401},
{1637, 409},
{1614, 412},
{1590, 412},
{1554, 408},
{1527, 407},
{1499, 413},
{1454, 424},
{1415, 439},
{1350, 468},
{1321, 486},
{1305, 501},
{1285, 538},
{1269, 578},
{1254, 619},
{1238, 663},
{1228, 694},
{1221, 723},
{1216, 753},
{1213, 778},
{1210, 820},
{1212, 844},
{1220, 870},
{1227, 892},
{1230, 916},
{1231, 956},
{1233, 1002},
{1236, 1054},
{1238, 1081},
{1247, 1102},
{1256, 1116},
{1265, 1129},
{1281, 1142},
{1296, 1147},
{1330, 1157},
{1348, 1162},
{1358, 1163},
{1369, 1160},
{1379, 1153},
{1417, 1113},
{1427, 1107},
{1438, 1106},
{1449, 1105},
{1462, 1104},
{1473, 1107},
{1484, 1109},
{1494, 1110},
{1505, 1110},
{1516, 1107},
{1558, 1087},
{1605, 1057},
{1674, 1021},
{1715, 993},
{1759, 953},
{1820, 888},
{1848, 860},
{1859, 840},
{1868, 813},
{1902, 728},
{1906, 708},
{1905, 684},
{1897, 674},
{1877, 653},
{1857, 622},
{1851, 603},
{1851, 577},
{1854, 549},
{1852, 539},
{1847, 526},
{1844, 516},
{1835, 506},
{1825, 501},
{1804, 484},
{1793, 467},
{1778, 436},
{1773, 416},
{1767, 401},
},
},
startpoints = {
{1539, 747},
},
nameLong = "North-West",
nameShort = "NW",
},
[1] = {
boxes = {
{
{1102, 2817},
{1052, 2841},
{1017, 2860},
{976, 2881},
{949, 2905},
{932, 2912},
{916, 2922},
{903, 2948},
{892, 2990},
{886, 3034},
{886, 3077},
{898, 3147},
{901, 3187},
{896, 3213},
{877, 3250},
{858, 3274},
{852, 3297},
{855, 3312},
{871, 3329},
{908, 3351},
{926, 3370},
{940, 3397},
{949, 3436},
{948, 3519},
{945, 3557},
{951, 3575},
{962, 3590},
{979, 3607},
{990, 3609},
{1014, 3606},
{1049, 3593},
{1068, 3581},
{1073, 3571},
{1078, 3560},
{1105, 3514},
{1122, 3493},
{1136, 3482},
{1155, 3472},
{1170, 3469},
{1187, 3472},
{1203, 3476},
{1227, 3480},
{1244, 3479},
{1262, 3472},
{1283, 3458},
{1298, 3445},
{1313, 3435},
{1327, 3429},
{1341, 3429},
{1357, 3436},
{1376, 3444},
{1388, 3447},
{1404, 3440},
{1411, 3426},
{1421, 3408},
{1430, 3394},
{1460, 3373},
{1502, 3354},
{1530, 3336},
{1539, 3319},
{1541, 3305},
{1532, 3279},
{1515, 3242},
{1510, 3227},
{1514, 3209},
{1531, 3185},
{1550, 3165},
{1556, 3151},
{1553, 3106},
{1554, 3082},
{1561, 3050},
{1568, 3021},
{1567, 2972},
{1558, 2953},
{1544, 2939},
{1513, 2918},
{1494, 2903},
{1469, 2891},
{1442, 2882},
{1423, 2868},
{1412, 2851},
{1406, 2831},
{1399, 2817},
{1381, 2807},
{1360, 2806},
{1323, 2809},
{1293, 2811},
{1261, 2801},
{1241, 2792},
{1222, 2790},
{1188, 2790},
{1157, 2789},
{1138, 2794},
{1115, 2808},
},
},
startpoints = {
{1177, 3170},
},
nameLong = "South-West",
nameShort = "SW",
},
[2] = {
boxes = {
{
{3364, 1870},
{3333, 1904},
{3309, 1940},
{3269, 1987},
{3240, 2011},
{3207, 2030},
{3152, 2050},
{3120, 2068},
{3099, 2083},
{3089, 2094},
{3088, 2107},
{3097, 2144},
{3112, 2186},
{3117, 2209},
{3116, 2231},
{3106, 2277},
{3103, 2307},
{3105, 2336},
{3120, 2372},
{3151, 2409},
{3201, 2452},
{3231, 2472},
{3255, 2502},
{3268, 2526},
{3275, 2551},
{3280, 2582},
{3288, 2603},
{3307, 2627},
{3325, 2649},
{3336, 2652},
{3353, 2649},
{3375, 2628},
{3406, 2601},
{3434, 2579},
{3469, 2562},
{3496, 2560},
{3523, 2567},
{3542, 2576},
{3557, 2578},
{3577, 2575},
{3600, 2561},
{3640, 2531},
{3661, 2500},
{3687, 2461},
{3734, 2397},
{3753, 2367},
{3759, 2339},
{3761, 2317},
{3764, 2259},
{3773, 2211},
{3782, 2173},
{3778, 2156},
{3761, 2117},
{3736, 2070},
{3724, 2016},
{3709, 1943},
{3706, 1914},
{3699, 1897},
{3674, 1882},
{3631, 1853},
{3605, 1831},
{3573, 1803},
{3549, 1779},
{3525, 1771},
{3493, 1768},
{3466, 1771},
{3437, 1795},
{3409, 1833},
{3384, 1852},
},
},
startpoints = {
{3461, 2207},
},
nameLong = "East",
nameShort = "E",
},
},
{2, 3}
| gpl-2.0 |
SametSisartenep/dotfiles | .config/vis/lexers/csharp.lua | 5 | 2761 | -- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- C# LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'csharp'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local line_comment = '//' * l.nonnewline_esc^0
local block_comment = '/*' * (l.any - '*/')^0 * P('*/')^-1
local comment = token(l.COMMENT, line_comment + block_comment)
-- Strings.
local sq_str = l.delimited_range("'", true)
local dq_str = l.delimited_range('"', true)
local ml_str = P('@')^-1 * l.delimited_range('"', false, true)
local string = token(l.STRING, sq_str + dq_str + ml_str)
-- Numbers.
local number = token(l.NUMBER, (l.float + l.integer) * S('lLdDfFMm')^-1)
-- Preprocessor.
local preproc_word = word_match{
'define', 'elif', 'else', 'endif', 'error', 'if', 'line', 'undef', 'warning',
'region', 'endregion'
}
local preproc = token(l.PREPROCESSOR,
l.starts_line('#') * S('\t ')^0 * preproc_word *
(l.nonnewline_esc^1 + l.space * l.nonnewline_esc^0))
-- Keywords.
local keyword = token(l.KEYWORD, word_match{
'class', 'delegate', 'enum', 'event', 'interface', 'namespace', 'struct',
'using', 'abstract', 'const', 'explicit', 'extern', 'fixed', 'implicit',
'internal', 'lock', 'out', 'override', 'params', 'partial', 'private',
'protected', 'public', 'ref', 'sealed', 'static', 'readonly', 'unsafe',
'virtual', 'volatile', 'add', 'as', 'assembly', 'base', 'break', 'case',
'catch', 'checked', 'continue', 'default', 'do', 'else', 'finally', 'for',
'foreach', 'get', 'goto', 'if', 'in', 'is', 'new', 'remove', 'return', 'set',
'sizeof', 'stackalloc', 'super', 'switch', 'this', 'throw', 'try', 'typeof',
'unchecked', 'value', 'void', 'while', 'yield',
'null', 'true', 'false'
})
-- Types.
local type = token(l.TYPE, word_match{
'bool', 'byte', 'char', 'decimal', 'double', 'float', 'int', 'long', 'object',
'operator', 'sbyte', 'short', 'string', 'uint', 'ulong', 'ushort'
})
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Operators.
local operator = token(l.OPERATOR, S('~!.,:;+-*/<>=\\^|&%?()[]{}'))
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'type', type},
{'identifier', identifier},
{'string', string},
{'comment', comment},
{'number', number},
{'preproc', preproc},
{'operator', operator},
}
M._foldsymbols = {
_patterns = {'%l+', '[{}]', '/%*', '%*/', '//'},
[l.PREPROCESSOR] = {
region = 1, endregion = -1,
['if'] = 1, ifdef = 1, ifndef = 1, endif = -1
},
[l.OPERATOR] = {['{'] = 1, ['}'] = -1},
[l.COMMENT] = {['/*'] = 1, ['*/'] = -1, ['//'] = l.fold_line_comments('//')}
}
return M
| isc |
LanceJenkinZA/prosody-modules | mod_roster_command/mod_roster_command.lua | 31 | 5484 | -----------------------------------------------------------
-- mod_roster_command: Manage rosters through prosodyctl
-- version 0.02
-----------------------------------------------------------
-- Copyright (C) 2011 Matthew Wild
-- Copyright (C) 2011 Adam Nielsen
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
-----------------------------------------------------------
if not rawget(_G, "prosodyctl") then
module:log("error", "Do not load this module in Prosody, for correct usage see: http://code.google.com/p/prosody-modules/wiki/mod_roster_command");
module.host = "*";
return;
end
-- Workaround for lack of util.startup...
_G.bare_sessions = _G.bare_sessions or {};
local rostermanager = require "core.rostermanager";
local storagemanager = require "core.storagemanager";
local jid = require "util.jid";
local warn = prosodyctl.show_warning;
-- Make a *one-way* subscription. User will see when contact is online,
-- contact will not see when user is online.
function subscribe(user_jid, contact_jid)
local user_username, user_host = jid.split(user_jid);
local contact_username, contact_host = jid.split(contact_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
if hosts[user_host].users.name == "null" then
storagemanager.initialize_host(user_host);
usermanager.initialize_host(user_host);
end
-- Update user's roster to say subscription request is pending...
rostermanager.set_contact_pending_out(user_username, user_host, contact_jid);
if hosts[contact_host] then
if contact_host ~= user_host and hosts[contact_host].users.name == "null" then
storagemanager.initialize_host(contact_host);
usermanager.initialize_host(contact_host);
end
-- Update contact's roster to say subscription request is pending...
rostermanager.set_contact_pending_in(contact_username, contact_host, user_jid);
-- Update contact's roster to say subscription request approved...
rostermanager.subscribed(contact_username, contact_host, user_jid);
-- Update user's roster to say subscription request approved...
rostermanager.process_inbound_subscription_approval(user_username, user_host, contact_jid);
end
end
-- Make a mutual subscription between jid1 and jid2. Each JID will see
-- when the other one is online.
function subscribe_both(jid1, jid2)
subscribe(jid1, jid2);
subscribe(jid2, jid1);
end
-- Unsubscribes user from contact (not contact from user, if subscribed).
function unsubscribe(user_jid, contact_jid)
local user_username, user_host = jid.split(user_jid);
local contact_username, contact_host = jid.split(contact_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
if hosts[user_host].users.name == "null" then
storagemanager.initialize_host(user_host);
usermanager.initialize_host(user_host);
end
-- Update user's roster to say subscription is cancelled...
rostermanager.unsubscribe(user_username, user_host, contact_jid);
if hosts[contact_host] then
if contact_host ~= user_host and hosts[contact_host].users.name == "null" then
storagemanager.initialize_host(contact_host);
usermanager.initialize_host(contact_host);
end
-- Update contact's roster to say subscription is cancelled...
rostermanager.unsubscribed(contact_username, contact_host, user_jid);
end
end
-- Cancel any subscription in either direction.
function unsubscribe_both(jid1, jid2)
unsubscribe(jid1, jid2);
unsubscribe(jid2, jid1);
end
-- Set the name shown and group used in the contact list
function rename(user_jid, contact_jid, contact_nick, contact_group)
local user_username, user_host = jid.split(user_jid);
if not hosts[user_host] then
warn("The host '%s' is not configured for this server.", user_host);
return;
end
if hosts[user_host].users.name == "null" then
storagemanager.initialize_host(user_host);
usermanager.initialize_host(user_host);
end
-- Load user's roster and find the contact
local roster = rostermanager.load_roster(user_username, user_host);
local item = roster[contact_jid];
if item then
if contact_nick then
item.name = contact_nick;
end
if contact_group then
item.groups = {}; -- Remove from all current groups
item.groups[contact_group] = true;
end
rostermanager.save_roster(user_username, user_host, roster);
end
end
function remove(user_jid, contact_jid)
unsubscribe_both(user_jid, contact_jid);
local user_username, user_host = jid.split(user_jid);
local roster = rostermanager.load_roster(user_username, user_host);
roster[contact_jid] = nil;
rostermanager.save_roster(user_username, user_host, roster);
end
function module.command(arg)
local command = arg[1];
if not command then
warn("Valid subcommands: (un)subscribe(_both) | rename");
return 0;
end
table.remove(arg, 1);
if command == "subscribe" then
subscribe(arg[1], arg[2]);
return 0;
elseif command == "subscribe_both" then
subscribe_both(arg[1], arg[2]);
return 0;
elseif command == "unsubscribe" then
unsubscribe(arg[1], arg[2]);
return 0;
elseif command == "unsubscribe_both" then
unsubscribe_both(arg[1], arg[2]);
return 0;
elseif command == "remove" then
remove(arg[1], arg[2]);
return 0;
elseif command == "rename" then
rename(arg[1], arg[2], arg[3], arg[4]);
return 0;
else
warn("Unknown command: %s", command);
return 1;
end
return 0;
end
| mit |
rollasoul/HaikuDenseCap | densecap/modules/PosSlicer.lua | 4 | 1939 | local layer, parent = torch.class('nn.PosSlicer', 'nn.Module')
--[[
A PosSlicer receives two inputs:
- features: Tensor of shape (N, d1, ..., dk)
- gt_features: Tensor of shape (P, e1, ..., en) or an empty Tensor
If gt_features is not empty, then return the first P rows of features
(along the first dimension). If gt_features is nil, then just return
features.
This operation is needed in the recognition network. At training time, the
LocalizationLayer produces both positive and negative regions of interest, with
the positive regions first in the minibatch. We only want to run the language
model and final box regression on the positive minibatch elements, so we use
the ground-truth box coordinates from the LocalizationLayer to figure out
how many positives there were in the minibatch.
At test time, we do not have access to ground-truth so the LocalizationLayer
produces nil for the ground-truth, and we want to run the language model and
box regression for all boxes.
--]]
function layer:__init()
parent.__init(self)
self.grad_features = torch.Tensor()
self.grad_gt_features = torch.Tensor()
end
function layer:updateOutput(input)
local features = input[1]
local gt_features = input[2]
if gt_features:nElement() == 0 then
self.output = features
else
local P = gt_features:size(1)
assert(P <= features:size(1), "Must have P <= N")
self.output = features[{{1, P}}]
end
return self.output
end
function layer:updateGradInput(input, gradOutput)
local features = input[1]
local gt_features = input[2]
self.grad_gt_features:resizeAs(gt_features):zero()
if gt_features:nElement() == 0 then
self.gradInput = {gradOutput, self.grad_gt_features}
else
local P = gt_features:size(1)
self.grad_features:resizeAs(features):zero()
self.grad_features[{{1, P}}]:copy(gradOutput)
self.gradInput = {self.grad_features, self.grad_gt_features}
end
return self.gradInput
end
| mit |
LightenPan/skynet-yule | yule/minesweeper/profile.lua | 1 | 1107 | local skynet = require "skynet"
local snax = require "snax"
local protobuf = require "protobuf"
local cmd2name = {
["s101_1"] = {reqname = "profilesvr_protos.GetUserInfoReq", rspname = "profilesvr_protos.GetUserInfoRsp"}
}
local command = {}
local PBCMD = {}
function PBCMD.s101_1(req)
oUserInfo = {user_id = "test", nick = "test_nick", level = 0, edge = 0}
rsp = {result = 0, user_info = oUserInfo}
LOG_INFO(tostring(oUserInfo))
return rsp
end
skynet.start(function()
skynet.dispatch("lua", function(_, _, cmd, data)
local name = cmd2name[cmd]
local req = protobuf.decode(name.reqname, data)
if not req then
LOG_INFO(string.format("protobuf.decode failed. cmd: %s, reqname: %s", cmd, name.reqname))
error(string.format("protobuf.decode failed. cmd: %s, reqname: %s", cmd, name.reqname))
end
local f = PBCMD[cmd]
if f then
local rsp = f(cshead, req)
local rspbody = protobuf.encode(name.rspname, rsp)
skynet.ret(skynet.pack(rspbody))
else
error(string.format("Unknown command %s", tostring(cmd)))
end
end)
protobuf.register_file "protocol/profilesvr.pb"
end)
| mit |
fegimanam/crd | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
punisherbot/ma | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
UB12/lion | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armveil.lua | 1 | 2451 | return {
armveil = {
acceleration = 0,
activatewhenbuilt = true,
brakerate = 0,
buildangle = 8192,
buildcostenergy = 17501,
buildcostmetal = 119,
buildinggrounddecaldecayspeed = 30,
buildinggrounddecalsizex = 4,
buildinggrounddecalsizey = 4,
buildinggrounddecaltype = "armveil_aoplane.dds",
buildpic = "ARMVEIL.DDS",
buildtime = 9080,
canattack = false,
category = "ALL NOTLAND NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE",
collisionvolumeoffsets = "0 0 0",
collisionvolumescales = "32 73 32",
collisionvolumetest = 1,
collisionvolumetype = "CylY",
corpse = "DEAD",
description = "Long-Range Jamming Tower",
energyuse = 125,
explodeas = "SMALL_BUILDINGEX",
footprintx = 2,
footprintz = 2,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
maxdamage = 750,
maxslope = 10,
maxwaterdepth = 0,
name = "Veil",
objectname = "ARMVEIL",
onoffable = true,
radardistancejam = 760,
seismicsignature = 0,
selfdestructas = "SMALL_BUILDING",
sightdistance = 155,
usebuildinggrounddecal = true,
usepiececollisionvolumes = 1,
yardmap = "oooo",
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "-7.16355133057 1.47216796904e-05 -4.91466522217",
collisionvolumescales = "47.5629425049 83.2464294434 33.8293304443",
collisionvolumetype = "Box",
damage = 450,
description = "Veil Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 2,
footprintz = 2,
height = 20,
hitdensity = 100,
metal = 77,
object = "ARMVEIL_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 225,
description = "Veil Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 2,
footprintz = 2,
height = 4,
hitdensity = 100,
metal = 31,
object = "2X2A",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "kbarmmov",
},
select = {
[1] = "radjam1",
},
},
},
}
| gpl-2.0 |
wesnoth/wesnoth | data/ai/micro_ais/cas/ca_big_animals.lua | 6 | 4084 | local AH = wesnoth.require "ai/lua/ai_helper.lua"
local LS = wesnoth.require "location_set"
local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua"
local function get_big_animals(cfg)
local big_animals = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and" , wml.get_child(cfg, "filter") }
}
return big_animals
end
local ca_big_animals = {}
function ca_big_animals:evaluation(cfg)
if get_big_animals(cfg)[1] then return cfg.ca_score end
return 0
end
function ca_big_animals:execution(cfg)
-- Big animals just move toward a goal that gets (re)set occasionally
-- and attack whatever is in their range (except for some units that they avoid)
local unit = get_big_animals(cfg)[1]
local avoid_tag = wml.get_child(cfg, "avoid_unit")
local avoid_map = LS.create()
if avoid_tag then
local enemies_to_be_avoided = AH.get_attackable_enemies(avoid_tag)
for _,enemy in ipairs(enemies_to_be_avoided) do
avoid_map:insert(enemy.x, enemy.y)
for xa,ya in wesnoth.current.map:iter_adjacent(enemy) do
avoid_map:insert(xa, ya)
end
end
end
local goal = MAIUV.get_mai_unit_variables(unit, cfg.ai_id)
-- Unit gets a new goal if none is set or on any move with a 10% random chance
local r = math.random(10)
if (not goal.goal_x) or (r == 1) then
local locs = AH.get_passable_locations(wml.get_child(cfg, "filter_location") or {})
local rand = math.random(#locs)
goal.goal_x, goal.goal_y = locs[rand][1], locs[rand][2]
MAIUV.set_mai_unit_variables(unit, cfg.ai_id, goal)
end
local reach_map = AH.get_reachable_unocc(unit)
local wander_terrain = wml.get_child(cfg, "filter_location_wander") or {}
-- Remove tiles that do not comform to the wander terrain filter
reach_map = reach_map:filter(function(x, y, v)
return wesnoth.map.matches(x, y, wander_terrain)
end)
-- Now find the one of these hexes that is closest to the goal
local max_rating, best_hex = - math.huge, nil
reach_map:iter( function(x, y, v)
local rating = -wesnoth.map.distance_between(x, y, goal.goal_x, goal.goal_y)
-- Proximity to an enemy unit is a plus
local enemy_hp = 500
for xa,ya in wesnoth.current.map:iter_adjacent(x, y) do
local enemy = wesnoth.units.get(xa, ya)
if AH.is_attackable_enemy(enemy) then
if (enemy.hitpoints < enemy_hp) then enemy_hp = enemy.hitpoints end
end
end
rating = rating + 500 - enemy_hp -- Prefer attack on weakest enemy
-- Hexes reachable by units to be be avoided get a massive negative hit
if avoid_map:get(x, y) then rating = rating - 1000 end
if (rating > max_rating) then
max_rating, best_hex = rating, { x, y }
end
end)
if (best_hex[1] ~= unit.x) or (best_hex[2] ~= unit.y) then
AH.checked_move(ai, unit, best_hex[1], best_hex[2]) -- Partial move only
if (not unit) or (not unit.valid) then return end
else -- If unit did not move, we need to stop it (also delete the goal)
AH.checked_stopunit_moves(ai, unit)
if (not unit) or (not unit.valid) then return end
MAIUV.delete_mai_unit_variables(unit, cfg.ai_id)
end
-- If this gets the unit to the goal, we also delete the goal
if (unit.x == goal.goal_x) and (unit.y == goal.goal_y) then
MAIUV.delete_mai_unit_variables(unit, cfg.ai_id)
end
-- Finally, if the unit ended up next to enemies, attack the weakest of those
local min_hp, target = math.huge, nil
for xa,ya in wesnoth.current.map:iter_adjacent(unit) do
local enemy = wesnoth.units.get(xa, ya)
if AH.is_attackable_enemy(enemy) then
if (enemy.hitpoints < min_hp) then
min_hp, target = enemy.hitpoints, enemy
end
end
end
if target then
AH.checked_attack(ai, unit, target)
end
end
return ca_big_animals
| gpl-2.0 |
imashkan/ABCYAGOP | plugins/twitter_send.lua | 627 | 1555 | do
local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function run(msg, matches)
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/twitter_send.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua"
end
if not is_sudo(msg) then
return "You aren't allowed to send tweets"
end
local response_code, response_headers, response_status_line, response_body =
client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", {
status = matches[1]
})
if response_code ~= 200 then
return "Error: "..response_code
end
return "Tweet sent"
end
return {
description = "Sends a tweet",
usage = "!tw [text]: Sends the Tweet with the configured account.",
patterns = {"^!tw (.+)"},
run = run
}
end
| gpl-2.0 |
flavorzyb/cocos2d-x | scripting/lua/luajit/LuaJIT-2.0.1/src/host/genminilua.lua | 73 | 11943 | ----------------------------------------------------------------------------
-- Lua script to generate a customized, minified version of Lua.
-- The resulting 'minilua' is used for the build process of LuaJIT.
----------------------------------------------------------------------------
-- Copyright (C) 2005-2013 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
local sub, match, gsub = string.sub, string.match, string.gsub
local LUA_VERSION = "5.1.5"
local LUA_SOURCE
local function usage()
io.stderr:write("Usage: ", arg and arg[0] or "genminilua",
" lua-", LUA_VERSION, "-source-dir\n")
os.exit(1)
end
local function find_sources()
LUA_SOURCE = arg and arg[1]
if not LUA_SOURCE then usage() end
if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end
local fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then
LUA_SOURCE = LUA_SOURCE.."src/"
fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then usage() end
end
local all = fp:read("*a")
fp:close()
if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then
io.stderr:write("Error: version mismatch\n")
usage()
end
end
local LUA_FILES = {
"lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c",
"lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c",
"llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c",
"lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c",
}
local REMOVE_LIB = {}
gsub([[
collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset
select tostring xpcall
foreach foreachi getn maxn setn
popen tmpfile seek setvbuf __tostring
clock date difftime execute getenv rename setlocale time tmpname
dump gfind len reverse
LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME
]], "%S+", function(name)
REMOVE_LIB[name] = true
end)
local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, }
local CUSTOM_MAIN = [[
typedef unsigned int UB;
static UB barg(lua_State *L,int idx){
union{lua_Number n;U64 b;}bn;
bn.n=lua_tonumber(L,idx)+6755399441055744.0;
if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number");
return(UB)bn.b;
}
#define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1;
static int tobit(lua_State *L){
BRET(barg(L,1))}
static int bnot(lua_State *L){
BRET(~barg(L,1))}
static int band(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)}
static int bor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)}
static int bxor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)}
static int lshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)}
static int rshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)}
static int arshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)}
static int rol(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))}
static int ror(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))}
static int bswap(lua_State *L){
UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)}
static int tohex(lua_State *L){
UB b=barg(L,1);
int n=lua_isnone(L,2)?8:(int)barg(L,2);
const char *hexdigits="0123456789abcdef";
char buf[8];
int i;
if(n<0){n=-n;hexdigits="0123456789ABCDEF";}
if(n>8)n=8;
for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;}
lua_pushlstring(L,buf,(size_t)n);
return 1;
}
static const struct luaL_Reg bitlib[] = {
{"tobit",tobit},
{"bnot",bnot},
{"band",band},
{"bor",bor},
{"bxor",bxor},
{"lshift",lshift},
{"rshift",rshift},
{"arshift",arshift},
{"rol",rol},
{"ror",ror},
{"bswap",bswap},
{"tohex",tohex},
{NULL,NULL}
};
int main(int argc, char **argv){
lua_State *L = luaL_newstate();
int i;
luaL_openlibs(L);
luaL_register(L, "bit", bitlib);
if (argc < 2) return sizeof(void *);
lua_createtable(L, 0, 1);
lua_pushstring(L, argv[1]);
lua_rawseti(L, -2, 0);
lua_setglobal(L, "arg");
if (luaL_loadfile(L, argv[1]))
goto err;
for (i = 2; i < argc; i++)
lua_pushstring(L, argv[i]);
if (lua_pcall(L, argc - 2, 0, 0)) {
err:
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
return 1;
}
lua_close(L);
return 0;
}
]]
local function read_sources()
local t = {}
for i, name in ipairs(LUA_FILES) do
local fp = assert(io.open(LUA_SOURCE..name, "r"))
t[i] = fp:read("*a")
assert(fp:close())
end
t[#t+1] = CUSTOM_MAIN
return table.concat(t)
end
local includes = {}
local function merge_includes(src)
return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name)
if includes[name] then return "" end
includes[name] = true
local fp = assert(io.open(LUA_SOURCE..name, "r"))
local src = fp:read("*a")
assert(fp:close())
src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "")
src = gsub(src, "#endif%s*$", "")
return merge_includes(src)
end)
end
local function get_license(src)
return match(src, "/%*+\n%* Copyright %(.-%*/\n")
end
local function fold_lines(src)
return gsub(src, "\\\n", " ")
end
local strings = {}
local function save_str(str)
local n = #strings+1
strings[n] = str
return "\1"..n.."\2"
end
local function save_strings(src)
src = gsub(src, '"[^"\n]*"', save_str)
return gsub(src, "'[^'\n]*'", save_str)
end
local function restore_strings(src)
return gsub(src, "\1(%d+)\2", function(numstr)
return strings[tonumber(numstr)]
end)
end
local function def_istrue(def)
return def == "INT_MAX > 2147483640L" or
def == "LUAI_BITSINT >= 32" or
def == "SIZE_Bx < LUAI_BITSINT-1" or
def == "cast" or
def == "defined(LUA_CORE)" or
def == "MINSTRTABSIZE" or
def == "LUA_MINBUFFER" or
def == "HARDSTACKTESTS" or
def == "UNUSED"
end
local head, defs = {[[
#ifdef _MSC_VER
typedef unsigned __int64 U64;
#else
typedef unsigned long long U64;
#endif
]]}, {}
local function preprocess(src)
local t = { match(src, "^(.-)#") }
local lvl, on, oldon = 0, true, {}
for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do
if pp == "if" or pp == "ifdef" or pp == "ifndef" then
lvl = lvl + 1
oldon[lvl] = on
on = def_istrue(def)
elseif pp == "else" then
if oldon[lvl] then
if on == false then on = true else on = false end
end
elseif pp == "elif" then
if oldon[lvl] then
on = def_istrue(def)
end
elseif pp == "endif" then
on = oldon[lvl]
lvl = lvl - 1
elseif on then
if pp == "include" then
if not head[def] and not REMOVE_EXTINC[def] then
head[def] = true
head[#head+1] = "#include "..def.."\n"
end
elseif pp == "define" then
local k, sp, v = match(def, "([%w_]+)(%s*)(.*)")
if k and not (sp == "" and sub(v, 1, 1) == "(") then
defs[k] = gsub(v, "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
else
t[#t+1] = "#define "..def.."\n"
end
elseif pp ~= "undef" then
error("unexpected directive: "..pp.." "..def)
end
end
if on then t[#t+1] = txt end
end
return gsub(table.concat(t), "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
end
local function merge_header(src, license)
local hdr = string.format([[
/* This is a heavily customized and minimized copy of Lua %s. */
/* It's only used to build LuaJIT. It does NOT have all standard functions! */
]], LUA_VERSION)
return hdr..license..table.concat(head)..src
end
local function strip_unused1(src)
return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func)
return REMOVE_LIB[func] and "" or line
end)
end
local function strip_unused2(src)
return gsub(src, "Symbolic Execution.-}=", "")
end
local function strip_unused3(src)
src = gsub(src, "extern", "static")
src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(")
src = gsub(src, "#define lua_assert[^\n]*\n", "")
src = gsub(src, "lua_assert%b();?", "")
src = gsub(src, "default:\n}", "default:;\n}")
src = gsub(src, "lua_lock%b();", "")
src = gsub(src, "lua_unlock%b();", "")
src = gsub(src, "luai_threadyield%b();", "")
src = gsub(src, "luai_userstateopen%b();", "{}")
src = gsub(src, "luai_userstate%w+%b();", "")
src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser")
src = gsub(src, "trydecpoint%(ls,seminfo%)",
"luaX_lexerror(ls,\"malformed number\",TK_NUMBER)")
src = gsub(src, "int c=luaZ_lookahead%b();", "")
src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;",
"return 1;")
src = gsub(src, "getfuncname%b():", "NULL:")
src = gsub(src, "getobjname%b():", "NULL:")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "")
src = gsub(src, "(twoto%b()%()", "%1(size_t)")
src = gsub(src, "i<sizenode", "i<(int)sizenode")
return gsub(src, "\n\n+", "\n")
end
local function strip_comments(src)
return gsub(src, "/%*.-%*/", " ")
end
local function strip_whitespace(src)
src = gsub(src, "^%s+", "")
src = gsub(src, "%s*\n%s*", "\n")
src = gsub(src, "[ \t]+", " ")
src = gsub(src, "(%W) ", "%1")
return gsub(src, " (%W)", "%1")
end
local function rename_tokens1(src)
src = gsub(src, "getline", "getline_")
src = gsub(src, "struct ([%w_]+)", "ZX%1")
return gsub(src, "union ([%w_]+)", "ZY%1")
end
local function rename_tokens2(src)
src = gsub(src, "ZX([%w_]+)", "struct %1")
return gsub(src, "ZY([%w_]+)", "union %1")
end
local function func_gather(src)
local nodes, list = {}, {}
local pos, len = 1, #src
while pos < len do
local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos)
if d then
local n = #list+1
list[n] = d
nodes[w] = n
else
local s
d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos)
if not d then
d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos)
if not d then d = match(src, "^[^\n]*\n", pos) end
end
if s == "{" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
if sub(d, -2) == "{\n" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
end
end
local k, v = nil, d
if w == "typedef" then
if match(d, "^typedef enum") then
head[#head+1] = d
else
k = match(d, "([%w_]+);\n$")
if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end
end
elseif w == "enum" then
head[#head+1] = v
elseif w ~= nil then
k = match(d, "^[^\n]-([%w_]+)[(%[=]")
if k then
if w ~= "static" and k ~= "main" then v = "static "..d end
else
k = w
end
end
if w and k then
local o = nodes[k]
if o then nodes["*"..k] = o end
local n = #list+1
list[n] = v
nodes[k] = n
end
end
pos = pos + #d
end
return nodes, list
end
local function func_visit(nodes, list, used, n)
local i = nodes[n]
for m in string.gmatch(list[i], "[%w_]+") do
if nodes[m] then
local j = used[m]
if not j then
used[m] = i
func_visit(nodes, list, used, m)
elseif i < j then
used[m] = i
end
end
end
end
local function func_collect(src)
local nodes, list = func_gather(src)
local used = {}
func_visit(nodes, list, used, "main")
for n,i in pairs(nodes) do
local j = used[n]
if j and j < i then used["*"..n] = j end
end
for n,i in pairs(nodes) do
if not used[n] then list[i] = "" end
end
return table.concat(list)
end
find_sources()
local src = read_sources()
src = merge_includes(src)
local license = get_license(src)
src = fold_lines(src)
src = strip_unused1(src)
src = save_strings(src)
src = strip_unused2(src)
src = strip_comments(src)
src = preprocess(src)
src = strip_whitespace(src)
src = strip_unused3(src)
src = rename_tokens1(src)
src = func_collect(src)
src = rename_tokens2(src)
src = restore_strings(src)
src = merge_header(src, license)
io.write(src)
| gpl-2.0 |
MinaciousGrace/Til-Death | Scripts/TabManager.lua | 1 | 2082 |
-- Tabs are 0 indexed
local tabIndex = 0
local tabSize = 5
local availTabSize = 2
local availableTabs1P = {true,false,true,false,false,false}
local availableTabs2P = {true,false,false,false,true}
--0 indexed tabs... yet 1 indexed lua tables mfw. Will probably go into infinite loop if everything is false.
-- Recursively grabs the next available tab. Looping around to start if needed.
local function getNextAvailable(players,index)
local table = {}
if players == 1 then
table = availableTabs1P
else
table = availableTabs2P
end;
if table[index+1] == true then
return index
else
return getNextAvailable(players,(index+1)%tabSize)
end;
end;
-- Resets the index of the tabs to 0
function resetTabIndex()
tabIndex = 0
end;
function setTabIndex(index)
if GAMESTATE:GetNumPlayersEnabled() == 1 then
if availableTabs1P[index+1] then
tabIndex = index
end;
else
if availableTabs2P[index+1] then
tabIndex = index
end;
end;
end;
-- Incements the tab index by 1 given the tab is available.
function incrementTabIndex()
local players = GAMESTATE:GetNumPlayersEnabled()
tabIndex = (tabIndex+1)%tabSize
if players == 1 and availableTabs1P[tabIndex+1] == false then
tabIndex = getNextAvailable(players,tabIndex+1)%tabSize
end;
if players > 1 and availableTabs2P[tabIndex+1] == false then
tabIndex = getNextAvailable(players,tabIndex+1)%tabSize
end;
end;
-- Returns the current tab index
function getTabIndex()
return tabIndex
end;
-- Returns the total number of tabs
function getTabSize()
return tabSize
end;
-- Returns the highest index out of all available tabs
function getMaxAvailIndex()
local high = 0
local table = 0
if GAMESTATE:GetNumPlayersEnabled() == 1 then
table = availableTabs1P
else
table = availableTabs2P
end;
for k,v in ipairs(table) do
if v == true then
high = math.max(high,k)
end
end
return high
end;
-- Returns whether a certain tab is enabled
function isTabEnabled(index)
if GAMESTATE:GetNumPlayersEnabled() == 1 then
return availableTabs1P[index]
else
return availableTabs2P[index]
end;
end;
| mit |
gbox3d/nodemcu-firmware | examples/telnet.lua | 5 | 1067 | print("====Wicon, a LUA console over wifi.==========")
print("Author: openthings@163.com. copyright&GPL V2.")
print("Last modified 2014-11-19. V0.2")
print("Wicon Server starting ......")
function startServer()
print("Wifi AP connected. Wicon IP:")
print(wifi.sta.getip())
sv=net.createServer(net.TCP, 180)
sv:listen(8080, function(conn)
print("Wifi console connected.")
function s_output(str)
if (conn~=nil) then
conn:send(str)
end
end
node.output(s_output,0)
conn:on("receive", function(conn, pl)
node.input(pl)
if (conn==nil) then
print("conn is nil.")
end
end)
conn:on("disconnection",function(conn)
node.output(nil)
end)
end)
print("Wicon Server running at :8080")
print("===Now,Using xcon_tcp logon and input LUA.====")
end
tmr.alarm(1000, 1, function()
if wifi.sta.getip()=="0.0.0.0" then
print("Connect AP, Waiting...")
else
startServer()
tmr.stop()
end
end)
| mit |
LanceJenkinZA/prosody-modules | mod_mam/mamprefsxml.lib.lua | 36 | 1467 | -- XEP-0313: Message Archive Management for Prosody
-- Copyright (C) 2011-2013 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require"util.stanza";
local xmlns_mam = "urn:xmpp:mam:0";
local global_default_policy = module:get_option("default_archive_policy", false);
local default_attrs = {
always = true, [true] = "always",
never = false, [false] = "never",
roster = "roster",
}
local function tostanza(prefs)
local default = prefs[false];
default = default ~= nil and default_attrs[default] or global_default_policy;
local prefstanza = st.stanza("prefs", { xmlns = xmlns_mam, default = default });
local always = st.stanza("always");
local never = st.stanza("never");
for jid, choice in pairs(prefs) do
if jid then
(choice and always or never):tag("jid"):text(jid):up();
end
end
prefstanza:add_child(always):add_child(never);
return prefstanza;
end
local function fromstanza(prefstanza)
local prefs = {};
local default = prefstanza.attr.default;
if default then
prefs[false] = default_attrs[default];
end
local always = prefstanza:get_child("always");
if always then
for rule in always:childtags("jid") do
local jid = rule:get_text();
prefs[jid] = true;
end
end
local never = prefstanza:get_child("never");
if never then
for rule in never:childtags("jid") do
local jid = rule:get_text();
prefs[jid] = false;
end
end
return prefs;
end
return {
tostanza = tostanza;
fromstanza = fromstanza;
}
| mit |
ivendrov/nn | JoinTable.lua | 25 | 1958 | local JoinTable, parent = torch.class('nn.JoinTable', 'nn.Module')
function JoinTable:__init(dimension, nInputDims)
parent.__init(self)
self.size = torch.LongStorage()
self.dimension = dimension
self.gradInput = {}
self.nInputDims = nInputDims
end
function JoinTable:updateOutput(input)
local dimension = self.dimension
if self.nInputDims and input[1]:dim()==(self.nInputDims+1) then
dimension = dimension + 1
end
for i=1,#input do
local currentOutput = input[i]
if i == 1 then
self.size:resize(currentOutput:dim()):copy(currentOutput:size())
else
self.size[dimension] = self.size[dimension]
+ currentOutput:size(dimension)
end
end
self.output:resize(self.size)
local offset = 1
for i=1,#input do
local currentOutput = input[i]
self.output:narrow(dimension, offset,
currentOutput:size(dimension)):copy(currentOutput)
offset = offset + currentOutput:size(dimension)
end
return self.output
end
function JoinTable:updateGradInput(input, gradOutput)
local dimension = self.dimension
if self.nInputDims and input[1]:dim()==(self.nInputDims+1) then
dimension = dimension + 1
end
for i=1,#input do
if self.gradInput[i] == nil then
self.gradInput[i] = input[i].new()
end
self.gradInput[i]:resizeAs(input[i])
end
-- clear out invalid gradInputs
for i=#input+1, #self.gradInput do
self.gradInput[i] = nil
end
local offset = 1
for i=1,#input do
local currentOutput = input[i]
local currentGradInput = gradOutput:narrow(dimension, offset,
currentOutput:size(dimension))
self.gradInput[i]:copy(currentGradInput)
offset = offset + currentOutput:size(dimension)
end
return self.gradInput
end
function JoinTable:type(type, tensorCache)
self.gradInput = {}
return parent.type(self, type, tensorCache)
end
| bsd-3-clause |
Dahkelor/theorycraft | dep/recastnavigation/RecastDemo/premake4.lua | 82 | 3551 | --
-- premake4 file to build RecastDemo
-- http://industriousone.com/premake
--
local action = _ACTION or ""
local todir = "Build/" .. action
solution "recastnavigation"
configurations {
"Debug",
"Release"
}
location (todir)
-- extra warnings, no exceptions or rtti
flags {
"ExtraWarnings",
"FloatFast",
"NoExceptions",
"NoRTTI",
"Symbols"
}
-- debug configs
configuration "Debug*"
defines { "DEBUG" }
targetdir ( todir .. "/lib/Debug" )
-- release configs
configuration "Release*"
defines { "NDEBUG" }
flags { "Optimize" }
targetdir ( todir .. "/lib/Release" )
-- windows specific
configuration "windows"
defines { "WIN32", "_WINDOWS", "_CRT_SECURE_NO_WARNINGS" }
project "DebugUtils"
language "C++"
kind "StaticLib"
includedirs {
"../DebugUtils/Include",
"../Detour/Include",
"../DetourTileCache/Include",
"../Recast/Include"
}
files {
"../DebugUtils/Include/*.h",
"../DebugUtils/Source/*.cpp"
}
project "Detour"
language "C++"
kind "StaticLib"
includedirs {
"../Detour/Include"
}
files {
"../Detour/Include/*.h",
"../Detour/Source/*.cpp"
}
project "DetourCrowd"
language "C++"
kind "StaticLib"
includedirs {
"../DetourCrowd/Include",
"../Detour/Include",
"../Recast/Include"
}
files {
"../DetourCrowd/Include/*.h",
"../DetourCrowd/Source/*.cpp"
}
project "DetourTileCache"
language "C++"
kind "StaticLib"
includedirs {
"../DetourTileCache/Include",
"../Detour/Include",
"../Recast/Include"
}
files {
"../DetourTileCache/Include/*.h",
"../DetourTileCache/Source/*.cpp"
}
project "Recast"
language "C++"
kind "StaticLib"
includedirs {
"../Recast/Include"
}
files {
"../Recast/Include/*.h",
"../Recast/Source/*.cpp"
}
project "RecastDemo"
language "C++"
kind "WindowedApp"
includedirs {
"../RecastDemo/Include",
"../RecastDemo/Contrib",
"../RecastDemo/Contrib/fastlz",
"../DebugUtils/Include",
"../Detour/Include",
"../DetourCrowd/Include",
"../DetourTileCache/Include",
"../Recast/Include"
}
files {
"../RecastDemo/Include/*.h",
"../RecastDemo/Source/*.cpp",
"../RecastDemo/Contrib/fastlz/*.h",
"../RecastDemo/Contrib/fastlz/*.c"
}
-- project dependencies
links {
"DebugUtils",
"Detour",
"DetourCrowd",
"DetourTileCache",
"Recast"
}
-- distribute executable in RecastDemo/Bin directory
targetdir "Bin"
-- linux library cflags and libs
configuration { "linux", "gmake" }
buildoptions {
"`pkg-config --cflags sdl`",
"`pkg-config --cflags gl`",
"`pkg-config --cflags glu`"
}
linkoptions {
"`pkg-config --libs sdl`",
"`pkg-config --libs gl`",
"`pkg-config --libs glu`"
}
-- windows library cflags and libs
configuration { "windows" }
includedirs { "../RecastDemo/Contrib/SDL/include" }
libdirs { "../RecastDemo/Contrib/SDL/lib/x86" }
links {
"opengl32",
"glu32",
"sdlmain",
"sdl"
}
-- mac includes and libs
configuration { "macosx" }
kind "ConsoleApp" -- xcode4 failes to run the project if using WindowedApp
includedirs { "/Library/Frameworks/SDL.framework/Headers" }
buildoptions { "-Wunused-value -Wshadow -Wreorder -Wsign-compare -Wall" }
links {
"OpenGL.framework",
"/Library/Frameworks/SDL.framework",
"Cocoa.framework",
}
files {
"../RecastDemo/Include/SDLMain.h",
"../RecastDemo/Source/SDLMain.m",
-- These don't seem to work in xcode4 target yet.
-- "Info.plist",
-- "Icon.icns",
-- "English.lproj/InfoPlist.strings",
-- "English.lproj/MainMenu.xib",
}
| gpl-2.0 |
wesnoth/wesnoth | data/ai/micro_ais/cas/ca_healer_move.lua | 6 | 5392 | local AH = wesnoth.require "ai/lua/ai_helper.lua"
local BC = wesnoth.require "ai/lua/battle_calcs.lua"
local M = wesnoth.map
local ca_healer_move, best_healer, best_hex = {}, nil, nil
function ca_healer_move:evaluation(cfg, data)
-- Should happen with higher priority than attacks, except at beginning of turn,
-- when we want attacks (by other units) done first
-- This is done so that it is possible for healers to attack, if they do not
-- find an appropriate hex to back up other units
local score = data.HS_healer_move_score or 105000
local all_healers = wesnoth.units.find_on_map {
side = wesnoth.current.side,
ability = "healing",
{ "and", wml.get_child(cfg, "filter") }
}
local healers, healers_noMP = {}, {}
for _,healer in ipairs(all_healers) do
-- For the purpose of this evaluation, guardians count as units without moves, as do passive leaders
if (healer.moves > 0) and (not healer.status.guardian)
and ((not healer.canrecruit) or (not ai.aspects.passive_leader))
then
table.insert(healers, healer)
else
table.insert(healers_noMP, healer)
end
end
if (not healers[1]) then return 0 end
local all_healees = wesnoth.units.find_on_map {
side = wesnoth.current.side,
{ "and", wml.get_child(cfg, "filter_second") }
}
local healees, healees_MP = {}, {}
for _,healee in ipairs(all_healees) do
-- Potential healees are units without MP that don't already have a healer (also without MP) next to them
-- Also, they cannot be on a healing location or regenerate
if (healee.moves == 0) then
if (not healee:matches { ability = "regenerates" }) then
local healing = wesnoth.terrain_types[wesnoth.current.map[healee]].healing
if (healing == 0) then
local is_healee = true
for _,healer in ipairs(healers_noMP) do
if (M.distance_between(healee.x, healee.y, healer.x, healer.y) == 1) then
is_healee = false
break
end
end
if is_healee then table.insert(healees, healee) end
end
end
else
table.insert(healees_MP, healee)
end
end
local enemies = AH.get_attackable_enemies()
for _,healee in ipairs(healees_MP) do healee:extract() end
local enemy_attack_map = BC.get_attack_map(enemies)
for _,healee in ipairs(healees_MP) do healee:to_map() end
-- Other options of adding avoid zones may be added later
local avoid_map = AH.get_avoid_map(ai, nil, true)
local max_rating = - math.huge
for _,healer in ipairs(healers) do
local reach_map = AH.get_reachmap(healer, { avoid_map = avoid_map, exclude_occupied = true })
reach_map:iter( function(x, y, v)
-- Only consider hexes that are next to at least one noMP unit that
-- - either can be attacked by an enemy (15 points per enemy)
-- - or has non-perfect HP (1 point per missing HP)
local rating, adjacent_healer = 0, nil
for _,healee in ipairs(healees) do
if (M.distance_between(healee.x, healee.y, x, y) == 1) then
-- Note: These ratings have to be positive or the method doesn't work
rating = rating + healee.max_hitpoints - healee.hitpoints
-- If injured_units_only = true then don't count units with full HP
if (healee.max_hitpoints - healee.hitpoints > 0) or (not cfg.injured_units_only) then
rating = rating + 15 * (enemy_attack_map.units:get(healee.x, healee.y) or 0)
end
end
end
-- Number of enemies that can threaten the healer at that position
-- This has to be no larger than cfg.max_threats for hex to be considered
local enemies_in_reach = enemy_attack_map.units:get(x, y) or 0
-- If this hex fulfills those requirements, 'rating' is now greater than 0
-- and we do the rest of the rating, otherwise set rating to below max_rating
if (rating == 0) or (enemies_in_reach > (cfg.max_threats or 9999)) then
rating = max_rating - 1
else
-- Strongly discourage hexes that can be reached by enemies
rating = rating - enemies_in_reach * 1000
-- All else being more or less equal, prefer villages and strong terrain
local terrain = wesnoth.current.map[{x, y}]
local is_village = wesnoth.terrain_types[terrain].village
if is_village then rating = rating + 2 end
local defense = healer:defense_on(terrain)
rating = rating + defense / 10.
end
if (rating > max_rating) then
max_rating, best_healer, best_hex = rating, healer, { x, y }
end
end)
end
if best_healer then
return score
end
return 0
end
function ca_healer_move:execution(cfg)
AH.robust_move_and_attack(ai, best_healer, best_hex)
best_healer, best_hex = nil, nil
end
return ca_healer_move
| gpl-2.0 |
TheMarex/delightful | delightful/widgets/cpu.lua | 1 | 5770 | -------------------------------------------------------------------------------
--
-- CPU widget for Awesome 3.4
-- Copyright (C) 2011 Tuomas Jormola <tj@solitudo.net>
--
-- Licensed under the terms of GNU General Public License Version 2.0.
--
-- Description:
--
-- Displays horizontal usage trend graph of all the CPUs combined.
-- Also displays a CPU icon next to the graph. Clicking the icon
-- launches an external application (if configured).
--
-- Widget extends vicious.widgets.cpu from Vicious widget framework.
--
-- Widget tries to use an icon from the package sensors-applet
-- if available.
--
--
-- Configuration:
--
-- The load() function can be supplied with configuration.
-- Format of the configuration is as follows.
-- {
-- -- Width of the graph in pixels. Default is 20.
-- graph_width = 50,
-- -- Command to execute when left-clicking the widget icon.
-- -- Empty by default.
-- command = 'gnome-system-monitor',
-- -- Don't try to display any icons. Default is false (i.e. display icons).
-- no_icon = true,
-- -- How often update the widget data. Default is 1 second.
-- update_interval = 2
-- }
--
--
-- Theme:
--
-- The widget uses following colors and icons if available in
-- the Awesome theme.
--
-- theme.bg_widget - widget background color
-- theme.fg_widget - widget foreground color
-- theme.fg_center_widget - widget gradient color, middle
-- theme.fg_end_widget - widget gradient color, end
-- theme.delightful_cpu - icon shown next to the CPU graph
---
-------------------------------------------------------------------------------
local awful_button = require('awful.button')
local awful_tooltip = require('awful.tooltip')
local awful_util = require('awful.util')
local awful_widget = require('awful.widget')
local wibox = require('wibox')
local delightful_utils = require('delightful.utils')
local vicious = require('vicious')
local pairs = pairs
local string = { format = string.format }
module('delightful.widgets.cpu')
local cpu_config
local fatal_error
local icon_tooltip
local config_description = {
{
name = 'graph_width',
required = true,
default = 20,
validate = function(value) return delightful_utils.config_int(value) end
},
{
name = 'command',
validate = function(value) return delightful_utils.config_string(value) end
},
{
name = 'no_icon',
validate = function(value) return delightful_utils.config_boolean(value) end
},
{
name = 'update_interval',
required = true,
default = 1,
validate = function(value) return delightful_utils.config_int(value) end
},
}
local icon_description = {
cpu = { beautiful_name = 'delightful_cpu', default_icon = function() return 'sensors-applet-cpu' end },
}
-- Configuration handler
function handle_config(user_config)
local empty_config = delightful_utils.get_empty_config(config_description)
if not user_config then
user_config = empty_config
end
local config_data = delightful_utils.normalize_config(user_config, config_description)
local validation_errors = delightful_utils.validate_config(config_data, config_description)
if validation_errors then
fatal_error = 'Configuration errors: \n'
for error_index, error_entry in pairs(validation_errors) do
fatal_error = string.format('%s %s', fatal_error, error_entry)
if error_index < #validation_errors then
fatal_error = string.format('%s \n', fatal_error)
end
end
cpu_config = empty_config
return
end
cpu_config = config_data
end
-- Initalization
function load(self, config)
handle_config(config)
if fatal_error then
delightful_utils.print_error('cpu', fatal_error)
return nil, nil
end
local icon
local icon_files
if not cpu_config.no_icon then
icon_files = delightful_utils.find_icon_files(icon_description)
end
local icon_file = icon_files and icon_files.cpu
if icon_file then
if icon_data then
local buttons = awful_button({}, 1, function()
if not fatal_error and cpu_config.command then
awful_util.spawn(cpu_config.command, true)
end
end)
icon = wibox.widget.imagebox()
icon:buttons(buttons)
icon:set_image(icon_file)
icon_tooltip = awful_tooltip({ objects = { icon } })
end
end
local bg_color = delightful_utils.find_theme_color({ 'bg_widget', 'bg_normal' })
local fg_color = delightful_utils.find_theme_color({ 'fg_widget', 'fg_normal' })
local fg_center_color = delightful_utils.find_theme_color({ 'fg_center_widget', 'fg_widget', 'fg_normal' })
local fg_end_color = delightful_utils.find_theme_color({ 'fg_end_widget', 'fg_widget', 'fg_normal' })
local cpu_widget = awful_widget.graph({ layout = awful_widget.layout.horizontal.rightleft })
if bg_color then
cpu_widget:set_background_color(bg_color)
cpu_widget:set_border_color(bg_color)
end
if fg_color then
cpu_widget:set_color(fg_color)
end
if fg_color and fg_center_color and fg_end_color then
cpu_widget:set_color({ type = "linear", from = { 0, 0 }, to = { 19, 0 }, stops = { { 0, fg_color }, { 0.5, fg_center_color }, { 1, fg_end_color} }})
end
cpu_widget:set_width(cpu_config.graph_width)
cpu_widget:set_height(19)
cpu_widget:set_gradient_angle(180)
vicious.register(cpu_widget, vicious.widgets.cpu, vicious_formatter, cpu_config.update_interval)
return { cpu_widget }, { icon }
end
-- Vicious display formatter, also update widget tooltip
function vicious_formatter(widget, data)
if icon_tooltip then
local tooltip_text = string.format(' CPU usage trend graph of all the CPUs in the system \n Current CPU usage: %d%% ', data[1])
icon_tooltip:set_text(tooltip_text)
end
return data[1]
end
| gpl-2.0 |
helingping/Urho3D | bin/Data/LuaScripts/15_Navigation.lua | 5 | 19734 | -- Navigation example.
-- This sample demonstrates:
-- - Generating a navigation mesh into the scene
-- - Performing path queries to the navigation mesh
-- - Rebuilding the navigation mesh partially when adding or removing objects
-- - Visualizing custom debug geometry
-- - Raycasting drawable components
-- - Making a node follow the Detour path
require "LuaScripts/Utilities/Sample"
local endPos = nil
local currentPath = {}
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateUI()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Hook up to the frame update and render post-update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
-- Also create a DebugRenderer component so that we can draw debug geometry
scene_:CreateComponent("Octree")
scene_:CreateComponent("DebugRenderer")
-- Create scene node & StaticModel component for showing a static plane
local planeNode = scene_:CreateChild("Plane")
planeNode.scale = Vector3(100.0, 1.0, 100.0)
local planeObject = planeNode:CreateComponent("StaticModel")
planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
-- Create a Zone component for ambient lighting & fog control
local zoneNode = scene_:CreateChild("Zone")
local zone = zoneNode:CreateComponent("Zone")
zone.boundingBox = BoundingBox(-1000.0, 1000.0)
zone.ambientColor = Color(0.15, 0.15, 0.15)
zone.fogColor = Color(0.5, 0.5, 0.7)
zone.fogStart = 100.0
zone.fogEnd = 300.0
-- Create a directional light to the world. Enable cascaded shadows on it
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(0.6, -1.0, 0.8)
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
light.castShadows = true
light.shadowBias = BiasParameters(0.00025, 0.5)
-- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
-- Create some mushrooms
local NUM_MUSHROOMS = 100
for i = 1, NUM_MUSHROOMS do
CreateMushroom(Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0))
end
-- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
-- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
local NUM_BOXES = 20
for i = 1, NUM_BOXES do
local boxNode = scene_:CreateChild("Box")
local size = 1.0 + Random(10.0)
boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0)
boxNode:SetScale(size)
local boxObject = boxNode:CreateComponent("StaticModel")
boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
boxObject.material = cache:GetResource("Material", "Materials/Stone.xml")
boxObject.castShadows = true
if size >= 3.0 then
boxObject.occluder = true
end
end
-- Create Jack node that will follow the path
jackNode = scene_:CreateChild("Jack")
jackNode.position = Vector3(-5, 0, 20)
local modelObject = jackNode:CreateComponent("AnimatedModel")
modelObject.model = cache:GetResource("Model", "Models/Jack.mdl")
modelObject.material = cache:GetResource("Material", "Materials/Jack.xml")
modelObject.castShadows = true
-- Create a NavigationMesh component to the scene root
local navMesh = scene_:CreateComponent("NavigationMesh")
-- Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the
-- navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable
scene_:CreateComponent("Navigable")
-- Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes
-- in the scene and still update the mesh correctly
navMesh.padding = Vector3(0.0, 10.0, 0.0)
-- Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use
-- physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example)
-- it will use renderable geometry instead
navMesh:Build()
-- Create the camera. Limit far clip distance to match the fog
cameraNode = scene_:CreateChild("Camera")
local camera = cameraNode:CreateComponent("Camera")
camera.farClip = 300.0
-- Set an initial position for the camera scene node above the plane and looking down
cameraNode.position = Vector3(0.0, 50.0, 0.0)
pitch = 80.0
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
end
function CreateUI()
-- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
-- control the camera, and when visible, it will point the raycast target
local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
local cursor = Cursor:new()
cursor:SetStyleAuto(style)
ui.cursor = cursor
-- Set starting position of the cursor at the rendering window center
cursor:SetPosition(graphics.width / 2, graphics.height / 2)
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText.text = "Use WASD keys to move, RMB to rotate view\n"..
"LMB to set destination, SHIFT+LMB to teleport\n"..
"MMB or O key to add or remove obstacles\n"..
"Space to toggle debug geometry"
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- The text has multiple rows. Center them in relation to each other
instructionText.textAlignment = HA_CENTER
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
-- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
-- debug geometry
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
end
function MoveCamera(timeStep)
input.mouseVisible = input.mouseMode ~= MM_RELATIVE
mouseDown = input:GetMouseButtonDown(MOUSEB_RIGHT)
-- Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI
input.mouseGrabbed = mouseDown
-- Right mouse button controls mouse cursor visibility: hide when pressed
ui.cursor.visible = not mouseDown
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
-- Only move the camera when the cursor is hidden
if not ui.cursor.visible then
local mouseMove = input.mouseMove
yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
end
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
-- Set destination or teleport with left mouse button
if input:GetMouseButtonPress(MOUSEB_LEFT) then
SetPathPoint()
end
-- Add or remove objects with middle mouse button, then rebuild navigation mesh partially
if input:GetMouseButtonPress(MOUSEB_MIDDLE) or input:GetKeyPress(KEY_O) then
AddOrRemoveObject()
end
-- Toggle debug geometry with space
if input:GetKeyPress(KEY_SPACE) then
drawDebug = not drawDebug
end
end
function SetPathPoint()
local hitPos, hitDrawable = Raycast(250.0)
local navMesh = scene_:GetComponent("NavigationMesh")
if hitPos then
local pathPos = navMesh:FindNearestPoint(hitPos, Vector3.ONE)
if input:GetQualifierDown(QUAL_SHIFT) then
-- Teleport
currentPath = {}
jackNode:LookAt(Vector3(pathPos.x, jackNode.position.y, pathPos.z), Vector3(0.0, 1.0, 0.0))
jackNode.position = pathPos
else
-- Calculate path from Jack's current position to the end point
endPos = pathPos
currentPath = navMesh:FindPath(jackNode.position, endPos)
end
end
end
function AddOrRemoveObject()
-- Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one
local hitPos, hitDrawable = Raycast(250.0)
if hitDrawable then
-- The part of the navigation mesh we must update, which is the world bounding box of the associated
-- drawable component
local updateBox = nil
local hitNode = hitDrawable.node
if hitNode.name == "Mushroom" then
updateBox = hitDrawable.worldBoundingBox
hitNode:Remove()
else
local newNode = CreateMushroom(hitPos)
local newObject = newNode:GetComponent("StaticModel")
updateBox = newObject.worldBoundingBox
end
-- Rebuild part of the navigation mesh, then recalculate path if applicable
local navMesh = scene_:GetComponent("NavigationMesh")
navMesh:Build(updateBox)
if table.maxn(currentPath) > 0 then
currentPath = navMesh:FindPath(jackNode.position, endPos)
end
end
end
function CreateMushroom(pos)
local mushroomNode = scene_:CreateChild("Mushroom")
mushroomNode.position = pos
mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
mushroomNode:SetScale(2.0 + Random(0.5))
local mushroomObject = mushroomNode:CreateComponent("StaticModel")
mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
mushroomObject.castShadows = true
return mushroomNode
end
function Raycast(maxDistance)
local pos = ui.cursorPosition
-- Check the cursor is visible and there is no UI element in front of the cursor
if (not ui.cursor.visible) or (ui:GetElementAt(pos, true) ~= nil) then
return nil, nil
end
local camera = cameraNode:GetComponent("Camera")
local cameraRay = camera:GetScreenRay(pos.x / graphics.width, pos.y / graphics.height)
-- Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
local octree = scene_:GetComponent("Octree")
local result = octree:RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY)
if result.drawable ~= nil then
return result.position, result.drawable
end
return nil, nil
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
-- Make Jack follow the Detour path
FollowPath(timeStep)
end
function FollowPath(timeStep)
if table.maxn(currentPath) > 0 then
local nextWaypoint = currentPath[1] -- NB: currentPath[1] is the next waypoint in order
-- Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target
local move = 5 * timeStep
local distance = (jackNode.position - nextWaypoint):Length()
if move > distance then
move = distance
end
jackNode:LookAt(nextWaypoint, Vector3(0.0, 1.0, 0.0))
jackNode:Translate(Vector3(0.0, 0.0, 1.0) * move)
-- Remove waypoint if reached it
if distance < 0.1 then
table.remove(currentPath, 1)
end
end
end
function HandlePostRenderUpdate(eventType, eventData)
-- If draw debug mode is enabled, draw navigation mesh debug geometry
if drawDebug then
local navMesh = scene_:GetComponent("NavigationMesh")
navMesh:DrawDebugGeometry(true)
end
-- Visualize the start and end points and the last calculated path
local size = table.maxn(currentPath)
if size > 0 then
local debug = scene_:GetComponent("DebugRenderer")
debug:AddBoundingBox(BoundingBox(endPos - Vector3(0.1, 0.1, 0.1), endPos + Vector3(0.1, 0.1, 0.1)), Color(1.0, 1.0, 1.0))
-- Draw the path with a small upward bias so that it does not clip into the surfaces
local bias = Vector3(0.0, 0.05, 0.0)
debug:AddLine(jackNode.position + bias, currentPath[1] + bias, Color(1.0, 1.0, 1.0))
if size > 1 then
for i = 1, size - 1 do
debug:AddLine(currentPath[i] + bias, currentPath[i + 1] + bias, Color(1.0, 1.0, 1.0))
end
end
end
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <add sel=\"/element\">" ..
" <element type=\"Button\">" ..
" <attribute name=\"Name\" value=\"Button3\" />" ..
" <attribute name=\"Position\" value=\"-120 -120\" />" ..
" <attribute name=\"Size\" value=\"96 96\" />" ..
" <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
" <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
" <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
" <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
" <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
" <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"Label\" />" ..
" <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
" <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
" <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
" <attribute name=\"Text\" value=\"Teleport\" />" ..
" </element>" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"LSHIFT\" />" ..
" </element>" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
" <attribute name=\"Text\" value=\"LEFT\" />" ..
" </element>" ..
" </element>" ..
" <element type=\"Button\">" ..
" <attribute name=\"Name\" value=\"Button4\" />" ..
" <attribute name=\"Position\" value=\"-120 -12\" />" ..
" <attribute name=\"Size\" value=\"96 96\" />" ..
" <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
" <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
" <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
" <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
" <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
" <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"Label\" />" ..
" <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
" <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
" <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
" <attribute name=\"Text\" value=\"Obstacles\" />" ..
" </element>" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
" <attribute name=\"Text\" value=\"MIDDLE\" />" ..
" </element>" ..
" </element>" ..
" </add>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
" <attribute name=\"Text\" value=\"LEFT\" />" ..
" </element>" ..
" </add>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"SPACE\" />" ..
" </element>" ..
" </add>" ..
"</patch>"
end
| mit |
Anarchid/Zero-K | LuaRules/Gadgets/unit_boolean_disable.lua | 6 | 10720 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Boolean Disable",
desc = "Handles disables which act in a boolean way (similar to engine default emp).",
author = "Google Frog",
date = "25th August 2013",
license = "GNU GPL, v2 or later",
layer = -1,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (not gadgetHandler:IsSyncedCode()) then
return false -- no unsynced code
end
local GetUnitCost = Spring.Utilities.GetUnitCost
local FRAMES_PER_SECOND = Game.gameSpeed
local DECAY_FRAMES = 40 * FRAMES_PER_SECOND -- time in frames it takes to decay 100% para to 0
local LOS_ACCESS = {inlos = true}
local wantedWeaponList = {}
local disarmWeapons = {}
local paraWeapons = {}
local overstunDamageMult = {}
for wid = 1, #WeaponDefs do
local wd = WeaponDefs[wid]
local wcp = wd.customParams or {}
if wcp.disarmdamagemult then
disarmWeapons[wid] = {
damageMult = wcp.disarmdamagemult,
normalDamage = 1 - (wcp.disarmdamageonly or 0),
disarmTimer = wcp.disarmtimer*FRAMES_PER_SECOND,
}
wantedWeaponList[#wantedWeaponList + 1] = wid
elseif wd.paralyzer or wd.customParams.extra_damage then
local paraTime = wd.paralyzer and wd.damages.paralyzeDamageTime or wd.customParams.extra_paratime
paraWeapons[wid] = paraTime * FRAMES_PER_SECOND
wantedWeaponList[#wantedWeaponList + 1] = wid
end
if wd.customParams and wd.customParams.overstun_damage_mult then
overstunDamageMult[wid] = tonumber(wd.customParams.overstun_damage_mult)
end
end
local partialUnits = {}
local paraUnits = {}
-- structure of the above tables.
-- table[frameID] = {count = x, data = {[1] = unitID, [2] = unitID, ... [x] = unitID}
-- They hold the units in a frame that change state
-- paraUnits are those that unparalyse on frame frameID
-- partialUnits are those that lose all paralysis damage on frame frameID
-- Elements are NOT REMOVED from table[frameID].data, only set to nil as the table does not need to be reused.
local partialUnitID = {}
local paraUnitID = {}
-- table[unitID] = {frameID = x, index = y}
-- stores current frame and index of unitID in their respective tables
local weaponCount = {}
for udid, ud in pairs(UnitDefs) do
weaponCount[udid] = #ud.weapons
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local f = 0 -- frame, set in game frame
local function applyEffect(unitID)
Spring.SetUnitRulesParam(unitID, "disarmed", 1, LOS_ACCESS)
GG.UpdateUnitAttributes(unitID)
GG.ScriptNotifyDisarmed(unitID, true)
end
local function removeEffect(unitID)
Spring.SetUnitRulesParam(unitID, "disarmed", 0, LOS_ACCESS)
GG.UpdateUnitAttributes(unitID)
GG.ScriptNotifyDisarmed(unitID, false)
end
local function HaltBurst(unitID, untilFrame)
local unitDefID = Spring.GetUnitDefID(unitID)
for i = 1, weaponCount[unitDefID] do
Spring.SetUnitWeaponState (unitID, i, "nextSalvo", untilFrame)
end
end
local function addUnitID(unitID, byFrame, byUnitID, frame, extraParamFrames)
byFrame[frame] = byFrame[frame] or {count = 0, data = {}}
byFrame[frame].count = byFrame[frame].count + 1
byFrame[frame].data[byFrame[frame].count] = unitID
byUnitID[unitID] = {frameID = frame, index = byFrame[frame].count}
if (extraParamFrames > 0) then
HaltBurst(unitID, frame)
end
Spring.SetUnitRulesParam(unitID, "disarmframe", frame + extraParamFrames, LOS_ACCESS)
end
local function removeUnitID(unitID, byFrame, byUnitID)
byFrame[byUnitID[unitID].frameID].data[byUnitID[unitID].index] = nil
byUnitID[unitID] = nil
end
-- move a unit from one frame to another
local function moveUnitID(unitID, byFrame, byUnitID, frame, extraParamFrames)
byFrame[byUnitID[unitID].frameID].data[byUnitID[unitID].index] = nil
byFrame[frame] = byFrame[frame] or {count = 0, data = {}}
byFrame[frame].count = byFrame[frame].count + 1
byFrame[frame].data[ byFrame[frame].count] = unitID
byUnitID[unitID] = {frameID = frame, index = byFrame[frame].count}
if (extraParamFrames > 0) then
HaltBurst(unitID, frame)
end
Spring.SetUnitRulesParam(unitID, "disarmframe", frame + extraParamFrames, LOS_ACCESS)
end
local function addParalysisDamageToUnit(unitID, damage, pTime, overstunMult)
local health, maxHealth, paralyzeDamage = Spring.GetUnitHealth(unitID)
if partialUnitID[unitID] then -- if the unit is partially paralysed
local extraTime = math.floor(damage/health*DECAY_FRAMES) -- time that the damage would add
local newPara = partialUnitID[unitID].frameID+extraTime
if newPara - f > DECAY_FRAMES then -- the new para damage exceeds 100%
removeUnitID(unitID, partialUnits, partialUnitID) -- remove from partial table
newPara = newPara - DECAY_FRAMES -- take away the para used to get 100%
if overstunMult then
newPara = f + math.ceil((newPara - f) * overstunMult)
end
if pTime and pTime < newPara - f then -- prevent weapon going over para timer
newPara = math.floor(pTime) + f
end
addUnitID(unitID, paraUnits, paraUnitID, newPara, DECAY_FRAMES)
applyEffect(unitID)
else
moveUnitID(unitID, partialUnits, partialUnitID, newPara, 0)
end
elseif paraUnitID[unitID] then -- the unit is fully paralysed, just add more damage
local extraTime = math.floor((overstunMult or 1)*damage/health*DECAY_FRAMES) -- time that the damage would add
local newPara = paraUnitID[unitID].frameID
if (not pTime) or pTime > newPara - f then -- if the para time on the unit is less than this weapons para timer
newPara = newPara + extraTime
if pTime and pTime < newPara - f then -- prevent going over para time
newPara = math.floor(pTime) + f
end
moveUnitID(unitID, paraUnits, paraUnitID, newPara, DECAY_FRAMES)
end
else -- unit is not paralysed at all
local extraTime = math.floor((damage/health + paralyzeDamage/maxHealth)*DECAY_FRAMES)
if extraTime > DECAY_FRAMES then -- if the new paralysis puts it over 100%
local newPara = extraTime + f
newPara = newPara - DECAY_FRAMES
if overstunMult then
if paralyzeDamage < maxHealth then
newPara = f + math.ceil((newPara - f) * overstunMult)
else
newPara = f + math.floor((overstunMult*damage/health + paralyzeDamage/maxHealth)*DECAY_FRAMES)
end
end
if pTime and pTime < newPara - f then -- prevent going over para time
newPara = math.floor(pTime) + f
end
addUnitID(unitID, paraUnits, paraUnitID, newPara, DECAY_FRAMES)
applyEffect(unitID)
else
addUnitID(unitID, partialUnits, partialUnitID, extraTime+f, 0)
end
end
end
-- used by morph unit
local function GetUnitPara(unitID)
if (partialUnitID[unitID]) then
return 1,partialUnitID[unitID].frameID
elseif (paraUnitID[unitID]) then
return 2,paraUnitID[unitID].frameID
end
return nil
end
local function SetUnitPara(unitID, what, when)
if (what == 1) then
addUnitID(unitID, partialUnits, partialUnitID, when, 0)
else
addUnitID(unitID, paraUnits, paraUnitID, when, DECAY_FRAMES)
applyEffect(unitID)
end
end
-- used by morph unit
GG.getUnitParalysisExternal = GetUnitPara
GG.setUnitParalysisExternal = SetUnitPara
GG.addParalysisDamageToUnit = addParalysisDamageToUnit
function gadget:UnitPreDamaged_GetWantedWeaponDef()
return wantedWeaponList
end
function gadget:UnitPreDamaged(unitID, unitDefID, unitTeam, damage, paralyzer,
weaponDefID, attackerID, attackerDefID, attackerTeam)
if disarmWeapons[weaponDefID] then
local def = disarmWeapons[weaponDefID]
addParalysisDamageToUnit(unitID, damage*def.damageMult, def.disarmTimer, overstunDamageMult[weaponDefID])
if GG.Awards and GG.Awards.AddAwardPoints then
local _, maxHP = Spring.GetUnitHealth(unitID)
local cost_disarm = (damage * def.damageMult / maxHP) * GetUnitCost(unitID)
GG.Awards.AddAwardPoints ('disarm', attackerTeam, cost_disarm)
end
return damage*def.normalDamage
end
if paralyzer and (partialUnitID[unitID] or paraUnitID[unitID]) then
addParalysisDamageToUnit(unitID, damage, paraWeapons[weaponDefID], overstunDamageMult[weaponDefID])
end
return damage
end
function gadget:GameFrame(n)
f = n
if paraUnits[n] then
for i = 1, paraUnits[n].count do
local unitID = paraUnits[n].data[i]
if unitID then
removeEffect(unitID)
paraUnitID[unitID] = nil
addUnitID(unitID, partialUnits, partialUnitID, DECAY_FRAMES+n, 0)
end
end
paraUnits[n] = nil
end
if partialUnits[n] then
for i = 1, partialUnits[n].count do
local unitID = partialUnits[n].data[i]
if unitID then
partialUnitID[unitID] = nil
Spring.SetUnitRulesParam(unitID, "disarmframe", -1, LOS_ACCESS)
end
end
partialUnits[n] = nil
end
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
if partialUnitID[unitID] then
removeUnitID(unitID, partialUnits, partialUnitID)
end
if paraUnitID[unitID] then
removeUnitID(unitID, paraUnits, paraUnitID)
end
end
--helps removing "disarmed" attribute from unit upon gadget reload
local function InitReload()
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local gameFrame = Spring.GetGameFrame()
local allUnits = Spring.GetAllUnits()
for _, unitID in pairs(allUnits) do
local disarmFrame = spGetUnitRulesParam(unitID, "disarmframe")
if (disarmFrame and gameFrame == -1) then disarmFrame = gameFrame end
if disarmFrame then
if disarmFrame > gameFrame + DECAY_FRAMES then --fully disarmed
addUnitID(unitID, paraUnits, paraUnitID, disarmFrame - DECAY_FRAMES, DECAY_FRAMES)
elseif disarmFrame > gameFrame then --partially disarmed
removeEffect(unitID)
addUnitID(unitID, partialUnits, partialUnitID, disarmFrame, 0)
end
end
end
end
function gadget:Initialize()
InitReload()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Save/Load
function gadget:Load(zip)
local frameOffset = Spring.GetGameRulesParam("lastSaveGameFrame") or 0
for _, unitID in ipairs(Spring.GetAllUnits()) do
local disarmFrame = Spring.GetUnitRulesParam(unitID, "disarmframe")
if disarmFrame and (disarmFrame - frameOffset > 0) then
gadget:UnitDestroyed(unitID) -- Because units are added in gadget:Initialize()
Spring.SetUnitRulesParam(unitID, "disarmframe", disarmFrame - frameOffset, LOS_ACCESS)
end
end
InitReload()
end
| gpl-2.0 |
Anarchid/Zero-K | LuaRules/Gadgets/CAI/UnitClusterHandler.lua | 8 | 5498 | --[[ Determines the cluster structure of a list of units.
== CreateUnitList(losCheckAllyTeamID, clusterRadius)
losCheckAllyTeamID is for the underlying UnitList.
clusterRadius is how close two units need to be to be within the
same cluster. Close units may be in different clusters depending
on how the boundaries work out.
=== local functions ===
All UnitList local functions are accessible along with two more.
== UpdateUnitPositions()
Updates the clusters based on the current unit positions.
== ClusterIterator() -> averageX, averageZ, totalCost, unitCount
Iterates over the clusters of units.
--]]
local UnitListHandler = VFS.Include("LuaRules/Gadgets/CAI/UnitListHandler.lua")
local UnitClusterHandler = {}
local function DisSQ(x1,z1,x2,z2)
return (x1 - x2)^2 + (z1 - z2)^2
end
function UnitClusterHandler.CreateUnitCluster(losCheckAllyTeamID, clusterRadius)
local unitList = UnitListHandler.CreateUnitList(losCheckAllyTeamID)
local clusterRadiusSq = clusterRadius^2
local clusterList = {}
local clusterCount = 0
-- Cluster Handling
local function AddUnitToCluster(index, unitID)
local x,_,z = unitList.GetUnitPosition(unitID)
if not x then
return
end
if not index then
local cost = unitList.GetUnitCost(unitID)
clusterCount = clusterCount + 1
clusterList[clusterCount] = {
x = x,
z = z,
averageX = x,
averageZ = z,
xSum = x*cost,
zSum = z*cost,
costSum = cost,
unitCount = 1,
unitMap = {[unitID] = true},
}
unitList.SetUnitDataValue(unitID, "clusterX", x)
unitList.SetUnitDataValue(unitID, "clusterZ", z)
return
end
local clusterData = clusterList[index]
local cost = unitList.GetUnitCost(unitID)
unitList.SetUnitDataValue(unitID, "clusterX", x)
unitList.SetUnitDataValue(unitID, "clusterZ", z)
clusterData.xSum = clusterData.xSum + x*cost
clusterData.zSum = clusterData.zSum + z*cost
clusterData.costSum = clusterData.costSum + cost
clusterData.averageX = clusterData.xSum/clusterData.costSum
clusterData.averageZ = clusterData.zSum/clusterData.costSum
clusterData.unitMap[unitID] = true
clusterData.unitCount = clusterData.unitCount + 1
end
local function RemoveUnitFromCluster(index, unitID)
local clusterData = clusterList[index]
if clusterData.unitCount == 1 then
clusterList[index] = clusterList[clusterCount]
clusterList[clusterCount] = nil
clusterCount = clusterCount - 1
return
end
local cost = unitList.GetUnitCost(unitID)
local unitData = unitList.GetUnitData(unitID)
local x, z = unitData.clusterX, unitData.clusterZ
clusterData.xSum = clusterData.xSum - x*cost
clusterData.zSum = clusterData.zSum - z*cost
clusterData.costSum = clusterData.costSum - cost
clusterData.averageX = clusterData.xSum/clusterData.costSum
clusterData.averageZ = clusterData.zSum/clusterData.costSum
clusterData.unitMap[unitID] = nil
clusterData.unitCount = clusterData.unitCount - 1
end
local function HandleUnitAddition(unitID)
local x,_,z = unitList.GetUnitPosition(unitID)
if not x then
return false
end
local minDis = false
local minIndex = false
for i = 1, clusterCount do
local clusterData = clusterList[i]
local disSq = DisSQ(x,z,clusterData.x,clusterData.z)
if disSq < clusterRadiusSq then
local aDisSq = DisSQ(x,z,clusterData.averageX,clusterData.averageZ)
if (not minDis) or aDisSq < minDis then
minDis = disSq
minIndex = i
end
end
end
AddUnitToCluster(minIndex, unitID)
end
local function HandleUnitRemoval(unitID)
for i = 1, clusterCount do
local clusterData = clusterList[i]
if clusterData.unitMap[unitID] then
RemoveUnitFromCluster(i, unitID)
return
end
end
end
-- Extra Cluster External local functions
local function ClusterIterator() -- x, z, cost, count
local i = 0
return function ()
i = i + 1
if i <= clusterCount then
local clusterData = clusterList[i]
return clusterData.averageX, clusterData.averageZ, clusterData.costSum, clusterData.unitCount
end
end
end
local function UpdateUnitPositions(range)
for unitID,_ in unitList.Iterator() do
if unitList.HasUnitMoved(unitID,range) then
HandleUnitRemoval(unitID)
HandleUnitAddition(unitID)
end
end
end
-- UnitListHandler External local functions
local function AddUnit(unitID, cost, static, newData)
if unitList.AddUnit(unitID, cost, static, newData) then
HandleUnitAddition(unitID)
end
end
local function RemoveUnit(unitID)
if unitList.ValidUnitID(unitID) then
HandleUnitRemoval(unitID)
end
unitList.RemoveUnit(unitID)
end
local function SetUnitDataValue(unitID, key, value)
if key ~= "clusterX" and key ~= "clusterZ" then
unitList.SetUnitDataValue(unitID, key, value)
end
end
local unitCluster = {
ClusterIterator = ClusterIterator,
UpdateUnitPositions = UpdateUnitPositions,
AddUnit = AddUnit,
RemoveUnit = RemoveUnit,
SetUnitDataValue = SetUnitDataValue,
GetUnitPosition = unitList.GetUnitPosition,
GetNearestUnit = unitList.GetNearestUnit,
HasUnitMoved = unitList.HasUnitMoved,
IsPositionNearUnit = unitList.IsPositionNearUnit,
OverwriteUnitData = unitList.OverwriteUnitData,
GetUnitData = unitList.GetUnitData,
GetUnitCost = unitList.GetUnitCost,
GetTotalCost = unitList.GetTotalCost,
ValidUnitID = unitList.ValidUnitID,
Iterator = unitList.Iterator,
}
return unitCluster
end
return UnitClusterHandler
| gpl-2.0 |
LuaDist2/luacv | samples/drawing.lua | 3 | 3856 | #!/usr/bin/env lua
cv=require('luacv')
local NUMBER=100
local DELAY=5
local wndname="Drawing Demo"
function random_color(rng)
return cv.CV_RGB(cv.RandInt(rng)%255,cv.RandInt(rng)%255,cv.RandInt(rng)%255);
end
local line_type = cv.CV_AA
local angle;
local width=1000
local height=700
local width3 = width*3
local height3 = height*3
local ymin = 0;
image=cv.CreateImage( cv.Size(width,height), cv.IPL_DEPTH_8U, 3 );
cv.NamedWindow(wndname, 1 );
cv.Zero( image );
cv.ShowImage(wndname,image);
cv.WaitKey(DELAY);
local rng = cv.RNG(-1);
pt1=cv.Point(0,0)
pt2=cv.Point(0,0)
for i=0,NUMBER-1 do
pt1.x=cv.RandInt(rng) % width3 - width;
pt1.y=cv.RandInt(rng) % height3 - height;
pt2.x=cv.RandInt(rng) % width3 - width;
pt2.y=cv.RandInt(rng) % height3 - height;
cv.Line( image, pt1, pt2, random_color(rng), cv.RandInt(rng)%10, line_type, 0 );
cv.ShowImage(wndname,image);
if (cv.WaitKey(DELAY) >= 0) then os.exit(0) end;
end
for i=0,NUMBER-1 do
pt1.x=cv.RandInt(rng) % width3 - width;
pt1.y=cv.RandInt(rng) % height3 - height;
pt2.x=cv.RandInt(rng) % width3 - width;
pt2.y=cv.RandInt(rng) % height3 - height;
cv.Rectangle( image,pt1, pt2, random_color(rng), cv.RandInt(rng)%10-1, line_type, 0 );
cv.ShowImage(wndname,image);
if(cv.WaitKey(DELAY) >= 0) then os.exit(0) end
end
local sz=cv.Size(0,0)
for i=0,NUMBER-1 do
pt1.x=cv.RandInt(rng) % width3 - width;
pt1.y=cv.RandInt(rng) % height3 - height;
sz.width =cv.RandInt(rng)%200;
sz.height=cv.RandInt(rng)%200;
angle = (cv.RandInt(rng)%1000)*0.180;
cv.Ellipse( image, pt1, sz, angle, angle - 100, angle + 200,
random_color(rng), cv.RandInt(rng)%10-1, line_type, 0 );
cv.ShowImage(wndname,image);
if (cv.WaitKey(DELAY) >= 0) then os.exit(0) end
end
local pt={{cv.Point(0,0),cv.Point(0,0),cv.Point(0,0)},{cv.Point(0,0),cv.Point(0,0),cv.Point(0,0)}}
local arr={2,3}
for i=0,NUMBER-1 do
for j=1,arr[1] do
for k=1,arr[2] do
pt[j][k].x=cv.RandInt(rng) % width3 - width;
pt[j][k].y=cv.RandInt(rng) % height3 - height;
end
end
cv.PolyLine( image, pt, arr, 2, 1, random_color(rng), cv.RandInt(rng)%10, line_type, 0 );
cv.ShowImage(wndname,image);
if(cv.WaitKey(DELAY) >= 0) then os.exit(0); end
end
for i=0,NUMBER-1 do
for j=1,arr[1] do
for k=1,arr[2] do
pt[j][k].x=cv.RandInt(rng) % width3 - width;
pt[j][k].y=cv.RandInt(rng) % height3 - height;
end
end
cv.FillPoly( image, pt, arr, 2, random_color(rng), line_type, 0 );
cv.ShowImage(wndname,image);
if(cv.WaitKey(DELAY) >= 0) then os.exit(0) end
end
for i=0,NUMBER-1 do
pt1.x=cv.RandInt(rng) % width3 - width;
pt1.y=cv.RandInt(rng) % height3 - height;
cv.Circle( image, pt1, cv.RandInt(rng)%300, random_color(rng),
cv.RandInt(rng)%10-1, line_type, 0 );
cv.ShowImage(wndname,image);
if (cv.WaitKey(DELAY) >= 0) then os.exit(0) end
end
local font=cv.Font(1)
for i=1,NUMBER-1 do
pt1.x=cv.RandInt(rng) % width3 - width;
pt1.y=cv.RandInt(rng) % height3 - height;
cv.InitFont( font, cv.RandInt(rng) % 8,
(cv.RandInt(rng)%100)*0.05+0.1, (cv.RandInt(rng)%100)*0.05+0.1,
(cv.RandInt(rng)%5)*0.1, cv.Round(cv.RandInt(rng)%10), line_type );
cv.PutText( image, "Testing text rendering!", pt1, font, random_color(rng));
cv.ShowImage(wndname,image);
if(cv.WaitKey(DELAY) >= 0)then os.exit(0) end
end
cv.InitFont(font,cv.CV_FONT_HERSHEY_COMPLEX, 3, 3, 0.0, 5, line_type );
local text_size=cv.Size(0,0)
cv.GetTextSize( "OpenCV forever!", font, text_size, ymin );
pt1.x = (width - text_size.width)/2;
pt1.y = (height + text_size.height)/2;
image2 = cv.CloneImage(image);
for i=0,254 do
cv.SubS( image2, cv.ScalarAll(i), image, nil );
cv.PutText( image, "OpenCV forever!", pt1, font, cv.CV_RGB(255,i,i));
cv.ShowImage(wndname,image);
if(cv.WaitKey(DELAY) >= 0) then os.exit(0) end
end
cv.WaitKey();
cv.DestroyAllWindows()
| lgpl-3.0 |
Whit3Tig3R/bestspammbot2 | plugins/anti-flood.lua | 281 | 2422 | local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 5
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
local text = 'I can\'t kick '..data.user..' but should be kicked'
send_msg(data.chat, '', ok_cb, nil)
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
else
local chat = msg.to.id
local hash = 'anti-flood:enabled:'..chat
if matches[1] == 'enable' then
redis:set(hash, true)
return 'Anti-flood enabled on chat'
end
if matches[1] == 'disable' then
redis:del(hash)
return 'Anti-flood disabled on chat'
end
end
end
local function pre_process (msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
local hash_enable = 'anti-flood:enabled:'..msg.to.id
local enabled = redis:get(hash_enable)
if enabled then
print('anti-flood enabled')
-- Check flood
if msg.from.type == 'user' then
-- Increase the number of messages from the user on the chat
local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
local receiver = get_receiver(msg)
local user = msg.from.id
local text = 'User '..user..' is flooding'
local chat = msg.to.id
send_msg(receiver, text, ok_cb, nil)
if msg.to.type ~= 'chat' then
print("Flood in not a chat group!")
elseif user == tostring(our_id) then
print('I won\'t kick myself')
elseif is_sudo(msg) then
print('I won\'t kick an admin!')
else
-- Ban user
-- TODO: Check on this plugin bans
local bhash = 'banned:'..msg.to.id..':'..msg.from.id
redis:set(bhash, true)
kick_user(user, chat)
end
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
return msg
end
return {
description = 'Plugin to kick flooders from group.',
usage = {},
patterns = {
'^!antiflood (enable)$',
'^!antiflood (disable)$'
},
run = run,
privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
hacklex/OpenRA | mods/ra/maps/soviet-04b/soviet04b-reinforcements_teams.lua | 13 | 2708 | Civs = { civ1, civ2, civ3, civ4 }
Village = { civ1, civ3, civ4, village1, village3 }
Guards = { Guard1, Guard2, Guard3 }
SovietMCV = { "mcv" }
InfantryReinfGreece = { "e1", "e1", "e1", "e1", "e1" }
Avengers = { "jeep", "1tnk", "2tnk", "2tnk", "1tnk" }
Patrol1Group = { "jeep", "jeep", "2tnk", "2tnk" }
Patrol2Group = { "jeep", "1tnk", "1tnk", "1tnk" }
AlliedInfantryTypes = { "e1", "e3" }
AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "1tnk" }
InfAttack = { }
ArmorAttack = { }
InfReinfPath = { NRoadPoint.Location, CrossroadsPoint.Location, ToVillageRoadPoint.Location, VillagePoint.Location }
Patrol1Path = { ToVillageRoadPoint.Location, ToBridgePoint.Location, InBasePoint.Location }
Patrol2Path = { EntranceSouthPoint.Location, ToRadarBridgePoint.Location, IslandPoint.Location, ToRadarBridgePoint.Location }
VillageCamArea = { CPos.New(37, 58),CPos.New(37, 59),CPos.New(37, 60),CPos.New(38, 60),CPos.New(39, 60), CPos.New(40, 60), CPos.New(41, 60), CPos.New(35, 57), CPos.New(34, 57), CPos.New(33, 57), CPos.New(32, 57) }
if Map.Difficulty == "Easy" then
ArmorReinfGreece = { "jeep", "1tnk", "1tnk" }
else
ArmorReinfGreece = { "jeep", "jeep", "1tnk", "1tnk", "1tnk" }
end
AttackPaths =
{
{ CrossroadsPoint, ToVillageRoadPoint, VillagePoint },
{ EntranceSouthPoint, OrefieldSouthPoint },
{ CrossroadsPoint, ToBridgePoint }
}
ReinfInf = function()
if Radar.IsDead or Radar.Owner ~= Greece then
return
end
Reinforcements.Reinforce(Greece, InfantryReinfGreece, InfReinfPath, 0, function(soldier)
soldier.Hunt()
end)
end
ReinfArmor = function()
if not Radar.IsDead and Radar.Owner == Greece then
RCheck = true
Reinforcements.Reinforce(Greece, ArmorReinfGreece, InfReinfPath, 0, function(soldier)
soldier.Hunt()
end)
end
end
BringPatrol1 = function()
if Radar.IsDead or Radar.Owner ~= Greece then
return
end
local units = Reinforcements.Reinforce(Greece, Patrol1Group, { NRoadPoint.Location }, 0)
Utils.Do(units, function(patrols)
patrols.Patrol(Patrol1Path, true, 250)
end)
Trigger.OnAllKilled(units, function()
if Map.Difficulty == "Hard" then
Trigger.AfterDelay(DateTime.Minutes(4), BringPatrol1)
else
Trigger.AfterDelay(DateTime.Minutes(7), BringPatrol1)
end
end)
end
BringPatrol2 = function()
if Radar.IsDead or Radar.Owner ~= Greece then
return
end
local units = Reinforcements.Reinforce(Greece, Patrol2Group, { NRoadPoint.Location }, 0)
Utils.Do(units, function(patrols)
patrols.Patrol(Patrol2Path, true, 250)
end)
Trigger.OnAllKilled(units, function()
if Map.Difficulty == "Hard" then
Trigger.AfterDelay(DateTime.Minutes(4), BringPatrol2)
else
Trigger.AfterDelay(DateTime.Minutes(7), BringPatrol2)
end
end)
end
| gpl-3.0 |
mohammad4569/matrix | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
Anarchid/Zero-K | LuaRules/Configs/StartBoxes/Lonely Oasis v1.lua | 19 | 5097 | local boxes = {
[0] = {
boxes = {
{
{5486, 2151},
{5537, 2426},
{5583, 2551},
{5648, 2630},
{5748, 2676},
{5924, 2680},
{6078, 2669},
{6165, 2687},
{6272, 2746},
{6420, 2777},
{6541, 2769},
{6668, 2694},
{6734, 2594},
{6765, 2447},
{6757, 2289},
{6719, 2132},
{6731, 2092},
{6821, 1998},
{6854, 1915},
{6853, 1594},
{6820, 1505},
{6765, 1433},
{6647, 1373},
{6593, 1312},
{6572, 1201},
{6584, 946},
{6561, 852},
{6460, 704},
{6354, 622},
{6295, 583},
{6273, 533},
{6161, 465},
{5986, 459},
{5902, 448},
{5758, 396},
{5621, 361},
{5480, 352},
{5379, 348},
{5288, 376},
{5199, 429},
{5128, 509},
{5086, 611},
{5009, 703},
{4958, 766},
{4940, 843},
{4944, 951},
{4986, 1041},
{5066, 1155},
{5175, 1256},
{5275, 1378},
{5400, 1738},
},
{
{4916, 1171},
{4757, 1138},
{4599, 1118},
{4446, 1131},
{4320, 1173},
{4227, 1244},
{4162, 1327},
{4073, 1370},
{3973, 1363},
{3899, 1313},
{3861, 1239},
{3857, 1121},
{3898, 1044},
{3969, 954},
{4096, 835},
{4124, 758},
{4121, 670},
{4089, 590},
{4013, 523},
{3924, 501},
{3837, 519},
{3675, 582},
{3531, 609},
{3393, 599},
{3268, 536},
{3061, 444},
{2812, 371},
{2654, 377},
{2262, 451},
{2117, 507},
{1998, 612},
{1888, 775},
{1862, 890},
{1870, 1021},
{1909, 1143},
{1981, 1221},
{2063, 1291},
{2166, 1432},
{2240, 1548},
{2319, 1664},
{2399, 1738},
{2498, 1761},
{2620, 1732},
{2693, 1650},
{2747, 1498},
{2799, 1408},
{2907, 1358},
{3064, 1367},
{3270, 1441},
{3613, 1617},
{3757, 1715},
{3814, 1784},
{3902, 1986},
{3980, 2125},
{4001, 2227},
{4036, 2359},
{4100, 2468},
{4289, 2619},
{4571, 2842},
{4634, 2924},
{4711, 2980},
{4814, 2999},
{4982, 2923},
{5121, 2857},
{5319, 2804},
{5441, 2754},
{5509, 2714},
{5543, 2700},
{5458, 2561},
{5422, 2427},
{5396, 2290},
{5345, 2201},
{5237, 2037},
{5116, 1784},
{5076, 1585},
{5082, 1436},
{5006, 1267},
},
},
startpoints = {
{5919, 1528},
{4583, 1335},
{2535, 606},
},
nameLong = "North-East",
nameShort = "NE",
},
[1] = {
boxes = {
{
{1664, 4973},
{1614, 4812},
{1563, 4717},
{1485, 4648},
{1413, 4617},
{1352, 4614},
{1268, 4640},
{1197, 4635},
{1141, 4579},
{1048, 4530},
{936, 4498},
{833, 4501},
{747, 4514},
{643, 4552},
{570, 4604},
{510, 4672},
{481, 4728},
{477, 4793},
{478, 4940},
{462, 5052},
{415, 5144},
{367, 5219},
{335, 5347},
{329, 5463},
{364, 5591},
{462, 5723},
{631, 5904},
{664, 5976},
{665, 6074},
{690, 6167},
{775, 6250},
{858, 6309},
{911, 6400},
{975, 6511},
{1066, 6574},
{1174, 6606},
{1259, 6643},
{1388, 6759},
{1461, 6793},
{1623, 6812},
{1758, 6813},
{1935, 6769},
{2051, 6709},
{2132, 6607},
{2153, 6467},
{2149, 6209},
{2118, 6071},
{2044, 5915},
{1945, 5756},
{1768, 5407},
},
{
{1771, 4943},
{1669, 4692},
{1675, 4620},
{1772, 4456},
{1875, 4314},
{1973, 4241},
{2101, 4208},
{2224, 4205},
{2337, 4191},
{2387, 4164},
{2476, 4152},
{2547, 4172},
{2623, 4226},
{2694, 4343},
{2783, 4454},
{2903, 4551},
{3031, 4697},
{3137, 4882},
{3236, 5076},
{3310, 5293},
{3396, 5419},
{3532, 5530},
{3766, 5639},
{3953, 5715},
{4193, 5763},
{4303, 5749},
{4412, 5672},
{4452, 5583},
{4469, 5505},
{4499, 5448},
{4570, 5389},
{4665, 5364},
{4800, 5401},
{4908, 5466},
{4995, 5571},
{5075, 5694},
{5189, 5856},
{5261, 6119},
{5253, 6242},
{5190, 6410},
{5070, 6538},
{4896, 6636},
{4663, 6697},
{4542, 6771},
{4370, 6803},
{4180, 6779},
{3941, 6692},
{3767, 6595},
{3660, 6496},
{3585, 6477},
{3518, 6499},
{3435, 6539},
{3326, 6538},
{3229, 6498},
{3161, 6410},
{3152, 6279},
{3178, 6189},
{3254, 6107},
{3267, 5996},
{3253, 5885},
{3182, 5830},
{3096, 5841},
{3031, 5919},
{2885, 6057},
{2702, 6119},
{2441, 6068},
{2238, 5966},
{2174, 5912},
{2104, 5800},
{2115, 5683},
{2032, 5239},
{1891, 5058},
},
},
startpoints = {
{1212, 5656},
{2606, 5888},
{4527, 6500},
},
nameLong = "South-West",
nameShort = "SW",
},
}
-- use a smaller box for duel
if #Spring.GetTeamList(0) == 1 and #Spring.GetTeamList(1) == 1 then
boxes[0].boxes[2] = nil
boxes[1].boxes[2] = nil
boxes[0].startpoints[2] = nil
boxes[0].startpoints[3] = nil
boxes[1].startpoints[2] = nil
boxes[1].startpoints[3] = nil
end
return boxes, { 2 }
| gpl-2.0 |
haste/oUF | elements/raidtargetindicator.lua | 10 | 2510 | --[[
# Element: Raid Target Indicator
Handles the visibility and updating of an indicator based on the unit's raid target assignment.
## Widget
RaidTargetIndicator - A `Texture` used to display the raid target icon.
## Notes
A default texture will be applied if the widget is a Texture and doesn't have a texture set.
## Examples
-- Position and size
local RaidTargetIndicator = self:CreateTexture(nil, 'OVERLAY')
RaidTargetIndicator:SetSize(16, 16)
RaidTargetIndicator:SetPoint('TOPRIGHT', self)
-- Register it with oUF
self.RaidTargetIndicator = RaidTargetIndicator
--]]
local _, ns = ...
local oUF = ns.oUF
local GetRaidTargetIndex = GetRaidTargetIndex
local SetRaidTargetIconTexture = SetRaidTargetIconTexture
local function Update(self, event)
local element = self.RaidTargetIndicator
--[[ Callback: RaidTargetIndicator:PreUpdate()
Called before the element has been updated.
* self - the RaidTargetIndicator element
--]]
if(element.PreUpdate) then
element:PreUpdate()
end
local index = GetRaidTargetIndex(self.unit)
if(index) then
SetRaidTargetIconTexture(element, index)
element:Show()
else
element:Hide()
end
--[[ Callback: RaidTargetIndicator:PostUpdate(index)
Called after the element has been updated.
* self - the RaidTargetIndicator element
* index - the index of the raid target marker (number?)[1-8]
--]]
if(element.PostUpdate) then
return element:PostUpdate(index)
end
end
local function Path(self, ...)
--[[ Override: RaidTargetIndicator.Override(self, event)
Used to completely override the internal update function.
* self - the parent object
* event - the event triggering the update (string)
--]]
return (self.RaidTargetIndicator.Override or Update) (self, ...)
end
local function ForceUpdate(element)
if(not element.__owner.unit) then return end
return Path(element.__owner, 'ForceUpdate')
end
local function Enable(self)
local element = self.RaidTargetIndicator
if(element) then
element.__owner = self
element.ForceUpdate = ForceUpdate
self:RegisterEvent('RAID_TARGET_UPDATE', Path, true)
if(element:IsObjectType('Texture') and not element:GetTexture()) then
element:SetTexture([[Interface\TargetingFrame\UI-RaidTargetingIcons]])
end
return true
end
end
local function Disable(self)
local element = self.RaidTargetIndicator
if(element) then
element:Hide()
self:UnregisterEvent('RAID_TARGET_UPDATE', Path)
end
end
oUF:AddElement('RaidTargetIndicator', Path, Enable, Disable)
| mit |
jerizm/kong | spec/03-plugins/001-tcp-log/01-tcp-log_spec.lua | 3 | 2437 | local cjson = require "cjson"
local helpers = require "spec.helpers"
local TCP_PORT = 35000
local HTTP_DELAY_PORT = 35003
describe("Plugin: tcp-log (log)", function()
local client
setup(function()
assert(helpers.start_kong())
client = helpers.proxy_client()
local api1 = assert(helpers.dao.apis:insert {
request_host = "tcp_logging.com",
upstream_url = "http://mockbin.com",
})
local api2 = assert(helpers.dao.apis:insert {
request_host = "tcp_logging2.com",
upstream_url = "http://127.0.0.1:"..HTTP_DELAY_PORT,
})
assert(helpers.dao.plugins:insert {
api_id = api1.id,
name = "tcp-log",
config = {
host = "127.0.0.1",
port = TCP_PORT
},
})
assert(helpers.dao.plugins:insert {
api_id = api2.id,
name = "tcp-log",
config = {
host = "127.0.0.1",
port = TCP_PORT
},
})
end)
teardown(function()
if client then client:close() end
helpers.stop_kong()
end)
it("logs to TCP", function()
local thread = helpers.tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local r = assert(client:send {
method = "GET",
path = "/request",
headers = {
host = "tcp_logging.com"
},
})
assert.response(r).has.status(200)
-- Getting back the TCP server input
local ok, res = thread:join()
assert.True(ok)
assert.is_string(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.equal("127.0.0.1", log_message.client_ip)
end)
it("logs proper latencies", function()
local http_thread = helpers.http_server(HTTP_DELAY_PORT) -- Starting the mock TCP server
local tcp_thread = helpers.tcp_server(TCP_PORT) -- Starting the mock TCP server
-- Making the request
local r = assert(client:send {
method = "GET",
path = "/request/delay",
headers = {
host = "tcp_logging2.com"
}
})
assert.response(r).has.status(200)
-- Getting back the TCP server input
local ok, res = tcp_thread:join()
assert.True(ok)
assert.is_string(res)
-- Making sure it's alright
local log_message = cjson.decode(res)
assert.True(log_message.latencies.proxy < 3000)
assert.True(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy)
http_thread:join()
end)
end)
| apache-2.0 |
chukong/sdkbox-facebook-sample-v2 | tools/tolua++/basic.lua | 5 | 8706 | -- usage: (use instead of ant)
-- tolua++ "-L" "basic.lua" "-o" "../../scripting/lua/cocos2dx_support/LuaCocos2d.cpp" "Cocos2d.pkg"
_is_functions = _is_functions or {}
_to_functions = _to_functions or {}
_push_functions = _push_functions or {}
local CCObjectTypes = {
"CCObject",
"CCAction",
"CCImage",
"CCFiniteTimeAction",
"CCActionInstant",
"CCCallFunc",
"CCCallFuncN",
"CCFlipX",
"CCFlipY",
"CCHide",
"CCPlace",
"CCReuseGrid",
"CCShow",
"CCStopGrid",
"CCToggleVisibility",
"CCActionInterval",
"CCAccelAmplitude",
"CCAccelDeccelAmplitude",
"CCActionCamera",
"CCOrbitCamera",
"CCCardinalSplineTo",
"CCCardinalSplineBy",
"CCCatmullRomTo",
"CCCatmullRomBy",
"CCActionEase",
"CCEaseBackIn",
"CCEaseBackInOut",
"CCEaseBackOut",
"CCEaseBounce",
"CCEaseElastic",
"CCEaseExponentialIn",
"CCEaseExponentialInOut",
"CCEaseExponentialOut",
"CCEaseRateAction",
"CCEaseSineIn",
"CCEaseSineInOut",
"CCEaseSineOut",
"CCAnimate",
"CCBezierBy",
"CCBezierTo",
"CCBlink",
"CCDeccelAmplitude",
"CCDelayTime",
"CCFadeIn",
"CCFadeOut",
"CCFadeTo",
"CCGridAction",
"CCJumpBy",
"CCJumpTo",
"CCMoveTo",
"CCMoveBy",
"CCProgressFromTo",
"CCProgressTo",
"CCRepeat",
"CCRepeatForever",
"CCReverseTime",
"CCRotateBy",
"CCRotateTo",
"CCScaleTo",
"CCScaleBy",
"CCSequence",
"CCSkewTo",
"CCSkewBy",
"CCSpawn",
"CCTintBy",
"CCTintTo",
"CCActionManager",
"CCAnimation",
"CCAnimationCache",
"CCArray",
"CCAsyncObject",
"CCAutoreleasePool",
"CCBMFontConfiguration",
"CCCamera",
"CCConfiguration",
"CCData",
"CCDirector",
"CCDisplayLinkDirector",
"CCEvent",
"CCGrabber",
"CCGrid3D",
"CCTiledGrid3D",
"CCKeypadDispatcher",
"CCKeypadHandler",
"CCDictionary",
"CCNode",
"CCAtlasNode",
"CCLabelAtlas",
"CCTileMapAtlas",
"CCLayer",
"CCLayerColor",
"CCLayerGradient",
"CCLayerMultiplex",
"CCMenu",
"CCMenuItem",
"CCMenuItemLabel",
"CCMenuItemAtlasFont",
"CCMenuItemFont",
"CCMenuItemSprite",
"CCMenuItemImage",
"CCMenuItemToggle",
"CCMotionStreak",
"CCParallaxNode",
"CCParticleSystem",
"CCParticleBatchNode",
"CCParticleSystemQuad",
"CCProgressTimer",
"CCRenderTexture",
"CCRibbon",
"CCScene",
"CCTransitionScene",
"CCTransitionCrossFade",
"CCTransitionFade",
"CCTransitionFadeTR",
"CCTransitionFadeBL",
"CCTransitionFadeDown",
"CCTransitionFadeUp",
"CCTransitionJumpZoom",
"CCTransitionMoveInL",
"CCTransitionMoveInB",
"CCTransitionMoveInR",
"CCTransitionMoveInT",
"CCTransitionPageTurn",
"CCTransitionRotoZoom",
"CCTransitionSceneOriented",
"CCTransitionFlipAngular",
"CCTransitionFlipX",
"CCTransitionFlipY",
"CCTransitionZoomFlipAngular",
"CCTransitionZoomFlipX",
"CCTransitionZoomFlipY",
"CCTransitionShrinkGrow",
"CCTransitionSlideInL",
"CCTransitionSlideInB",
"CCTransitionSlideInR",
"CCTransitionSlideInT",
"CCTransitionSplitCols",
"CCTransitionSplitRows",
"CCTransitionTurnOffTiles",
"CCTransitionProgress",
"CCTransitionProgressRadialCCW",
"CCTransitionProgressRadialCW",
"CCTransitionProgressHorizontal",
"CCTransitionProgressVertical",
"CCTransitionProgressInOut",
"CCTransitionProgressOutIn",
"CCSprite",
"CCLabelTTF",
"CCTextFieldTTF",
"CCSpriteBatchNode",
"CCLabelBMFont",
"CCTMXLayer",
"CCTMXTiledMap",
"CCPointObject",
"CCProjectionProtocol",
"CCRibbonSegment",
"CCScheduler",
"CCSet",
"CCSpriteFrame",
"CCSpriteFrameCache",
"CCString",
"CCTexture2D",
"CCTextureAtlas",
"CCTextureCache",
"CCTexturePVR",
"CCTimer",
"CCTMXLayerInfo",
"CCTMXMapInfo",
"CCTMXObjectGroup",
"CCTMXTilesetInfo",
"CCTouch",
"CCTouchDispatcher",
"CCTouchHandler",
"CCParticleFire",
"CCParticleFireworks",
"CCParticleSun",
"CCParticleGalaxy",
"CCParticleFlower",
"CCParticleMeteor",
"CCParticleSpiral",
"CCParticleExplosion",
"CCParticleSmoke",
"CCParticleSnow",
"CCParticleRain",
"CCScale9Sprite",
"CCControl",
"CCControlButton",
"CCControlColourPicker",
"CCControlPotentiometer",
"CCControlSlider",
"CCControlStepper",
"CCControlSwitch",
"CCEditBox",
"CCInteger",
"CCScrollView",
"CCTableViewCell",
"CCTableView",
"CCComponent",
}
-- register CCObject types
for i = 1, #CCObjectTypes do
_push_functions[CCObjectTypes[i]] = "toluafix_pushusertype_ccobject"
end
-- register LUA_FUNCTION, LUA_TABLE, LUA_HANDLE type
_to_functions["LUA_FUNCTION"] = "toluafix_ref_function"
_is_functions["LUA_FUNCTION"] = "toluafix_isfunction"
_to_functions["LUA_TABLE"] = "toluafix_totable"
_is_functions["LUA_TABLE"] = "toluafix_istable"
local toWrite = {}
local currentString = ''
local out
local WRITE, OUTPUT = write, output
function output(s)
out = _OUTPUT
output = OUTPUT -- restore
output(s)
end
function write(a)
if out == _OUTPUT then
currentString = currentString .. a
if string.sub(currentString,-1) == '\n' then
toWrite[#toWrite+1] = currentString
currentString = ''
end
else
WRITE(a)
end
end
function post_output_hook(package)
local result = table.concat(toWrite)
local function replace(pattern, replacement)
local k = 0
local nxt, currentString = 1, ''
repeat
local s, e = string.find(result, pattern, nxt, true)
if e then
currentString = currentString .. string.sub(result, nxt, s-1) .. replacement
nxt = e + 1
k = k + 1
end
until not e
result = currentString..string.sub(result, nxt)
if k == 0 then print('Pattern not replaced', pattern) end
end
replace([[#ifndef __cplusplus
#include "stdlib.h"
#endif
#include "string.h"
#include "tolua++.h"]],
[[/****************************************************************************
Copyright (c) 2011 cocos2d-x.org
http://www.cocos2d-x.org
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.
****************************************************************************/
extern "C" {
#include "tolua_fix.h"
}
#include <map>
#include <string>
#include "cocos2d.h"
#include "CCLuaEngine.h"
#include "SimpleAudioEngine.h"
#include "cocos-ext.h"
using namespace cocos2d;
using namespace cocos2d::extension;
using namespace CocosDenshion;]])
replace([[/* Exported function */
TOLUA_API int tolua_Cocos2d_open (lua_State* tolua_S);]], [[]])
replace([[*((LUA_FUNCTION*)]], [[(]])
replace([[unsigned void* tolua_ret = (unsigned void*) self->getTiles();]],
[[unsigned int* tolua_ret = (unsigned int*) self->getTiles();]])
replace([[ccColor3B color = *((ccColor3B*) tolua_tousertype(tolua_S,4,(void*)&(const ccColor3B)ccBLACK));]],
[[const ccColor3B clr = ccBLACK;
ccColor3B color = *((ccColor3B*) tolua_tousertype(tolua_S,4,(void*)&clr));]])
replace([[tolua_usertype(tolua_S,"LUA_FUNCTION");]], [[]])
replace([[toluafix_pushusertype_ccobject(tolua_S,(void*)tolua_ret]],
[[int nID = (tolua_ret) ? (int)tolua_ret->m_uID : -1;
int* pLuaID = (tolua_ret) ? &tolua_ret->m_nLuaID : NULL;
toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret]])
replace('\t', ' ')
WRITE(result)
end
| mit |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/corroach.lua | 1 | 2374 | return {
corroach = {
acceleration = 0.11999999731779,
activatewhenbuilt = true,
brakerate = 0.15000000596046,
buildcostenergy = 5471,
buildcostmetal = 65,
buildpic = "CORROACH.DDS",
buildtime = 7899,
canmove = true,
category = "KBOT MOBILE WEAPON ALL NOTSUB NOTSHIP NOTAIR NOTHOVER SURFACE",
description = "Amphibious Crawling Bomb",
energymake = 0.10000000149012,
energyuse = 0.10000000149012,
explodeas = "CRAWL_BLASTSML",
firestate = 2,
footprintx = 2,
footprintz = 2,
idleautoheal = 5,
idletime = 1800,
mass = 1500,
maxdamage = 560,
maxslope = 32,
maxvelocity = 2.7000000476837,
maxwaterdepth = 112,
movementclass = "AKBOTBOMB2",
name = "Roach",
nochasecategory = "VTOL",
objectname = "CORROACH",
seismicsignature = 0,
selfdestructas = "CRAWL_BLAST",
selfdestructcountdown = 0,
sightdistance = 260,
smoothanim = true,
turninplace = 0,
turnrate = 1507,
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "servsml6",
},
select = {
[1] = "servsml6",
},
},
weapondefs = {
crawl_detonator = {
areaofeffect = 5,
craterboost = 0,
cratermult = 0,
edgeeffectiveness = 0,
explosiongenerator = "",
firesubmersed = true,
gravityaffected = "true",
impulseboost = 0,
impulsefactor = 0,
name = "Mine Detonator",
range = 1,
reloadtime = 0.10000000149012,
weapontype = "Cannon",
weaponvelocity = 1000,
damage = {
crawlingbombs = 1000,
default = 0,
},
},
crawl_dummy = {
areaofeffect = 0,
craterboost = 0,
cratermult = 0,
edgeeffectiveness = 0,
explosiongenerator = "",
firesubmersed = true,
impulseboost = 0,
impulsefactor = 0,
name = "Crawlingbomb Dummy Weapon",
range = 80,
reloadtime = 0.10000000149012,
tolerance = 100000,
weapontype = "Melee",
weaponvelocity = 100000,
damage = {
default = 0,
},
},
},
weapons = {
[1] = {
badtargetcategory = "VTOL",
def = "CRAWL_DUMMY",
onlytargetcategory = "SURFACE",
},
[2] = {
def = "CRAWL_DETONATOR",
onlytargetcategory = "NOTSUB",
},
},
},
}
| gpl-2.0 |
halolpd/vlc | share/lua/modules/simplexml.lua | 103 | 3732 | --[==========================================================================[
simplexml.lua: Lua simple xml parser wrapper
--[==========================================================================[
Copyright (C) 2010 Antoine Cellerier
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
module("simplexml",package.seeall)
--[[ Returns the xml tree structure
-- Each node is of one of the following types:
-- { name (string), attributes (key->value map), children (node array) }
-- text content (string)
--]]
local function parsexml(stream, errormsg)
if not stream then return nil, errormsg end
local xml = vlc.xml()
local reader = xml:create_reader(stream)
local tree
local parents = {}
local nodetype, nodename = reader:next_node()
while nodetype > 0 do
if nodetype == 1 then
local node = { name= nodename, attributes= {}, children= {} }
local attr, value = reader:next_attr()
while attr ~= nil do
node.attributes[attr] = value
attr, value = reader:next_attr()
end
if tree then
table.insert(tree.children, node)
table.insert(parents, tree)
end
tree = node
elseif nodetype == 2 then
if #parents > 0 then
local tmp = {}
while nodename ~= tree.name do
if #parents == 0 then
error("XML parser error/faulty logic")
end
local child = tree
tree = parents[#parents]
table.remove(parents)
table.remove(tree.children)
table.insert(tmp, 1, child)
for i, node in pairs(child.children) do
table.insert(tmp, i+1, node)
end
child.children = {}
end
for _, node in pairs(tmp) do
table.insert(tree.children, node)
end
tree = parents[#parents]
table.remove(parents)
end
elseif nodetype == 3 then
table.insert(tree.children, nodename)
end
nodetype, nodename = reader:next_node()
end
if #parents > 0 then
error("XML parser error/Missing closing tags")
end
return tree
end
function parse_url(url)
return parsexml(vlc.stream(url))
end
function parse_string(str)
return parsexml(vlc.memory_stream(str))
end
function add_name_maps(tree)
tree.children_map = {}
for _, node in pairs(tree.children) do
if type(node) == "table" then
if not tree.children_map[node.name] then
tree.children_map[node.name] = {}
end
table.insert(tree.children_map[node.name], node)
add_name_maps(node)
end
end
end
| gpl-2.0 |
ivendrov/nn | SpatialFullConvolution.lua | 42 | 1589 | local SpatialFullConvolution, parent = torch.class('nn.SpatialFullConvolution','nn.Module')
function SpatialFullConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH)
parent.__init(self)
dW = dW or 1
dH = dH or 1
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.weight = torch.Tensor(nInputPlane, nOutputPlane, kH, kW)
self.gradWeight = torch.Tensor(nInputPlane, nOutputPlane, kH, kW)
self.bias = torch.Tensor(self.nOutputPlane)
self.gradBias = torch.Tensor(self.nOutputPlane)
self:reset()
end
function SpatialFullConvolution:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
local nInputPlane = self.nInputPlane
local kH = self.kH
local kW = self.kW
stdv = 1/math.sqrt(kW*kH*nInputPlane)
end
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
end
function SpatialFullConvolution:updateOutput(input)
return input.nn.SpatialFullConvolution_updateOutput(self, input)
end
function SpatialFullConvolution:updateGradInput(input, gradOutput)
if self.gradInput then
return input.nn.SpatialFullConvolution_updateGradInput(self, input, gradOutput)
end
end
function SpatialFullConvolution:accGradParameters(input, gradOutput, scale)
return input.nn.SpatialFullConvolution_accGradParameters(self, input, gradOutput, scale)
end
| bsd-3-clause |
ggcrunchy/Old-Love2D-Demo | Scripts/Game/Game.lua | 1 | 3400 | -- Standard library imports --
local wrap = coroutine.wrap
-- Imports --
local ApplyScissorState = graphics.ApplyScissorState
local GetEventStream = section.GetEventStream
local KeyPressed = keylogic.KeyPressed
local KeyReleased = keylogic.KeyReleased
local SectionGroup = windows.SectionGroup
local WithBoundGroups = windows.WithBoundGroups
-- Modules --
local coroutineops = coroutineops
local love = love
local tasks = tasks
-- Install a default time lapse function.
funcops.SetTimeLapseFunc(nil, love.timer.getDelta)
-- Set the current language.
settings.SetLanguage("english")
-- Export the game namespace.
module "game"
-- Actions in progress? --
local KeyActionStates = {}
-- Specialized key actions --
local KeyActions = {}
-- F4 state --
local F4_WasPressed
-- Install a timed task that runs for 7/10ths of a second --
KeyActions[love.key_f1] = function()
local updates = 0
GetEventStream("leave_update"):Add(tasks.WithTimer(
.7, -- TIMED TASK DURATION --
function() -- UPDATE FUNCTION --
updates = updates + 1
end,
function() -- QUIT FUNCTION --
printf("Timed task done! %i updates", updates)
KeyActionStates[love.key_f1] = false
end)
)
end
-- Install a periodic task that goes off every second --
KeyActions[love.key_f2] = function()
local update = 0
GetEventStream("leave_update"):Add(tasks.WithPeriod(
1, -- TIMEOUT DURATION --
function()
update = update + 1
printf("Periodic timeout #%i", update)
end)
)
end
-- Install a coroutine as a task --
KeyActions[love.key_f3] = function()
local func = wrap(function()
printf("Starting coroutine event, waiting 1.5 seconds, then printing for a couple seconds...")
coroutineops.Wait(1.5, nil, nil, true) -- yvalue of true so that the coroutine op yields true and event persists in stream
coroutineops.Wait(2, function(time)
printf("Update at time: %f", time)
end, nil, true)
printf("Waiting for user to press F4")
coroutineops.WaitUntil(function()
return F4_WasPressed
end, nil, nil, true)
printf("Ending coroutine event")
F4_WasPressed = false
KeyActionStates[love.key_f3] = false
end)
GetEventStream("leave_update"):Add(func)
end
-- Helper function to cooperate with coroutine task --
KeyActions[love.key_f4] = function()
F4_WasPressed = true
KeyActionStates[love.key_f4] = false
end
do
-- Key pressed function --
function keypressed (key)
if not KeyActions[key] then
KeyPressed(key, .15)
end
end
-- Key released function --
function keyreleased (key)
if KeyActions[key] then
if not KeyActionStates[key] then
KeyActionStates[key] = true
KeyActions[key]()
end
else
KeyReleased(key)
end
end
end
do
-- Render body
---------------
local function Render ()
SectionGroup()("render")
end
-- Draw function --
function draw ()
-- If necessary, restore the scissor state.
ApplyScissorState()
--
WithBoundGroups(Render, 0)
end
end
do
local DT
-- Between body
----------------
local function Between ()
GetEventStream("between_frames")()
end
-- Trap body
-------------
local function Trap ()
SectionGroup()("trap")
end
-- Update body
---------------
local function Update ()
SectionGroup()("update", DT)
end
-- Update function --
function update (dt)
DT = dt
WithBoundGroups(Between, 0)
WithBoundGroups(Trap, 0)
WithBoundGroups(Update, 0)
end
end | mit |
TabindaAshraf/google-diff-match-patch | lua/diff_match_patch.lua | 265 | 73869 | --[[
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser.
* Ported to Lua by Duncan Cross.
*
* 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.
--]]
--[[
-- Lua 5.1 and earlier requires the external BitOp library.
-- This library is built-in from Lua 5.2 and later as 'bit32'.
require 'bit' -- <http://bitop.luajit.org/>
local band, bor, lshift
= bit.band, bit.bor, bit.lshift
--]]
local band, bor, lshift
= bit32.band, bit32.bor, bit32.lshift
local type, setmetatable, ipairs, select
= type, setmetatable, ipairs, select
local unpack, tonumber, error
= unpack, tonumber, error
local strsub, strbyte, strchar, gmatch, gsub
= string.sub, string.byte, string.char, string.gmatch, string.gsub
local strmatch, strfind, strformat
= string.match, string.find, string.format
local tinsert, tremove, tconcat
= table.insert, table.remove, table.concat
local max, min, floor, ceil, abs
= math.max, math.min, math.floor, math.ceil, math.abs
local clock = os.clock
-- Utility functions.
local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]'
local function percentEncode_replace(v)
return strformat('%%%02X', strbyte(v))
end
local function tsplice(t, idx, deletions, ...)
local insertions = select('#', ...)
for i = 1, deletions do
tremove(t, idx)
end
for i = insertions, 1, -1 do
-- do not remove parentheses around select
tinsert(t, idx, (select(i, ...)))
end
end
local function strelement(str, i)
return strsub(str, i, i)
end
local function indexOf(a, b, start)
if (#b == 0) then
return nil
end
return strfind(a, b, start, true)
end
local htmlEncode_pattern = '[&<>\n]'
local htmlEncode_replace = {
['&'] = '&', ['<'] = '<', ['>'] = '>', ['\n'] = '¶<br>'
}
-- Public API Functions
-- (Exported at the end of the script)
local diff_main,
diff_cleanupSemantic,
diff_cleanupEfficiency,
diff_levenshtein,
diff_prettyHtml
local match_main
local patch_make,
patch_toText,
patch_fromText,
patch_apply
--[[
* The data structure representing a diff is an array of tuples:
* {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}}
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
--]]
local DIFF_DELETE = -1
local DIFF_INSERT = 1
local DIFF_EQUAL = 0
-- Number of seconds to map a diff before giving up (0 for infinity).
local Diff_Timeout = 1.0
-- Cost of an empty edit operation in terms of edit characters.
local Diff_EditCost = 4
-- At what point is no match declared (0.0 = perfection, 1.0 = very loose).
local Match_Threshold = 0.5
-- How far to search for a match (0 = exact location, 1000+ = broad match).
-- A match this many characters away from the expected location will add
-- 1.0 to the score (0.0 is a perfect match).
local Match_Distance = 1000
-- When deleting a large block of text (over ~64 characters), how close do
-- the contents have to be to match the expected contents. (0.0 = perfection,
-- 1.0 = very loose). Note that Match_Threshold controls how closely the
-- end points of a delete need to match.
local Patch_DeleteThreshold = 0.5
-- Chunk size for context length.
local Patch_Margin = 4
-- The number of bits in an int.
local Match_MaxBits = 32
function settings(new)
if new then
Diff_Timeout = new.Diff_Timeout or Diff_Timeout
Diff_EditCost = new.Diff_EditCost or Diff_EditCost
Match_Threshold = new.Match_Threshold or Match_Threshold
Match_Distance = new.Match_Distance or Match_Distance
Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold
Patch_Margin = new.Patch_Margin or Patch_Margin
Match_MaxBits = new.Match_MaxBits or Match_MaxBits
else
return {
Diff_Timeout = Diff_Timeout;
Diff_EditCost = Diff_EditCost;
Match_Threshold = Match_Threshold;
Match_Distance = Match_Distance;
Patch_DeleteThreshold = Patch_DeleteThreshold;
Patch_Margin = Patch_Margin;
Match_MaxBits = Match_MaxBits;
}
end
end
-- ---------------------------------------------------------------------------
-- DIFF API
-- ---------------------------------------------------------------------------
-- The private diff functions
local _diff_compute,
_diff_bisect,
_diff_halfMatchI,
_diff_halfMatch,
_diff_cleanupSemanticScore,
_diff_cleanupSemanticLossless,
_diff_cleanupMerge,
_diff_commonPrefix,
_diff_commonSuffix,
_diff_commonOverlap,
_diff_xIndex,
_diff_text1,
_diff_text2,
_diff_toDelta,
_diff_fromDelta
--[[
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} opt_checklines Has no effect in Lua.
* @param {number} opt_deadline Optional time when the diff should be complete
* by. Used internally for recursive calls. Users should set DiffTimeout
* instead.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
--]]
function diff_main(text1, text2, opt_checklines, opt_deadline)
-- Set a deadline by which time the diff must be complete.
if opt_deadline == nil then
if Diff_Timeout <= 0 then
opt_deadline = 2 ^ 31
else
opt_deadline = clock() + Diff_Timeout
end
end
local deadline = opt_deadline
-- Check for null inputs.
if text1 == nil or text1 == nil then
error('Null inputs. (diff_main)')
end
-- Check for equality (speedup).
if text1 == text2 then
if #text1 > 0 then
return {{DIFF_EQUAL, text1}}
end
return {}
end
-- LUANOTE: Due to the lack of Unicode support, Lua is incapable of
-- implementing the line-mode speedup.
local checklines = false
-- Trim off common prefix (speedup).
local commonlength = _diff_commonPrefix(text1, text2)
local commonprefix
if commonlength > 0 then
commonprefix = strsub(text1, 1, commonlength)
text1 = strsub(text1, commonlength + 1)
text2 = strsub(text2, commonlength + 1)
end
-- Trim off common suffix (speedup).
commonlength = _diff_commonSuffix(text1, text2)
local commonsuffix
if commonlength > 0 then
commonsuffix = strsub(text1, -commonlength)
text1 = strsub(text1, 1, -commonlength - 1)
text2 = strsub(text2, 1, -commonlength - 1)
end
-- Compute the diff on the middle block.
local diffs = _diff_compute(text1, text2, checklines, deadline)
-- Restore the prefix and suffix.
if commonprefix then
tinsert(diffs, 1, {DIFF_EQUAL, commonprefix})
end
if commonsuffix then
diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix}
end
_diff_cleanupMerge(diffs)
return diffs
end
--[[
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupSemantic(diffs)
local changes = false
local equalities = {} -- Stack of indices where equalities are found.
local equalitiesLength = 0 -- Keeping our own length var is faster.
local lastequality = nil
-- Always equal to diffs[equalities[equalitiesLength]][2]
local pointer = 1 -- Index of current position.
-- Number of characters that changed prior to the equality.
local length_insertions1 = 0
local length_deletions1 = 0
-- Number of characters that changed after the equality.
local length_insertions2 = 0
local length_deletions2 = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
length_insertions1 = length_insertions2
length_deletions1 = length_deletions2
length_insertions2 = 0
length_deletions2 = 0
lastequality = diffs[pointer][2]
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_INSERT then
length_insertions2 = length_insertions2 + #(diffs[pointer][2])
else
length_deletions2 = length_deletions2 + #(diffs[pointer][2])
end
-- Eliminate an equality that is smaller or equal to the edits on both
-- sides of it.
if lastequality
and (#lastequality <= max(length_insertions1, length_deletions1))
and (#lastequality <= max(length_insertions2, length_deletions2)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
-- Throw away the previous equality (it needs to be reevaluated).
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
length_insertions1, length_deletions1 = 0, 0 -- Reset the counters.
length_insertions2, length_deletions2 = 0, 0
lastequality = nil
changes = true
end
end
pointer = pointer + 1
end
-- Normalize the diff.
if changes then
_diff_cleanupMerge(diffs)
end
_diff_cleanupSemanticLossless(diffs)
-- Find any overlaps between deletions and insertions.
-- e.g: <del>abcxxx</del><ins>xxxdef</ins>
-- -> <del>abc</del>xxx<ins>def</ins>
-- e.g: <del>xxxabc</del><ins>defxxx</ins>
-- -> <ins>def</ins>xxx<del>abc</del>
-- Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 2
while diffs[pointer] do
if (diffs[pointer - 1][1] == DIFF_DELETE and
diffs[pointer][1] == DIFF_INSERT) then
local deletion = diffs[pointer - 1][2]
local insertion = diffs[pointer][2]
local overlap_length1 = _diff_commonOverlap(deletion, insertion)
local overlap_length2 = _diff_commonOverlap(insertion, deletion)
if (overlap_length1 >= overlap_length2) then
if (overlap_length1 >= #deletion / 2 or
overlap_length1 >= #insertion / 2) then
-- Overlap found. Insert an equality and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(insertion, 1, overlap_length1)})
diffs[pointer - 1][2] =
strsub(deletion, 1, #deletion - overlap_length1)
diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1)
pointer = pointer + 1
end
else
if (overlap_length2 >= #deletion / 2 or
overlap_length2 >= #insertion / 2) then
-- Reverse overlap found.
-- Insert an equality and swap and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(deletion, 1, overlap_length2)})
diffs[pointer - 1] = {DIFF_INSERT,
strsub(insertion, 1, #insertion - overlap_length2)}
diffs[pointer + 1] = {DIFF_DELETE,
strsub(deletion, overlap_length2 + 1)}
pointer = pointer + 1
end
end
pointer = pointer + 1
end
pointer = pointer + 1
end
end
--[[
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupEfficiency(diffs)
local changes = false
-- Stack of indices where equalities are found.
local equalities = {}
-- Keeping our own length var is faster.
local equalitiesLength = 0
-- Always equal to diffs[equalities[equalitiesLength]][2]
local lastequality = nil
-- Index of current position.
local pointer = 1
-- The following four are really booleans but are stored as numbers because
-- they are used at one point like this:
--
-- (pre_ins + pre_del + post_ins + post_del) == 3
--
-- ...i.e. checking that 3 of them are true and 1 of them is false.
-- Is there an insertion operation before the last equality.
local pre_ins = 0
-- Is there a deletion operation before the last equality.
local pre_del = 0
-- Is there an insertion operation after the last equality.
local post_ins = 0
-- Is there a deletion operation after the last equality.
local post_del = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
local diffText = diffs[pointer][2]
if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then
-- Candidate found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
pre_ins, pre_del = post_ins, post_del
lastequality = diffText
else
-- Not a candidate, and can never become one.
equalitiesLength = 0
lastequality = nil
end
post_ins, post_del = 0, 0
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_DELETE then
post_del = 1
else
post_ins = 1
end
--[[
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
--]]
if lastequality and (
(pre_ins+pre_del+post_ins+post_del == 4)
or
(
(#lastequality < Diff_EditCost / 2)
and
(pre_ins+pre_del+post_ins+post_del == 3)
)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
lastequality = nil
if (pre_ins == 1) and (pre_del == 1) then
-- No changes made which could affect previous entry, keep going.
post_ins, post_del = 1, 1
equalitiesLength = 0
else
-- Throw away the previous equality.
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
post_ins, post_del = 0, 0
end
changes = true
end
end
pointer = pointer + 1
end
if changes then
_diff_cleanupMerge(diffs)
end
end
--[[
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {number} Number of changes.
--]]
function diff_levenshtein(diffs)
local levenshtein = 0
local insertions, deletions = 0, 0
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op == DIFF_INSERT) then
insertions = insertions + #data
elseif (op == DIFF_DELETE) then
deletions = deletions + #data
elseif (op == DIFF_EQUAL) then
-- A deletion and an insertion is one substitution.
levenshtein = levenshtein + max(insertions, deletions)
insertions = 0
deletions = 0
end
end
levenshtein = levenshtein + max(insertions, deletions)
return levenshtein
end
--[[
* Convert a diff array into a pretty HTML report.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} HTML representation.
--]]
function diff_prettyHtml(diffs)
local html = {}
for x, diff in ipairs(diffs) do
local op = diff[1] -- Operation (insert, delete, equal)
local data = diff[2] -- Text of change.
local text = gsub(data, htmlEncode_pattern, htmlEncode_replace)
if op == DIFF_INSERT then
html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>'
elseif op == DIFF_DELETE then
html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>'
elseif op == DIFF_EQUAL then
html[x] = '<span>' .. text .. '</span>'
end
end
return tconcat(html)
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE DIFF FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Has no effect in Lua.
* @param {number} deadline Time when the diff should be complete by.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_compute(text1, text2, checklines, deadline)
if #text1 == 0 then
-- Just add some text (speedup).
return {{DIFF_INSERT, text2}}
end
if #text2 == 0 then
-- Just delete some text (speedup).
return {{DIFF_DELETE, text1}}
end
local diffs
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
local i = indexOf(longtext, shorttext)
if i ~= nil then
-- Shorter text is inside the longer text (speedup).
diffs = {
{DIFF_INSERT, strsub(longtext, 1, i - 1)},
{DIFF_EQUAL, shorttext},
{DIFF_INSERT, strsub(longtext, i + #shorttext)}
}
-- Swap insertions for deletions if diff is reversed.
if #text1 > #text2 then
diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE
end
return diffs
end
if #shorttext == 1 then
-- Single character string.
-- After the previous speedup, the character can't be an equality.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
-- Check to see if the problem can be split in two.
do
local
text1_a, text1_b,
text2_a, text2_b,
mid_common = _diff_halfMatch(text1, text2)
if text1_a then
-- A half-match was found, sort out the return data.
-- Send both pairs off for separate processing.
local diffs_a = diff_main(text1_a, text2_a, checklines, deadline)
local diffs_b = diff_main(text1_b, text2_b, checklines, deadline)
-- Merge the results.
local diffs_a_len = #diffs_a
diffs = diffs_a
diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common}
for i, b_diff in ipairs(diffs_b) do
diffs[diffs_a_len + 1 + i] = b_diff
end
return diffs
end
end
return _diff_bisect(text1, text2, deadline)
end
--[[
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisect(text1, text2, deadline)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
local _sub, _element
local max_d = ceil((text1_length + text2_length) / 2)
local v_offset = max_d
local v_length = 2 * max_d
local v1 = {}
local v2 = {}
-- Setting all elements to -1 is faster in Lua than mixing integers and nil.
for x = 0, v_length - 1 do
v1[x] = -1
v2[x] = -1
end
v1[v_offset + 1] = 0
v2[v_offset + 1] = 0
local delta = text1_length - text2_length
-- If the total number of characters is odd, then
-- the front path will collide with the reverse path.
local front = (delta % 2 ~= 0)
-- Offsets for start and end of k loop.
-- Prevents mapping of space beyond the grid.
local k1start = 0
local k1end = 0
local k2start = 0
local k2end = 0
for d = 0, max_d - 1 do
-- Bail out if deadline is reached.
if clock() > deadline then
break
end
-- Walk the front path one step.
for k1 = -d + k1start, d - k1end, 2 do
local k1_offset = v_offset + k1
local x1
if (k1 == -d) or ((k1 ~= d) and
(v1[k1_offset - 1] < v1[k1_offset + 1])) then
x1 = v1[k1_offset + 1]
else
x1 = v1[k1_offset - 1] + 1
end
local y1 = x1 - k1
while (x1 <= text1_length) and (y1 <= text2_length)
and (strelement(text1, x1) == strelement(text2, y1)) do
x1 = x1 + 1
y1 = y1 + 1
end
v1[k1_offset] = x1
if x1 > text1_length + 1 then
-- Ran off the right of the graph.
k1end = k1end + 2
elseif y1 > text2_length + 1 then
-- Ran off the bottom of the graph.
k1start = k1start + 2
elseif front then
local k2_offset = v_offset + delta - k1
if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then
-- Mirror x2 onto top-left coordinate system.
local x2 = text1_length - v2[k2_offset] + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
-- Walk the reverse path one step.
for k2 = -d + k2start, d - k2end, 2 do
local k2_offset = v_offset + k2
local x2
if (k2 == -d) or ((k2 ~= d) and
(v2[k2_offset - 1] < v2[k2_offset + 1])) then
x2 = v2[k2_offset + 1]
else
x2 = v2[k2_offset - 1] + 1
end
local y2 = x2 - k2
while (x2 <= text1_length) and (y2 <= text2_length)
and (strelement(text1, -x2) == strelement(text2, -y2)) do
x2 = x2 + 1
y2 = y2 + 1
end
v2[k2_offset] = x2
if x2 > text1_length + 1 then
-- Ran off the left of the graph.
k2end = k2end + 2
elseif y2 > text2_length + 1 then
-- Ran off the top of the graph.
k2start = k2start + 2
elseif not front then
local k1_offset = v_offset + delta - k2
if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then
local x1 = v1[k1_offset]
local y1 = v_offset + x1 - k1_offset
-- Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2 + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
end
-- Diff took too long and hit the deadline or
-- number of diffs equals number of characters, no commonality at all.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
--[[
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisectSplit(text1, text2, x, y, deadline)
local text1a = strsub(text1, 1, x - 1)
local text2a = strsub(text2, 1, y - 1)
local text1b = strsub(text1, x)
local text2b = strsub(text2, y)
-- Compute both diffs serially.
local diffs = diff_main(text1a, text2a, false, deadline)
local diffsb = diff_main(text1b, text2b, false, deadline)
local diffs_len = #diffs
for i, v in ipairs(diffsb) do
diffs[diffs_len + i] = v
end
return diffs
end
--[[
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
--]]
function _diff_commonPrefix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1))
then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerstart = 1
while (pointermin < pointermid) do
if (strsub(text1, pointerstart, pointermid)
== strsub(text2, pointerstart, pointermid)) then
pointermin = pointermid
pointerstart = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
--]]
function _diff_commonSuffix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0)
or (strbyte(text1, -1) ~= strbyte(text2, -1)) then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerend = 1
while (pointermin < pointermid) do
if (strsub(text1, -pointermid, -pointerend)
== strsub(text2, -pointermid, -pointerend)) then
pointermin = pointermid
pointerend = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
--]]
function _diff_commonOverlap(text1, text2)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
-- Eliminate the null case.
if text1_length == 0 or text2_length == 0 then
return 0
end
-- Truncate the longer string.
if text1_length > text2_length then
text1 = strsub(text1, text1_length - text2_length + 1)
elseif text1_length < text2_length then
text2 = strsub(text2, 1, text1_length)
end
local text_length = min(text1_length, text2_length)
-- Quick check for the worst case.
if text1 == text2 then
return text_length
end
-- Start by looking for a single character match
-- and increase length until no match is found.
-- Performance analysis: http://neil.fraser.name/news/2010/11/04/
local best = 0
local length = 1
while true do
local pattern = strsub(text1, text_length - length + 1)
local found = strfind(text2, pattern, 1, true)
if found == nil then
return best
end
length = length + found - 1
if found == 1 or strsub(text1, text_length - length + 1) ==
strsub(text2, 1, length) then
best = length
length = length + 1
end
end
end
--[[
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* This speedup can produce non-minimal diffs.
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {?Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatchI(longtext, shorttext, i)
-- Start with a 1/4 length substring at position i as a seed.
local seed = strsub(longtext, i, i + floor(#longtext / 4))
local j = 0 -- LUANOTE: do not change to 1, was originally -1
local best_common = ''
local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b
while true do
j = indexOf(shorttext, seed, j + 1)
if (j == nil) then
break
end
local prefixLength = _diff_commonPrefix(strsub(longtext, i),
strsub(shorttext, j))
local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1),
strsub(shorttext, 1, j - 1))
if #best_common < suffixLength + prefixLength then
best_common = strsub(shorttext, j - suffixLength, j - 1)
.. strsub(shorttext, j, j + prefixLength - 1)
best_longtext_a = strsub(longtext, 1, i - suffixLength - 1)
best_longtext_b = strsub(longtext, i + prefixLength)
best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1)
best_shorttext_b = strsub(shorttext, j + prefixLength)
end
end
if #best_common * 2 >= #longtext then
return {best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common}
else
return nil
end
end
--[[
* Do the two texts share a substring which is at least half the length of the
* longer text?
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {?Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatch(text1, text2)
if Diff_Timeout <= 0 then
-- Don't risk returning a non-optimal diff if we have unlimited time.
return nil
end
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
if (#longtext < 4) or (#shorttext * 2 < #longtext) then
return nil -- Pointless.
end
-- First check if the second quarter is the seed for a half-match.
local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4))
-- Check again based on the third quarter.
local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2))
local hm
if not hm1 and not hm2 then
return nil
elseif not hm2 then
hm = hm1
elseif not hm1 then
hm = hm2
else
-- Both matched. Select the longest.
hm = (#hm1[5] > #hm2[5]) and hm1 or hm2
end
-- A half-match was found, sort out the return data.
local text1_a, text1_b, text2_a, text2_b
if (#text1 > #text2) then
text1_a, text1_b = hm[1], hm[2]
text2_a, text2_b = hm[3], hm[4]
else
text2_a, text2_b = hm[1], hm[2]
text1_a, text1_b = hm[3], hm[4]
end
local mid_common = hm[5]
return text1_a, text1_b, text2_a, text2_b, mid_common
end
--[[
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
* @param {string} one First string.
* @param {string} two Second string.
* @return {number} The score.
* @private
--]]
function _diff_cleanupSemanticScore(one, two)
if (#one == 0) or (#two == 0) then
-- Edges are the best.
return 6
end
-- Each port of this function behaves slightly differently due to
-- subtle differences in each language's definition of things like
-- 'whitespace'. Since this function's purpose is largely cosmetic,
-- the choice has been made to use each language's native features
-- rather than force total conformity.
local char1 = strsub(one, -1)
local char2 = strsub(two, 1, 1)
local nonAlphaNumeric1 = strmatch(char1, '%W')
local nonAlphaNumeric2 = strmatch(char2, '%W')
local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s')
local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s')
local lineBreak1 = whitespace1 and strmatch(char1, '%c')
local lineBreak2 = whitespace2 and strmatch(char2, '%c')
local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$')
local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n')
if blankLine1 or blankLine2 then
-- Five points for blank lines.
return 5
elseif lineBreak1 or lineBreak2 then
-- Four points for line breaks.
return 4
elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then
-- Three points for end of sentences.
return 3
elseif whitespace1 or whitespace2 then
-- Two points for whitespace.
return 2
elseif nonAlphaNumeric1 or nonAlphaNumeric2 then
-- One point for non-alphanumeric.
return 1
end
return 0
end
--[[
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupSemanticLossless(diffs)
local pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while diffs[pointer + 1] do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local equality1 = prevDiff[2]
local edit = diff[2]
local equality2 = nextDiff[2]
-- First, shift the edit as far left as possible.
local commonOffset = _diff_commonSuffix(equality1, edit)
if commonOffset > 0 then
local commonString = strsub(edit, -commonOffset)
equality1 = strsub(equality1, 1, -commonOffset - 1)
edit = commonString .. strsub(edit, 1, -commonOffset - 1)
equality2 = commonString .. equality2
end
-- Second, step character by character right, looking for the best fit.
local bestEquality1 = equality1
local bestEdit = edit
local bestEquality2 = equality2
local bestScore = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
while strbyte(edit, 1) == strbyte(equality2, 1) do
equality1 = equality1 .. strsub(edit, 1, 1)
edit = strsub(edit, 2) .. strsub(equality2, 1, 1)
equality2 = strsub(equality2, 2)
local score = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
-- The >= encourages trailing rather than leading whitespace on edits.
if score >= bestScore then
bestScore = score
bestEquality1 = equality1
bestEdit = edit
bestEquality2 = equality2
end
end
if prevDiff[2] ~= bestEquality1 then
-- We have an improvement, save it back to the diff.
if #bestEquality1 > 0 then
diffs[pointer - 1][2] = bestEquality1
else
tremove(diffs, pointer - 1)
pointer = pointer - 1
end
diffs[pointer][2] = bestEdit
if #bestEquality2 > 0 then
diffs[pointer + 1][2] = bestEquality2
else
tremove(diffs, pointer + 1, 1)
pointer = pointer - 1
end
end
end
pointer = pointer + 1
end
end
--[[
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupMerge(diffs)
diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end.
local pointer = 1
local count_delete, count_insert = 0, 0
local text_delete, text_insert = '', ''
local commonlength
while diffs[pointer] do
local diff_type = diffs[pointer][1]
if diff_type == DIFF_INSERT then
count_insert = count_insert + 1
text_insert = text_insert .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_DELETE then
count_delete = count_delete + 1
text_delete = text_delete .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_EQUAL then
-- Upon reaching an equality, check for prior redundancies.
if count_delete + count_insert > 1 then
if (count_delete > 0) and (count_insert > 0) then
-- Factor out any common prefixies.
commonlength = _diff_commonPrefix(text_insert, text_delete)
if commonlength > 0 then
local back_pointer = pointer - count_delete - count_insert
if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL)
then
diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2]
.. strsub(text_insert, 1, commonlength)
else
tinsert(diffs, 1,
{DIFF_EQUAL, strsub(text_insert, 1, commonlength)})
pointer = pointer + 1
end
text_insert = strsub(text_insert, commonlength + 1)
text_delete = strsub(text_delete, commonlength + 1)
end
-- Factor out any common suffixies.
commonlength = _diff_commonSuffix(text_insert, text_delete)
if commonlength ~= 0 then
diffs[pointer][2] =
strsub(text_insert, -commonlength) .. diffs[pointer][2]
text_insert = strsub(text_insert, 1, -commonlength - 1)
text_delete = strsub(text_delete, 1, -commonlength - 1)
end
end
-- Delete the offending records and add the merged ones.
if count_delete == 0 then
tsplice(diffs, pointer - count_insert,
count_insert, {DIFF_INSERT, text_insert})
elseif count_insert == 0 then
tsplice(diffs, pointer - count_delete,
count_delete, {DIFF_DELETE, text_delete})
else
tsplice(diffs, pointer - count_delete - count_insert,
count_delete + count_insert,
{DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert})
end
pointer = pointer - count_delete - count_insert
+ (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1
elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then
-- Merge this equality with the previous one.
diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2]
tremove(diffs, pointer)
else
pointer = pointer + 1
end
count_insert, count_delete = 0, 0
text_delete, text_insert = '', ''
end
end
if diffs[#diffs][2] == '' then
diffs[#diffs] = nil -- Remove the dummy entry at the end.
end
-- Second pass: look for single edits surrounded on both sides by equalities
-- which can be shifted sideways to eliminate an equality.
-- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
local changes = false
pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while pointer < #diffs do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local currentText = diff[2]
local prevText = prevDiff[2]
local nextText = nextDiff[2]
if strsub(currentText, -#prevText) == prevText then
-- Shift the edit over the previous equality.
diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1)
nextDiff[2] = prevText .. nextDiff[2]
tremove(diffs, pointer - 1)
changes = true
elseif strsub(currentText, 1, #nextText) == nextText then
-- Shift the edit over the next equality.
prevDiff[2] = prevText .. nextText
diff[2] = strsub(currentText, #nextText + 1) .. nextText
tremove(diffs, pointer + 1)
changes = true
end
end
pointer = pointer + 1
end
-- If shifts were made, the diff needs reordering and another shift sweep.
if changes then
-- LUANOTE: no return value, but necessary to use 'return' to get
-- tail calls.
return _diff_cleanupMerge(diffs)
end
end
--[[
* loc is a location in text1, compute and return the equivalent location in
* text2.
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @param {number} loc Location within text1.
* @return {number} Location within text2.
--]]
function _diff_xIndex(diffs, loc)
local chars1 = 1
local chars2 = 1
local last_chars1 = 1
local last_chars2 = 1
local x
for _x, diff in ipairs(diffs) do
x = _x
if diff[1] ~= DIFF_INSERT then -- Equality or deletion.
chars1 = chars1 + #diff[2]
end
if diff[1] ~= DIFF_DELETE then -- Equality or insertion.
chars2 = chars2 + #diff[2]
end
if chars1 > loc then -- Overshot the location.
break
end
last_chars1 = chars1
last_chars2 = chars2
end
-- Was the location deleted?
if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then
return last_chars2
end
-- Add the remaining character length.
return last_chars2 + (loc - last_chars1)
end
--[[
* Compute and return the source text (all equalities and deletions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Source text.
--]]
function _diff_text1(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_INSERT then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Compute and return the destination text (all equalities and insertions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Destination text.
--]]
function _diff_text2(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_DELETE then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Crush the diff into an encoded string which describes the operations
* required to transform text1 into text2.
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
* Operations are tab-separated. Inserted text is escaped using %xx notation.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Delta text.
--]]
function _diff_toDelta(diffs)
local text = {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if op == DIFF_INSERT then
text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace)
elseif op == DIFF_DELETE then
text[x] = '-' .. #data
elseif op == DIFF_EQUAL then
text[x] = '=' .. #data
end
end
return tconcat(text, '\t')
end
--[[
* Given the original text1, and an encoded string which describes the
* operations required to transform text1 into text2, compute the full diff.
* @param {string} text1 Source string for the diff.
* @param {string} delta Delta text.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @throws {Errorend If invalid input.
--]]
function _diff_fromDelta(text1, delta)
local diffs = {}
local diffsLength = 0 -- Keeping our own length var is faster
local pointer = 1 -- Cursor in text1
for token in gmatch(delta, '[^\t]+') do
-- Each token begins with a one character parameter which specifies the
-- operation of this token (delete, insert, equality).
local tokenchar, param = strsub(token, 1, 1), strsub(token, 2)
if (tokenchar == '+') then
local invalidDecode = false
local decoded = gsub(param, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in _diff_fromDelta: ' .. param)
end
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_INSERT, decoded}
elseif (tokenchar == '-') or (tokenchar == '=') then
local n = tonumber(param)
if (n == nil) or (n < 0) then
error('Invalid number in _diff_fromDelta: ' .. param)
end
local text = strsub(text1, pointer, pointer + n - 1)
pointer = pointer + n
if (tokenchar == '=') then
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_EQUAL, text}
else
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_DELETE, text}
end
else
error('Invalid diff operation in _diff_fromDelta: ' .. token)
end
end
if (pointer ~= #text1 + 1) then
error('Delta length (' .. (pointer - 1)
.. ') does not equal source text length (' .. #text1 .. ').')
end
return diffs
end
-- ---------------------------------------------------------------------------
-- MATCH API
-- ---------------------------------------------------------------------------
local _match_bitap, _match_alphabet
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc'.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
--]]
function match_main(text, pattern, loc)
-- Check for null inputs.
if text == nil or pattern == nil or loc == nil then
error('Null inputs. (match_main)')
end
if text == pattern then
-- Shortcut (potentially not guaranteed by the algorithm)
return 1
elseif #text == 0 then
-- Nothing to match.
return -1
end
loc = max(1, min(loc, #text))
if strsub(text, loc, loc + #pattern - 1) == pattern then
-- Perfect match at the perfect spot! (Includes case of null pattern)
return loc
else
-- Do a fuzzy compare.
return _match_bitap(text, pattern, loc)
end
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE MATCH FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Initialise the alphabet for the Bitap algorithm.
* @param {string} pattern The text to encode.
* @return {Object} Hash of character locations.
* @private
--]]
function _match_alphabet(pattern)
local s = {}
local i = 0
for c in gmatch(pattern, '.') do
s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1))
i = i + 1
end
return s
end
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
* Bitap algorithm.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
* @private
--]]
function _match_bitap(text, pattern, loc)
if #pattern > Match_MaxBits then
error('Pattern too long.')
end
-- Initialise the alphabet.
local s = _match_alphabet(pattern)
--[[
* Compute and return the score for a match with e errors and x location.
* Accesses loc and pattern through being a closure.
* @param {number} e Number of errors in match.
* @param {number} x Location of match.
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
* @private
--]]
local function _match_bitapScore(e, x)
local accuracy = e / #pattern
local proximity = abs(loc - x)
if (Match_Distance == 0) then
-- Dodge divide by zero error.
return (proximity == 0) and 1 or accuracy
end
return accuracy + (proximity / Match_Distance)
end
-- Highest score beyond which we give up.
local score_threshold = Match_Threshold
-- Is there a nearby exact match? (speedup)
local best_loc = indexOf(text, pattern, loc)
if best_loc then
score_threshold = min(_match_bitapScore(0, best_loc), score_threshold)
-- LUANOTE: Ideally we'd also check from the other direction, but Lua
-- doesn't have an efficent lastIndexOf function.
end
-- Initialise the bit arrays.
local matchmask = lshift(1, #pattern - 1)
best_loc = -1
local bin_min, bin_mid
local bin_max = #pattern + #text
local last_rd
for d = 0, #pattern - 1, 1 do
-- Scan for the best match; each iteration allows for one more error.
-- Run a binary search to determine how far from 'loc' we can stray at this
-- error level.
bin_min = 0
bin_mid = bin_max
while (bin_min < bin_mid) do
if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then
bin_min = bin_mid
else
bin_max = bin_mid
end
bin_mid = floor(bin_min + (bin_max - bin_min) / 2)
end
-- Use the result from this iteration as the maximum for the next.
bin_max = bin_mid
local start = max(1, loc - bin_mid + 1)
local finish = min(loc + bin_mid, #text) + #pattern
local rd = {}
for j = start, finish do
rd[j] = 0
end
rd[finish + 1] = lshift(1, d) - 1
for j = finish, start, -1 do
local charMatch = s[strsub(text, j - 1, j - 1)] or 0
if (d == 0) then -- First pass: exact match.
rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch)
else
-- Subsequent passes: fuzzy match.
-- Functions instead of operators make this hella messy.
rd[j] = bor(
band(
bor(
lshift(rd[j + 1], 1),
1
),
charMatch
),
bor(
bor(
lshift(bor(last_rd[j + 1], last_rd[j]), 1),
1
),
last_rd[j + 1]
)
)
end
if (band(rd[j], matchmask) ~= 0) then
local score = _match_bitapScore(d, j - 1)
-- This match will almost certainly be better than any existing match.
-- But check anyway.
if (score <= score_threshold) then
-- Told you so.
score_threshold = score
best_loc = j - 1
if (best_loc > loc) then
-- When passing loc, don't exceed our current distance from loc.
start = max(1, loc * 2 - best_loc)
else
-- Already passed loc, downhill from here on in.
break
end
end
end
end
-- No hope for a (better) match at greater error levels.
if (_match_bitapScore(d + 1, loc) > score_threshold) then
break
end
last_rd = rd
end
return best_loc
end
-- -----------------------------------------------------------------------------
-- PATCH API
-- -----------------------------------------------------------------------------
local _patch_addContext,
_patch_deepCopy,
_patch_addPadding,
_patch_splitMax,
_patch_appendText,
_new_patch_obj
--[[
* Compute a list of patches to turn text1 into text2.
* Use diffs if provided, otherwise compute it ourselves.
* There are four ways to call this function, depending on what data is
* available to the caller:
* Method 1:
* a = text1, b = text2
* Method 2:
* a = diffs
* Method 3 (optimal):
* a = text1, b = diffs
* Method 4 (deprecated, use method 3):
* a = text1, b = text2, c = diffs
*
* @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or
* Array of diff tuples for text1 to text2 (method 2).
* @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
* @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for
* text1 to text2 (method 4) or undefined (methods 1,2,3).
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function patch_make(a, opt_b, opt_c)
local text1, diffs
local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c)
if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then
-- Method 1: text1, text2
-- Compute diffs from text1 and text2.
text1 = a
diffs = diff_main(text1, opt_b, true)
if (#diffs > 2) then
diff_cleanupSemantic(diffs)
diff_cleanupEfficiency(diffs)
end
elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then
-- Method 2: diffs
-- Compute text1 from diffs.
diffs = a
text1 = _diff_text1(diffs)
elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then
-- Method 3: text1, diffs
text1 = a
diffs = opt_b
elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table')
then
-- Method 4: text1, text2, diffs
-- text2 is not used.
text1 = a
diffs = opt_c
else
error('Unknown call format to patch_make.')
end
if (diffs[1] == nil) then
return {} -- Get rid of the null case.
end
local patches = {}
local patch = _new_patch_obj()
local patchDiffLength = 0 -- Keeping our own length var is faster.
local char_count1 = 0 -- Number of characters into the text1 string.
local char_count2 = 0 -- Number of characters into the text2 string.
-- Start with text1 (prepatch_text) and apply the diffs until we arrive at
-- text2 (postpatch_text). We recreate the patches one by one to determine
-- context info.
local prepatch_text, postpatch_text = text1, text1
for x, diff in ipairs(diffs) do
local diff_type, diff_text = diff[1], diff[2]
if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then
-- A new patch starts here.
patch.start1 = char_count1 + 1
patch.start2 = char_count2 + 1
end
if (diff_type == DIFF_INSERT) then
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length2 = patch.length2 + #diff_text
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. diff_text .. strsub(postpatch_text, char_count2 + 1)
elseif (diff_type == DIFF_DELETE) then
patch.length1 = patch.length1 + #diff_text
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. strsub(postpatch_text, char_count2 + #diff_text + 1)
elseif (diff_type == DIFF_EQUAL) then
if (#diff_text <= Patch_Margin * 2)
and (patchDiffLength ~= 0) and (#diffs ~= x) then
-- Small equality inside a patch.
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length1 = patch.length1 + #diff_text
patch.length2 = patch.length2 + #diff_text
elseif (#diff_text >= Patch_Margin * 2) then
-- Time for a new patch.
if (patchDiffLength ~= 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
patch = _new_patch_obj()
patchDiffLength = 0
-- Unlike Unidiff, our patch lists have a rolling context.
-- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
-- Update prepatch text & pos to reflect the application of the
-- just completed patch.
prepatch_text = postpatch_text
char_count1 = char_count2
end
end
end
-- Update the current character count.
if (diff_type ~= DIFF_INSERT) then
char_count1 = char_count1 + #diff_text
end
if (diff_type ~= DIFF_DELETE) then
char_count2 = char_count2 + #diff_text
end
end
-- Pick up the leftover patch if not empty.
if (patchDiffLength > 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
end
return patches
end
--[[
* Merge a set of patches onto the text. Return a patched text, as well
* as a list of true/false values indicating which patches were applied.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @param {string} text Old text.
* @return {Array.<string|Array.<boolean>>} Two return values, the
* new text and an array of boolean values.
--]]
function patch_apply(patches, text)
if patches[1] == nil then
return text, {}
end
-- Deep copy the patches so that no changes are made to originals.
patches = _patch_deepCopy(patches)
local nullPadding = _patch_addPadding(patches)
text = nullPadding .. text .. nullPadding
_patch_splitMax(patches)
-- delta keeps track of the offset between the expected and actual location
-- of the previous patch. If there are patches expected at positions 10 and
-- 20, but the first patch was found at 12, delta is 2 and the second patch
-- has an effective expected position of 22.
local delta = 0
local results = {}
for x, patch in ipairs(patches) do
local expected_loc = patch.start2 + delta
local text1 = _diff_text1(patch.diffs)
local start_loc
local end_loc = -1
if #text1 > Match_MaxBits then
-- _patch_splitMax will only provide an oversized pattern in
-- the case of a monster delete.
start_loc = match_main(text,
strsub(text1, 1, Match_MaxBits), expected_loc)
if start_loc ~= -1 then
end_loc = match_main(text, strsub(text1, -Match_MaxBits),
expected_loc + #text1 - Match_MaxBits)
if end_loc == -1 or start_loc >= end_loc then
-- Can't find valid trailing context. Drop this patch.
start_loc = -1
end
end
else
start_loc = match_main(text, text1, expected_loc)
end
if start_loc == -1 then
-- No match found. :(
results[x] = false
-- Subtract the delta for this failed patch from subsequent patches.
delta = delta - patch.length2 - patch.length1
else
-- Found a match. :)
results[x] = true
delta = start_loc - expected_loc
local text2
if end_loc == -1 then
text2 = strsub(text, start_loc, start_loc + #text1 - 1)
else
text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1)
end
if text1 == text2 then
-- Perfect match, just shove the replacement text in.
text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs)
.. strsub(text, start_loc + #text1)
else
-- Imperfect match. Run a diff to get a framework of equivalent
-- indices.
local diffs = diff_main(text1, text2, false)
if (#text1 > Match_MaxBits)
and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then
-- The end points match, but the content is unacceptably bad.
results[x] = false
else
_diff_cleanupSemanticLossless(diffs)
local index1 = 1
local index2
for y, mod in ipairs(patch.diffs) do
if mod[1] ~= DIFF_EQUAL then
index2 = _diff_xIndex(diffs, index1)
end
if mod[1] == DIFF_INSERT then
text = strsub(text, 1, start_loc + index2 - 2)
.. mod[2] .. strsub(text, start_loc + index2 - 1)
elseif mod[1] == DIFF_DELETE then
text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text,
start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1))
end
if mod[1] ~= DIFF_DELETE then
index1 = index1 + #mod[2]
end
end
end
end
end
end
-- Strip the padding off.
text = strsub(text, #nullPadding + 1, -#nullPadding - 1)
return text, results
end
--[[
* Take a list of patches and return a textual representation.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} Text representation of patches.
--]]
function patch_toText(patches)
local text = {}
for x, patch in ipairs(patches) do
_patch_appendText(patch, text)
end
return tconcat(text)
end
--[[
* Parse a textual representation of patches and return a list of patch objects.
* @param {string} textline Text representation of patches.
* @return {Array.<_new_patch_obj>} Array of patch objects.
* @throws {Error} If invalid input.
--]]
function patch_fromText(textline)
local patches = {}
if (#textline == 0) then
return patches
end
local text = {}
for line in gmatch(textline, '([^\n]*)') do
text[#text + 1] = line
end
local textPointer = 1
while (textPointer <= #text) do
local start1, length1, start2, length2
= strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$')
if (start1 == nil) then
error('Invalid patch string: "' .. text[textPointer] .. '"')
end
local patch = _new_patch_obj()
patches[#patches + 1] = patch
start1 = tonumber(start1)
length1 = tonumber(length1) or 1
if (length1 == 0) then
start1 = start1 + 1
end
patch.start1 = start1
patch.length1 = length1
start2 = tonumber(start2)
length2 = tonumber(length2) or 1
if (length2 == 0) then
start2 = start2 + 1
end
patch.start2 = start2
patch.length2 = length2
textPointer = textPointer + 1
while true do
local line = text[textPointer]
if (line == nil) then
break
end
local sign; sign, line = strsub(line, 1, 1), strsub(line, 2)
local invalidDecode = false
local decoded = gsub(line, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in patch_fromText: ' .. line)
end
line = decoded
if (sign == '-') then
-- Deletion.
patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line}
elseif (sign == '+') then
-- Insertion.
patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line}
elseif (sign == ' ') then
-- Minor equality.
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line}
elseif (sign == '@') then
-- Start of next patch.
break
elseif (sign == '') then
-- Blank line? Whatever.
else
-- WTF?
error('Invalid patch mode "' .. sign .. '" in: ' .. line)
end
textPointer = textPointer + 1
end
end
return patches
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE PATCH FUNCTIONS
-- ---------------------------------------------------------------------------
local patch_meta = {
__tostring = function(patch)
local buf = {}
_patch_appendText(patch, buf)
return tconcat(buf)
end
}
--[[
* Class representing one patch operation.
* @constructor
--]]
function _new_patch_obj()
return setmetatable({
--[[ @type {Array.<Array.<number|string>>} ]]
diffs = {};
--[[ @type {?number} ]]
start1 = 1; -- nil;
--[[ @type {?number} ]]
start2 = 1; -- nil;
--[[ @type {number} ]]
length1 = 0;
--[[ @type {number} ]]
length2 = 0;
}, patch_meta)
end
--[[
* Increase the context until it is unique,
* but don't let the pattern expand beyond Match_MaxBits.
* @param {_new_patch_obj} patch The patch to grow.
* @param {string} text Source text.
* @private
--]]
function _patch_addContext(patch, text)
if (#text == 0) then
return
end
local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1)
local padding = 0
-- LUANOTE: Lua's lack of a lastIndexOf function results in slightly
-- different logic here than in other language ports.
-- Look for the first two matches of pattern in text. If two are found,
-- increase the pattern length.
local firstMatch = indexOf(text, pattern)
local secondMatch = nil
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
end
while (#pattern == 0 or secondMatch ~= nil)
and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do
padding = padding + Patch_Margin
pattern = strsub(text, max(1, patch.start2 - padding),
patch.start2 + patch.length1 - 1 + padding)
firstMatch = indexOf(text, pattern)
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
else
secondMatch = nil
end
end
-- Add one chunk for good luck.
padding = padding + Patch_Margin
-- Add the prefix.
local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1)
if (#prefix > 0) then
tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix})
end
-- Add the suffix.
local suffix = strsub(text, patch.start2 + patch.length1,
patch.start2 + patch.length1 - 1 + padding)
if (#suffix > 0) then
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix}
end
-- Roll back the start points.
patch.start1 = patch.start1 - #prefix
patch.start2 = patch.start2 - #prefix
-- Extend the lengths.
patch.length1 = patch.length1 + #prefix + #suffix
patch.length2 = patch.length2 + #prefix + #suffix
end
--[[
* Given an array of patches, return another array that is identical.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function _patch_deepCopy(patches)
local patchesCopy = {}
for x, patch in ipairs(patches) do
local patchCopy = _new_patch_obj()
local diffsCopy = {}
for i, diff in ipairs(patch.diffs) do
diffsCopy[i] = {diff[1], diff[2]}
end
patchCopy.diffs = diffsCopy
patchCopy.start1 = patch.start1
patchCopy.start2 = patch.start2
patchCopy.length1 = patch.length1
patchCopy.length2 = patch.length2
patchesCopy[x] = patchCopy
end
return patchesCopy
end
--[[
* Add some padding on text start and end so that edges can match something.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} The padding string added to each side.
--]]
function _patch_addPadding(patches)
local paddingLength = Patch_Margin
local nullPadding = ''
for x = 1, paddingLength do
nullPadding = nullPadding .. strchar(x)
end
-- Bump all the patches forward.
for x, patch in ipairs(patches) do
patch.start1 = patch.start1 + paddingLength
patch.start2 = patch.start2 + paddingLength
end
-- Add some padding on start of first diff.
local patch = patches[1]
local diffs = patch.diffs
local firstDiff = diffs[1]
if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
tinsert(diffs, 1, {DIFF_EQUAL, nullPadding})
patch.start1 = patch.start1 - paddingLength -- Should be 0.
patch.start2 = patch.start2 - paddingLength -- Should be 0.
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #firstDiff[2]) then
-- Grow first equality.
local extraLength = paddingLength - #firstDiff[2]
firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2]
patch.start1 = patch.start1 - extraLength
patch.start2 = patch.start2 - extraLength
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
-- Add some padding on end of last diff.
patch = patches[#patches]
diffs = patch.diffs
local lastDiff = diffs[#diffs]
if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding}
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #lastDiff[2]) then
-- Grow last equality.
local extraLength = paddingLength - #lastDiff[2]
lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength)
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
return nullPadding
end
--[[
* Look through the patches and break up any which are longer than the maximum
* limit of the match algorithm.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
--]]
function _patch_splitMax(patches)
local patch_size = Match_MaxBits
local x = 1
while true do
local patch = patches[x]
if patch == nil then
return
end
if patch.length1 > patch_size then
local bigpatch = patch
-- Remove the big old patch.
tremove(patches, x)
x = x - 1
local start1 = bigpatch.start1
local start2 = bigpatch.start2
local precontext = ''
while bigpatch.diffs[1] do
-- Create one of several smaller patches.
local patch = _new_patch_obj()
local empty = true
patch.start1 = start1 - #precontext
patch.start2 = start2 - #precontext
if precontext ~= '' then
patch.length1, patch.length2 = #precontext, #precontext
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext}
end
while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do
local diff_type = bigpatch.diffs[1][1]
local diff_text = bigpatch.diffs[1][2]
if (diff_type == DIFF_INSERT) then
-- Insertions are harmless.
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1]
tremove(bigpatch.diffs, 1)
empty = false
elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1)
and (patch.diffs[1][1] == DIFF_EQUAL)
and (#diff_text > 2 * patch_size) then
-- This is a large deletion. Let it pass in one chunk.
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
empty = false
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
tremove(bigpatch.diffs, 1)
else
-- Deletion or equality.
-- Only take as much as we can stomach.
diff_text = strsub(diff_text, 1,
patch_size - patch.length1 - Patch_Margin)
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
if (diff_type == DIFF_EQUAL) then
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
else
empty = false
end
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
if (diff_text == bigpatch.diffs[1][2]) then
tremove(bigpatch.diffs, 1)
else
bigpatch.diffs[1][2]
= strsub(bigpatch.diffs[1][2], #diff_text + 1)
end
end
end
-- Compute the head context for the next patch.
precontext = _diff_text2(patch.diffs)
precontext = strsub(precontext, -Patch_Margin)
-- Append the end context for this patch.
local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin)
if postcontext ~= '' then
patch.length1 = patch.length1 + #postcontext
patch.length2 = patch.length2 + #postcontext
if patch.diffs[1]
and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then
patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2]
.. postcontext
else
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext}
end
end
if not empty then
x = x + 1
tinsert(patches, x, patch)
end
end
end
x = x + 1
end
end
--[[
* Emulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* @return {string} The GNU diff string.
--]]
function _patch_appendText(patch, text)
local coords1, coords2
local length1, length2 = patch.length1, patch.length2
local start1, start2 = patch.start1, patch.start2
local diffs = patch.diffs
if length1 == 1 then
coords1 = start1
else
coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1
end
if length2 == 1 then
coords2 = start2
else
coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2
end
text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n'
local op
-- Escape the body of the patch with %xx notation.
for x, diff in ipairs(patch.diffs) do
local diff_type = diff[1]
if diff_type == DIFF_INSERT then
op = '+'
elseif diff_type == DIFF_DELETE then
op = '-'
elseif diff_type == DIFF_EQUAL then
op = ' '
end
text[#text + 1] = op
.. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace)
.. '\n'
end
return text
end
-- Expose the API
local _M = {}
_M.DIFF_DELETE = DIFF_DELETE
_M.DIFF_INSERT = DIFF_INSERT
_M.DIFF_EQUAL = DIFF_EQUAL
_M.diff_main = diff_main
_M.diff_cleanupSemantic = diff_cleanupSemantic
_M.diff_cleanupEfficiency = diff_cleanupEfficiency
_M.diff_levenshtein = diff_levenshtein
_M.diff_prettyHtml = diff_prettyHtml
_M.match_main = match_main
_M.patch_make = patch_make
_M.patch_toText = patch_toText
_M.patch_fromText = patch_fromText
_M.patch_apply = patch_apply
-- Expose some non-API functions as well, for testing purposes etc.
_M.diff_commonPrefix = _diff_commonPrefix
_M.diff_commonSuffix = _diff_commonSuffix
_M.diff_commonOverlap = _diff_commonOverlap
_M.diff_halfMatch = _diff_halfMatch
_M.diff_bisect = _diff_bisect
_M.diff_cleanupMerge = _diff_cleanupMerge
_M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless
_M.diff_text1 = _diff_text1
_M.diff_text2 = _diff_text2
_M.diff_toDelta = _diff_toDelta
_M.diff_fromDelta = _diff_fromDelta
_M.diff_xIndex = _diff_xIndex
_M.match_alphabet = _match_alphabet
_M.match_bitap = _match_bitap
_M.new_patch_obj = _new_patch_obj
_M.patch_addContext = _patch_addContext
_M.patch_splitMax = _patch_splitMax
_M.patch_addPadding = _patch_addPadding
_M.settings = settings
return _M
| apache-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armuwadvms.lua | 1 | 2260 | return {
armuwadvms = {
buildangle = 5049,
buildcostenergy = 10493,
buildcostmetal = 705,
buildinggrounddecaldecayspeed = 30,
buildinggrounddecalsizex = 6,
buildinggrounddecalsizey = 6,
buildinggrounddecaltype = "armuwadvms_aoplane.dds",
buildpic = "ARMUWADVMS.DDS",
buildtime = 20391,
category = "ALL NOTSUB NOWEAPON NOTAIR NOTHOVER SURFACE",
collisionvolumeoffsets = "0 0 0",
collisionvolumescales = "45 48 45",
collisionvolumetest = 1,
collisionvolumetype = "CylY",
corpse = "DEAD",
description = "Increases Metal Storage (10000)",
explodeas = "LARGE_BUILDINGEX",
footprintx = 4,
footprintz = 4,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
maxdamage = 9300,
maxslope = 20,
maxwaterdepth = 9999,
metalstorage = 10000,
name = "Hardened Metal Storage",
objectname = "ARMUWADVMS",
seismicsignature = 0,
selfdestructas = "LARGE_BUILDING",
sightdistance = 195,
usebuildinggrounddecal = true,
yardmap = "oooooooooooooooo",
featuredefs = {
dead = {
blocking = true,
category = "corpses",
collisionvolumeoffsets = "7.62939453125e-06 -3.51196289046e-05 -0.0",
collisionvolumescales = "45.1519927979 49.1111297607 45.1520080566",
collisionvolumetype = "Box",
damage = 3720,
description = "Advanced Metal Storage Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 4,
footprintz = 4,
height = 9,
hitdensity = 100,
metal = 458,
object = "ARMUWADVMS_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "all",
},
heap = {
blocking = false,
category = "heaps",
damage = 1860,
description = "Advanced Metal Storage Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 4,
footprintz = 4,
hitdensity = 100,
metal = 183,
object = "4X4A",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "all",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
select = {
[1] = "stormtl1",
},
},
},
}
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/armfmkr.lua | 1 | 1101 | return {
armfmkr = {
acceleration = 0,
activatewhenbuilt = true,
brakerate = 0,
buildangle = 8192,
buildcostenergy = 2480,
buildcostmetal = 1,
buildpic = "ARMFMKR.DDS",
buildtime = 2958,
category = "ALL NOTLAND NOTSUB NOWEAPON NOTSHIP NOTAIR NOTHOVER SURFACE",
description = "Converts up to 60 energy into 1.1 metal per second",
explodeas = "ARMESTOR_BUILDINGEX",
footprintx = 3,
footprintz = 3,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
maxdamage = 110,
maxslope = 10,
maxwaterdepth = 0,
minwaterdepth = 11,
name = "Floating Energy Converter",
objectname = "ARMFMKR",
seismicsignature = 0,
selfdestructas = "ARMESTOR_BUILDING",
sightdistance = 273,
waterline = 4,
yardmap = "wwwwwwwww",
sounds = {
activate = "metlon1",
canceldestruct = "cancel2",
deactivate = "metloff1",
underattack = "warning1",
working = "metlrun1",
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
select = {
[1] = "metlon1",
},
},
},
}
| gpl-2.0 |
electric-cloud/metakit | lua/util.lua | 1 | 7380 | -- utility code, included in other scripts
-- 01/02/2001 jcw@equi4.com
-- dump data, adapted from lua/test/save.lua
function savevar (n,v)
if v == nil then return end
if type(v)=="userdata" or type(v)=="function" then return end
-- if type(v)=="userdata" or type(v)=="function" then write("\t-- ") end
write(n,"=")
if type(v) == "string" then write(format("%q",v))
elseif type(v) == "table" then
if v.__visited__ ~= nil then
write(v.__visited__, "\n")
else
write("{}\n")
v.__visited__ = n
for r,f in v do
if r ~= "__visited__" then
if type(r) == 'string' then
savevar(n.."."..r,f)
else
savevar(n.."["..r.."]",f)
end
end
end
end
return
else write(tostring(v)) end
write("\n")
end
-- pretty displays a value, properly dealing with tables and cycles
local displayvalue=
function (s)
if not s or type(s)=='function' or type(s)=='userdata' then
s=tostring(s)
elseif type(s)~='number' then
s=gsub(format('%q',s),'^"([^"\']*)"$',"'%1'")
end
return s
end
local askeystr=
function (u,s)
if type(u)=='string' and strfind(u,'^[%w_]+$') then return s..u end
return '['..%displayvalue(u)..']'
end
local horizvec=
function (x,n)
local o,e='',''
for i=1,getn(x) do
if type(x[i])=='table' then return end
o=o..e..%displayvalue(x[i])
if strlen(o)>n then return end
e=','
end
return '{'..o..'}'
end
local horizmap=
function (x,n)
local o,e='',''
for k,v in x do
if type(v)=='table' then return end
o=o..e..%askeystr(k,'')..'='..%displayvalue(v)
if strlen(o)>n then return end
e=','
end
return '{'..o..'}'
end
function pretty(p,x,h,q)
if not p then p,x='globals',globals() end
if type(x)=='table' then
if not h then h={} end
if h[x] then
x=h[x]
else
if not q then q=p end
h[x]=q
local s={}
for k,v in x do tinsert(s,k) end
if getn(s)>0 then
local n=75-strlen(p)
local f=getn(s)==getn(x) and %horizvec(x,n)
if not f then f=%horizmap(x,n) end
if not f then
sort(s,function (a,b)
if tag(a)~=tag(b) then a,b=tag(b),tag(a) end
return a<b
end)
for i=1,getn(s) do
if s[i] then
local u=%askeystr(s[i],'.')
pretty(p..u,x[s[i]],h,q..u)
p=strrep(' ',strlen(p))
end
end
return
end
x=f
else
x='{}'
end
end
else
x=%displayvalue(x)
end
print(p..' = '..x)
end
-- lispy is a compact pretty-printer for limited datasets
local showasstr=
function (s)
return type(s)=='string' and format('%q',s) or tostring(s)
end
horizstr=
function (x,n)
if type(x)~='table' then return %showasstr(x) end
if getn(x)==0 then return '()' end
local o,e=x[1]
for i=2,getn(x) do
local s=x[i]
if type(s)=='table' then
s=horizstr(s,n-strlen(o))
else
s=%showasstr(s)
end
if not s then return end
o=o..' '..s
if strlen(o)>n then return end
end
return '('..o..')'
end
function lispy(t,l,f)
local n=strlen(t)
local h=horizstr(l,70-n)
if h then
write(t,' ',h)
else
assert(type(l)=='table',l)
t=t..' ('..l[1]
local e=''
for i=2,getn(l) do
write(e)
lispy(t,l[i],1)
t=strrep(' ',strlen(t))
e='\n'
end
write(')')
end
if not f then write('\n') end
end
-- dump global names (or another table), summarizing keys (and scalar values)
function gdump(g)
g=g or globals()
local s={}
for i,v in g do
tinsert(s, i)
end
call(sort,{s},"x",nil) --XXX comparisons can fail
local f,t,u="","",""
print("\n<<<Scalars:>>>")
for i=1,getn(s) do
local n=s[i]
if type(g[n]) == 'function' then
f=f.." "..n
elseif type(g[n]) == 'table' then
t=t.." "..n
elseif type(g[n]) == 'userdata' then
u=u.." "..n
else
print(format(" %11s =",n),g[n])
end
end
if f~="" then print("\n<<<Functions>>>",f) end
if t~="" then print("\n<<<Tables>>>",t) end
if u~="" then print("\n<<<Userdata>>>",u) end
print("\nTotal:",getn(s))
end
-- evaluate each line in turn, optionally comparing results
-- if a comparison is included and it matches, nil is returned
-- otherwise, output is such that it can be re-used as match input
function tester(lines)
local t={}
gsub(lines,"\n*([^\n]+)\n*", function (v) tinsert(%t,v) end)
local f = function (s,t)
local r=dostring('return '..s)
if type(r)=="nil" then
r="nil"
elseif type(r)=="number" then
r=r..""
elseif type(r)=="table" then
r='table, n = '..getn(r)..', tag = '..tag(r)
elseif type(r)=="userdata" then
r='userdata, tag = '..tag(r)
elseif type(r)=="function" then
r=type(r)
else
r=format('%q',r)
end
if r~=t then return format('%36s == %s',s,r) end
end
local m,c=0,0
for i=1,getn(t) do
local l=gsub(gsub(t[i],'^ +',''),' +$','')
if i==getn(t) and l=="" then break end
if strfind(l,' == ') then
c=c+1
local o=gsub(l,'^(.*) == (.*)$',f,1)
if o~="" then print(o) else m=m+1 end
else
print(f(l))
end
end
if m<c then print(m..' results out of '..c..' matched') end
end
-- join vector with separator string
function join(v,s)
s=s or " "
local r=""
for i=1,getn(v) do
if i>1 then r=r..s end
r=r..(v[i] or "nil")
end
return r
end
-- split string on character set (freely adapted from cgilua)
function strsplit(s,c)
local t={}
gsub(s,"["..c.."]*([^"..c.."]+)["..c.."]*",
function (v) tinsert(%t,v) end)
return t
end
-- return file contents, or nil if reading failed
function fetchfile(p)
local f,e=openfile(p,'rb')
if f then
local d=read(f,'*a')
closefile(f)
return d
else
error(p..': '..e)
end
end
-- escape the most basic characters in html
function htmlize(s)
--s=gsub(s,'&','&')
s=gsub(s,'&','&')
s=gsub(s,'<','<')
s=gsub(s,'>','>')
return s
end
-- split a string on the newline character
function linesplit(s)
local t={}
gsub(s,"([^\n]*)\n",function (v) tinsert(%t,v) end)
return t
end
-- convert raw string to big-endian int
function beInt(s)
local v=0
for i=1,strlen(s) do v=v*256+strbyte(s,i) end
return v
end
-- convert raw string to little-endian int
function leInt(s)
local v=0
for i=strlen(s),1,-1 do v=v*256+strbyte(s,i) end
return v
end
-- cut up a string in big-endian ints of given size
function beStrCuts(s,...)
local o,r=1,{}
for i=1,getn(arg) do
tinsert(r,beInt(strsub(s,o,o+arg[i]-1)))
o=o+arg[i]
end
return r
end
-- cut up a string in little-endian ints of given size
function leStrCuts(s,...)
local o,r=1,{}
for i=1,getn(arg) do
tinsert(r,leInt(strsub(s,o,o+arg[i]-1)))
o=o+arg[i]
end
return r
end
-- convert string to hex chars
function hex(s)
-- is this faster than "for i=1,strlen(s) do ... end"?
local r=gsub(s,'(.)', function (c)
return format('%02X',strbyte(c))
end)
return r
end
-- map a function to each element in a vector
function map(t,f)
local r={}
for i=1,getn(t) do tinsert(r,f(t[i])) end
return r
end
-- filter only those elements which are selected by f
function filter(t,f)
local r={}
for i=1,getn(t) do
if f(t[i]) then tinsert(r,t[i]) end
end
return r
end
-- implement floor, without requiring the math lib
function intval(v)
return bor(v,0)
end
| mit |
MinaciousGrace/Til-Death | BGAnimations/ScreenSelectMusic decorations/simfile.lua | 2 | 12140 | local update = false
local t = Def.ActorFrame{
BeginCommand=cmd(queuecommand,"Set";visible,false);
OffCommand=cmd(bouncebegin,0.2;xy,-500,0;diffusealpha,0;); -- visible(false) doesn't seem to work with sleep
OnCommand=cmd(bouncebegin,0.2;xy,0,0;diffusealpha,1;);
SetCommand=function(self)
self:finishtweening()
if getTabIndex() == 3 then
self:queuecommand("On");
self:visible(true)
update = true
else
self:queuecommand("Off");
update = false
end;
end;
TabChangedMessageCommand=cmd(queuecommand,"Set");
PlayerJoinedMessageCommand=cmd(queuecommand,"Set");
};
local frameX = 10
local frameY = 45
local frameWidth = capWideScale(320,400)
local frameHeight = 350
local fontScale = 0.4
local distY = 15
local offsetX = 10
local offsetY = 20
local pn = GAMESTATE:GetEnabledPlayers()[1]
t[#t+1] = Def.Quad{
InitCommand=cmd(xy,frameX,frameY;zoomto,frameWidth,frameHeight;halign,0;valign,0;diffuse,color("#333333CC"));
};
t[#t+1] = Def.Quad{
InitCommand=cmd(xy,frameX+5,frameY+offsetY+5;zoomto,150,150*3/4;halign,0;valign,0;diffuse,color("#000000CC"));
};
t[#t+1] = Def.Sprite {
InitCommand=cmd(xy,frameX,frameY+offsetY-75;diffusealpha,0.8;);
Name="BG";
SetCommand=function(self)
if update then
self:finishtweening()
self:sleep(0.25)
local song = GAMESTATE:GetCurrentSong()
if song then
if song:HasJacket() then
self:visible(true);
self:Load(song:GetJacketPath())
elseif song:HasBackground() then
self:visible(true)
self:Load(song:GetBackgroundPath())
else
self:visible(false)
end
else
self:visible(false)
end;
self:scaletofit(frameX+5,frameY+5+offsetY,frameX+150+5,frameY+150*3/4+offsetY+5)
self:y(frameY+5+offsetY+150*3/8)
self:x(frameX+75+5)
self:smooth(0.5)
self:diffusealpha(0.8)
end
end;
BeginCommand=cmd(queuecommand,"Set");
CurrentSongChangedMessageCommand=cmd(finishtweening;smooth,0.5;diffusealpha,0;sleep,0.35;queuecommand,"Set");
};
t[#t+1] = Def.Sprite {
InitCommand=cmd(xy,frameX+75,frameY+125;zoomy,0;valign,1);
Name="CDTitle";
SetCommand=function(self)
if update then
self:finishtweening()
self:sleep(0.45)
local song = GAMESTATE:GetCurrentSong()
if song then
if song:HasCDTitle() then
self:visible(true)
self:Load(song:GetCDTitlePath())
else
self:visible(false)
end
else
self:visible(false)
end;
local height = self:GetHeight()
local width = self:GetWidth()
if height >= 80 and width >= 100 then
if height*(100/80) >= width then
self:zoom(80/height)
else
self:zoom(100/width)
end
elseif height >= 80 then
self:zoom(80/height)
elseif width >= 100 then
self:zoom(100/width)
else
self:zoom(1)
end
self:smooth(0.5)
self:diffusealpha(1)
end
end;
BeginCommand=cmd(queuecommand,"Set");
CurrentSongChangedMessageCommand=cmd(finishtweening;smooth,0.5;diffusealpha,0;sleep,0.35;queuecommand,"Set");
};
t[#t+1] = LoadFont("Common Normal")..{
Name="StepsAndMeter";
InitCommand=cmd(xy,frameX+frameWidth-offsetX,frameY+offsetY+10;zoom,0.5;halign,1;);
SetCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(pn)
if steps ~= nil and update then
local diff = getDifficulty(steps:GetDifficulty())
local stype = ToEnumShortString(steps:GetStepsType()):gsub("%_"," ")
local meter = steps:GetMeter()
self:settext(stype.." "..diff.." "..meter)
self:diffuse(getDifficultyColor(GetCustomDifficulty(steps:GetStepsType(),steps:GetDifficulty())))
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
CurrentStepsP1ChangedMessageCommand=cmd(queuecommand,"Set");
CurrentStepsP2ChangedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = LoadFont("Common Normal")..{
Name="StepsAndMeter";
InitCommand=cmd(xy,frameX+frameWidth-offsetX,frameY+offsetY+23;zoom,0.4;halign,1;);
SetCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(pn)
local song = GAMESTATE:GetCurrentSong()
local notecount = 0
local length = 1
if steps ~= nil and song ~= nil and update then
length = song:GetStepsSeconds()
notecount = steps:GetRadarValues(pn):GetValue("RadarCategory_Notes")
self:settext(string.format("%0.2f Average NPS",notecount/length))
self:diffuse(Saturation(getDifficultyColor(GetCustomDifficulty(steps:GetStepsType(),steps:GetDifficulty())),0.3))
else
self:settext("0.00 Average NPS")
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
CurrentStepsP1ChangedMessageCommand=cmd(queuecommand,"Set");
CurrentStepsP2ChangedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = LoadFont("Common Normal")..{
Name="Song Title";
InitCommand=cmd(xy,frameX+offsetX+150,frameY+offsetY+45;zoom,0.6;halign,0;maxwidth,((frameWidth-offsetX*2-150)/0.6)-40);
SetCommand=function(self)
if update then
local song = GAMESTATE:GetCurrentSong()
if song ~= nil then
self:settext(song:GetDisplayMainTitle())
self:diffuse(color("#FFFFFF"))
else
self:settext("Not Available")
self:diffuse(getMainColor("disabled"))
end
self:GetParent():GetChild("Song Length"):x(math.min(((frameWidth-offsetX*2-150)/0.6)-5,self:GetWidth()*0.6+self:GetX()+5))
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = LoadFont("Common Normal")..{
Name="Song SubTitle";
InitCommand=cmd(xy,frameX+offsetX+150,frameY+offsetY+60;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4);
SetCommand=function(self)
if update then
local song = GAMESTATE:GetCurrentSong()
if song ~= nil then
self:visible(true)
self:settext(song:GetDisplaySubTitle())
else
self:visible(false)
end
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = LoadFont("Common Normal")..{
Name="Song Artist";
InitCommand=cmd(xy,frameX+offsetX+150,frameY+offsetY+73;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4);
SetCommand=function(self)
local song = GAMESTATE:GetCurrentSong()
if song ~= nil then
self:visible(true)
self:settext(song:GetDisplayArtist())
self:diffuse(color("#FFFFFF"))
if #song:GetDisplaySubTitle() == 0 then
self:y(frameY+offsetY+60)
else
self:y(frameY+offsetY+73)
end
else
self:y(frameY+offsetY+60)
self:settext("Not Available")
self:diffuse(getMainColor("disabled"))
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = LoadFont("Common Normal")..{
Name="Song BPM";
InitCommand=cmd(xy,frameX+offsetX+150,frameY+offsetY+130;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4);
SetCommand=function(self)
local song = GAMESTATE:GetCurrentSong()
local bpms = {0,0}
if song ~= nil then
bpms = song:GetTimingData():GetActualBPM()
for k,v in pairs(bpms) do
bpms[k] = math.round(bpms[k])
end
self:visible(true)
if bpms[1] == bpms[2] and bpms[1]~= nil then
self:settext(string.format("BPM: %d",bpms[1]))
else
self:settext(string.format("BPM: %d-%d (%d)",bpms[1],bpms[2],getCommonBPM(song:GetTimingData():GetBPMsAndTimes(true),song:GetLastBeat())))
end
self:diffuse(color("#FFFFFF"))
else
self:settext("Not Available")
self:diffuse(getMainColor("disabled"))
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = LoadFont("Common Normal")..{
Name="BPM Change Count";
InitCommand=cmd(xy,frameX+offsetX+150,frameY+offsetY+145;zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4);
SetCommand=function(self)
local song = GAMESTATE:GetCurrentSong()
local bpms = {0,0}
if song ~= nil then
self:settext(string.format("BPM Changes: %d",getBPMChangeCount(song:GetTimingData():GetBPMsAndTimes(true))))
self:diffuse(color("#FFFFFF"))
else
self:settext("Not Available")
self:diffuse(getMainColor("disabled"))
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
local radarValues = {
{'RadarCategory_Notes','Notes'},
{'RadarCategory_TapsAndHolds','Taps'},
{'RadarCategory_Holds','Holds'},
{'RadarCategory_Rolls','Rolls'},
{'RadarCategory_Mines','Mines'},
{'RadarCategory_Lifts','Lifts'},
{'RadarCategory_Fakes','Fakes'},
}
for k,v in ipairs(radarValues) do
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+offsetX,frameY+offsetY+130+(15*(k-1));zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4);
OnCommand=function(self)
self:settext(v[2]..": ")
end;
}
t[#t+1] = LoadFont("Common Normal")..{
Name="RadarValue"..v[1];
InitCommand=cmd(xy,frameX+offsetX+40,frameY+offsetY+130+(15*(k-1));zoom,0.4;halign,0;maxwidth,(frameWidth-offsetX*2-150)/0.4);
SetCommand=function(self)
local song = GAMESTATE:GetCurrentSong()
local steps = GAMESTATE:GetCurrentSteps(pn)
local count = 0
if song ~= nil and steps ~= nil and update then
count = steps:GetRadarValues(pn):GetValue(v[1])
self:settext(count)
self:diffuse(color("#FFFFFF"))
else
self:settext(0)
self:diffuse(getMainColor("disabled"))
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
CurrentStepsP1ChangedMessageCommand=cmd(queuecommand,"Set");
CurrentStepsP2ChangedMessageCommand=cmd(queuecommand,"Set");
}
end
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+offsetX,frameY+frameHeight-10-distY*2;zoom,fontScale;halign,0;);
BeginCommand=function(self)
self:settext("Path:")
end
}
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+offsetX+35,frameY+frameHeight-10-distY*2;zoom,fontScale;halign,0;maxwidth,(frameWidth-35-offsetX-10)/fontScale);
BeginCommand=cmd(queuecommand,"Set");
SetCommand=function(self)
if update then
local song = GAMESTATE:GetCurrentSong()
if song ~= nil then
self:settext(song:GetSongDir())
self:diffuse(color("#FFFFFF"))
else
self:settext("Not Available")
self:diffuse(getMainColor("disabled"))
end
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
}
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+offsetX,frameY+frameHeight-10-distY;zoom,fontScale;halign,0;);
BeginCommand=function(self)
self:settext("SHA-1:")
end
}
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+offsetX+35,frameY+frameHeight-10-distY;zoom,fontScale;halign,0;maxwidth,(frameWidth-35)/fontScale);
BeginCommand=cmd(queuecommand,"Set");
SetCommand=function(self)
if update then
local pn = GAMESTATE:GetEnabledPlayers()[1]
local step = GAMESTATE:GetCurrentSteps(pn)
if song ~= nil then
self:diffuse(color("#FFFFFF"))
self:settext(SHA1FileHex(step:GetFilename()))
else
self:settext("Not Available")
self:diffuse(getMainColor("disabled"))
end
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+offsetX,frameY+frameHeight-10;zoom,fontScale;halign,0;);
BeginCommand=function(self)
self:settext("MD5:")
end
}
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+frameWidth/2,frameY+frameHeight-75;zoom,fontScale;);
BeginCommand=function(self)
self:settext("More to be added soon(TM)....ish")
self:diffusealpha(0.2)
end
}
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+offsetX+35,frameY+frameHeight-10;zoom,fontScale;halign,0;maxwidth,(frameWidth-35)/fontScale);
BeginCommand=cmd(queuecommand,"Set");
SetCommand=function(self)
if update then
local pn = GAMESTATE:GetEnabledPlayers()[1]
local step = GAMESTATE:GetCurrentSteps(pn)
if song ~= nil then
self:diffuse(color("#FFFFFF"))
self:settext(MD5FileHex(step:GetFilename()))
else
self:settext("Not Available")
self:diffuse(getMainColor("disabled"))
end
end
end;
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set");
};
t[#t+1] = Def.Quad{
InitCommand=cmd(xy,frameX,frameY;zoomto,frameWidth,offsetY;halign,0;valign,0;diffuse,getMainColor('frames'));
};
t[#t+1] = LoadFont("Common Normal")..{
InitCommand=cmd(xy,frameX+5,frameY+offsetY-9;zoom,0.6;halign,0;diffuse,getMainColor('highlight'));
BeginCommand=cmd(settext,"Simfile Info")
};
return t | mit |
jerizm/kong | kong/plugins/basic-auth/api.lua | 4 | 1897 | local crud = require "kong.api.crud_helpers"
local utils = require "kong.tools.utils"
return {
["/consumers/:username_or_id/basic-auth/"] = {
before = function(self, dao_factory, helpers)
crud.find_consumer_by_username_or_id(self, dao_factory, helpers)
self.params.consumer_id = self.consumer.id
end,
GET = function(self, dao_factory)
crud.paginated_set(self, dao_factory.basicauth_credentials)
end,
PUT = function(self, dao_factory)
crud.put(self.params, dao_factory.basicauth_credentials)
end,
POST = function(self, dao_factory)
crud.post(self.params, dao_factory.basicauth_credentials)
end
},
["/consumers/:username_or_id/basic-auth/:credential_username_or_id"] = {
before = function(self, dao_factory, helpers)
crud.find_consumer_by_username_or_id(self, dao_factory, helpers)
self.params.consumer_id = self.consumer.id
local filter_keys = {
[utils.is_valid_uuid(self.params.credential_username_or_id) and "id" or "username"] = self.params.credential_username_or_id,
consumer_id = self.params.consumer_id,
}
self.params.credential_username_or_id = nil
local credentials, err = dao_factory.basicauth_credentials:find_all(filter_keys)
if err then
return helpers.yield_error(err)
elseif next(credentials) == nil then
return helpers.responses.send_HTTP_NOT_FOUND()
end
self.basicauth_credential = credentials[1]
end,
GET = function(self, dao_factory, helpers)
return helpers.responses.send_HTTP_OK(self.basicauth_credential)
end,
PATCH = function(self, dao_factory)
crud.patch(self.params, dao_factory.basicauth_credentials, self.basicauth_credential)
end,
DELETE = function(self, dao_factory)
crud.delete(self.basicauth_credential, dao_factory.basicauth_credentials)
end
}
}
| apache-2.0 |
Sannis/tarantool | test/app/msgpackffi.test.lua | 8 | 2398 | #!/usr/bin/env tarantool
package.path = "lua/?.lua;"..package.path
local tap = require('tap')
local common = require('serializer_test')
local function is_map(s)
local b = string.byte(string.sub(s, 1, 1))
return b >= 0x80 and b <= 0x8f or b == 0xde or b == 0xdf
end
local function is_array(s)
local b = string.byte(string.sub(s, 1, 1))
return b >= 0x90 and b <= 0x9f or b == 0xdc or b == 0xdd
end
local function test_offsets(test, s)
test:plan(6)
local arr1 = {1, 2, 3}
local arr2 = {4, 5, 6}
local dump = s.encode(arr1)..s.encode(arr2)
test:is(dump:len(), 8, "length of part1 + part2")
local a
local offset = 1
a, offset = s.decode(dump, offset)
test:is_deeply(a, arr1, "decoded part1")
test:is(offset, 5, "offset of part2")
a, offset = s.decode(dump, offset)
test:is_deeply(a, arr2, "decoded part2")
test:is(offset, 9, "offset of end")
test:ok(not pcall(s.decode, dump, offset), "invalid offset")
end
local function test_other(test, s)
test:plan(3)
local buf = string.char(0x93, 0x6e, 0xcb, 0x42, 0x2b, 0xed, 0x30, 0x47,
0x6f, 0xff, 0xff, 0xac, 0x77, 0x6b, 0x61, 0x71, 0x66, 0x7a, 0x73,
0x7a, 0x75, 0x71, 0x71, 0x78)
local num = s.decode(buf)[2]
test:ok(num < 59971740600 and num > 59971740599, "gh-633 double decode")
-- gh-596: msgpack and msgpackffi have different behaviour
local arr = {1, 2, 3}
local map = {k1 = 'v1', k2 = 'v2', k3 = 'v3'}
test:is(getmetatable(s.decode(s.encode(arr))).__serialize, "seq",
"array save __serialize")
test:is(getmetatable(s.decode(s.encode(map))).__serialize, "map",
"map save __serialize")
end
tap.test("msgpackffi", function(test)
local serializer = require('msgpackffi')
test:plan(9)
test:test("unsigned", common.test_unsigned, serializer)
test:test("signed", common.test_signed, serializer)
test:test("double", common.test_double, serializer)
test:test("boolean", common.test_boolean, serializer)
test:test("string", common.test_string, serializer)
test:test("nil", common.test_nil, serializer)
test:test("table", common.test_table, serializer, is_array, is_map)
-- udata/cdata hooks are not implemented
--test:test("ucdata", common.test_ucdata, serializer)
test:test("offsets", test_offsets, serializer)
test:test("other", test_other, serializer)
end)
| bsd-2-clause |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/luarules/gadgets/lups_shockwaves.lua | 1 | 2323 |
function gadget:GetInfo()
return {
name = "Shockwaves",
desc = "",
author = "jK",
date = "Jan. 2008",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true
}
end
if (gadgetHandler:IsSyncedCode()) then
local SHOCK_WEAPONS = {
["armcom_arm_disintegrator"] = true,
["corcom_arm_disintegrator"] = true,
["armthund_armbomb"] = true,
-- ["armpnix_armadvbomb"] = true,
["armshock_shocker"] = true,
["armfboy_arm_fatboy_notalaser"] = true,
["armsb_seaadvbomb"] = true,
}
--// find weapons which cause a shockwave
for i=1,#WeaponDefs do
local wd = WeaponDefs[i]
if SHOCK_WEAPONS[wd.name] then
Script.SetWatchWeapon(wd.id,true)
SHOCK_WEAPONS[wd.id] = true
end
end
function gadget:Explosion(weaponID, px, py, pz, ownerID)
if SHOCK_WEAPONS[weaponID] then
local wd = WeaponDefs[weaponID]
if (wd.type == "DGun") then
SendToUnsynced("lups_shockwave", px, py, pz, 4.0, 18, 0.13, true)
else
local growth = (wd.damageAreaOfEffect*1.1)/20
SendToUnsynced("lups_shockwave", px, py, pz, growth, false)
end
end
return false
end
function gadget:RecvLuaMsg(msg, id)
if (msg == "lups shutdown") then
SendToUnsynced("shockwave_Toggle",false,id)
elseif (msg == "lups running") then
SendToUnsynced("shockwave_Toggle",true,id)
end
end
else
local enabled = false
local function SpawnShockwave(_,px,py,pz, growth, life, strength, desintergrator)
if (enabled) then
local Lups = GG['Lups']
if (desintergrator) then
Lups.AddParticles('SphereDistortion',{pos={px,py,pz}, life=life, strength=strength, growth=growth})
else
Lups.AddParticles('ShockWave',{pos={px,py,pz}, growth=growth})
end
end
end
local function Toggle(_,enable,playerId)
if (playerId == Spring.GetMyPlayerID()) then
if enable then
enabled = true
else
enabled = false
end
end
end
function gadget:Initialize()
gadgetHandler:AddSyncAction("lups_shockwave", SpawnShockwave)
gadgetHandler:AddSyncAction("shockwave_Toggle", Toggle)
end
function gadget:Shutdown()
gadgetHandler.RemoveSyncAction("lups_shockwave")
gadgetHandler.RemoveSyncAction("shockwave_Toggle")
end
end | gpl-2.0 |
PichotM/DarkRP | gamemode/modules/f4menu/cl_categories.lua | 5 | 3378 | --[[---------------------------------------------------------------------------
Category header
---------------------------------------------------------------------------]]
local PANEL = {}
function PANEL:Init()
self:SetContentAlignment(4)
self:SetTextInset(5, 0)
self:SetFont("DarkRPHUD2")
end
function PANEL:Paint(w, h)
if not self.category then return end
draw.RoundedBox(4, 0, 0, w, h, self.category.color)
end
function PANEL:UpdateColours() end
function PANEL:SetCategory(cat)
self.category = cat
self:SetText(cat.name)
end
derma.DefineControl("F4MenuCategoryHeader", "", PANEL, "DCategoryHeader")
--[[---------------------------------------------------------------------------
Contents of category headers
---------------------------------------------------------------------------]]
PANEL = {}
function PANEL:Init()
self:EnableVerticalScrollbar()
end
function PANEL:Rebuild()
if #self.Items == 0 then return end
local height = 0
local k = 0
for i, item in pairs(self.Items) do
if not item:IsVisible() then continue end
k = k + 1
item:SetWide(self:GetWide() - 10)
item:SetPos(5, height)
height = height + item:GetTall() + 2
end
self:GetCanvas():SetTall(height)
self:SetTall(height)
end
function PANEL:Refresh()
for k,v in pairs(self.Items) do
if v.Refresh then v:Refresh() end
end
self:InvalidateLayout()
end
derma.DefineControl("F4MenuCategoryContents", "", PANEL, "DPanelList")
--[[---------------------------------------------------------------------------
Category panel
---------------------------------------------------------------------------]]
PANEL = {}
function PANEL:Init()
if self.Header then self.Header:Remove() end
self.Header = vgui.Create("F4MenuCategoryHeader", self)
self.Header:Dock(TOP)
self.Header:SetSize(20, 40)
self:SetSize(16, 16)
self:SetExpanded(true)
self:SetMouseInputEnabled(true)
self:SetAnimTime(0.2)
self.animSlide = Derma_Anim("Anim", self, self.AnimSlide)
self:SetPaintBackgroundEnabled(false)
self:DockMargin(0, 0, 0, 10)
self:DockPadding(0, 0, 0, 10)
self:SetContents(vgui.Create("F4MenuCategoryContents", self))
end
function PANEL:Paint()
end
function PANEL:SetButtonFactory(f)
self.buttonFactory = f
end
function PANEL:SetCategory(cat)
self.category = cat
self.Header:SetCategory(cat)
self:Fill()
self:SetExpanded(cat.startExpanded)
end
function PANEL:SetPerformLayout(f)
self.Contents.PerformLayout = function()
f(self.Contents)
self.Contents.BaseClass.PerformLayout(self.Contents)
end
end
function PANEL:GetItems()
return self.Contents:GetItems()
end
function PANEL:Fill()
self.Contents:Clear(true)
for k, v in ipairs(self.category.members) do
local pnl = self.buttonFactory(v, self.Contents)
self.Contents:AddItem(pnl)
end
self:InvalidateLayout(true)
end
function PANEL:Refresh()
if IsValid(self.Contents) then self.Contents:Refresh() end
if not self.category then return end
local canSee = #self.category.members == 0 or isfunction(self.category.canSee) and not self.category.canSee(LocalPlayer())
self:SetVisible(not canSee)
self:InvalidateLayout()
end
derma.DefineControl("F4MenuCategory", "", PANEL, "DCollapsibleCategory")
| mit |
ggcrunchy/Old-Love2D-Demo | Scripts/Class/UI/Widget/ArrayView/Listbox.lua | 1 | 4453 | -- See TacoShell Copyright Notice in main folder of distribution
-- Standard library imports --
local assert = assert
local ipairs = ipairs
local max = math.max
local min = math.min
-- Imports --
local DrawString = widgetops.DrawString
local Find = table_ex.Find
local New = class.New
local PointInBox = numericops.PointInBox
local StateSwitch = widgetops.StateSwitch
local SuperCons = class.SuperCons
-- Cached methods --
local AddEntry = class.GetMember("ArrayView", "AddEntry")
local RemoveEntry = class.GetMember("ArrayView", "RemoveEntry")
-- Unique member keys --
local _selection = {}
-- Stock signals --
local Signals = {}
---
function Signals:render (x, y, w, h)
self:DrawPicture("main", x, y, w, h)
-- Draw each visible item and its string, highlighting any selection.
local dh = h / #self.view
local selection = self[_selection]:Get()
for i, text in self:View() do
if i == selection then
self:DrawPicture("highlight", x, y, w, dh)
end
DrawString(self, text, "center", "center", x, y, w, dh)
y = y + dh
end
-- Frame the listbox.
self:DrawPicture("frame", x, y, w, h)
end
---
function Signals:test (cx, cy, x, y, w, h)
if PointInBox(cx, cy, x, y, w, h) then
local dh = h / #self.view
local index = 1
for _ in self:View() do
if cy >= y and cy < y + dh then
return self.view[index]
end
index, y = index + 1, y + dh
end
return self
end
end
-- P: Part handle
local function PartGrab (P)
local listbox = P:GetOwner()
listbox:Select(Find(listbox.view, P, true))
end
-- Listbox class definition --
class.Define("Listbox", function(Listbox)
-- L: Listbox handle
-- index: Index to assign
local function Select (L, index)
L[_selection]:Set(index)
end
-- Adds an entry
-- index: Entry index
-- text: Text to assign
-- ...: Entry members
------------------------
function Listbox:AddEntry (index, text, ...)
AddEntry(self, index, text, ...)
-- Make a selection if there is none.
if #self == 1 then
Select(self, 1)
self:Signal("switch_to", "first")
end
end
-- Appends an entry
-- text: Text to assign
-- ...: Entry members
------------------------
function Listbox:Append (text, ...)
self:AddEntry(#self + 1, text, ...)
end
-- L: Listbox handle
-- Returns: Selection index
local function Selection (L)
return L[_selection]:Get()
end
-- Returns: Selection entry text, members
------------------------------------------
function Listbox:GetSelection ()
local selection = Selection(self)
if selection then
return self:GetEntry(selection)
end
end
-- Removes an entry
-- index: Entry index
----------------------
function Listbox:RemoveEntry (index)
assert(index > 0 and index <= #self, "Invalid removal")
-- If the selection is being removed, alert the listbox.
local is_selection = index == Selection(self)
if is_selection then
self:Signal("switch_from", "remove_selection")
end
-- Perform the removal.
RemoveEntry(self, index)
-- If the selection moved, respond to the switch.
if is_selection and #self > 0 then
self:Signal("switch_to", "remove_selection")
end
end
-- Selects an entry
-- index: Command or entry index
-- always_refresh: If true, refresh on no change
-------------------------------------------------
function Listbox:Select (index, always_refresh)
local selection = assert(Selection(self), "No selections available")
local size = #self
if index == "-" then
index = max(selection - 1, 1)
elseif index == "+" then
index = min(selection + 1, size)
end
assert(index > 0 and index <= size, "Invalid selection")
StateSwitch(self, index ~= selection, always_refresh, Select, "select", index)
-- Put the selection in view if it switched while out of view.
local offset = self.offset:Get()
if index < offset then
self.offset:Set(index)
elseif index >= offset + #self.view then
self.offset:Set(index - #self.view + 1)
end
end
--- Current selection
Listbox.Selection = Selection
end,
--- Class constructor.
-- @class function
-- @name Constructor
-- @param group Group handle.
-- @param capacity Listbox capacity.
function(L, group, capacity)
SuperCons(L, "ArrayView", group, capacity)
-- Selection offset --
L[_selection] = L.sequence:CreateSpot(false, true)
-- View part signals --
for _, part in ipairs(L.view) do
part:SetSignal("grab", PartGrab)
end
-- Signals --
L:SetMultipleSignals(Signals)
end, { base = "ArrayView" }) | mit |
Anarchid/Zero-K | LuaUI/Widgets/dbg_widget_profiler_new.lua | 6 | 14208 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Widget Profiler New",
desc = "Profiles widgets' performance cost",
author = "jK, Bluestone",
version = "2.0",
date = "2007+",
license = "GNU GPL, v2 or later",
layer = -math.huge,
handler = true,
enabled = false -- loaded by default?
}
end
local usePrefixedNames = true
local PROFILE_POS_X = 425
local PROFILE_POS_Y = 80
local COL_SPACING = 420
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local prefixedWnames = {}
local function ConstructPrefixedName (ghInfo)
local gadgetName = ghInfo.name
local baseName = ghInfo.basename
local _pos = baseName:find("_", 1)
local prefix = ((_pos and usePrefixedNames) and (baseName:sub(1, _pos-1)..": ") or "")
local prefixedGadgetName = "\255\200\200\200" .. prefix .. "\255\255\255\255" .. gadgetName
prefixedWnames[gadgetName] = prefixedGadgetName
return prefixedWnames[gadgetName]
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local callinStats = {}
local spGetTimer = Spring.GetTimer
local spDiffTimers = Spring.DiffTimers
local spGetLuaMemUsage = Spring.GetLuaMemUsage
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function ArrayInsert(t, f, g)
if (f) then
local layer = g.whInfo.layer
local index = 1
for i,v in ipairs(t) do
if (v == g) then
return -- already in the table
end
if (layer >= v.whInfo.layer) then
index = i + 1
end
end
table.insert(t, index, g)
end
end
local function ArrayRemove(t, g)
for k,v in ipairs(t) do
if (v == g) then
table.remove(t, k)
-- break
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- make a table of the names of user widgets
local userWidgets = {}
function widget:Initialize()
for name,wData in pairs(widgetHandler.knownWidgets) do
userWidgets[name] = (not wData.fromZip)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local oldUpdateWidgetCallIn
local oldInsertWidget
local listOfHooks = {}
setmetatable(listOfHooks, { __mode = 'k' })
local inHook = false
local function IsHook(func)
return listOfHooks[func]
end
local function Hook(w,name) -- name is the callin
local widgetName = w.whInfo.name
local wname = prefixedWnames[widgetName] or ConstructPrefixedName(w.whInfo)
local realFunc = w[name]
w["_old" .. name] = realFunc
if (widgetName=="Widget Profiler") then
return realFunc -- don't profile the profilers callins (it works, but it is better that our DrawScreen call is unoptimized and expensive anyway!)
end
local widgetCallinTime = callinStats[wname] or {}
callinStats[wname] = widgetCallinTime
widgetCallinTime[name] = widgetCallinTime[name] or {0,0,0,0}
local c = widgetCallinTime[name]
local t
local helper_func = function(...)
local dt = spDiffTimers(spGetTimer(),t)
local _,_,new_s,_ = spGetLuaMemUsage()
local ds = new_s - s
c[1] = c[1] + dt
c[2] = c[2] + dt
c[3] = c[3] + ds
c[4] = c[4] + ds
inHook = nil
return ...
end
local hook_func = function(...)
if (inHook) then
return realFunc(...)
end
inHook = true
t = spGetTimer()
local _,_,new_s,_ = spGetLuaMemUsage()
s = new_s
return helper_func(realFunc(...))
end
listOfHooks[hook_func] = true
return hook_func
end
local function StartHook()
Spring.Echo("start profiling")
local wh = widgetHandler
local CallInsList = {}
for name,e in pairs(wh) do
local i = name:find("List")
if (i)and(type(e)=="table") then
CallInsList[#CallInsList+1] = name:sub(1,i-1)
end
end
--// hook all existing callins
for _,callin in ipairs(CallInsList) do
local callinGadgets = wh[callin .. "List"]
for _,w in ipairs(callinGadgets or {}) do
w[callin] = Hook(w,callin)
end
end
Spring.Echo("hooked all callins")
--// hook the UpdateCallin function
oldUpdateWidgetCallIn = wh.UpdateWidgetCallIn
wh.UpdateWidgetCallIn = function(self,name,w)
local listName = name .. 'List'
local ciList = self[listName]
if (ciList) then
local func = w[name]
if (type(func) == 'function') then
if (not IsHook(func)) then
w[name] = Hook(w,name)
end
ArrayInsert(ciList, func, w)
else
ArrayRemove(ciList, w)
end
self:UpdateCallIn(name)
else
print('UpdateWidgetCallIn: bad name: ' .. name)
end
end
Spring.Echo("hooked UpdateCallin")
--// hook the InsertWidget function
oldInsertWidget = wh.InsertWidget
widgetHandler.InsertWidget = function(self,widget)
if (widget == nil) then
return
end
oldInsertWidget(self,widget)
for _,callin in ipairs(CallInsList) do
local func = widget[callin]
if (type(func) == 'function') then
widget[callin] = Hook(widget,callin)
end
end
end
Spring.Echo("hooked InsertWidget")
end
local function StopHook()
Spring.Echo("stop profiling")
local wh = widgetHandler
local CallInsList = {}
for name,e in pairs(wh) do
local i = name:find("List")
if (i)and(type(e)=="table") then
CallInsList[#CallInsList+1] = name:sub(1,i-1)
end
end
--// unhook all existing callins
for _,callin in ipairs(CallInsList) do
local callinWidgets = wh[callin .. "List"]
for _,w in ipairs(callinWidgets or {}) do
if (w["_old" .. callin]) then
w[callin] = w["_old" .. callin]
end
end
end
Spring.Echo("unhooked all callins")
--// unhook the UpdateCallin and InsertWidget functions
wh.UpdateWidgetCallIn = oldUpdateWidgetCallIn
Spring.Echo("unhooked UpdateCallin")
wh.InsertWidget = oldInsertWidget
Spring.Echo("unhooked InsertWidget")
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local tick = 0.2
local averageTime = 2
local timeLoadAverages = {}
local spaceLoadAverages = {}
local startTimer
function widget:Update()
widgetHandler:RemoveWidgetCallIn("Update", self)
StartHook()
startTimer = Spring.GetTimer()
end
function widget:Shutdown()
StopHook()
end
local lm,_,gm,_,um,_,sm,_ = spGetLuaMemUsage()
local allOverTime = 0
local allOverTimeSec = 0 -- currently unused
local allOverSpace = 0
local totalSpace = {}
local sortedList = {}
local function SortFunc(a,b)
return a.plainname < b.plainname
end
local deltaTime
local redStrength = {}
local minPerc = 0.005 -- above this value, we fade in how red we mark a widget
local maxPerc = 0.02 -- above this value, we mark a widget as red
local minSpace = 10 -- Kb
local maxSpace = 100
local title_colour = "\255\160\255\160"
local totals_colour = "\255\200\200\255"
local maxLines = 50
local function CalcLoad(old_load, new_load, t)
return old_load*math.exp(-tick/t) + new_load*(1 - math.exp(-tick/t))
end
function ColourString(R,G,B)
R255 = math.floor(R*255)
G255 = math.floor(G*255)
B255 = math.floor(B*255)
if (R255%10 == 0) then R255 = R255+1 end
if (G255%10 == 0) then G255 = G255+1 end
if (B255%10 == 0) then B255 = B255+1 end
return "\255"..string.char(R255)..string.char(G255)..string.char(B255)
end
function GetRedColourStrings(v) --tLoad is %
local tTime = v.tTime
local sLoad = v.sLoad
local name = v.plainname
local u = math.exp(-deltaTime/5) --magic colour changing rate
if tTime>maxPerc then tTime = maxPerc end
if tTime<minPerc then tTime = minPerc end
-- time
local new_r = ((tTime-minPerc)/(maxPerc-minPerc))
redStrength[name..'_time'] = redStrength[name..'_time'] or 0
redStrength[name..'_time'] = u*redStrength[name..'_time'] + (1-u)*new_r
local r,g,b = 1, 1-redStrength[name.."_time"]*((255-64)/255), 1-redStrength[name.."_time"]*((255-64)/255)
v.timeColourString = ColourString(r,g,b)
-- space
new_r = math.max(0,math.min(1,(sLoad-minSpace)/(maxSpace-minSpace)))
redStrength[name..'_space'] = redStrength[name..'_space'] or 0
redStrength[name..'_space'] = u*redStrength[name..'_space'] + (1-u)*new_r
g = 1-redStrength[name.."_space"]*((255-64)/255)
b = g
v.spaceColourString = ColourString(r,g,b)
end
function DrawWidgetList(list,name,x,y,j)
if j>=maxLines-5 then x = x - 350; j = 0; end
j = j + 1
gl.Text(title_colour..name.." WIDGETS", x+152, y-1-(12)*j, 10, "no")
j = j + 2
for i=1,#list do
if j>=maxLines then x = x - 350; j = 0; end
local v = list[i]
local name = v.plainname
local wname = v.fullname
local tLoad = v.tLoad
local sLoad = v.sLoad
local tColour = v.timeColourString
local sColour = v.spaceColourString
gl.Text(wname, x+150, y+1-(12)*j, 10, "no")
gl.Text(tColour .. ('%.2f%%'):format(tLoad), x+60, y+1-(12)*j, 10, "no")
gl.Text(sColour .. ('%.0f'):format(sLoad) .. 'kB/s', x+105, y+1-(12)*j, 10, "no")
j = j + 1
end
gl.Text(totals_colour.."totals ("..string.lower(name)..")", x+152, y+1-(12)*j, 10, "no")
gl.Text(totals_colour..('%.2f%%'):format(list.allOverTime), x+60, y+1-(12)*j, 10, "no")
gl.Text(totals_colour..('%.0f'):format(list.allOverSpace) .. 'kB/s', x+105, y+1-(12)*j, 10, "no")
j = j + 1
return x,j
end
function widget:DrawScreen()
if not (next(callinStats)) then
return --// nothing to do
end
deltaTime = Spring.DiffTimers(Spring.GetTimer(),startTimer)
-- sort & count timing
if (deltaTime>=tick) then
startTimer = Spring.GetTimer()
sortedList = {}
allOverTime = 0
allOverSpace = 0
local n = 1
for wname,callins in pairs(callinStats) do
local t = 0 -- would call it time, but protected
local cmax_t = 0
local cmaxname_t = "-"
local space = 0
local cmax_space = 0
local cmaxname_space = "-"
for cname,c in pairs(callins) do
t = t + c[1]
if (c[2]>cmax_t) then
cmax_t = c[2]
cmaxname_t = cname
end
c[1] = 0
space = space + c[3]
if (c[4]>cmax_space) then
cmax_space = c[4]
cmaxname_space = cname
end
c[3] = 0
end
local relTime = 100 * t / deltaTime
timeLoadAverages[wname] = CalcLoad(timeLoadAverages[wname] or relTime, relTime, averageTime)
local relSpace = space / deltaTime
spaceLoadAverages[wname] = CalcLoad(spaceLoadAverages[wname] or relSpace, relSpace, averageTime)
allOverTimeSec = allOverTimeSec + t
local tLoad = timeLoadAverages[wname]
local sLoad = spaceLoadAverages[wname]
sortedList[n] = {plainname=wname, fullname=wname..' \255\200\200\200('..cmaxname_t..','..cmaxname_space..')', tLoad=tLoad, sLoad=sLoad, tTime=t/deltaTime}
allOverTime = allOverTime + tLoad
allOverSpace = allOverSpace + sLoad
n = n + 1
end
table.sort(sortedList,SortFunc)
for i=1,#sortedList do
GetRedColourStrings(sortedList[i])
end
lm,_,gm,_,um,_,sm,_ = spGetLuaMemUsage()
end
if (not sortedList[1]) then
return --// nothing to do
end
-- add to category and set colour
local userList = {}
local gameList = {}
userList.allOverTime = 0
gameList.allOverTime = 0
userList.allOverSpace = 0
gameList.allOverSpace = 0
for i=1,#sortedList do
if userWidgets[sortedList[i].plainname] then
userList[#userList+1] = sortedList[i]
userList.allOverTime = userList.allOverTime + sortedList[i].tLoad
userList.allOverSpace = userList.allOverSpace + sortedList[i].sLoad
else
gameList[#gameList+1] = sortedList[i]
gameList.allOverTime = gameList.allOverTime + sortedList[i].tLoad
gameList.allOverSpace = gameList.allOverSpace + sortedList[i].sLoad
end
end
-- draw
local vsx, vsy = gl.GetViewSizes()
local x,y = vsx - PROFILE_POS_X, vsy - PROFILE_POS_Y
local widgetScale = (1 + (vsx*vsy / 7500000))
gl.PushMatrix()
gl.Translate(vsx-(vsx*widgetScale),vsy-(vsy*widgetScale),0)
gl.Scale(widgetScale,widgetScale,1)
gl.Color(1,1,1,1)
gl.BeginText()
local j = -1 --line number
x,j = DrawWidgetList(gameList,"GAME",x,y,j)
x,j = DrawWidgetList(userList,"USER",x,y,j)
if j>=maxLines-15 then x = x - COL_SPACING; j = 0; end
j = j + 1
gl.Text(title_colour.."ALL", x+152, y-1-(12)*j, 10, "no")
j = j + 1
j = j + 1
gl.Text(totals_colour.."total percentage of running time spent in luaui callins", x+152, y-1-(12)*j, 10, "no")
gl.Text(totals_colour..('%.1f%%'):format(allOverTime), x+65, y-1-(12)*j, 10, "no")
j = j + 1
gl.Text(totals_colour.."total rate of mem allocation by luaui callins", x+152, y-1-(12)*j, 10, "no")
gl.Text(totals_colour..('%.0f'):format(allOverSpace) .. 'kB/s', x+105, y-1-(12)*j, 10, "no")
if gm then
j = j + 2
gl.Text(totals_colour..'total lua memory usage is '.. ('%.0f'):format(gm/1000) .. 'MB, of which:', x+65, y-1-(12)*j, 10, "no")
if lm then
j = j + 1
gl.Text(totals_colour..' '..('%.0f'):format(100*lm/gm) .. '% is from luaui', x+65, y-1-(12)*j, 10, "no")
end
if um then
j = j + 1
gl.Text(totals_colour..' '..('%.0f'):format(100*um/gm) .. '% is from unsynced states (luarules+luagaia+luaui)', x+65, y-1-(12)*j, 10, "no")
end
if sm then
j = j + 1
gl.Text(totals_colour..' '..('%.0f'):format(100*sm/gm) .. '% is from synced states (luarules+luagaia)', x+65, y-1-(12)*j, 10, "no")
end
end
j = j + 2
gl.Text(title_colour.."All data excludes load from garbage collection & executing GL calls", x+65, y-1-(12)*j, 10, "no")
j = j + 1
gl.Text(title_colour.."Callins in brackets are heaviest per widget for (time,allocs)", x+65, y-1-(12)*j, 10, "no")
j = j + 2
gl.Text(title_colour.."Tick time: " .. tick .. "s", x+65, y-1-(12)*j, 10, "no")
j = j + 1
gl.Text(title_colour.."Smoothing time: " .. averageTime .. "s", x+65, y-1-(12)*j, 10, "no")
gl.EndText()
gl.PopMatrix()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
LightenPan/skynet-yule | lualib/sharemap.lua | 78 | 1496 | local stm = require "stm"
local sprotoloader = require "sprotoloader"
local sproto = require "sproto"
local setmetatable = setmetatable
local sharemap = {}
function sharemap.register(protofile)
-- use global slot 0 for type define
sprotoloader.register(protofile, 0)
end
local sprotoobj
local function loadsp()
if sprotoobj == nil then
sprotoobj = sprotoloader.load(0)
end
return sprotoobj
end
function sharemap:commit()
self.__obj(sprotoobj:encode(self.__typename, self.__data))
end
function sharemap:copy()
return stm.copy(self.__obj)
end
function sharemap.writer(typename, obj)
local sp = loadsp()
obj = obj or {}
local stmobj = stm.new(sp:encode(typename,obj))
local ret = {
__typename = typename,
__obj = stmobj,
__data = obj,
commit = sharemap.commit,
copy = sharemap.copy,
}
return setmetatable(ret, { __index = obj, __newindex = obj })
end
local function decode(msg, sz, self)
local data = self.__data
for k in pairs(data) do
data[k] = nil
end
return sprotoobj:decode(self.__typename, msg, sz, data)
end
function sharemap:update()
return self.__obj(decode, self)
end
function sharemap.reader(typename, stmcpy)
local sp = loadsp()
local stmobj = stm.newcopy(stmcpy)
local _, data = stmobj(function(msg, sz)
return sp:decode(typename, msg, sz)
end)
local obj = {
__typename = typename,
__obj = stmobj,
__data = data,
update = sharemap.update,
}
return setmetatable(obj, { __index = data, __newindex = error })
end
return sharemap
| mit |
lxl1140989/dmsdk | feeds/luci/modules/base/luasrc/ccache.lua | 82 | 1863 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local io = require "io"
local fs = require "nixio.fs"
local util = require "luci.util"
local nixio = require "nixio"
local debug = require "debug"
local string = require "string"
local package = require "package"
local type, loadfile = type, loadfile
module "luci.ccache"
function cache_ondemand(...)
if debug.getinfo(1, 'S').source ~= "=?" then
cache_enable(...)
end
end
function cache_enable(cachepath, mode)
cachepath = cachepath or "/tmp/luci-modulecache"
mode = mode or "r--r--r--"
local loader = package.loaders[2]
local uid = nixio.getuid()
if not fs.stat(cachepath) then
fs.mkdir(cachepath)
end
local function _encode_filename(name)
local encoded = ""
for i=1, #name do
encoded = encoded .. ("%2X" % string.byte(name, i))
end
return encoded
end
local function _load_sane(file)
local stat = fs.stat(file)
if stat and stat.uid == uid and stat.modestr == mode then
return loadfile(file)
end
end
local function _write_sane(file, func)
if nixio.getuid() == uid then
local fp = io.open(file, "w")
if fp then
fp:write(util.get_bytecode(func))
fp:close()
fs.chmod(file, mode)
end
end
end
package.loaders[2] = function(mod)
local encoded = cachepath .. "/" .. _encode_filename(mod)
local modcons = _load_sane(encoded)
if modcons then
return modcons
end
-- No cachefile
modcons = loader(mod)
if type(modcons) == "function" then
_write_sane(encoded, modcons)
end
return modcons
end
end
| gpl-2.0 |
TheBuzzSaw/Nullocity | project/Lua/main.lua | 1 | 6898 | local gr = Nullocity.GetRandom
entitiesByHandle = {}
cameraEntity = nil
function FixPosition(entity)
local px, py = entity.GetPosition()
local vx, vy = entity.GetVelocity()
local radius = entity.GetRadius()
local changed = false
local n = 16
local high = px + radius
local low = px - radius
if vx > 0 and high > n then
px = n + n - high - radius
vx = -vx
changed = true
elseif vx < 0 and low < -n then
px = -low + radius - n - n
vx = -vx
changed = true
end
high = py + radius
low = py - radius
if vy > 0 and high > n then
py = n + n - high - radius
vy = -vy
changed = true
elseif vy < 0 and low < -n then
py = -low + radius - n - n
vy = -vy
changed = true
end
if changed then
entity.SetPosition(px, py)
entity.SetVelocity(vx, vy)
entity.SetTorque(gr(-4, 4), gr(-4, 4))
end
end
function OnUpdate()
for _, v in pairs(entitiesByHandle) do
FixPosition(v)
end
local x, y = cameraEntity.GetPosition()
Nullocity.SetCameraPosition(x, y, 0)
end
function OnCollision(a, b)
a = entitiesByHandle[a]
b = entitiesByHandle[b]
-- If an entity has been removed, it'll come back nil.
if a and b then
local avx, avy = a.GetVelocity()
local bvx, bvy = b.GetVelocity()
local xVel = bvx - avx
local yVel = bvy - avy
local apx, apy = a.GetPosition()
local bpx, bpy = b.GetPosition()
local xDist = apx - bpx
local yDist = apy - bpy
local dotProduct = xDist*xVel + yDist*yVel
if dotProduct > 0 then
local am = a.GetMass()
local bm = b.GetMass()
local combinedMass = am + bm
local differenceMass = am - bm
local bNewVelX = (bvx * differenceMass + (2 * am * avx)) / combinedMass
local bNewVelY = (bvy * differenceMass + (2 * am * avy)) / combinedMass
local aNewVelX = (avx * -differenceMass + (2 * bm * bvx)) / combinedMass
local aNewVelY = (avy * -differenceMass + (2 * bm * bvy)) / combinedMass
local amx = avx * am
local amy = avy * am
local bmx = bvx * bm
local bmy = bvy * bm
a.SetVelocity(aNewVelX, aNewVelY)
b.SetVelocity(bNewVelX, bNewVelY)
a.SetTorque(gr(-4, 4), gr(-4, 4))
b.SetTorque(gr(-4, 4), gr(-4, 4))
end
end
end
function CheckAxisCollision(av, bv, ap, bp)
local result = false
if bp < ap then
if (bv - av) > 0 then
result = true
end
else
if (bv - av) < 0 then
result = true
end
end
return result
end
function NewBaseEntity(mass)
local roll = gr(0, 5)
local model = 'Icosahedron'
if roll > 4 then
model = 'Sphere'
elseif roll > 3 then
model = 'Cube'
elseif roll > 2 then
model = 'Pyramid'
elseif roll > 1 then
model = 'SquarePyramid'
end
local self = { entity = Nullocity.AddEntity(model), mass = mass }
local Remove = function()
entitiesByHandle[self.entity] = nil
Nullocity.RemoveEntity(self.entity)
end
local SetPosition = function(x, y)
Nullocity.SetPosition(self.entity, x, y)
end
local SetVelocity = function(x, y)
Nullocity.SetVelocity(self.entity, x, y)
end
local SetRotation = function(x, y)
Nullocity.SetRotation(self.entity, x, y)
end
local SetTorque = function(x, y)
Nullocity.SetTorque(self.entity, x, y)
end
local SetRadius = function(radius)
Nullocity.SetRadius(self.entity, radius)
end
local SetScale = function(scale)
Nullocity.SetScale(self.entity, scale)
end
local SetMass = function(mass)
self.mass = mass;
end
local GetPosition = function()
return Nullocity.GetPosition(self.entity)
end
local GetVelocity = function()
return Nullocity.GetVelocity(self.entity)
end
local GetRotation = function()
return Nullocity.GetRotation(self.entity)
end
local GetTorque = function()
return Nullocity.GetTorque(self.entity)
end
local GetRadius = function()
return Nullocity.GetRadius(self.entity)
end
local GetScale = function()
return Nullocity.GetScale(self.entity)
end
local GetMass = function() return self.mass end
local result = {
Remove = Remove,
SetPosition = SetPosition,
SetVelocity = SetVelocity,
SetRotation = SetRotation,
SetTorque = SetTorque,
SetRadius = SetRadius,
SetScale = SetScale,
SetMass = SetMass,
GetPosition = GetPosition,
GetVelocity = GetVelocity,
GetRotation = GetRotation,
GetTorque = GetTorque,
GetRadius = GetRadius,
GetScale = GetScale,
GetMass = GetMass }
entitiesByHandle[self.entity] = result
return result
end
function Debug()
print("--- Entity Position Dump ---")
for _, v in pairs(entitiesByHandle) do
print(v.GetPosition())
end
end
function OnSpaceBar(isKeyDown)
if isKeyDown == 1 then
print("It WORKS!")
end
end
for i = 1, 16 do
local size = gr(.5,1.5)
local entity = NewBaseEntity(size)
entity.SetPosition(gr(-16, 16), gr(-16, 16))
entity.SetVelocity(gr(-.5, .5), gr(-.5, .5))
entity.SetRotation(gr(-135, 135), gr(-135, 135))
entity.SetTorque(gr(-4, 4), gr(-4, 4))
entity.SetRadius(size * 1.25)
entity.SetScale(size)
if not cameraEntity then cameraEntity = entity end
print("Size is: ", size)
print("Position: ", entity.GetPosition())
print("Velocity: ", entity.GetVelocity())
print("Rotation: ", entity.GetRotation())
print("Torque: ", entity.GetTorque())
print("Radius: ", entity.GetRadius())
print("Scale: ", entity.GetScale())
end
sound = Nullocity.GetAudioBuffer('Nullocity.wav')
function PlaySound()
Nullocity.PlayAudioBuffer(sound)
end
Nullocity.SetCollisionCallback(OnCollision)
Nullocity.SetUpdateCallback(OnUpdate)
| unlicense |
Anarchid/Zero-K | effects/gundam_330rlexplode.lua | 6 | 5722 | -- 330rlexplode
-- 165rlexplode
local baseExplode = {
dirt = {
count = 4,
ground = true,
properties = {
alphafalloff = 2,
color = [[0.2, 0.1, 0.05]],
pos = [[r-10 r10, 0, r-10 r10]],
size = 22,
speed = [[r1.5 r-1.5, 4, r1.5 r-1.5]],
},
},
dirtw1 = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = true,
colormap = [[0.9 0.9 0.9 1.0 0.3 0.3 0.3 0.0]],
directional = true,
emitrot = 80,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.08, 0]],
numparticles = 28,
particlelife = 20,
particlelifespread = 6,
particlesize = 10,
particlesizespread = 5,
particlespeed = 10,
particlespeedspread = 12,
pos = [[r-1 r1, 1, r-1 r1]],
sizegrowth = 1.18,
sizemod = 1.0,
texture = [[randdots]],
useairlos = true,
},
},
dirtw2 = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
properties = {
airdrag = 0.7,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 1.0 0.5 0.5 0.8 0.4 0.3 0.3 0.4 0.1 0.1 0.1 0.16 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 0,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 10,
particlelife = 15,
particlelifespread = 10,
particlesize = 35,
particlesizespread = 5,
particlespeed = 10,
particlespeedspread = 10,
pos = [[r-1 r1, 1, r-1 r1]],
sizegrowth = 1.2,
sizemod = 1.0,
texture = [[dirt]],
useairlos = true,
},
},
flare = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.8,
alwaysvisible = true,
colormap = [[1 1 1 0.01 0.9 0.8 0.7 0.04 0.9 0.5 0.2 0.01 0.5 0.1 0.1 0.01]],
directional = true,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.01, 0]],
numparticles = 8,
particlelife = 14,
particlelifespread = 0,
particlesize = 70,
particlesizespread = 0,
particlespeed = 10,
particlespeedspread = 5,
pos = [[0, 2, 0]],
sizegrowth = 1,
sizemod = 1.0,
texture = [[flashside1]],
useairlos = false,
},
},
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 0.5,
circlegrowth = 8,
flashalpha = 0.9,
flashsize = 150,
ground = true,
ttl = 17,
water = true,
color = {
[1] = 1,
[2] = 0.5,
[3] = 0.20000000298023,
},
},
pop1 = {
air = true,
class = [[heatcloud]],
count = 2,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 1.4,
maxheat = 15,
pos = [[r-2 r2, 5, r-2 r2]],
size = 5,
sizegrowth = 24,
speed = [[0, 1 0, 0]],
texture = [[redexplo]],
},
},
whiteglow = {
air = true,
class = [[heatcloud]],
count = 1,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 1.1,
maxheat = 15,
pos = [[r-2 r2, 5, r-2 r2]],
size = 10,
sizegrowth = 25,
speed = [[0, 1 0, 0]],
texture = [[laserend]],
},
},
}
local halfExplode = Spring.Utilities.MergeTable({
dirt = {
count = 2,
properties = {
pos = [[r-5 r5, 0, r-5 r5]],
size = 14,
speed = [[r1.5 r-1.5, 4, r1.5 r-1.5]],
},
},
dirtw1 = {
properties = {
numparticles = 10,
particlesize = 6,
particlesizespread = 4,
particlespeed = 6,
particlespeedspread = 6,
},
},
dirtw2 = {
properties = {
numparticles = 6,
particlesize = 18,
particlesizespread = 5,
particlespeed = 6,
particlespeedspread = 6,
},
},
flare = {
properties = {
numparticles = 6,
particlesize = 36,
particlesizespread = 0,
particlespeed = 6,
particlespeedspread = 3,
},
},
groundflash = {
flashsize = 76,
ttl = 15,
},
pop1 = {
properties = {
size = 2.8,
sizegrowth = 12,
},
},
whiteglow = {
properties = {
size = 8,
sizegrowth = 14,
},
},
}, baseExplode)
return {
["330rlexplode"] = baseExplode,
["165rlexplode"] = halfExplode,
}
| gpl-2.0 |
bugobliterator/ardupilot | libraries/AP_Scripting/examples/plane-wind-failsafe.lua | 26 | 1195 | -- warn the user if wind speed exceeds a threshold, failsafe if a second threshold is exceeded
-- note that this script is only intended to be run on ArduPlane
-- tuning parameters
local warn_speed = 10 -- metres/second
local failsafe_speed = 15 -- metres/second
local warning_interval_ms = uint32_t(15000) -- send user message every 15s
local warning_last_sent_ms = uint32_t() -- time we last sent a warning message to the user
function update()
local wind = ahrs:wind_estimate() -- get the wind estimate
if wind then
-- make a 2D wind vector
wind_xy = Vector2f()
wind_xy:x(wind:x())
wind_xy:y(wind:y())
speed = wind_xy:length() -- compute the wind speed
if speed > failsafe_speed then
gcs:send_text(0, "Wind failsafe at " .. speed .. " metres/second")
vehicle:set_mode(11) -- FIXME: should be an enum. 11 is RTL.
return
end
if speed > warn_speed then
if millis() - warning_last_sent_ms > warning_interval_ms then
gcs:send_text(4, "Wind warning at " .. speed .. " metres/second")
warning_last_sent_ms = millis()
end
end
end
return update, 1000
end
return update, 1000
| gpl-3.0 |
Anarchid/Zero-K | units/gunshipassault.lua | 5 | 3945 | return { gunshipassault = {
unitname = [[gunshipassault]],
name = [[Revenant]],
description = [[Heavy Raider/Assault Gunship]],
acceleration = 0.15,
brakeRate = 0.13,
buildCostMetal = 850,
builder = false,
buildPic = [[gunshipassault.png]],
canFly = true,
canGuard = true,
canMove = true,
canPatrol = true,
canSubmerge = false,
category = [[GUNSHIP]],
collide = true,
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[50 15 50]],
collisionVolumeType = [[cylY]],
corpse = [[DEAD]],
cruiseAlt = 135,
customParams = {
bait_level_default = 1,
airstrafecontrol = [[1]],
modelradius = [[10]],
},
explodeAs = [[GUNSHIPEX]],
floater = true,
footprintX = 3,
footprintZ = 3,
hoverAttack = true,
iconType = [[heavygunshipassault]],
maxDamage = 3600,
maxVelocity = 4.5,
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB]],
objectName = [[Black_Dawn.s3o]],
script = [[gunshipassault.lua]],
selfDestructAs = [[GUNSHIPEX]],
sightDistance = 585,
turnRate = 1000,
weapons = {
{
def = [[VTOL_SALVO]],
mainDir = [[0 -0.35 1]],
maxAngleDif = 90,
badTargetCategory = [[FIXEDWING GUNSHIP]],
onlyTargetCategory = [[SWIM LAND SHIP SINK TURRET FLOAT GUNSHIP FIXEDWING HOVER]],
},
},
weaponDefs = {
VTOL_SALVO = {
name = [[Rocket Salvo]],
areaOfEffect = 96,
avoidFeature = false,
avoidFriendly = false,
burst = 8,
burstrate = 2/30,
cegTag = [[BANISHERTRAIL]],
collideFriendly = false,
craterBoost = 0.123,
craterMult = 0.246,
customparams = {
burst = Shared.BURST_UNRELIABLE,
light_camera_height = 2500,
light_color = [[0.55 0.27 0.05]],
light_radius = 360,
combatrange = 160,
},
damage = {
default = 220.5,
},
dance = 30,
edgeEffectiveness = 0.5,
explosionGenerator = [[custom:MEDMISSILE_EXPLOSION]],
fireStarter = 70,
flightTime = 5,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 2,
model = [[hobbes_nohax.s3o]],
noSelfDamage = true,
range = 270,
reloadtime = 9,
smokeTrail = false,
soundHit = [[weapon/missile/rapid_rocket_hit]],
soundStart = [[weapon/missile/rapid_rocket_fire]],
startVelocity = 150,
tolerance = 15000,
tracks = true,
turnRate = 1400,
turret = true,
weaponAcceleration = 100,
weaponType = [[MissileLauncher]],
weaponVelocity = 250,
wobble = 8000,
},
},
featureDefs = {
DEAD = {
blocking = true,
collisionVolumeScales = [[65 20 65]],
collisionVolumeType = [[CylY]],
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[blackdawn_d.dae]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
} }
| gpl-2.0 |
Bew78LesellB/awesome | tests/examples/wibox/container/arcchart/bg.lua | 6 | 1046 | --DOC_HIDE_ALL
local parent = ...
local wibox = require( "wibox" )
local beautiful = require( "beautiful" )
local l = wibox.layout.fixed.horizontal()
l.spacing = 10
parent:add(l)
for _, v in ipairs {"", "#00ff00", "#0000ff"} do
l:add(wibox.widget {
{
text = v~="" and v or "nil",
align = "center",
valign = "center",
widget = wibox.widget.textbox,
},
colors = {
beautiful.bg_normal,
beautiful.bg_highlight,
beautiful.border_color,
},
values = {
1,
2,
3,
},
max_value = 10,
min_value = 0,
rounded_edge = false,
bg = v~="" and v or nil,
border_width = 0.5,
border_color = "#000000",
widget = wibox.container.arcchart
})
end
return nil, 60
--DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.