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 |
|---|---|---|---|---|---|
xponen/Zero-K | scripts/armnanotc.lua | 2 | 1668 | include "constants.lua"
include "nanoaim.h.lua"
--pieces
local body = piece "body"
local aim = piece "aim"
local emitnano = piece "emitnano"
--local vars
local smokePiece = { piece "aim", piece "body" }
local nanoPieces = { piece "aim" }
local nanoTurnSpeedHori = 0.5 * math.pi
local nanoTurnSpeedVert = 0.1 * math.pi
function script.Create()
StartThread(SmokeUnit, smokePiece)
StartThread(UpdateNanoDirectionThread, nanoPieces, 500, nanoTurnSpeedHori, nanoTurnSpeedVert)
Spring.SetUnitNanoPieces(unitID, {emitnano})
end
function script.StartBuilding()
UpdateNanoDirection(nanoPieces, nanoTurnSpeedHori, nanoTurnSpeedVert)
Spring.SetUnitCOBValue(unitID, COB.INBUILDSTANCE, 1);
end
function script.StopBuilding()
Spring.SetUnitCOBValue(unitID, COB.INBUILDSTANCE, 0);
end
function script.QueryNanoPiece()
--// send to LUPS
GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),emitnano)
return emitnano
end
function script.Killed(recentDamage, maxHealth)
Explode( body, SFX.EXPLODE )
Explode( aim, SFX.EXPLODE )
--[[
if( severity <= 25 )
{
corpsetype = 1;
explode body type BITMAPONLY | BITMAP1;
explode aim type BITMAPONLY | BITMAP3;
return (0);
}
if( severity <= 50 )
{
corpsetype = 2;
explode body type FALL | BITMAP1;
explode aim type FALL | BITMAP3;
return (0);
}
if( severity <= 99 )
{
corpsetype = 3;
explode body type FALL | SMOKE | FIRE | EXPLODE_ON_HIT | BITMAP1;
explode aim type FALL | SMOKE | FIRE | EXPLODE_ON_HIT | BITMAP3;
return (0);
}
corpsetype = 3;
explode body type FALL | SMOKE | FIRE | EXPLODE_ON_HIT | BITMAP1;
explode aim type SHATTER | EXPLODE_ON_HIT | BITMAP3;
--]]
end
| gpl-2.0 |
xuejian1354/barrier_breaker | feeds/luci/applications/luci-radvd/luasrc/model/cbi/radvd/interface.lua | 78 | 7996 | --[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sid = arg[1]
local utl = require "luci.util"
m = Map("radvd", translatef("Radvd - Interface %q", "?"),
translate("Radvd is a router advertisement daemon for IPv6. " ..
"It listens to router solicitations and sends router advertisements " ..
"as described in RFC 4861."))
m.redirect = luci.dispatcher.build_url("admin/network/radvd")
if m.uci:get("radvd", sid) ~= "interface" then
luci.http.redirect(m.redirect)
return
end
m.uci:foreach("radvd", "interface",
function(s)
if s['.name'] == sid and s.interface then
m.title = translatef("Radvd - Interface %q", s.interface)
return false
end
end)
s = m:section(NamedSection, sid, "interface", translate("Interface Configuration"))
s.addremove = false
s:tab("general", translate("General"))
s:tab("timing", translate("Timing"))
s:tab("mobile", translate("Mobile IPv6"))
--
-- General
--
o = s:taboption("general", Flag, "ignore", translate("Enable"))
o.rmempty = false
function o.cfgvalue(...)
local v = Flag.cfgvalue(...)
return v == "1" and "0" or "1"
end
function o.write(self, section, value)
Flag.write(self, section, value == "1" and "0" or "1")
end
o = s:taboption("general", Value, "interface", translate("Interface"),
translate("Specifies the logical interface name this section belongs to"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.optional = false
function o.formvalue(...)
return Value.formvalue(...) or "-"
end
function o.validate(self, value)
if value == "-" then
return nil, translate("Interface required")
end
return value
end
function o.write(self, section, value)
m.uci:set("radvd", section, "ignore", 0)
m.uci:set("radvd", section, "interface", value)
end
o = s:taboption("general", DynamicList, "client", translate("Clients"),
translate("Restrict communication to specified clients, leave empty to use multicast"))
o.rmempty = true
o.datatype = "ip6addr"
o.placeholder = "any"
function o.cfgvalue(...)
local v = Value.cfgvalue(...)
local l = { }
for v in utl.imatch(v) do
l[#l+1] = v
end
return l
end
o = s:taboption("general", Flag, "AdvSendAdvert", translate("Enable advertisements"),
translate("Enables router advertisements and solicitations"))
o.rmempty = false
function o.write(self, section, value)
if value == "1" then
m.uci:set("radvd", section, "ignore", 0)
m.uci:set("radvd", section, "IgnoreIfMissing", 1)
end
m.uci:set("radvd", section, "AdvSendAdvert", value)
end
o = s:taboption("general", Flag, "UnicastOnly", translate("Unicast only"),
translate("Indicates that the underlying link is not broadcast capable, prevents unsolicited advertisements from being sent"))
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Flag, "AdvManagedFlag", translate("Managed flag"),
translate("Enables the additional stateful administered autoconfiguration protocol (RFC2462)"))
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Flag, "AdvOtherConfigFlag", translate("Configuration flag"),
translate("Enables the autoconfiguration of additional, non address information (RFC2462)"))
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Flag, "AdvSourceLLAddress", translate("Source link-layer address"),
translate("Includes the link-layer address of the outgoing interface in the RA"))
o.rmempty = false
o.default = "1"
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Value, "AdvLinkMTU", translate("Link MTU"),
translate("Advertises the given link MTU in the RA if specified. 0 disables MTU advertisements"))
o.datatype = "uinteger"
o.placeholder = 0
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", Value, "AdvCurHopLimit", translate("Current hop limit"),
translate("Advertises the default Hop Count value for outgoing unicast packets in the RA. 0 disables hopcount advertisements"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 64
o:depends("AdvSendAdvert", "1")
o = s:taboption("general", ListValue, "AdvDefaultPreference", translate("Default preference"),
translate("Advertises the default router preference"))
o.optional = false
o.default = "medium"
o:value("low", translate("low"))
o:value("medium", translate("medium"))
o:value("high", translate("high"))
o:depends("AdvSendAdvert", "1")
--
-- Timing
--
o = s:taboption("timing", Value, "MinRtrAdvInterval", translate("Minimum advertisement interval"),
translate("The minimum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 198
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "MaxRtrAdvInterval", translate("Maximum advertisement interval"),
translate("The maximum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 600
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "MinDelayBetweenRAs", translate("Minimum advertisement delay"),
translate("The minimum time allowed between sending multicast router advertisements from the interface, in seconds"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 3
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "AdvReachableTime", translate("Reachable time"),
translate("Advertises assumed reachability time in milliseconds of neighbours in the RA if specified. 0 disables reachability advertisements"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 0
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "AdvRetransTimer", translate("Retransmit timer"),
translate("Advertises wait time in milliseconds between Neighbor Solicitation messages in the RA if specified. 0 disables retransmit advertisements"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 0
o:depends("AdvSendAdvert", "1")
o = s:taboption("timing", Value, "AdvDefaultLifetime", translate("Default lifetime"),
translate("Advertises the lifetime of the default router in seconds. 0 indicates that the node is no default router"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 1800
o:depends("AdvSendAdvert", "1")
--
-- Mobile
--
o = s:taboption("mobile", Flag, "AdvHomeAgentFlag", translate("Advertise Home Agent flag"),
translate("Advertises Mobile IPv6 Home Agent capability (RFC3775)"))
o:depends("AdvSendAdvert", "1")
o = s:taboption("mobile", Flag, "AdvIntervalOpt", translate("Mobile IPv6 interval option"),
translate("Include Mobile IPv6 Advertisement Interval option to RA"))
o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"})
o = s:taboption("mobile", Flag, "AdvHomeAgentInfo", translate("Home Agent information"),
translate("Include Home Agent Information in the RA"))
o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"})
o = s:taboption("mobile", Flag, "AdvMobRtrSupportFlag", translate("Mobile IPv6 router registration"),
translate("Advertises Mobile Router registration capability (NEMO Basic)"))
o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"})
o = s:taboption("mobile", Value, "HomeAgentLifetime", translate("Home Agent lifetime"),
translate("Advertises the time in seconds the router is offering Mobile IPv6 Home Agent services"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 1800
o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"})
o = s:taboption("mobile", Value, "HomeAgentPreference", translate("Home Agent preference"),
translate("The preference for the Home Agent sending this RA"))
o.datatype = "uinteger"
o.optional = false
o.placeholder = 0
o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"})
return m
| gpl-2.0 |
xponen/Zero-K | LuaRules/Gadgets/unit_timeslow.lua | 1 | 8138 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Time slow v2",
desc = "Time slow Weapon",
author = "Google Frog , (MidKnight made orig)",
date = "2010-05-31",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--SYNCED
if (not gadgetHandler:IsSyncedCode()) then
return false
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitCOBValue = Spring.GetUnitCOBValue
local spAreTeamsAllied = Spring.AreTeamsAllied
local spValidUnitID = Spring.ValidUnitID
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spGetUnitHealth = Spring.GetUnitHealth
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local spGetCommandQueue = Spring.GetCommandQueue
local spGetUnitStates = Spring.GetUnitStates
local spGetUnitTeam = Spring.GetUnitTeam
local spSetUnitTarget = Spring.SetUnitTarget
local spGetUnitNearestEnemy = Spring.GetUnitNearestEnemy
local CMD_ATTACK = CMD.ATTACK
local CMD_REMOVE = CMD.REMOVE
local CMD_MOVE = CMD.MOVE
local CMD_FIGHT = CMD.FIGHT
local CMD_SET_WANTED_MAX_SPEED = CMD.SET_WANTED_MAX_SPEED
local LOS_ACCESS = {inlos = true}
local gaiaTeamID = Spring.GetGaiaTeamID()
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local attritionWeaponDefs, MAX_SLOW_FACTOR, DEGRADE_TIMER, DEGRADE_FACTOR, UPDATE_PERIOD = include("LuaRules/Configs/timeslow_defs.lua")
local slowedUnits = {}
Spring.SetGameRulesParam("slowState",1)
function gadget:Initialize()
end
local function checkTargetRandomTarget(unitID)
end
local function updateSlow(unitID, state)
local health = spGetUnitHealth(unitID)
if health then
if state.slowDamage > health*MAX_SLOW_FACTOR then
state.slowDamage = health*MAX_SLOW_FACTOR
end
local percentSlow = state.slowDamage/health
spSetUnitRulesParam(unitID,"slowState",percentSlow, LOS_ACCESS)
end
end
function gadget:UnitPreDamaged_GetWantedWeaponDef()
local wantedWeaponList = {}
for wdid = 1, #WeaponDefs do
if attritionWeaponDefs[wdid] then
wantedWeaponList[#wantedWeaponList + 1] = wdid
end
end
return wantedWeaponList
end
function gadget:UnitPreDamaged(unitID, unitDefID, unitTeam, damage, paralyzer, weaponID,
attackerID, attackerDefID, attackerTeam)
if (not spValidUnitID(unitID)) or (not weaponID) or (not attritionWeaponDefs[weaponID]) or ((not attackerID) and attritionWeaponDefs[weaponID].noDeathBlast)
or (attritionWeaponDefs[weaponID].scaleSlow and damage == 0) then
return damage
end
-- add stats that the unit requires for this gadget
if not slowedUnits[unitID] then
slowedUnits[unitID] = {
slowDamage = 0,
degradeTimer = DEGRADE_TIMER,
perma = false,
}
GG.attUnits[unitID] = true -- unit with attribute change to be handled by unit_attributes
end
-- add slow damage
local slowdown = attritionWeaponDefs[weaponID].slowDamage
if attritionWeaponDefs[weaponID].scaleSlow then
slowdown = slowdown * (damage/WeaponDefs[weaponID].damages[0])
end --scale slow damage based on real damage (i.e. take into account armortypes etc.)
slowedUnits[unitID].slowDamage = slowedUnits[unitID].slowDamage + slowdown
slowedUnits[unitID].degradeTimer = DEGRADE_TIMER
if GG.Awards and GG.Awards.AddAwardPoints then
local ud = UnitDefs[unitDefID]
local cost_slowdown = (slowdown / ud.health) * ud.metalCost
GG.Awards.AddAwardPoints ('slow', attackerTeam, cost_slowdown)
end
-- check if a target change is needed
-- only changes target if the target is fully slowed and next order is an attack order
if spValidUnitID(attackerID) and attritionWeaponDefs[weaponID].smartRetarget then
local health = spGetUnitHealth(unitID)
if slowedUnits[unitID].slowDamage > health*attritionWeaponDefs[weaponID].smartRetarget then
local cmd = spGetCommandQueue(attackerID, 3)
-- set order by player
if #cmd > 1 and (cmd[1].id == CMD_ATTACK and #cmd[1].params == 1 and cmd[1].params[1] == unitID
and (cmd[2].id == CMD_ATTACK or
(#cmd > 2 and cmd[2].id == CMD_SET_WANTED_MAX_SPEED and cmd[3].id == CMD_ATTACK))) then
local re = spGetUnitStates(attackerID)["repeat"]
if cmd[2].id == CMD_SET_WANTED_MAX_SPEED then
spGiveOrderToUnit(attackerID,CMD_REMOVE,{cmd[1].tag,cmd[2].tag},{})
else
spGiveOrderToUnit(attackerID,CMD_REMOVE,{cmd[1].tag},{})
end
if re then
spGiveOrderToUnit(attackerID,CMD_ATTACK,cmd[1].params,{"shift"})
end
end
-- if attack is a non-player command
if #cmd == 0 or cmd[1].id ~= CMD_ATTACK or (cmd[1].id == CMD_ATTACK and cmd[1].options.internal) then
local newTargetID = spGetUnitNearestEnemy(attackerID,UnitDefs[attackerDefID].range, true)
if newTargetID ~= unitID and spValidUnitID(attackerID) and spValidUnitID(newTargetID) then
local team = spGetUnitTeam(newTargetID)
if (not team) or team ~= gaiaTeamID then
spSetUnitTarget(attackerID,newTargetID)
if #cmd > 0 and cmd[1].id == CMD_ATTACK then
if #cmd > 1 and cmd[2].id == CMD_SET_WANTED_MAX_SPEED then
spGiveOrderToUnit(attackerID,CMD_REMOVE,{cmd[1].tag,cmd[2].tag},{})
else
spGiveOrderToUnit(attackerID,CMD_REMOVE,{cmd[1].tag},{})
end
elseif #cmd > 1 and cmd[1].id == CMD_MOVE and cmd[2].id == CMD_FIGHT and
cmd[2].options.internal and #cmd[2].params == 1 and cmd[2].params[1] == unitID then
spGiveOrderToUnit(attackerID,CMD_REMOVE,{cmd[2].tag},{})
end
end
end
end
end
end
-- write to unit rules param
updateSlow( unitID, slowedUnits[unitID])
if attritionWeaponDefs[weaponID].onlySlow then
return 0
else
return damage
end
end
local function addSlowDamage(unitID, damage)
-- add stats that the unit requires for this gadget
if not slowedUnits[unitID] then
slowedUnits[unitID] = {
slowDamage = 0,
degradeTimer = DEGRADE_TIMER,
perma = false,
}
GG.attUnits[unitID] = true -- unit with attribute change to be handled by unit_attributes
end
-- add slow damage
slowedUnits[unitID].slowDamage = slowedUnits[unitID].slowDamage + damage
slowedUnits[unitID].degradeTimer = DEGRADE_TIMER
updateSlow( unitID, slowedUnits[unitID]) -- without this unit does not fire slower, only moves slower
end
local function getSlowDamage(unitID)
if slowedUnits[unitID] then
return slowedUnits[unitID].slowDamage
end
return false
end
local function permaSlowDamage(unitID, perma)
if slowedUnits[unitID] then
slowedUnits[unitID].perma = perma
end
end
-- morph uses this
GG.getSlowDamage = getSlowDamage
GG.addSlowDamage = addSlowDamage
GG.permaSlowDamage = permaSlowDamage -- true/false whether unit is permaslowed, used by unit_zombies.lua
local function removeUnit(unitID)
slowedUnits[unitID] = nil
end
function gadget:GameFrame(f)
if (f-1) % UPDATE_PERIOD == 0 then
for unitID, state in pairs(slowedUnits) do
if not(state.perma) then
if state.degradeTimer <= 0 then
local health = spGetUnitHealth(unitID) or 0
state.slowDamage = state.slowDamage-health*DEGRADE_FACTOR
if state.slowDamage < 0 then
state.slowDamage = 0
updateSlow(unitID, state)
removeUnit(unitID)
else
updateSlow(unitID, state)
end
else
state.degradeTimer = state.degradeTimer-1
end
end
end
end
end
function gadget:UnitDestroyed(unitID)
removeUnit(unitID)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
keesklopt/matrix | profiles/car.lua | 1 | 6551 | -- Begin of globals
require("lib/access")
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true, ["entrance"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
restriction_exception_tags = { "motorcar", "motor_vehicle", "vehicle" }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["shuttle_train"] = 10,
["default"] = 50
}
take_minimum_of_speeds = false
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function get_exceptions(vector)
for i,v in ipairs(restriction_exception_tags) do
vector:Add(v)
end
end
local function parse_maxspeed(source)
if source == nil then
return 0
end
local n = tonumber(source:match("%d*"))
if n == nil then
n = 0
end
if string.match(source, "mph") or string.match(source, "mp/h") then
n = (n*1609)/1000;
end
return math.abs(n)
end
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = Access.find_access_tag(node, access_tags_hierachy)
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
-- parse access and barrier tags
if access and access ~= "" then
if access_tag_blacklist[access] then
node.bollard = true
end
elseif barrier and barrier ~= "" then
if barrier_whitelist[barrier] then
return
else
node.bollard = true
end
end
return 1
end
function way_function (way)
-- we dont route over areas
local area = way.tags:Find("area")
if ignore_areas and ("yes" == area) then
return 0
end
-- check if oneway tag is unsupported
local oneway = way.tags:Find("oneway")
if "reversible" == oneway then
return 0
end
-- Check if we are allowed to access the way
local access = Access.find_access_tag(way, access_tags_hierachy)
if access_tag_blacklist[access] then
return 0
end
-- Second, parse the way according to these properties
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parse_maxspeed(way.tags:Find ( "maxspeed") )
local maxspeed_forward = parse_maxspeed(way.tags:Find( "maxspeed:forward"))
local maxspeed_backward = parse_maxspeed(way.tags:Find( "maxspeed:backward"))
local barrier = way.tags:Find("barrier")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
-- else
-- way.name = highway -- if no name exists, use way type
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) then
if durationIsValid(duration) then
way.duration = math.max( parseDuration(duration), 1 );
end
way.direction = Way.bidirectional
if speed_profile[route] ~= nil then
highway = route;
end
if tonumber(way.duration) < 0 then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if maxspeed > speed_profile[highway] then
way.speed = maxspeed
else
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
end
-- Set the avg speed on ways that are marked accessible
if "" ~= highway and access_tag_whitelist[access] and way.speed == -1 then
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
way.direction = Way.bidirectional
if obey_oneway then
if oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or
oneway == "1" or
oneway == "true" or
junction == "roundabout" or
(highway == "motorway_link" and oneway ~="no") or
(highway == "motorway" and oneway ~= "no")
then
way.direction = Way.oneway
end
end
-- Override speed settings if explicit forward/backward maxspeeds are given
if way.speed > 0 and maxspeed_forward ~= nil and maxspeed_forward > 0 then
if Way.bidirectional == way.direction then
way.backward_speed = way.speed
end
way.speed = maxspeed_forward
end
if maxspeed_backward ~= nil and maxspeed_backward > 0 then
way.backward_speed = maxspeed_backward
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT
function node_vector_function(vector)
for v in vector.nodes do
node_function(v)
end
end
| agpl-3.0 |
hugohuang1111/quick-framework | src/cc/Registry.lua | 23 | 1841 |
local Registry = class("Registry")
Registry.classes_ = {}
Registry.objects_ = {}
function Registry.add(cls, name)
assert(type(cls) == "table" and cls.__cname ~= nil, "Registry.add() - invalid class")
if not name then name = cls.__cname end
assert(Registry.classes_[name] == nil, string.format("Registry.add() - class \"%s\" already exists", tostring(name)))
Registry.classes_[name] = cls
end
function Registry.remove(name)
assert(Registry.classes_[name] ~= nil, string.format("Registry.remove() - class \"%s\" not found", name))
Registry.classes_[name] = nil
end
function Registry.exists(name)
return Registry.classes_[name] ~= nil
end
function Registry.newObject(name, ...)
local cls = Registry.classes_[name]
if not cls then
-- auto load
pcall(function()
cls = require(name)
Registry.add(cls, name)
end)
end
assert(cls ~= nil, string.format("Registry.newObject() - invalid class \"%s\"", tostring(name)))
return cls.new(...)
end
function Registry.setObject(object, name)
assert(Registry.objects_[name] == nil, string.format("Registry.setObject() - object \"%s\" already exists", tostring(name)))
assert(object ~= nil, "Registry.setObject() - object \"%s\" is nil", tostring(name))
Registry.objects_[name] = object
end
function Registry.getObject(name)
assert(Registry.objects_[name] ~= nil, string.format("Registry.getObject() - object \"%s\" not exists", tostring(name)))
return Registry.objects_[name]
end
function Registry.removeObject(name)
assert(Registry.objects_[name] ~= nil, string.format("Registry.removeObject() - object \"%s\" not exists", tostring(name)))
Registry.objects_[name] = nil
end
function Registry.isObjectExists(name)
return Registry.objects_[name] ~= nil
end
return Registry
| mit |
alexandergall/snabbswitch | lib/ljsyscall/syscall/openbsd/fcntl.lua | 24 | 1202 | -- OpenBSD fcntl
-- TODO incomplete, lots missing
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local function init(types)
local c = require "syscall.openbsd.constants"
local ffi = require "ffi"
local t, pt, s = types.t, types.pt, types.s
local h = require "syscall.helpers"
local ctobool, booltoc = h.ctobool, h.booltoc
local fcntl = { -- TODO some functionality missing
commands = {
[c.F.SETFL] = function(arg) return c.O[arg] end,
[c.F.SETFD] = function(arg) return c.FD[arg] end,
[c.F.GETLK] = t.flock,
[c.F.SETLK] = t.flock,
[c.F.SETLKW] = t.flock,
},
ret = {
[c.F.DUPFD] = function(ret) return t.fd(ret) end,
[c.F.DUPFD_CLOEXEC] = function(ret) return t.fd(ret) end,
[c.F.GETFD] = function(ret) return tonumber(ret) end,
[c.F.GETFL] = function(ret) return tonumber(ret) end,
[c.F.GETOWN] = function(ret) return tonumber(ret) end,
[c.F.GETLK] = function(ret, arg) return arg end,
}
}
return fcntl
end
return {init = init}
| apache-2.0 |
link4all/20170920openwrt | own_files/mt7628/files_wfnt_4g/usr/lib/lua/luci/controller/admin/servicectl.lua | 21 | 1168 | -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.admin.servicectl", package.seeall)
function index()
entry({"servicectl"}, alias("servicectl", "status")).sysauth = "admin"
entry({"servicectl", "status"}, call("action_status")).leaf = true
entry({"servicectl", "restart"}, call("action_restart")).leaf = true
end
function action_status()
local data = nixio.fs.readfile("/var/run/luci-reload-status")
if data then
luci.http.write("/etc/config/")
luci.http.write(data)
else
luci.http.write("finish")
end
end
function action_restart(args)
local uci = require "luci.model.uci".cursor()
if args then
local service
local services = { }
for service in args:gmatch("[%w_-]+") do
services[#services+1] = service
end
local command = uci:apply(services, true)
if nixio.fork() == 0 then
local i = nixio.open("/dev/null", "r")
local o = nixio.open("/dev/null", "w")
nixio.dup(i, nixio.stdin)
nixio.dup(o, nixio.stdout)
i:close()
o:close()
nixio.exec("/bin/sh", unpack(command))
else
luci.http.write("OK")
os.exit(0)
end
end
end
| gpl-2.0 |
ArashFaceBook/InfernalTG | plugins/dic.lua | 31 | 1662 | --[[
-- Translate text using Google Translate.
-- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello
--]]
do
function translate(source_lang, target_lang, text)
local path = "http://translate.google.com/translate_a/single"
-- URL query parameters
local params = {
client = "t",
ie = "UTF-8",
oe = "UTF-8",
hl = "en",
dt = "t",
tl = target_lang or "fa",
sl = source_lang or "auto",
text = URL.escape(text)
}
local query = format_http_params(params, true)
local url = path..query
local res, code = https.request(url)
-- Return nil if error
if code > 200 then return nil end
local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "")
return trans
end
function run(msg, matches)
-- Third pattern
if #matches == 1 then
print("First")
local text = matches[1]
return translate(nil, nil, text)
end
-- Second pattern
if #matches == 2 then
print("Second")
local target = matches[1]
local text = matches[2]
return translate(nil, target, text)
end
-- First pattern
if #matches == 3 then
print("Third")
local source = matches[1]
local target = matches[2]
local text = matches[3]
return translate(source, target, text)
end
end
return {
description = "Translate Text, Default Persian",
usage = {
"/dic (txt) : translate txt en to fa",
"/dic (lang) (txt) : translate en to other",
"/dic (lang1,lang2) (txt) : translate lang1 to lang2",
},
patterns = {
"^[!/]dic ([%w]+),([%a]+) (.+)",
"^[!/]dic ([%w]+) (.+)",
"^[!/]dic (.+)",
},
run = run
}
end
| gpl-2.0 |
xuejian1354/barrier_breaker | feeds/luci/contrib/luadoc/lua/luadoc/util.lua | 93 | 5826 | -------------------------------------------------------------------------------
-- General utilities.
-- @release $Id: util.lua,v 1.16 2008/02/17 06:42:51 jasonsantos Exp $
-------------------------------------------------------------------------------
local posix = require "nixio.fs"
local type, table, string, io, assert, tostring, setmetatable, pcall = type, table, string, io, assert, tostring, setmetatable, pcall
-------------------------------------------------------------------------------
-- Module with several utilities that could not fit in a specific module
module "luadoc.util"
-------------------------------------------------------------------------------
-- Removes spaces from the begining and end of a given string
-- @param s string to be trimmed
-- @return trimmed string
function trim (s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
-------------------------------------------------------------------------------
-- Removes spaces from the begining and end of a given string, considering the
-- string is inside a lua comment.
-- @param s string to be trimmed
-- @return trimmed string
-- @see trim
-- @see string.gsub
function trim_comment (s)
s = string.gsub(s, "%-%-+(.*)$", "%1")
return trim(s)
end
-------------------------------------------------------------------------------
-- Checks if a given line is empty
-- @param line string with a line
-- @return true if line is empty, false otherwise
function line_empty (line)
return (string.len(trim(line)) == 0)
end
-------------------------------------------------------------------------------
-- Appends two string, but if the first one is nil, use to second one
-- @param str1 first string, can be nil
-- @param str2 second string
-- @return str1 .. " " .. str2, or str2 if str1 is nil
function concat (str1, str2)
if str1 == nil or string.len(str1) == 0 then
return str2
else
return str1 .. " " .. str2
end
end
-------------------------------------------------------------------------------
-- Split text into a list consisting of the strings in text,
-- separated by strings matching delim (which may be a pattern).
-- @param delim if delim is "" then action is the same as %s+ except that
-- field 1 may be preceeded by leading whitespace
-- @usage split(",%s*", "Anna, Bob, Charlie,Dolores")
-- @usage split(""," x y") gives {"x","y"}
-- @usage split("%s+"," x y") gives {"", "x","y"}
-- @return array with strings
-- @see table.concat
function split(delim, text)
local list = {}
if string.len(text) > 0 then
delim = delim or ""
local pos = 1
-- if delim matches empty string then it would give an endless loop
if string.find("", delim, 1) and delim ~= "" then
error("delim matches empty string!")
end
local first, last
while 1 do
if delim ~= "" then
first, last = string.find(text, delim, pos)
else
first, last = string.find(text, "%s+", pos)
if first == 1 then
pos = last+1
first, last = string.find(text, "%s+", pos)
end
end
if first then -- found?
table.insert(list, string.sub(text, pos, first-1))
pos = last+1
else
table.insert(list, string.sub(text, pos))
break
end
end
end
return list
end
-------------------------------------------------------------------------------
-- Comments a paragraph.
-- @param text text to comment with "--", may contain several lines
-- @return commented text
function comment (text)
text = string.gsub(text, "\n", "\n-- ")
return "-- " .. text
end
-------------------------------------------------------------------------------
-- Wrap a string into a paragraph.
-- @param s string to wrap
-- @param w width to wrap to [80]
-- @param i1 indent of first line [0]
-- @param i2 indent of subsequent lines [0]
-- @return wrapped paragraph
function wrap(s, w, i1, i2)
w = w or 80
i1 = i1 or 0
i2 = i2 or 0
assert(i1 < w and i2 < w, "the indents must be less than the line width")
s = string.rep(" ", i1) .. s
local lstart, len = 1, string.len(s)
while len - lstart > w do
local i = lstart + w
while i > lstart and string.sub(s, i, i) ~= " " do i = i - 1 end
local j = i
while j > lstart and string.sub(s, j, j) == " " do j = j - 1 end
s = string.sub(s, 1, j) .. "\n" .. string.rep(" ", i2) ..
string.sub(s, i + 1, -1)
local change = i2 + 1 - (i - j)
lstart = j + change
len = len + change
end
return s
end
-------------------------------------------------------------------------------
-- Opens a file, creating the directories if necessary
-- @param filename full path of the file to open (or create)
-- @param mode mode of opening
-- @return file handle
function posix.open (filename, mode)
local f = io.open(filename, mode)
if f == nil then
filename = string.gsub(filename, "\\", "/")
local dir = ""
for d in string.gfind(filename, ".-/") do
dir = dir .. d
posix.mkdir(dir)
end
f = io.open(filename, mode)
end
return f
end
----------------------------------------------------------------------------------
-- Creates a Logger with LuaLogging, if present. Otherwise, creates a mock logger.
-- @param options a table with options for the logging mechanism
-- @return logger object that will implement log methods
function loadlogengine(options)
local logenabled = pcall(function()
require "logging"
require "logging.console"
end)
local logging = logenabled and logging
if logenabled then
if options.filelog then
logger = logging.file("luadoc.log") -- use this to get a file log
else
logger = logging.console("[%level] %message\n")
end
if options.verbose then
logger:setLevel(logging.INFO)
else
logger:setLevel(logging.WARN)
end
else
noop = {__index=function(...)
return function(...)
-- noop
end
end}
logger = {}
setmetatable(logger, noop)
end
return logger
end
| gpl-2.0 |
anvilvapre/OpenRA | mods/ra/maps/soviet-06a/soviet06a-AI.lua | 19 | 3128 | IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end
IdlingUnits = function()
local lazyUnits = enemy.GetGroundAttackers()
Utils.Do(lazyUnits, function(unit)
Trigger.OnDamaged(unit, function()
Trigger.ClearAll(unit)
Trigger.AfterDelay(0, function() IdleHunt(unit) end)
end)
end)
end
BaseApwr = { type = "apwr", pos = CVec.New(-13, 7), cost = 500, exists = true }
BaseTent = { type = "tent", pos = CVec.New(-2, 12), cost = 400, exists = true }
BaseProc = { type = "proc", pos = CVec.New(-7, 5), cost = 1400, exists = true }
BaseWeap = { type = "weap", pos = CVec.New(-9, 11), cost = 2000, exists = true }
BaseApwr2 = { type = "apwr", pos = CVec.New(-4, 1), cost = 500, exists = true }
BaseBuildings = { BaseApwr, BaseTent, BaseProc, BaseWeap, BaseApwr2 }
BuildBase = function()
for i,v in ipairs(BaseBuildings) do
if not v.exists then
BuildBuilding(v)
return
end
end
Trigger.AfterDelay(DateTime.Seconds(10), BuildBase)
end
BuildBuilding = function(building)
Trigger.AfterDelay(Actor.BuildTime(building.type), function()
if CYard.IsDead or CYard.Owner ~= enemy then
return
elseif Harvester.IsDead and enemy.Resources <= 299 then
return
end
local actor = Actor.Create(building.type, true, { Owner = enemy, Location = CYardLocation.Location + building.pos })
enemy.Cash = enemy.Cash - building.cost
building.exists = true
Trigger.OnKilled(actor, function() building.exists = false end)
Trigger.OnDamaged(actor, function(building)
if building.Owner == enemy and building.Health < building.MaxHealth * 3/4 then
building.StartBuildingRepairs()
end
end)
Trigger.AfterDelay(DateTime.Seconds(10), BuildBase)
end)
end
ProduceInfantry = function()
if not BaseTent.exists then
return
elseif Harvester.IsDead and enemy.Resources <= 299 then
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9))
local toBuild = { Utils.Random(AlliedInfantryTypes) }
local Path = Utils.Random(AttackPaths)
enemy.Build(toBuild, function(unit)
InfAttack[#InfAttack + 1] = unit[1]
if #InfAttack >= 10 then
SendUnits(InfAttack, Path)
InfAttack = { }
Trigger.AfterDelay(DateTime.Minutes(2), ProduceInfantry)
else
Trigger.AfterDelay(delay, ProduceInfantry)
end
end)
end
ProduceArmor = function()
if not BaseWeap.exists then
return
elseif Harvester.IsDead and enemy.Resources <= 599 then
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17))
local toBuild = { Utils.Random(AlliedArmorTypes) }
local Path = Utils.Random(AttackPaths)
enemy.Build(toBuild, function(unit)
ArmorAttack[#ArmorAttack + 1] = unit[1]
if #ArmorAttack >= 6 then
SendUnits(ArmorAttack, Path)
ArmorAttack = { }
Trigger.AfterDelay(DateTime.Minutes(3), ProduceArmor)
else
Trigger.AfterDelay(delay, ProduceArmor)
end
end)
end
SendUnits = function(units, waypoints)
Utils.Do(units, function(unit)
if not unit.IsDead then
Utils.Do(waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
end)
end
| gpl-3.0 |
xponen/Zero-K | LuaRules/Gadgets/astar.lua | 25 | 7226 | ---------------------------------------------------------------------
--[[
author: quantum
GPL v2 or later
http://www.policyalmanac.org/games/aStarTutorial.htm
http://en.wikipedia.org/wiki/A*_search_algorithm
use: override IsBlocked, GetDistance, etc and run aStar.GetPath
-- example --------------------------------
local aStar = dofile"astar.lua"
aStar.gridHeight = 250
aStar.gridWidth = 250
aStar.IsBlocked = function(id) return false end
function aStar.GetDistanceEstimate(a, b) -- heuristic estimate of distance to goal
local x1, y1 = aStar.ToCoords(a)
local x2, y2 = aStar.ToCoords(b)
return math.max(math.abs(x2-x1), math.abs(y2-y1)) + math.min(math.abs(x2-x1), math.abs(y2-y1))/2*1.001
end
function aStar.GetDistance(a, b) -- distance between two directly connected nodes (squares if in a grid)
local x1, y1 = aStar.ToCoords(a)
local x2, y2 = aStar.ToCoords(b)
if x1 == x2 or y1 == y2 then
return 1
else
return 2^0.5
end
end
local startID = aStar.ToID{1, 1}
local goalID = aStar.ToID{80, 90}
local path = aStar.GetPath(startID, goalID)
]]
---------------------------------------------------------------------
---------------------------------------------------------------------
local function GetSetCount(set)
local count = 0
for _ in pairs(set) do
count = count + 1
end
return count
end
local function ReconstructPath(parents, node)
local path = {}
repeat
path[#path + 1] = node
node = parents[node]
until not node
-- reverse it
local x, y, temp = 1, #path
while x < y do
temp = path[x]
path[x] = path[y]
path[y] = temp
x, y = x + 1, y - 1
end
return path
end
local aStar = {
-- set grid size
gridWidth = 250,
gridHeight = 250,
}
function aStar.NewPriorityQueue()
local heap = {} -- binary heap
local priorities = {}
local heapCount = 0
function heap.Insert(currentKey, currentPriority, currentPosition)
if not currentPosition then -- we are inserting a new item, as opposed to changing the f value of an item already in the heap
currentPosition = heapCount + 1
heapCount = heapCount + 1
end
priorities[currentKey] = currentPriority
heap[currentPosition] = currentKey
while true do
local parentPosition = math.floor(currentPosition/2)
if parentPosition == 1 then
break
end
local parentKey = heap[parentPosition]
if parentKey and priorities[parentKey] > currentPriority then -- swap parent and current node
heap[parentPosition] = currentKey
heap[currentPosition] = parentKey
currentPosition = parentPosition
else
break
end
end
end
function heap.UpdateNode(currentKey, currentPriority)
for position=1, heapCount do
local id = heap[position]
if id == currentKey then
heap.Insert(currentKey, currentPriority, position)
break
end
end
end
function heap.Pop()
local ret = heap[1]
if not ret then
error "queue is empty"
end
heap[1] = heap[heapCount]
heap[heapCount] = nil
heapCount = heapCount - 1
local currentPosition = 1
while true do
local currentKey = heap[currentPosition]
local currentPriority = priorities[currentKey]
local child1Position = currentPosition*2
local child1Key = heap[child1Position]
if not child1Key then
break
end
local child2Position = currentPosition*2 + 1
local child2Key = heap[child2Position]
if not child2Key then
break
end
local child1F = priorities[child1Key]
local child2F = priorities[child2Key]
if currentPriority < child1F and currentPriority < child2F then
break
elseif child1F < child2F then
heap[child1Position] = currentKey
heap[currentPosition] = child1Key
currentPosition = child1Position
else
heap[child2Position] = currentKey
heap[currentPosition] = child2Key
currentPosition = child2Position
end
end
return ret, priorities[ret]
end
return heap
end
function aStar.ToID(coords) -- override this function if necessary, converts grid coords to node id
local x, y = coords[1], coords[2]
return y * aStar.gridWidth + x
end
function aStar.ToCoords(id) -- override this function if necessary, converts node id to grid coords
return id % aStar.gridWidth, math.floor(id/aStar.gridWidth)
end
function aStar.GetDistance(a, b) -- override this function, exact distance beween adjacent nodes a and b
error"override this function"
end
function aStar.IsBlocked(id)
error"override this function"
end
function aStar.GetNeighbors(id, goal) -- override this if the nodes are not arranged in a grid
local x, y = aStar.ToCoords(id)
local nodes = {
aStar.ToID{x-1, y},
aStar.ToID{x, y-1},
aStar.ToID{x+1, y},
aStar.ToID{x, y+1},
aStar.ToID{x-1, y-1},
aStar.ToID{x-1, y+1},
aStar.ToID{x+1, y+1},
aStar.ToID{x+1, y-1}
}
local passable = {}
local passableCount = 0
for nodeIndex=1, 8 do
local node = nodes[nodeIndex]
if not aStar.IsBlocked(node) then
passableCount = passableCount + 1
passable[passableCount] = node
end
end
return passable
end
function aStar.GetDistanceEstimate(a, b) -- heuristic estimate of distance to goal
error"override this function"
end
function aStar.GetPathsThreaded(startID, goalID, cyclesBeforeYield)
cyclesBeforeYield = cyclesBeforeYield or 1000
return coroutine.create(aStar.GetPath)
end
function aStar.GetPath(startID, goalID, cyclesBeforeYield)
local parents = {}
local gScores = {} -- distance from start along optimal path
local closedSet = {} -- nodes already evaluated
local openHeap = aStar.NewPriorityQueue() -- binary heap of nodes by f score
gScores[startID] = 0
openHeap.Insert(startID, aStar.GetDistanceEstimate(startID, goalID))
local cyclesFromLastYield = 0
local cycleCounter = 0
while openHeap[1] do
-- threading
cycleCounter = cycleCounter + 1
if cyclesBeforeYield then
cyclesFromLastYield = cyclesFromLastYield + 1
if cyclesFromLastYield > cyclesBeforeYield then
cyclesFromLastYield= 0
coroutine.yield(cycleCounter)
end
end
local currentNode = openHeap.Pop()
if currentNode == goalID then -- goal reached
return ReconstructPath(parents, currentNode), closedSet
end
closedSet[currentNode] = true
for _, neighbor in ipairs(aStar.GetNeighbors(currentNode)) do
if not closedSet[neighbor] then
local tentativeGScore = gScores[currentNode] + aStar.GetDistance(currentNode, neighbor)
if not gScores[neighbor] then
parents[neighbor] = currentNode
gScores[neighbor] = tentativeGScore
openHeap.Insert(neighbor, gScores[neighbor] + aStar.GetDistanceEstimate(neighbor, goalID))
elseif tentativeGScore < gScores[neighbor] then
parents[neighbor] = currentNode
gScores[neighbor] = tentativeGScore
openHeap.UpdateNode(neighbor, gScores[neighbor] + aStar.GetDistanceEstimate(neighbor, goalID))
end
end
end
end
return false
end
return aStar | gpl-2.0 |
xponen/Zero-K | effects/gundam_prettypop.lua | 26 | 1976 | -- prettypop
return {
["prettypop"] = {
groundflash = {
air = true,
alwaysvisible = true,
circlealpha = 0.0,
circlegrowth = 8,
flashalpha = 0.9,
flashsize = 20,
ground = true,
ttl = 17,
water = true,
color = {
[1] = 1,
[2] = 0,
[3] = 0.5,
},
},
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.2,
alwaysvisible = true,
colormap = [[1.0 1.0 1.0 0.04 1.0 0.0 0.5 0.01 0.1 0.1 0.1 0.01]],
directional = false,
emitrot = 45,
emitrotspread = 32,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.005, 0]],
numparticles = 16,
particlelife = 5,
particlelifespread = 16,
particlesize = 20,
particlesizespread = 0,
particlespeed = 16,
particlespeedspread = 1,
pos = [[0, 2, 0]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[randdots]],
useairlos = false,
},
},
pop1 = {
air = true,
class = [[heatcloud]],
count = 1,
ground = true,
water = true,
properties = {
alwaysvisible = true,
heat = 10,
heatfalloff = 0.8,
maxheat = 10,
pos = [[r-2 r2, 5, r-2 r2]],
size = 1,
sizegrowth = 16,
speed = [[0, 0, 0]],
texture = [[bluenovaexplo]],
},
},
},
}
| gpl-2.0 |
alastair-robertson/awesome | lib/gears/protected_call.lua | 4 | 1797 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2016 Uli Schlachter
-- @release @AWESOME_VERSION@
-- @module gears.protected_call
---------------------------------------------------------------------------
local gdebug = require("gears.debug")
local tostring = tostring
local traceback = debug.traceback
local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1)
local xpcall = xpcall
local protected_call = {}
local function error_handler(err)
gdebug.print_error(traceback("Error during a protected call: " .. tostring(err)))
end
local function handle_result(success, ...)
if success then
return ...
end
end
local do_pcall
if _VERSION <= "Lua 5.1" then
-- Lua 5.1 doesn't support arguments in xpcall :-(
do_pcall = function(func, ...)
local args = { ... }
return handle_result(xpcall(function()
return func(unpack(args))
end, error_handler))
end
else
do_pcall = function(func, ...)
return handle_result(xpcall(func, error_handler, ...))
end
end
--- Call a function in protected mode and handle error-reporting.
-- If the function call succeeds, all results of the function are returned.
-- Otherwise, an error message is printed and nothing is returned.
-- @tparam function func The function to call
-- @param ... Arguments to the function
-- @return The result of the given function, or nothing if an error occurred.
function protected_call.call(func, ...)
return do_pcall(func, ...)
end
local pcall_mt = {}
function pcall_mt:__call(...)
return do_pcall(...)
end
return setmetatable(protected_call, pcall_mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
alastair-robertson/awesome | lib/wibox/widget/textclock.lua | 3 | 1814 | ---------------------------------------------------------------------------
--- Text clock widget.
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @release @AWESOME_VERSION@
-- @classmod wibox.widget.textclock
---------------------------------------------------------------------------
local setmetatable = setmetatable
local os = os
local textbox = require("wibox.widget.textbox")
local timer = require("gears.timer")
local DateTime = require("lgi").GLib.DateTime
local textclock = { mt = {} }
--- This lowers the timeout so that it occurs "correctly". For example, a timeout
-- of 60 is rounded so that it occurs the next time the clock reads ":00 seconds".
local function calc_timeout(real_timeout)
return real_timeout - os.time() % real_timeout
end
--- Create a textclock widget. It draws the time it is in a textbox.
--
-- @tparam[opt=" %a %b %d, %H:%M "] string format The time format.
-- @tparam[opt=60] number timeout How often update the time (in seconds).
-- @treturn table A textbox widget.
-- @function wibox.widget.textclock
function textclock.new(format, timeout)
format = format or " %a %b %d, %H:%M "
timeout = timeout or 60
local w = textbox()
local t
function w._private.textclock_update_cb()
w:set_markup(DateTime.new_now_local():format(format))
t.timeout = calc_timeout(timeout)
t:again()
return true -- Continue the timer
end
t = timer.weak_start_new(timeout, w._private.textclock_update_cb)
t:emit_signal("timeout")
return w
end
function textclock.mt:__call(...)
return textclock.new(...)
end
--@DOC_widget_COMMON@
--@DOC_object_COMMON@
return setmetatable(textclock, textclock.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
nwf/nodemcu-firmware | app/lua53/host/tests/strings.lua | 7 | 13415 | -- $Id: strings.lua,v 1.87 2016/12/21 19:23:02 roberto Exp $
-- See Copyright Notice in file all.lua
print('testing strings and string library')
local maxi, mini = math.maxinteger, math.mininteger
local function checkerror (msg, f, ...)
local s, err = pcall(f, ...)
assert(not s and string.find(err, msg))
end
-- testing string comparisons
assert('alo' < 'alo1')
assert('' < 'a')
assert('alo\0alo' < 'alo\0b')
assert('alo\0alo\0\0' > 'alo\0alo\0')
assert('alo' < 'alo\0')
assert('alo\0' > 'alo')
assert('\0' < '\1')
assert('\0\0' < '\0\1')
assert('\1\0a\0a' <= '\1\0a\0a')
assert(not ('\1\0a\0b' <= '\1\0a\0a'))
assert('\0\0\0' < '\0\0\0\0')
assert(not('\0\0\0\0' < '\0\0\0'))
assert('\0\0\0' <= '\0\0\0\0')
assert(not('\0\0\0\0' <= '\0\0\0'))
assert('\0\0\0' <= '\0\0\0')
assert('\0\0\0' >= '\0\0\0')
assert(not ('\0\0b' < '\0\0a\0'))
-- testing string.sub
assert(string.sub("123456789",2,4) == "234")
assert(string.sub("123456789",7) == "789")
assert(string.sub("123456789",7,6) == "")
assert(string.sub("123456789",7,7) == "7")
assert(string.sub("123456789",0,0) == "")
assert(string.sub("123456789",-10,10) == "123456789")
assert(string.sub("123456789",1,9) == "123456789")
assert(string.sub("123456789",-10,-20) == "")
assert(string.sub("123456789",-1) == "9")
assert(string.sub("123456789",-4) == "6789")
assert(string.sub("123456789",-6, -4) == "456")
assert(string.sub("123456789", mini, -4) == "123456")
assert(string.sub("123456789", mini, maxi) == "123456789")
assert(string.sub("123456789", mini, mini) == "")
assert(string.sub("\000123456789",3,5) == "234")
assert(("\000123456789"):sub(8) == "789")
-- testing string.find
assert(string.find("123456789", "345") == 3)
a,b = string.find("123456789", "345")
assert(string.sub("123456789", a, b) == "345")
assert(string.find("1234567890123456789", "345", 3) == 3)
assert(string.find("1234567890123456789", "345", 4) == 13)
assert(string.find("1234567890123456789", "346", 4) == nil)
assert(string.find("1234567890123456789", ".45", -9) == 13)
assert(string.find("abcdefg", "\0", 5, 1) == nil)
assert(string.find("", "") == 1)
assert(string.find("", "", 1) == 1)
assert(not string.find("", "", 2))
assert(string.find('', 'aaa', 1) == nil)
assert(('alo(.)alo'):find('(.)', 1, 1) == 4)
assert(string.len("") == 0)
assert(string.len("\0\0\0") == 3)
assert(string.len("1234567890") == 10)
assert(#"" == 0)
assert(#"\0\0\0" == 3)
assert(#"1234567890" == 10)
-- testing string.byte/string.char
assert(string.byte("a") == 97)
assert(string.byte("\xe4") > 127)
assert(string.byte(string.char(255)) == 255)
assert(string.byte(string.char(0)) == 0)
assert(string.byte("\0") == 0)
assert(string.byte("\0\0alo\0x", -1) == string.byte('x'))
assert(string.byte("ba", 2) == 97)
assert(string.byte("\n\n", 2, -1) == 10)
assert(string.byte("\n\n", 2, 2) == 10)
assert(string.byte("") == nil)
assert(string.byte("hi", -3) == nil)
assert(string.byte("hi", 3) == nil)
assert(string.byte("hi", 9, 10) == nil)
assert(string.byte("hi", 2, 1) == nil)
assert(string.char() == "")
assert(string.char(0, 255, 0) == "\0\255\0")
assert(string.char(0, string.byte("\xe4"), 0) == "\0\xe4\0")
assert(string.char(string.byte("\xe4l\0óu", 1, -1)) == "\xe4l\0óu")
assert(string.char(string.byte("\xe4l\0óu", 1, 0)) == "")
assert(string.char(string.byte("\xe4l\0óu", -10, 100)) == "\xe4l\0óu")
assert(string.upper("ab\0c") == "AB\0C")
assert(string.lower("\0ABCc%$") == "\0abcc%$")
assert(string.rep('teste', 0) == '')
assert(string.rep('tés\00tê', 2) == 'tés\0têtés\000tê')
assert(string.rep('', 10) == '')
if string.packsize("i") == 4 then
-- result length would be 2^31 (int overflow)
checkerror("too large", string.rep, 'aa', (1 << 30))
checkerror("too large", string.rep, 'a', (1 << 30), ',')
end
-- repetitions with separator
assert(string.rep('teste', 0, 'xuxu') == '')
assert(string.rep('teste', 1, 'xuxu') == 'teste')
assert(string.rep('\1\0\1', 2, '\0\0') == '\1\0\1\0\0\1\0\1')
assert(string.rep('', 10, '.') == string.rep('.', 9))
assert(not pcall(string.rep, "aa", maxi // 2 + 10))
assert(not pcall(string.rep, "", maxi // 2 + 10, "aa"))
assert(string.reverse"" == "")
assert(string.reverse"\0\1\2\3" == "\3\2\1\0")
assert(string.reverse"\0001234" == "4321\0")
for i=0,30 do assert(string.len(string.rep('a', i)) == i) end
assert(type(tostring(nil)) == 'string')
assert(type(tostring(12)) == 'string')
assert(string.find(tostring{}, 'table:'))
assert(string.find(tostring(print), 'function:'))
assert(#tostring('\0') == 1)
assert(tostring(true) == "true")
assert(tostring(false) == "false")
assert(tostring(-1203) == "-1203")
assert(tostring(1203.125) == "1203.125")
assert(tostring(-0.5) == "-0.5")
assert(tostring(-32767) == "-32767")
if math.tointeger(2147483647) then -- no overflow? (32 bits)
assert(tostring(-2147483647) == "-2147483647")
end
if math.tointeger(4611686018427387904) then -- no overflow? (64 bits)
assert(tostring(4611686018427387904) == "4611686018427387904")
assert(tostring(-4611686018427387904) == "-4611686018427387904")
end
if tostring(0.0) == "0.0" then -- "standard" coercion float->string
assert('' .. 12 == '12' and 12.0 .. '' == '12.0')
assert(tostring(-1203 + 0.0) == "-1203.0")
else -- compatible coercion
assert(tostring(0.0) == "0")
assert('' .. 12 == '12' and 12.0 .. '' == '12')
assert(tostring(-1203 + 0.0) == "-1203")
end
x = '"ílo"\n\\'
assert(string.format('%q%s', x, x) == '"\\"ílo\\"\\\n\\\\""ílo"\n\\')
assert(string.format('%q', "\0") == [["\0"]])
assert(load(string.format('return %q', x))() == x)
x = "\0\1\0023\5\0009"
assert(load(string.format('return %q', x))() == x)
assert(string.format("\0%c\0%c%x\0", string.byte("\xe4"), string.byte("b"), 140) ==
"\0\xe4\0b8c\0")
assert(string.format('') == "")
assert(string.format("%c",34)..string.format("%c",48)..string.format("%c",90)..string.format("%c",100) ==
string.format("%c%c%c%c", 34, 48, 90, 100))
assert(string.format("%s\0 is not \0%s", 'not be', 'be') == 'not be\0 is not \0be')
assert(string.format("%%%d %010d", 10, 23) == "%10 0000000023")
assert(tonumber(string.format("%f", 10.3)) == 10.3)
x = string.format('"%-50s"', 'a')
assert(#x == 52)
assert(string.sub(x, 1, 4) == '"a ')
assert(string.format("-%.20s.20s", string.rep("%", 2000)) ==
"-"..string.rep("%", 20)..".20s")
assert(string.format('"-%20s.20s"', string.rep("%", 2000)) ==
string.format("%q", "-"..string.rep("%", 2000)..".20s"))
do
local function checkQ (v)
local s = string.format("%q", v)
local nv = load("return " .. s)()
assert(v == nv and math.type(v) == math.type(nv))
end
checkQ("\0\0\1\255\u{234}")
checkQ(math.maxinteger)
checkQ(math.mininteger)
checkQ(math.pi)
checkQ(0.1)
checkQ(true)
checkQ(nil)
checkQ(false)
checkerror("no literal", string.format, "%q", {})
end
assert(string.format("\0%s\0", "\0\0\1") == "\0\0\0\1\0")
checkerror("contains zeros", string.format, "%10s", "\0")
-- format x tostring
assert(string.format("%s %s", nil, true) == "nil true")
assert(string.format("%s %.4s", false, true) == "false true")
assert(string.format("%.3s %.3s", false, true) == "fal tru")
local m = setmetatable({}, {__tostring = function () return "hello" end,
__name = "hi"})
assert(string.format("%s %.10s", m, m) == "hello hello")
getmetatable(m).__tostring = nil -- will use '__name' from now on
assert(string.format("%.4s", m) == "hi: ")
getmetatable(m).__tostring = function () return {} end
checkerror("'__tostring' must return a string", tostring, m)
assert(string.format("%x", 0.0) == "0")
assert(string.format("%02x", 0.0) == "00")
assert(string.format("%08X", 0xFFFFFFFF) == "FFFFFFFF")
assert(string.format("%+08d", 31501) == "+0031501")
assert(string.format("%+08d", -30927) == "-0030927")
--[[NodeMCU: this fails as a result of format size limitations
do -- longest number that can be formatted
local i = 1
local j = 10000
while i + 1 < j do -- binary search for maximum finite float
local m = (i + j) // 2
if 10^m < math.huge then i = m else j = m end
end
assert(10^i < math.huge and 10^j == math.huge)
local s = string.format('%.99f', -(10^i))
assert(string.len(s) >= i + 101)
assert(tonumber(s) == -(10^i)) --
end
]]
-- testing large numbers for format
do -- assume at least 32 bits
local max, min = 0x7fffffff, -0x80000000 -- "large" for 32 bits
assert(string.sub(string.format("%8x", -1), -8) == "ffffffff")
assert(string.format("%x", max) == "7fffffff")
assert(string.sub(string.format("%x", min), -8) == "80000000")
assert(string.format("%d", max) == "2147483647")
assert(string.format("%d", min) == "-2147483648")
assert(string.format("%u", 0xffffffff) == "4294967295")
assert(string.format("%o", 0xABCD) == "125715")
max, min = 0x7fffffffffffffff, -0x8000000000000000
if max > 2.0^53 then -- only for 64 bits
assert(string.format("%x", (2^52 | 0) - 1) == "fffffffffffff")
assert(string.format("0x%8X", 0x8f000003) == "0x8F000003")
assert(string.format("%d", 2^53) == "9007199254740992")
assert(string.format("%i", -2^53) == "-9007199254740992")
assert(string.format("%x", max) == "7fffffffffffffff")
assert(string.format("%x", min) == "8000000000000000")
assert(string.format("%d", max) == "9223372036854775807")
assert(string.format("%d", min) == "-9223372036854775808")
assert(string.format("%u", ~(-1 << 64)) == "18446744073709551615")
assert(tostring(1234567890123) == '1234567890123')
end
end
do print("testing 'format %a %A'")
local function matchhexa (n)
local s = string.format("%a", n)
-- result matches ISO C requirements
assert(string.find(s, "^%-?0x[1-9a-f]%.?[0-9a-f]*p[-+]?%d+$"))
assert(tonumber(s) == n) -- and has full precision
s = string.format("%A", n)
assert(string.find(s, "^%-?0X[1-9A-F]%.?[0-9A-F]*P[-+]?%d+$"))
assert(tonumber(s) == n)
end
for _, n in ipairs{0.1, -0.1, 1/3, -1/3, 1e30, -1e30,
-45/247, 1, -1, 2, -2, 3e-20, -3e-20} do
matchhexa(n)
end
assert(string.find(string.format("%A", 0.0), "^0X0%.?0?P%+?0$"))
assert(string.find(string.format("%a", -0.0), "^%-0x0%.?0?p%+?0$"))
if not _port then -- test inf, -inf, NaN, and -0.0
assert(string.find(string.format("%a", 1/0), "^inf"))
assert(string.find(string.format("%A", -1/0), "^%-INF"))
assert(string.find(string.format("%a", 0/0), "^%-?nan"))
assert(string.find(string.format("%a", -0.0), "^%-0x0"))
end
if not pcall(string.format, "%.3a", 0) then
(Message or print)("\n >>> modifiers for format '%a' not available <<<\n")
else
assert(string.find(string.format("%+.2A", 12), "^%+0X%x%.%x0P%+?%d$"))
assert(string.find(string.format("%.4A", -12), "^%-0X%x%.%x000P%+?%d$"))
end
end
-- errors in format
local function check (fmt, msg)
checkerror(msg, string.format, fmt, 10)
end
local aux = string.rep('0', 600)
check("%100.3d", "too long")
check("%1"..aux..".3d", "too long")
check("%1.100d", "too long")
check("%10.1"..aux.."004d", "too long")
check("%t", "invalid option")
check("%"..aux.."d", "repeated flags")
check("%d %d", "no value")
assert(load("return 1\n--comment without ending EOL")() == 1)
checkerror("table expected", table.concat, 3)
assert(table.concat{} == "")
assert(table.concat({}, 'x') == "")
assert(table.concat({'\0', '\0\1', '\0\1\2'}, '.\0.') == "\0.\0.\0\1.\0.\0\1\2")
local a = {}; for i=1,300 do a[i] = "xuxu" end
assert(table.concat(a, "123").."123" == string.rep("xuxu123", 300))
assert(table.concat(a, "b", 20, 20) == "xuxu")
assert(table.concat(a, "", 20, 21) == "xuxuxuxu")
assert(table.concat(a, "x", 22, 21) == "")
assert(table.concat(a, "3", 299) == "xuxu3xuxu")
assert(table.concat({}, "x", maxi, maxi - 1) == "")
assert(table.concat({}, "x", mini + 1, mini) == "")
assert(table.concat({}, "x", maxi, mini) == "")
assert(table.concat({[maxi] = "alo"}, "x", maxi, maxi) == "alo")
assert(table.concat({[maxi] = "alo", [maxi - 1] = "y"}, "-", maxi - 1, maxi)
== "y-alo")
assert(not pcall(table.concat, {"a", "b", {}}))
a = {"a","b","c"}
assert(table.concat(a, ",", 1, 0) == "")
assert(table.concat(a, ",", 1, 1) == "a")
assert(table.concat(a, ",", 1, 2) == "a,b")
assert(table.concat(a, ",", 2) == "b,c")
assert(table.concat(a, ",", 3) == "c")
assert(table.concat(a, ",", 4) == "")
_port = true -- NodeMCU: to support for locals
if not _port then
local locales = { "ptb", "pt_BR.iso88591", "ISO-8859-1" }
local function trylocale (w)
for i = 1, #locales do
if os.setlocale(locales[i], w) then
print(string.format("'%s' locale set to '%s'", w, locales[i]))
return locales[i]
end
end
print(string.format("'%s' locale not found", w))
return false
end
if trylocale("collate") then
assert("alo" < "álo" and "álo" < "amo")
end
if trylocale("ctype") then
assert(string.gsub("áéíóú", "%a", "x") == "xxxxx")
assert(string.gsub("áÁéÉ", "%l", "x") == "xÁxÉ")
assert(string.gsub("áÁéÉ", "%u", "x") == "áxéx")
assert(string.upper"áÁé{xuxu}ção" == "ÁÁÉ{XUXU}ÇÃO")
end
os.setlocale("C")
assert(os.setlocale() == 'C')
assert(os.setlocale(nil, "numeric") == 'C')
end
-- bug in Lua 5.3.2
-- 'gmatch' iterator does not work across coroutines
do
local f = string.gmatch("1 2 3 4 5", "%d+")
assert(f() == "1")
co = coroutine.wrap(f)
assert(co() == "2")
end
print('OK')
| mit |
rogerpueyo/luci | modules/luci-base/luasrc/sys.lua | 4 | 13380 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local io = require "io"
local os = require "os"
local table = require "table"
local nixio = require "nixio"
local fs = require "nixio.fs"
local uci = require "luci.model.uci"
local luci = {}
luci.util = require "luci.util"
luci.ip = require "luci.ip"
local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select, unpack =
tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select, unpack
module "luci.sys"
function call(...)
return os.execute(...) / 256
end
exec = luci.util.exec
-- containing the whole environment is returned otherwise this function returns
-- the corresponding string value for the given name or nil if no such variable
-- exists.
getenv = nixio.getenv
function hostname(newname)
if type(newname) == "string" and #newname > 0 then
fs.writefile( "/proc/sys/kernel/hostname", newname )
return newname
else
return nixio.uname().nodename
end
end
function httpget(url, stream, target)
if not target then
local source = stream and io.popen or luci.util.exec
return source("wget -qO- %s" % luci.util.shellquote(url))
else
return os.execute("wget -qO %s %s" %
{luci.util.shellquote(target), luci.util.shellquote(url)})
end
end
function reboot()
return os.execute("reboot >/dev/null 2>&1")
end
function syslog()
return luci.util.exec("logread")
end
function dmesg()
return luci.util.exec("dmesg")
end
function uniqueid(bytes)
local rand = fs.readfile("/dev/urandom", bytes)
return rand and nixio.bin.hexlify(rand)
end
function uptime()
return nixio.sysinfo().uptime
end
net = {}
local function _nethints(what, callback)
local _, k, e, mac, ip, name, duid, iaid
local cur = uci.cursor()
local ifn = { }
local hosts = { }
local lookup = { }
local function _add(i, ...)
local k = select(i, ...)
if k then
if not hosts[k] then hosts[k] = { } end
hosts[k][1] = select(1, ...) or hosts[k][1]
hosts[k][2] = select(2, ...) or hosts[k][2]
hosts[k][3] = select(3, ...) or hosts[k][3]
hosts[k][4] = select(4, ...) or hosts[k][4]
end
end
luci.ip.neighbors(nil, function(neigh)
if neigh.mac and neigh.family == 4 then
_add(what, neigh.mac:string(), neigh.dest:string(), nil, nil)
elseif neigh.mac and neigh.family == 6 then
_add(what, neigh.mac:string(), nil, neigh.dest:string(), nil)
end
end)
if fs.access("/etc/ethers") then
for e in io.lines("/etc/ethers") do
mac, name = e:match("^([a-fA-F0-9:-]+)%s+(%S+)")
mac = luci.ip.checkmac(mac)
if mac and name then
if luci.ip.checkip4(name) then
_add(what, mac, name, nil, nil)
else
_add(what, mac, nil, nil, name)
end
end
end
end
cur:foreach("dhcp", "dnsmasq",
function(s)
if s.leasefile and fs.access(s.leasefile) then
for e in io.lines(s.leasefile) do
mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
mac = luci.ip.checkmac(mac)
if mac and ip then
_add(what, mac, ip, nil, name ~= "*" and name)
end
end
end
end
)
cur:foreach("dhcp", "odhcpd",
function(s)
if type(s.leasefile) == "string" and fs.access(s.leasefile) then
for e in io.lines(s.leasefile) do
duid, iaid, name, _, ip = e:match("^# %S+ (%S+) (%S+) (%S+) (-?%d+) %S+ %S+ ([0-9a-f:.]+)/[0-9]+")
mac = net.duid_to_mac(duid)
if mac then
if ip and iaid == "ipv4" then
_add(what, mac, ip, nil, name ~= "*" and name)
elseif ip then
_add(what, mac, nil, ip, name ~= "*" and name)
end
end
end
end
end
)
cur:foreach("dhcp", "host",
function(s)
for mac in luci.util.imatch(s.mac) do
mac = luci.ip.checkmac(mac)
if mac then
_add(what, mac, s.ip, nil, s.name)
end
end
end)
for _, e in ipairs(nixio.getifaddrs()) do
if e.name ~= "lo" then
ifn[e.name] = ifn[e.name] or { }
if e.family == "packet" and e.addr and #e.addr == 17 then
ifn[e.name][1] = e.addr:upper()
elseif e.family == "inet" then
ifn[e.name][2] = e.addr
elseif e.family == "inet6" then
ifn[e.name][3] = e.addr
end
end
end
for _, e in pairs(ifn) do
if e[what] and (e[2] or e[3]) then
_add(what, e[1], e[2], e[3], e[4])
end
end
for _, e in pairs(hosts) do
lookup[#lookup+1] = (what > 1) and e[what] or (e[2] or e[3])
end
if #lookup > 0 then
lookup = luci.util.ubus("network.rrdns", "lookup", {
addrs = lookup,
timeout = 250,
limit = 1000
}) or { }
end
for _, e in luci.util.kspairs(hosts) do
callback(e[1], e[2], e[3], lookup[e[2]] or lookup[e[3]] or e[4])
end
end
-- Each entry contains the values in the following order:
-- [ "mac", "name" ]
function net.mac_hints(callback)
if callback then
_nethints(1, function(mac, v4, v6, name)
name = name or v4
if name and name ~= mac then
callback(mac, name or v4)
end
end)
else
local rv = { }
_nethints(1, function(mac, v4, v6, name)
name = name or v4
if name and name ~= mac then
rv[#rv+1] = { mac, name or v4 }
end
end)
return rv
end
end
-- Each entry contains the values in the following order:
-- [ "ip", "name" ]
function net.ipv4_hints(callback)
if callback then
_nethints(2, function(mac, v4, v6, name)
name = name or mac
if name and name ~= v4 then
callback(v4, name)
end
end)
else
local rv = { }
_nethints(2, function(mac, v4, v6, name)
name = name or mac
if name and name ~= v4 then
rv[#rv+1] = { v4, name }
end
end)
return rv
end
end
-- Each entry contains the values in the following order:
-- [ "ip", "name" ]
function net.ipv6_hints(callback)
if callback then
_nethints(3, function(mac, v4, v6, name)
name = name or mac
if name and name ~= v6 then
callback(v6, name)
end
end)
else
local rv = { }
_nethints(3, function(mac, v4, v6, name)
name = name or mac
if name and name ~= v6 then
rv[#rv+1] = { v6, name }
end
end)
return rv
end
end
function net.host_hints(callback)
if callback then
_nethints(1, function(mac, v4, v6, name)
if mac and mac ~= "00:00:00:00:00:00" and (v4 or v6 or name) then
callback(mac, v4, v6, name)
end
end)
else
local rv = { }
_nethints(1, function(mac, v4, v6, name)
if mac and mac ~= "00:00:00:00:00:00" and (v4 or v6 or name) then
local e = { }
if v4 then e.ipv4 = v4 end
if v6 then e.ipv6 = v6 end
if name then e.name = name end
rv[mac] = e
end
end)
return rv
end
end
function net.conntrack(callback)
local ok, nfct = pcall(io.lines, "/proc/net/nf_conntrack")
if not ok or not nfct then
return nil
end
local line, connt = nil, (not callback) and { }
for line in nfct do
local fam, l3, l4, timeout, tuples =
line:match("^(ipv[46]) +(%d+) +%S+ +(%d+) +(%d+) +(.+)$")
if fam and l3 and l4 and timeout and not tuples:match("^TIME_WAIT ") then
l4 = nixio.getprotobynumber(l4)
local entry = {
bytes = 0,
packets = 0,
layer3 = fam,
layer4 = l4 and l4.name or "unknown",
timeout = tonumber(timeout, 10)
}
local key, val
for key, val in tuples:gmatch("(%w+)=(%S+)") do
if key == "bytes" or key == "packets" then
entry[key] = entry[key] + tonumber(val, 10)
elseif key == "src" or key == "dst" then
if entry[key] == nil then
entry[key] = luci.ip.new(val):string()
end
elseif key == "sport" or key == "dport" then
if entry[key] == nil then
entry[key] = val
end
elseif val then
entry[key] = val
end
end
if callback then
callback(entry)
else
connt[#connt+1] = entry
end
end
end
return callback and true or connt
end
function net.devices()
local devs = {}
local seen = {}
for k, v in ipairs(nixio.getifaddrs()) do
if v.name and not seen[v.name] then
seen[v.name] = true
devs[#devs+1] = v.name
end
end
return devs
end
function net.duid_to_mac(duid)
local b1, b2, b3, b4, b5, b6
if type(duid) == "string" then
-- DUID-LLT / Ethernet
if #duid == 28 then
b1, b2, b3, b4, b5, b6 = duid:match("^00010001(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)%x%x%x%x%x%x%x%x$")
-- DUID-LL / Ethernet
elseif #duid == 20 then
b1, b2, b3, b4, b5, b6 = duid:match("^00030001(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)$")
-- DUID-LL / Ethernet (Without Header)
elseif #duid == 12 then
b1, b2, b3, b4, b5, b6 = duid:match("^(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)(%x%x)$")
end
end
return b1 and luci.ip.checkmac(table.concat({ b1, b2, b3, b4, b5, b6 }, ":"))
end
process = {}
function process.info(key)
local s = {uid = nixio.getuid(), gid = nixio.getgid()}
return not key and s or s[key]
end
function process.list()
local data = {}
local k
local ps = luci.util.execi("/bin/busybox top -bn1")
if not ps then
return
end
for line in ps do
local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match(
"^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][<NW ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)"
)
local idx = tonumber(pid)
if idx and not cmd:match("top %-bn1") then
data[idx] = {
['PID'] = pid,
['PPID'] = ppid,
['USER'] = user,
['STAT'] = stat,
['VSZ'] = vsz,
['%MEM'] = mem,
['%CPU'] = cpu,
['COMMAND'] = cmd
}
end
end
return data
end
function process.setgroup(gid)
return nixio.setgid(gid)
end
function process.setuser(uid)
return nixio.setuid(uid)
end
process.signal = nixio.kill
local function xclose(fd)
if fd and fd:fileno() > 2 then
fd:close()
end
end
function process.exec(command, stdout, stderr, nowait)
local out_r, out_w, err_r, err_w
if stdout then out_r, out_w = nixio.pipe() end
if stderr then err_r, err_w = nixio.pipe() end
local pid = nixio.fork()
if pid == 0 then
nixio.chdir("/")
local null = nixio.open("/dev/null", "w+")
if null then
nixio.dup(out_w or null, nixio.stdout)
nixio.dup(err_w or null, nixio.stderr)
nixio.dup(null, nixio.stdin)
xclose(out_w)
xclose(out_r)
xclose(err_w)
xclose(err_r)
xclose(null)
end
nixio.exec(unpack(command))
os.exit(-1)
end
local _, pfds, rv = nil, {}, { code = -1, pid = pid }
xclose(out_w)
xclose(err_w)
if out_r then
pfds[#pfds+1] = {
fd = out_r,
cb = type(stdout) == "function" and stdout,
name = "stdout",
events = nixio.poll_flags("in", "err", "hup")
}
end
if err_r then
pfds[#pfds+1] = {
fd = err_r,
cb = type(stderr) == "function" and stderr,
name = "stderr",
events = nixio.poll_flags("in", "err", "hup")
}
end
while #pfds > 0 do
local nfds, err = nixio.poll(pfds, -1)
if not nfds and err ~= nixio.const.EINTR then
break
end
local i
for i = #pfds, 1, -1 do
local rfd = pfds[i]
if rfd.revents > 0 then
local chunk, err = rfd.fd:read(4096)
if chunk and #chunk > 0 then
if rfd.cb then
rfd.cb(chunk)
else
rfd.buf = rfd.buf or {}
rfd.buf[#rfd.buf + 1] = chunk
end
else
table.remove(pfds, i)
if rfd.buf then
rv[rfd.name] = table.concat(rfd.buf, "")
end
rfd.fd:close()
end
end
end
end
if not nowait then
_, _, rv.code = nixio.waitpid(pid)
end
return rv
end
user = {}
-- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" }
user.getuser = nixio.getpw
function user.getpasswd(username)
local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username)
local pwh = pwe and (pwe.pwdp or pwe.passwd)
if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then
return nil, pwe
else
return pwh, pwe
end
end
function user.checkpasswd(username, pass)
local pwh, pwe = user.getpasswd(username)
if pwe then
return (pwh == nil or nixio.crypt(pass, pwh) == pwh)
end
return false
end
function user.setpasswd(username, password)
return os.execute("(echo %s; sleep 1; echo %s) | passwd %s >/dev/null 2>&1" %{
luci.util.shellquote(password),
luci.util.shellquote(password),
luci.util.shellquote(username)
})
end
wifi = {}
function wifi.getiwinfo(ifname)
local ntm = require "luci.model.network"
ntm.init()
local wnet = ntm:get_wifinet(ifname)
if wnet and wnet.iwinfo then
return wnet.iwinfo
end
local wdev = ntm:get_wifidev(ifname)
if wdev and wdev.iwinfo then
return wdev.iwinfo
end
return { ifname = ifname }
end
init = {}
init.dir = "/etc/init.d/"
function init.names()
local names = { }
for name in fs.glob(init.dir.."*") do
names[#names+1] = fs.basename(name)
end
return names
end
function init.index(name)
if fs.access(init.dir..name) then
return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null"
%{ init.dir, name })
end
end
local function init_action(action, name)
if fs.access(init.dir..name) then
return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action })
end
end
function init.enabled(name)
return (init_action("enabled", name) == 0)
end
function init.enable(name)
return (init_action("enable", name) == 0)
end
function init.disable(name)
return (init_action("disable", name) == 0)
end
function init.start(name)
return (init_action("start", name) == 0)
end
function init.stop(name)
return (init_action("stop", name) == 0)
end
function init.restart(name)
return (init_action("restart", name) == 0)
end
function init.reload(name)
return (init_action("reload", name) == 0)
end
| apache-2.0 |
Xamla/torch-pcl | KdTree.lua | 1 | 2444 | local ffi = require 'ffi'
local torch = require 'torch'
local utils = require 'pcl.utils'
local pcl = require 'pcl.PointTypes'
local KdTree = torch.class('pcl.KdTree', pcl)
local func_by_type = {}
local function init()
local KdTreeFLANN_method_names = {
'new',
'clone',
'delete',
'setInputCloud',
'getEpsilon',
'setEpsilon',
'setMinPts',
'getMinPts',
'setSortedResults',
'assign',
'nearestKSearch',
'radiusSearch'
}
for k,v in pairs(utils.type_key_map) do
func_by_type[k] = utils.create_typed_methods("pcl_KdTreeFLANN_TYPE_KEY_", KdTreeFLANN_method_names, v)
end
func_by_type[pcl.FPFHSignature33] = utils.create_typed_methods("pcl_KdTreeFLANN_TYPE_KEY_", KdTreeFLANN_method_names, 'FPFHSignature33')
func_by_type[pcl.VFHSignature308] = utils.create_typed_methods("pcl_KdTreeFLANN_TYPE_KEY_", KdTreeFLANN_method_names, 'VFHSignature308')
end
init()
function KdTree:__init(pointType, sorted)
if type(pointType) == 'boolean' then
sorted = pointType
pointType = pcl.PointXYZ
end
sorted = sorted or true
pointType = pcl.pointType(pointType)
rawset(self, 'f', func_by_type[pointType])
self.pointType = pointType
if type(sorted) == 'boolean' then
self.o = self.f.new(sorted)
elseif type(sorted) == 'cdata' then
self.o = sorted
end
end
function KdTree:cdata()
return self.o
end
function KdTree:clone()
local clone = self.f.clone(self.o)
return KdTree.new(self.pointType, clone)
end
function KdTree:setInputCloud(cloud, indices)
self.f.setInputCloud(self.o, cloud:cdata(), utils.cdata(indices))
end
function KdTree:getEpsilon()
return self.f.getEpsilon(self.o)
end
function KdTree:setEpsilon(eps)
self.f.setEpsilon(self.o, eps)
end
function KdTree:setMinPts(value)
self.f.setMinPts(self.o, value)
end
function KdTree:getMinPts()
return self.f.getMinPts(self.o)
end
function KdTree:setSortedResults(sorted)
self.f.setSortedResults(self.o, sorted)
end
function KdTree:set(other)
self.f.assign(self.o, other:cdata())
return self
end
function KdTree:nearestKSearch(point, k, indices, squaredDistances)
return self.f.nearestKSearch(self.o, point, k, utils.cdata(indices), utils.cdata(squaredDistances))
end
function KdTree:radiusSearch(point, radius, indices, squaredDistances, max_nn)
return self.f.radiusSearch(self.o, point, radius, utils.cdata(indices), utils.cdata(squaredDistances), max_nn or 0)
end
| bsd-3-clause |
Poyer/Anchor-BoT | 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 |
alexandergall/snabbswitch | lib/ljsyscall/syscall/openbsd/types.lua | 24 | 9707 | -- OpenBSD types
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local function init(types)
local abi = require "syscall.abi"
local t, pt, s, ctypes = types.t, types.pt, types.s, types.ctypes
local ffi = require "ffi"
local bit = require "syscall.bit"
local h = require "syscall.helpers"
local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2
local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn
= h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn
local ntohl, ntohl, ntohs, htons, octal = h.ntohl, h.ntohl, h.ntohs, h.htons, h.octal
local c = require "syscall.openbsd.constants"
local mt = {} -- metatables
local addtypes = {
}
local addstructs = {
}
for k, v in pairs(addtypes) do addtype(types, k, v) end
for k, v in pairs(addstructs) do addtype(types, k, v, lenmt) end
-- 32 bit dev_t, 24 bit minor, 8 bit major, but minor is a cookie and neither really used just legacy
local function makedev(major, minor)
if type(major) == "table" then major, minor = major[1], major[2] end
local dev = major or 0
if minor then dev = bit.bor(minor, bit.lshift(major, 8)) end
return dev
end
mt.device = {
index = {
major = function(dev) return bit.bor(bit.band(bit.rshift(dev.dev, 8), 0xff)) end,
minor = function(dev) return bit.band(dev.dev, 0xffff00ff) end,
device = function(dev) return tonumber(dev.dev) end,
},
newindex = {
device = function(dev, major, minor) dev.dev = makedev(major, minor) end,
},
__new = function(tp, major, minor)
return ffi.new(tp, makedev(major, minor))
end,
}
addtype(types, "device", "struct {dev_t dev;}", mt.device)
mt.stat = {
index = {
dev = function(st) return t.device(st.st_dev) end,
mode = function(st) return st.st_mode end,
ino = function(st) return tonumber(st.st_ino) end,
nlink = function(st) return st.st_nlink end,
uid = function(st) return st.st_uid end,
gid = function(st) return st.st_gid end,
rdev = function(st) return t.device(st.st_rdev) end,
atime = function(st) return st.st_atim.time end,
ctime = function(st) return st.st_ctim.time end,
mtime = function(st) return st.st_mtim.time end,
birthtime = function(st) return st.st_birthtim.time end,
size = function(st) return tonumber(st.st_size) end,
blocks = function(st) return tonumber(st.st_blocks) end,
blksize = function(st) return tonumber(st.st_blksize) end,
flags = function(st) return st.st_flags end,
gen = function(st) return st.st_gen end,
type = function(st) return bit.band(st.st_mode, c.S_I.FMT) end,
todt = function(st) return bit.rshift(st.type, 12) end,
isreg = function(st) return st.type == c.S_I.FREG end,
isdir = function(st) return st.type == c.S_I.FDIR end,
ischr = function(st) return st.type == c.S_I.FCHR end,
isblk = function(st) return st.type == c.S_I.FBLK end,
isfifo = function(st) return st.type == c.S_I.FIFO end,
islnk = function(st) return st.type == c.S_I.FLNK end,
issock = function(st) return st.type == c.S_I.FSOCK end,
iswht = function(st) return st.type == c.S_I.FWHT end,
},
}
-- add some friendlier names to stat, also for luafilesystem compatibility
mt.stat.index.access = mt.stat.index.atime
mt.stat.index.modification = mt.stat.index.mtime
mt.stat.index.change = mt.stat.index.ctime
local namemap = {
file = mt.stat.index.isreg,
directory = mt.stat.index.isdir,
link = mt.stat.index.islnk,
socket = mt.stat.index.issock,
["char device"] = mt.stat.index.ischr,
["block device"] = mt.stat.index.isblk,
["named pipe"] = mt.stat.index.isfifo,
}
mt.stat.index.typename = function(st)
for k, v in pairs(namemap) do if v(st) then return k end end
return "other"
end
addtype(types, "stat", "struct stat", mt.stat)
mt.flock = {
index = {
type = function(self) return self.l_type end,
whence = function(self) return self.l_whence end,
start = function(self) return self.l_start end,
len = function(self) return self.l_len end,
pid = function(self) return self.l_pid end,
sysid = function(self) return self.l_sysid end,
},
newindex = {
type = function(self, v) self.l_type = c.FCNTL_LOCK[v] end,
whence = function(self, v) self.l_whence = c.SEEK[v] end,
start = function(self, v) self.l_start = v end,
len = function(self, v) self.l_len = v end,
pid = function(self, v) self.l_pid = v end,
sysid = function(self, v) self.l_sysid = v end,
},
__new = newfn,
}
addtype(types, "flock", "struct flock", mt.flock)
mt.dirent = {
index = {
fileno = function(self) return tonumber(self.d_fileno) end,
reclen = function(self) return self.d_reclen end,
namlen = function(self) return self.d_namlen end,
type = function(self) return self.d_type end,
name = function(self) return ffi.string(self.d_name, self.d_namlen) end,
toif = function(self) return bit.lshift(self.d_type, 12) end, -- convert to stat types
},
__len = function(self) return self.d_reclen end,
}
mt.dirent.index.ino = mt.dirent.index.fileno -- alternate name
-- TODO previously this allowed lower case values, but this static version does not
-- could add mt.dirent.index[tolower(k)] = mt.dirent.index[k] but need to do consistently elsewhere
for k, v in pairs(c.DT) do
mt.dirent.index[k] = function(self) return self.type == v end
end
addtype(types, "dirent", "struct dirent", mt.dirent)
mt.fdset = {
index = {
fds_bits = function(self) return self.__fds_bits end,
},
}
addtype(types, "fdset", "fd_set", mt.fdset)
-- TODO see Linux notes. Also maybe can be shared with BSDs, have not checked properly
-- TODO also remove WIF prefixes.
mt.wait = {
__index = function(w, k)
local _WSTATUS = bit.band(w.status, octal("0177"))
local _WSTOPPED = octal("0177")
local WTERMSIG = _WSTATUS
local EXITSTATUS = bit.band(bit.rshift(w.status, 8), 0xff)
local WIFEXITED = (_WSTATUS == 0)
local tab = {
WIFEXITED = WIFEXITED,
WIFSTOPPED = bit.band(w.status, 0xff) == _WSTOPPED,
WIFSIGNALED = _WSTATUS ~= _WSTOPPED and _WSTATUS ~= 0
}
if tab.WIFEXITED then tab.EXITSTATUS = EXITSTATUS end
if tab.WIFSTOPPED then tab.WSTOPSIG = EXITSTATUS end
if tab.WIFSIGNALED then tab.WTERMSIG = WTERMSIG end
if tab[k] then return tab[k] end
local uc = 'W' .. k:upper()
if tab[uc] then return tab[uc] end
end
}
function t.waitstatus(status)
return setmetatable({status = status}, mt.wait)
end
local signames = {}
for k, v in pairs(c.SIG) do
signames[v] = k
end
mt.siginfo = {
index = {
signo = function(s) return s.si_signo end,
errno = function(s) return s.si_errno end,
code = function(s) return s.si_code end,
pid = function(s) return s.si_pid end,
uid = function(s) return s.si_uid end,
status = function(s) return s.si_status end,
addr = function(s) return s.si_addr end,
value = function(s) return s.si_value end,
trapno = function(s) return s._fault._trapno end,
timerid = function(s) return s._timer._timerid end,
overrun = function(s) return s._timer._overrun end,
mqd = function(s) return s._mesgq._mqd end,
band = function(s) return s._poll._band end,
signame = function(s) return signames[s.signo] end,
},
newindex = {
signo = function(s, v) s.si_signo = v end,
errno = function(s, v) s.si_errno = v end,
code = function(s, v) s.si_code = v end,
pid = function(s, v) s.si_pid = v end,
uid = function(s, v) s.si_uid = v end,
status = function(s, v) s.si_status = v end,
addr = function(s, v) s.si_addr = v end,
value = function(s, v) s.si_value = v end,
trapno = function(s, v) s._fault._trapno = v end,
timerid = function(s, v) s._timer._timerid = v end,
overrun = function(s, v) s._timer._overrun = v end,
mqd = function(s, v) s._mesgq._mqd = v end,
band = function(s, v) s._poll._band = v end,
},
__len = lenfn,
}
addtype(types, "siginfo", "siginfo_t", mt.siginfo)
-- sigaction, standard POSIX behaviour with union of handler and sigaction
addtype_fn(types, "sa_sigaction", "void (*)(int, siginfo_t *, void *)")
mt.sigaction = {
index = {
handler = function(sa) return sa.__sigaction_u.__sa_handler end,
sigaction = function(sa) return sa.__sigaction_u.__sa_sigaction end,
mask = function(sa) return sa.sa_mask end,
flags = function(sa) return tonumber(sa.sa_flags) end,
},
newindex = {
handler = function(sa, v)
if type(v) == "string" then v = pt.void(c.SIGACT[v]) end
if type(v) == "number" then v = pt.void(v) end
sa.__sigaction_u.__sa_handler = v
end,
sigaction = function(sa, v)
if type(v) == "string" then v = pt.void(c.SIGACT[v]) end
if type(v) == "number" then v = pt.void(v) end
sa.__sigaction_u.__sa_sigaction = v
end,
mask = function(sa, v)
if not ffi.istype(t.sigset, v) then v = t.sigset(v) end
sa.sa_mask = v
end,
flags = function(sa, v) sa.sa_flags = c.SA[v] end,
},
__new = function(tp, tab)
local sa = ffi.new(tp)
if tab then for k, v in pairs(tab) do sa[k] = v end end
if tab and tab.sigaction then sa.sa_flags = bit.bor(sa.flags, c.SA.SIGINFO) end -- this flag must be set if sigaction set
return sa
end,
}
addtype(types, "sigaction", "struct sigaction", mt.sigaction)
return types
end
return {init = init}
| apache-2.0 |
xponen/Zero-K | LuaUI/Widgets/gui_replace_cloak_con_order.lua | 12 | 2136 |
function widget:GetInfo()
return {
name = "Replace Cloak Con Orders",
desc = "Prevents constructor accidental decloak in enemy territory by replacing Repair, Reclaim and Rez with Move. .\n\nNOTE:Use command menu or command hotkeys to override.",
author = "GoogleFrog",
date = "13 August 2011",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = false -- loaded by default?
}
end
options_path = 'Game/Unit AI/Replace Cloak Con Orders'
options = {
reclaim = {name='Replace Reclaim', type='bool', value=true},
resurrect = {name='Replace Resurrect', type='bool', value=true},
repair = {name='Replace Repair', type='bool', value=true},
}
function widget:CommandNotify(id, params, cmdOptions)
if cmdOptions.right and #params < 4 and ((id == CMD.REPAIR and options.repair.value) or
(id == CMD.RECLAIM and options.reclaim.value) or (id == CMD.RESURRECT and options.resurrect.value)) then
local selUnits = Spring.GetSelectedUnits()
local replace = false
for i = 1, #selUnits do
local unitID = selUnits[i]
local ud = Spring.GetUnitDefID(unitID)
-- assumption here is that everything that can repair or rez can also reclaim
if ud and UnitDefs[ud] and UnitDefs[ud].canReclaim and Spring.GetUnitIsCloaked(unitID) and UnitDefs[ud].speed > 0 then
replace = true
break
end
end
if replace then
local x,y,z
if #params == 1 then
if id == CMD.REPAIR then
if Spring.ValidUnitID(params[1]) and Spring.GetUnitPosition(params[1]) then
x,_,z = Spring.GetUnitPosition(params[1])
y = Spring.GetGroundHeight(x,z)
end
else
params[1] = params[1] - Game.maxUnits
if Spring.ValidFeatureID(params[1]) and Spring.GetFeaturePosition(params[1]) then
x,_,z = Spring.GetFeaturePosition(params[1])
y = Spring.GetGroundHeight(x,z)
end
end
else
x,y,z = params[1], params[2], params[3]
end
if x and y then
for i = 1, #selUnits do
local unitID = selUnits[i]
Spring.GiveOrderToUnit(unitID,CMD.MOVE,{x,y,z},cmdOptions)
end
end
end
return replace
end
return false
end | gpl-2.0 |
infernal1200/infernall | plugins/banhammer.lua | 294 | 10470 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
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, ok_cb, true)
end
local function ban_user(user_id, chat_id)
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
-- Save to redis
local hash = 'superbanned:'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned or false
end
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, msg.to.id)
if superbanned or banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, chat_id)
if superbanned then
print('SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
end
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if get_cmd == 'kick' then
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'superban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!')
return superban_user(member_id, chat_id)
elseif get_cmd == 'whitelist user' then
local hash = 'whitelist:user#id'..member_id
redis:set(hash, true)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted')
elseif get_cmd == 'whitelist delete user' then
local hash = 'whitelist:user#id'..member_id
redis:del(hash)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist')
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1] == 'kickme' then
kick_user(msg.from.id, msg.to.id)
end
if not is_momod(msg) then
return nil
end
local receiver = get_receiver(msg)
if matches[4] then
get_cmd = matches[1]..' '..matches[2]..' '..matches[3]
elseif matches[3] then
get_cmd = matches[1]..' '..matches[2]
else
get_cmd = matches[1]
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
ban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'superban' and is_admin(msg) then
local user_id = matches[3]
local chat_id = msg.to.id
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
superban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' globally banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'superbanned:'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
kick_user(matches[2], msg.to.id)
else
local member = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
if string.match(matches[4], '^%d+$') then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
else
local member = string.gsub(matches[4], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
user = "!kickme : Exit from group",
moderator = {
"!whitelist <enable>/<disable> : Enable or disable whitelist mode",
"!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id> : Remove user from whitelist",
"!whitelist delete chat : Remove chat from whitelist",
"!ban user <user_id> : Kick user from chat and kicks it if joins chat again",
"!ban user <username> : Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id> : Unban user",
"!kick <user_id> : Kick user from chat group by id",
"!kick <username> : Kick user from chat group by username",
},
admin = {
"!superban user <user_id> : Kick user from all chat and kicks it if joins again",
"!superban user <username> : Kick user from all chat and kicks it if joins again",
"!superban delete <user_id> : Unban user",
},
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (.*)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (.*)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (.*)$",
"^!(ban) (delete) (.*)$",
"^!(superban) (user) (.*)$",
"^!(superban) (delete) (.*)$",
"^!(kick) (.*)$",
"^!(kickme)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
} | gpl-2.0 |
Vermeille/kong | spec/03-plugins/04-cors/01-access_spec.lua | 3 | 4538 | local helpers = require "spec.helpers"
local cjson = require "cjson"
describe("Plugin: cors (access)", function()
local client
setup(function()
assert(helpers.start_kong())
client = helpers.proxy_client()
local api1 = assert(helpers.dao.apis:insert {
request_host = "cors1.com",
upstream_url = "http://mockbin.com"
})
local api2 = assert(helpers.dao.apis:insert {
request_host = "cors2.com",
upstream_url = "http://mockbin.com"
})
local api3 = assert(helpers.dao.apis:insert {
request_host = "cors3.com",
upstream_url = "http://mockbin.com"
})
assert(helpers.dao.plugins:insert {
name = "cors",
api_id = api1.id
})
assert(helpers.dao.plugins:insert {
name = "cors",
api_id = api2.id,
config = {
origin = "example.com",
methods = {"GET"},
headers = {"origin", "type", "accepts"},
exposed_headers = {"x-auth-token"},
max_age = 23,
credentials = true
}
})
assert(helpers.dao.plugins:insert {
name = "cors",
api_id = api3.id,
config = {
origin = "example.com",
methods = {"GET"},
headers = {"origin", "type", "accepts"},
exposed_headers = {"x-auth-token"},
max_age = 23,
preflight_continue = true
}
})
end)
teardown(function()
if client then client:close() end
helpers.stop_kong()
end)
describe("HTTP method: OPTIONS", function()
it("gives appropriate defaults", function()
local res = assert(client:send {
method = "OPTIONS",
headers = {
["Host"] = "cors1.com"
}
})
assert.res_status(204, res)
assert.equal("GET,HEAD,PUT,PATCH,POST,DELETE", res.headers["Access-Control-Allow-Methods"])
assert.equal("*", res.headers["Access-Control-Allow-Origin"])
assert.is_nil(res.headers["Access-Control-Allow-Headers"])
assert.is_nil(res.headers["Access-Control-Expose-Headers"])
assert.is_nil(res.headers["Access-Control-Allow-Credentials"])
assert.is_nil(res.headers["Access-Control-Max-Age"])
end)
it("accepts config options", function()
local res = assert(client:send {
method = "OPTIONS",
headers = {
["Host"] = "cors2.com"
}
})
assert.res_status(204, res)
assert.equal("GET", res.headers["Access-Control-Allow-Methods"])
assert.equal("example.com", res.headers["Access-Control-Allow-Origin"])
assert.equal("23", res.headers["Access-Control-Max-Age"])
assert.equal("true", res.headers["Access-Control-Allow-Credentials"])
assert.equal("origin,type,accepts", res.headers["Access-Control-Allow-Headers"])
assert.is_nil(res.headers["Access-Control-Expose-Headers"])
end)
it("preflight_continue enabled", function()
local res = assert(client:send {
method = "OPTIONS",
path = "/status/201",
headers = {
["Host"] = "cors3.com"
}
})
local body = assert.res_status(201, res)
local json = cjson.decode(body)
assert.equal("201", json.code)
assert.equal("OK", json.message)
end)
end)
describe("HTTP method: others", function()
it("gives appropriate defaults", function()
local res = assert(client:send {
method = "GET",
headers = {
["Host"] = "cors1.com"
}
})
assert.res_status(200, res)
assert.equal("*", res.headers["Access-Control-Allow-Origin"])
assert.is_nil(res.headers["Access-Control-Allow-Methods"])
assert.is_nil(res.headers["Access-Control-Allow-Headers"])
assert.is_nil(res.headers["Access-Control-Expose-Headers"])
assert.is_nil(res.headers["Access-Control-Allow-Credentials"])
assert.is_nil(res.headers["Access-Control-Max-Age"])
end)
it("accepts config options", function()
local res = assert(client:send {
method = "GET",
headers = {
["Host"] = "cors2.com"
}
})
assert.res_status(200, res)
assert.equal("example.com", res.headers["Access-Control-Allow-Origin"])
assert.equal("x-auth-token", res.headers["Access-Control-Expose-Headers"])
assert.equal("true", res.headers["Access-Control-Allow-Credentials"])
assert.is_nil(res.headers["Access-Control-Allow-Methods"])
assert.is_nil(res.headers["Access-Control-Allow-Headers"])
assert.is_nil(res.headers["Access-Control-Max-Age"])
end)
end)
end)
| apache-2.0 |
xponen/Zero-K | LuaUI/Widgets/cmd_state_reverse_toggle.lua | 12 | 1055 | function widget:GetInfo()
return {
name = "State Reverse Toggle",
desc = "Makes multinary states reverse toggleable",
author = "Google Frog",
date = "Oct 2, 2009",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
local spGetSelectedUnits = Spring.GetSelectedUnits
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local CMD_FIRE_STATE = CMD.FIRE_STATE
local CMD_MOVE_STATE = CMD.MOVE_STATE
local multiStates = {
[CMD_FIRE_STATE] = 3,
[CMD_MOVE_STATE] = 3,
[CMD.AUTOREPAIRLEVEL] = 4,
}
function widget:CommandNotify(id, params, options)
if multiStates[id] then
if options.right then
local units = spGetSelectedUnits()
local state = params[1]
state = state - 2 -- engine sent us one step forward instead of one step back, so we go two steps back
if state < 0 then
state = multiStates[id] + state -- wrap
end
for i=1, #units do
spGiveOrderToUnit(units[i], id, { state }, {})
end
return true
end
end
end | gpl-2.0 |
Elanis/SciFi-Pack-Addon-Gamemode | lua/entities/sw_reta2actis/init.lua | 1 | 4420 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
function ENT:SpawnFunction( ply,tr )
local ent = ents.Create("sw_reta2actis") --SpaceShip entity
ent:SetPos( tr.HitPos + Vector(0,0,40))
ent:Spawn()
ent:Activate()
return ent
end
function ENT:Initialize()
self.MaxHealth = 1000
self.Pilot = nil
self.Piloting = false
self.WeaponsTable = {}
self.CanPrimary = true
self.CanSecondary = true
self.Entity:SetNetworkedInt("health",self.MaxHealth)
self.Entity:SetModel("models/obijf/obijf.mdl")
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
local phys = self.Entity:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
phys:SetMass(10000)
end
self.Entity:StartMotionController()
self.Speed=0
end
function ENT:Think()
if self.Piloting and self.Pilot and self.Pilot:IsValid() and IsValid(self.Pilot)then
if self.Pilot:KeyDown(IN_ATTACK) then
self:PrimaryFire()
elseif self.Pilot:KeyDown(IN_ATTACK2) then
self:SecondaryFire()
elseif self.Pilot:KeyDown(IN_USE) then
self.Piloting=false
self.Pilot:UnSpectate()
self.Pilot:DrawViewModel(true)
self.Pilot:DrawWorldModel(true)
self.Pilot:Spawn()
self.Entity:SetOwner(nil)
self.Pilot:SetNetworkedBool("Driving",false)
self.Pilot:SetPos(self.Entity:GetPos()+self.Entity:GetRight()*150)
self.Speed = 0 -- Stop the motor
self.Entity:SetLocalVelocity(Vector(0,0,0)) -- Stop the ship
for _,v in pairs(self.WeaponsTable) do
self.Pilot:Give(tostring(v));
end
table.Empty(self.WeaponsTable);
self.Pilot=nil
end
self.Entity:NextThink(CurTime())
else
self.Entity:NextThink(CurTime()+1)
end
return true
end
function ENT:OnTakeDamage(dmg)
local health = self.Entity:GetNetworkedInt("health")
local damage = dmg:GetDamage()
self.Entity:SetNetworkedInt("health",health-damage)
if(health<1) then
self.Entity:Remove()
end
end
function ENT:OnRemove()
local health = self.Entity:GetNetworkedInt("health")
if(health<1) then
local effect = EffectData()
effect:SetOrigin(self.Entity:GetPos())
util.Effect("Explosion", effect, true, true )
end
if(self.Piloting) then
self.Pilot:UnSpectate()
self.Pilot:DrawViewModel(true)
self.Pilot:DrawWorldModel(true)
self.Pilot:Spawn()
self.Pilot:SetNetworkedBool("Driving",false)
self.Pilot:SetPos(self.Entity:GetPos()+Vector(0,0,100))
end
end
function ENT:Use(ply,caller)
if not self.Piloting then
self.Piloting=true
ply:Spectate( OBS_MODE_CHASE )
ply:SpectateEntity(self.Entity)
ply:StripWeapons()
self.Entity:GetPhysicsObject():Wake()
self.Entity:GetPhysicsObject():EnableMotion(true)
self.Entity:SetOwner(ply)
ply:DrawViewModel(false)
ply:DrawWorldModel(false)
ply:SetNetworkedBool("Driving",true)
ply:SetNetworkedEntity("Ship",self.Entity)
self.Pilot=ply
end
end
function ENT:PhysicsSimulate( phys, deltatime )
if self.Piloting and IsValid(self.Pilot) then
local speedvalue=0
if self.Pilot:KeyDown(IN_FORWARD) then
speedvalue=500
elseif self.Pilot:KeyDown(IN_BACK) then
speedvalue=-500
elseif self.Pilot:KeyDown(IN_SPEED) then
speedvalue=1000
end
phys:Wake()
self.Speed = math.Approach(self.Speed,speedvalue,10)
local move = { }
move.secondstoarrive = 1
move.pos = self.Entity:GetPos()+self.Entity:GetForward()*self.Speed
if self.Pilot:KeyDown( IN_DUCK ) then
move.pos = move.pos+self.Entity:GetUp()*-200
elseif self.Pilot:KeyDown( IN_JUMP ) then
move.pos = move.pos+self.Entity:GetUp()*300
elseif self.Pilot:KeyDown( IN_MOVERIGHT ) then
move.pos = move.pos+self.Entity:GetRight()*200
elseif self.Pilot:KeyDown( IN_MOVELEFT ) then
move.pos = move.pos+self.Entity:GetRight()*-200
end
move.maxangular = 5000
move.maxangulardamp = 10000
move.maxspeed = 1000000
move.maxspeeddamp = 10000
move.dampfactor = 0.8
move.teleportdistance = 5000
local ang = self.Pilot:GetAimVector():Angle()
move.angle = ang
move.deltatime = deltatime
phys:ComputeShadowControl(move)
self.Pilot:SetPos(self.Entity:GetPos())
end
end
function ENT:PrimaryFire()
-- When we Push MOUSE_1
end
function ENT:SecondaryFire()
-- When we Push MOUSE_2
end | gpl-2.0 |
sandsmark/vlc-kio | share/lua/intf/dumpmeta.lua | 98 | 2125 | --[==========================================================================[
dumpmeta.lua: dump a file's meta data on stdout/stderr
--[==========================================================================[
Copyright (C) 2010 the VideoLAN team
$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.
--]==========================================================================]
--[[ to dump meta data information in the debug output, run:
vlc -I luaintf --lua-intf dumpmeta coolmusic.mp3
Additional options can improve performance and output readability:
-V dummy -A dummy --no-video-title --no-media-library -q
--]]
local item
repeat
item = vlc.input.item()
until (item and item:is_preparsed())
-- preparsing doesn't always provide all the information we want (like duration)
repeat
until item:stats()["demux_read_bytes"] > 0
vlc.msg.info("name: "..item:name())
vlc.msg.info("uri: "..vlc.strings.decode_uri(item:uri()))
vlc.msg.info("duration: "..tostring(item:duration()))
vlc.msg.info("meta data:")
local meta = item:metas()
if meta then
for key, value in pairs(meta) do
vlc.msg.info(" "..key..": "..value)
end
else
vlc.msg.info(" no meta data available")
end
vlc.msg.info("info:")
for cat, data in pairs(item:info()) do
vlc.msg.info(" "..cat)
for key, value in pairs(data) do
vlc.msg.info(" "..key..": "..value)
end
end
vlc.misc.quit()
| gpl-2.0 |
Schaka/gladdy | Libs/LibStub/LibStub.lua | 184 | 1367 | -- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info
-- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke
local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS!
local LibStub = _G[LIBSTUB_MAJOR]
if not LibStub or LibStub.minor < LIBSTUB_MINOR then
LibStub = LibStub or {libs = {}, minors = {} }
_G[LIBSTUB_MAJOR] = LibStub
LibStub.minor = LIBSTUB_MINOR
function LibStub:NewLibrary(major, minor)
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
minor = assert(tonumber(strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.")
local oldminor = self.minors[major]
if oldminor and oldminor >= minor then return nil end
self.minors[major], self.libs[major] = minor, self.libs[major] or {}
return self.libs[major], oldminor
end
function LibStub:GetLibrary(major, silent)
if not self.libs[major] and not silent then
error(("Cannot find a library instance of %q."):format(tostring(major)), 2)
end
return self.libs[major], self.minors[major]
end
function LibStub:IterateLibraries() return pairs(self.libs) end
setmetatable(LibStub, { __call = LibStub.GetLibrary })
end
| mit |
swichers/LootSounds | Libs/LibStub/LibStub.lua | 184 | 1367 | -- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info
-- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke
local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS!
local LibStub = _G[LIBSTUB_MAJOR]
if not LibStub or LibStub.minor < LIBSTUB_MINOR then
LibStub = LibStub or {libs = {}, minors = {} }
_G[LIBSTUB_MAJOR] = LibStub
LibStub.minor = LIBSTUB_MINOR
function LibStub:NewLibrary(major, minor)
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
minor = assert(tonumber(strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.")
local oldminor = self.minors[major]
if oldminor and oldminor >= minor then return nil end
self.minors[major], self.libs[major] = minor, self.libs[major] or {}
return self.libs[major], oldminor
end
function LibStub:GetLibrary(major, silent)
if not self.libs[major] and not silent then
error(("Cannot find a library instance of %q."):format(tostring(major)), 2)
end
return self.libs[major], self.minors[major]
end
function LibStub:IterateLibraries() return pairs(self.libs) end
setmetatable(LibStub, { __call = LibStub.GetLibrary })
end
| apache-2.0 |
4aiman/MineClone | mods/hardened_clay/init.lua | 2 | 1973 | local init = os.clock()
local clay = {}
clay.dyes = {
{"white", "White", "white"},
{"grey", "Grey", "dark_grey"},
{"silver", "Light Gray", "grey"},
{"black", "Black", "black"},
{"red", "Red", "red"},
{"yellow", "Yellow", "yellow"},
{"green", "Green", "dark_green"},
{"cyan", "Cyan", "cyan"},
{"blue", "Blue", "blue"},
{"magenta", "Magenta", "magenta"},
{"orange", "Orange", "orange"},
{"purple", "Purple", "violet"},
{"brown", "Brown", "dark_orange"},
{"pink", "Pink", "light_red"},
{"lime", "Lime", "green"},
{"light_blue", "Light Blue", "lightblue"},
}
minetest.register_node("hardened_clay:hardened_clay", {
description = "Hardened Clay",
tiles = {"hardened_clay.png"},
stack_max = 64,
groups = {cracky=3},
legacy_mineral = true,
})
minetest.register_craft({
type = "cooking",
output = "hardened_clay:hardened_clay",
recipe = "default:clay",
})
for _, row in ipairs(clay.dyes) do
local name = row[1]
local desc = row[2]
local craft_color_group = row[3]
-- Node Definition
minetest.register_node("hardened_clay:"..name, {
description = desc.." Hardened Clay",
tiles = {"hardened_clay_stained_"..name..".png"},
groups = {cracky=3,hardened_clay=1},
stack_max = 64,
sounds = default.node_sound_defaults(),
})
if craft_color_group then
minetest.register_craft({
output = 'hardened_clay:'..name..' 8',
recipe = {
{'hardened_clay:hardened_clay', 'hardened_clay:hardened_clay', 'hardened_clay:hardened_clay'},
{'hardened_clay:hardened_clay', 'dye:'..craft_color_group, 'hardened_clay:hardened_clay'},
{'hardened_clay:hardened_clay', 'hardened_clay:hardened_clay', 'hardened_clay:hardened_clay'},
},
})
end
end
local time_to_load= os.clock() - init
print(string.format("[MOD] "..minetest.get_current_modname().." loaded in %.4f s", time_to_load))
| lgpl-2.1 |
xponen/Zero-K | LuaUI/Widgets/chili/Controls/textbox.lua | 12 | 2553 | TextBox = Control:Inherit{
classname = "textbox",
padding = {0,0,0,0},
text = "line1\nline2",
autoHeight = true, --// sets height to text size, useful for embedding in scrollboxes
autoObeyLineHeight = true, --// (needs autoHeight) if true, autoHeight will obey the lineHeight (-> texts with the same line count will have the same height)
fontsize = 12,
_lines = {},
}
local this = TextBox
local inherited = this.inherited
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function TextBox:SetText(t)
self.text = t
self:RequestRealign()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function Split(s, separator)
local results = {}
for part in s:gmatch("[^"..separator.."]+") do
results[#results + 1] = part
end
return results
end
-- remove first n elemets from t, return them
local function Take(t, n)
local removed = {}
for i=1, n do
removed[#removed+1] = table.remove(t, 1)
end
return removed
end
-- appends t1 to t2 in-place
local function Append(t1, t2)
local l = #t1
for i = 1, #t2 do
t1[i + l] = t2[i]
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function TextBox:UpdateLayout()
local font = self.font
local padding = self.padding
local width = self.width - padding[1] - padding[3]
local height = self.height - padding[2] - padding[4]
if self.autoHeight then
height = 1e9
end
self._wrappedText = font:WrapText(self.text, width, height)
if self.autoHeight then
local textHeight,textDescender,numLines = font:GetTextHeight(self._wrappedText)
textHeight = textHeight-textDescender
if (self.autoObeyLineHeight) then
if (numLines>1) then
textHeight = numLines * font:GetLineHeight()
else
--// AscenderHeight = LineHeight w/o such deep chars as 'g','p',...
textHeight = math.min( math.max(textHeight, font:GetAscenderHeight()), font:GetLineHeight())
end
end
self:Resize(nil, textHeight, true, true)
end
end
function TextBox:DrawControl()
local paddx, paddy = unpack4(self.clientArea)
local x = math.ceil(self.x + paddx)
local y = math.ceil(self.y + paddy)
local font = self.font
font:Draw(self._wrappedText, x, y)
end
| gpl-2.0 |
xuejian1354/barrier_breaker | feeds/luci/applications/luci-ahcp/luasrc/model/cbi/ahcp.lua | 36 | 3895 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: init.lua 5764 2010-03-08 19:05:34Z jow $
]]--
m = Map("ahcpd", translate("AHCP Server"), translate("AHCP is an autoconfiguration protocol " ..
"for IPv6 and dual-stack IPv6/IPv4 networks designed to be used in place of router " ..
"discovery or DHCP on networks where it is difficult or impossible to configure a " ..
"server within every link-layer broadcast domain, for example mobile ad-hoc networks."))
m:section(SimpleSection).template = "ahcp_status"
s = m:section(TypedSection, "ahcpd")
s:tab("general", translate("General Setup"))
s:tab("advanced", translate("Advanced Settings"))
s.addremove = false
s.anonymous = true
mode = s:taboption("general", ListValue, "mode", translate("Operation mode"))
mode:value("server", translate("Server"))
mode:value("forwarder", translate("Forwarder"))
net = s:taboption("general", Value, "interface", translate("Served interfaces"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.nocreate = true
function net.cfgvalue(self, section)
return m.uci:get("ahcpd", section, "interface")
end
pfx = s:taboption("general", DynamicList, "prefix", translate("Announced prefixes"),
translate("Specifies the announced IPv4 and IPv6 network prefixes in CIDR notation"))
pfx.optional = true
pfx.datatype = "ipaddr"
pfx:depends("mode", "server")
nss = s:taboption("general", DynamicList, "name_server", translate("Announced DNS servers"),
translate("Specifies the announced IPv4 and IPv6 name servers"))
nss.optional = true
nss.datatype = "ipaddr"
nss:depends("mode", "server")
ntp = s:taboption("general", DynamicList, "ntp_server", translate("Announced NTP servers"),
translate("Specifies the announced IPv4 and IPv6 NTP servers"))
ntp.optional = true
ntp.datatype = "ipaddr"
ntp:depends("mode", "server")
mca = s:taboption("general", Value, "multicast_address", translate("Multicast address"))
mca.optional = true
mca.placeholder = "ff02::cca6:c0f9:e182:5359"
mca.datatype = "ip6addr"
port = s:taboption("general", Value, "port", translate("Port"))
port.optional = true
port.placeholder = 5359
port.datatype = "port"
fam = s:taboption("general", ListValue, "_family", translate("Protocol family"))
fam:value("", translate("IPv4 and IPv6"))
fam:value("ipv4", translate("IPv4 only"))
fam:value("ipv6", translate("IPv6 only"))
function fam.cfgvalue(self, section)
local v4 = m.uci:get_bool("ahcpd", section, "ipv4_only")
local v6 = m.uci:get_bool("ahcpd", section, "ipv6_only")
if v4 then
return "ipv4"
elseif v6 then
return "ipv6"
end
return ""
end
function fam.write(self, section, value)
if value == "ipv4" then
m.uci:set("ahcpd", section, "ipv4_only", "true")
m.uci:delete("ahcpd", section, "ipv6_only")
elseif value == "ipv6" then
m.uci:set("ahcpd", section, "ipv6_only", "true")
m.uci:delete("ahcpd", section, "ipv4_only")
end
end
function fam.remove(self, section)
m.uci:delete("ahcpd", section, "ipv4_only")
m.uci:delete("ahcpd", section, "ipv6_only")
end
ltime = s:taboption("general", Value, "lease_time", translate("Lease validity time"))
ltime.optional = true
ltime.placeholder = 3666
ltime.datatype = "uinteger"
ld = s:taboption("advanced", Value, "lease_dir", translate("Lease directory"))
ld.datatype = "directory"
ld.placeholder = "/var/lib/leases"
id = s:taboption("advanced", Value, "id_file", translate("Unique ID file"))
--id.datatype = "file"
id.placeholder = "/var/lib/ahcpd-unique-id"
log = s:taboption("advanced", Value, "log_file", translate("Log file"))
--log.datatype = "file"
log.placeholder = "/var/log/ahcpd.log"
return m
| gpl-2.0 |
xponen/Zero-K | units/chickenlandqueen.lua | 1 | 14833 | unitDef = {
unitname = [[chickenlandqueen]],
name = [[Chicken Queen]],
description = [[Clucking Hell!]],
acceleration = 1,
autoHeal = 0,
brakeRate = 1,
buildCostEnergy = 0,
buildCostMetal = 0,
builder = false,
buildPic = [[chickenflyerqueen.png]],
buildTime = 40000,
canAttack = true,
canGuard = true,
canMove = true,
canPatrol = true,
canstop = [[1]],
canSubmerge = false,
cantBeTransported = true,
category = [[LAND]],
collisionSphereScale = 1,
collisionVolumeOffsets = [[0 0 15]],
collisionVolumeScales = [[46 110 120]],
collisionVolumeTest = 1,
collisionVolumeType = [[box]],
customParams = {
description_fr = [[Le mal incarn?!]],
description_de = [[Lachende Höllenbrut!]],
description_pl = [[Krolowa Kurnika]],
helptext = [[Two words: RUN AWAY! The Chicken Queen is the matriach of the Thunderbird colony, and when aggravated is virtually impossible to stop. It can spit fiery napalm, spray spores to kill aircraft, and kick land units away from it. Most of all, its jaws can rip apart the largest assault mech in seconds. Only the most determined, focused assault can hope to stop this beast in her tracks.]],
helptext_fr = [[Deux mots : FUIS MALHEUREUX ! La reine poulet est la matriarche de la colonie et une fois sa col?re attis?e elle est presque indestructible. Elle crache un acide extr?mement corrosif, largue des poulets et envoie des spores aux unit?s volantes. Seulement les assauts les plus brutaux et coordonn?s peuvent esp?rer venir ? bout de cette monstruosit?.]],
helptext_de = [[Zwei Worte: LAUF WEG! Die Chicken Queen ist die Matriarchin der Thunderbirdkolonie und sobald verärgert ist es eigentlich unmöglich sie noch zu stoppen. Sie kann kraftvolle Säure spucken, Landchicken abwerfen und Sporen gegen Lufteinheiten versprühen. Nur der entschlossenste und konzentrierteste Angriff kann es ermöglichen dieses Biest eventuell doch noch zu stoppen.]],
helptext_pl = [[Dwa slowa: W NOGI! Krolowa kolonii kurczakow moze zostac powstrzymana tylko dzieki pelnej determinacji i przy udziale wielkiej sily ognia; pluje plonacym kwasem, wystrzeliwuje mase zarodnikow, rozdeptuje mniejsze jednostki i jest w stanie rozszarpac nawet ciezkie roboty szturmowe.]],
},
explodeAs = [[SMALL_UNITEX]],
footprintX = 8,
footprintZ = 8,
iconType = [[chickenq]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
mass = 4378,
maxDamage = 200000,
maxVelocity = 2.5,
minCloakDistance = 250,
movementClass = [[AKBOT6]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP STUPIDTARGET MINE]],
objectName = [[chickenflyerqueen.s3o]],
power = 65536,
script = [[chickenlandqueen.lua]],
seismicSignature = 4,
selfDestructAs = [[SMALL_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:blood_spray]],
[[custom:blood_explode]],
[[custom:dirt]],
},
},
side = [[THUNDERBIRDS]],
sightDistance = 2048,
smoothAnim = true,
sonarDistance = 450,
trackOffset = 18,
trackStrength = 8,
trackStretch = 1,
trackType = [[ChickenTrack]],
trackWidth = 100,
turnRate = 399,
upright = true,
workerTime = 0,
weapons = {
{
def = [[MELEE]],
mainDir = [[0 0 1]],
maxAngleDif = 150,
onlyTargetCategory = [[SWIM LAND SUB SINK TURRET FLOAT SHIP HOVER]],
},
{
def = [[FIREGOO]],
mainDir = [[0 0 1]],
maxAngleDif = 150,
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
{
def = [[SPORES]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[SPORES]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[SPORES]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[QUEENCRUSH]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
{
def = [[DODOBOMB]],
onlyTargetCategory = [[NONE]],
},
{
def = [[BASILISKBOMB]],
onlyTargetCategory = [[NONE]],
},
{
def = [[TIAMATBOMB]],
onlyTargetCategory = [[NONE]],
},
},
weaponDefs = {
BASILISKBOMB = {
name = [[Basilisk Bomb]],
accuracy = 60000,
areaOfEffect = 48,
avoidFeature = false,
avoidFriendly = false,
burnblow = true,
collideFriendly = false,
craterBoost = 1,
craterMult = 2,
damage = {
default = 180,
},
explosionGenerator = [[custom:none]],
fireStarter = 70,
flightTime = 0,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
manualBombSettings = true,
model = [[chickenc.s3o]],
range = 500,
reloadtime = 10,
renderType = 1,
smokedelay = [[0.1]],
smokeTrail = false,
startsmoke = [[1]],
startVelocity = 200,
targetMoveError = 0.2,
tolerance = 8000,
tracks = false,
turnRate = 4000,
turret = true,
waterweapon = true,
weaponAcceleration = 200,
weaponTimer = 0.1,
weaponType = [[AircraftBomb]],
weaponVelocity = 200,
},
DODOBOMB = {
name = [[Dodo Bomb]],
accuracy = 60000,
areaOfEffect = 1,
avoidFeature = false,
avoidFriendly = false,
burnblow = true,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
damage = {
default = 1,
},
explosionGenerator = [[custom:none]],
fireStarter = 70,
flightTime = 0,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
manualBombSettings = true,
model = [[chicken_dodobomb.s3o]],
range = 500,
reloadtime = 10,
renderType = 1,
smokedelay = [[0.1]],
smokeTrail = false,
startsmoke = [[1]],
startVelocity = 200,
targetMoveError = 0.2,
tolerance = 8000,
tracks = false,
turnRate = 4000,
turret = true,
waterweapon = true,
weaponAcceleration = 200,
weaponTimer = 0.1,
weaponType = [[AircraftBomb]],
weaponVelocity = 200,
},
TIAMATBOMB = {
name = [[Tiamat Bomb]],
accuracy = 60000,
areaOfEffect = 72,
avoidFeature = false,
avoidFriendly = false,
burnblow = true,
collideFriendly = false,
craterBoost = 1,
craterMult = 2,
damage = {
default = 350,
},
explosionGenerator = [[custom:none]],
fireStarter = 70,
flightTime = 0,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
manualBombSettings = true,
model = [[chickenbroodqueen.s3o]],
noSelfDamage = true,
range = 500,
reloadtime = 10,
renderType = 1,
smokedelay = [[0.1]],
smokeTrail = false,
startsmoke = [[1]],
startVelocity = 200,
targetMoveError = 0.2,
tolerance = 8000,
tracks = false,
turnRate = 4000,
turret = true,
waterweapon = true,
weaponAcceleration = 200,
weaponTimer = 0.1,
weaponType = [[AircraftBomb]],
weaponVelocity = 200,
},
FIREGOO = {
name = [[Napalm Goo]],
areaOfEffect = 256,
burst = 8,
burstrate = 0.01,
cegTag = [[queen_trail_fire]],
craterBoost = 0,
craterMult = 0,
damage = {
default = 400,
planes = 400,
subs = 2,
},
endsmoke = [[0]],
explosionGenerator = [[custom:napalm_koda]],
firestarter = 400,
impulseBoost = 0,
impulseFactor = 0.4,
intensity = 0.7,
interceptedByShieldType = 1,
lineOfSight = true,
noSelfDamage = true,
proximityPriority = -4,
range = 1200,
reloadtime = 6,
renderType = 4,
rgbColor = [[0.8 0.4 0]],
size = 8,
sizeDecay = 0,
soundHit = [[weapon/burn_mixed]],
soundStart = [[chickens/bigchickenroar]],
sprayAngle = 6100,
startsmoke = [[0]],
tolerance = 5000,
turret = true,
weaponTimer = 0.2,
weaponType = [[Cannon]],
weaponVelocity = 600,
},
MELEE = {
name = [[Chicken Claws]],
areaOfEffect = 32,
craterBoost = 1,
craterMult = 0,
damage = {
default = 1000,
planes = 1000,
subs = 1000,
},
endsmoke = [[0]],
explosionGenerator = [[custom:NONE]],
impulseBoost = 0,
impulseFactor = 1,
interceptedByShieldType = 0,
lineOfSight = true,
noSelfDamage = true,
range = 200,
reloadtime = 1,
size = 0,
soundStart = [[chickens/bigchickenbreath]],
startsmoke = [[0]],
targetborder = 1,
tolerance = 5000,
turret = true,
waterWeapon = true,
weaponType = [[Cannon]],
weaponVelocity = 600,
},
QUEENCRUSH = {
name = [[Chicken Kick]],
areaOfEffect = 400,
collideFriendly = false,
craterBoost = 0.001,
craterMult = 0.002,
customParams = {
lups_noshockwave = "1",
},
damage = {
default = 10,
chicken = 0.001,
planes = 10,
subs = 5,
},
edgeEffectiveness = 1,
explosionGenerator = [[custom:NONE]],
impulseBoost = 500,
impulseFactor = 1,
intensity = 1,
interceptedByShieldType = 1,
lineOfSight = false,
noSelfDamage = true,
range = 512,
reloadtime = 1,
renderType = 4,
rgbColor = [[1 1 1]],
thickness = 1,
tolerance = 100,
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 0.8,
},
SPORES = {
name = [[Spores]],
areaOfEffect = 24,
avoidFriendly = false,
burst = 8,
burstrate = 0.1,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
damage = {
default = 75,
planes = [[150]],
subs = 7.5,
},
dance = 60,
explosionGenerator = [[custom:NONE]],
fireStarter = 0,
flightTime = 5,
groundbounce = 1,
guidance = true,
heightmod = 0.5,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 2,
lineOfSight = true,
metalpershot = 0,
model = [[chickeneggpink.s3o]],
noSelfDamage = true,
range = 600,
reloadtime = 4,
renderType = 1,
selfprop = true,
smokedelay = [[0.1]],
smokeTrail = true,
startsmoke = [[1]],
startVelocity = 100,
texture1 = [[]],
texture2 = [[sporetrail]],
tolerance = 10000,
tracks = true,
turnRate = 24000,
turret = true,
waterweapon = true,
weaponAcceleration = 100,
weaponType = [[MissileLauncher]],
weaponVelocity = 500,
wobble = 32000,
},
},
}
return lowerkeys({ chickenlandqueen = unitDef })
| gpl-2.0 |
Elanis/SciFi-Pack-Addon-Gamemode | gamemodes/scifipack/entities/weapons/gmod_tool/init.lua | 5 | 1948 | AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
AddCSLuaFile( "ghostentity.lua" )
AddCSLuaFile( "object.lua" )
AddCSLuaFile( "stool.lua" )
AddCSLuaFile( "cl_viewscreen.lua" )
AddCSLuaFile( "stool_cl.lua" )
include('shared.lua')
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
--[[---------------------------------------------------------
Desc: Convenience function to check object limits
-----------------------------------------------------------]]
function SWEP:CheckLimit( str )
local ply = self.Weapon:GetOwner()
return ply:CheckLimit( str )
end
--[[---------------------------------------------------------
Name: ShouldDropOnDie
Desc: Should this weapon be dropped when its owner dies?
-----------------------------------------------------------]]
function SWEP:ShouldDropOnDie()
return false
end
--[[---------------------------------------------------------
Name: CC_GMOD_Tool
Desc: Console Command to switch weapon/toolmode
-----------------------------------------------------------]]
function CC_GMOD_Tool( player, command, arguments )
if ( arguments[1] == nil ) then return end
if ( GetConVarNumber( "toolmode_allow_"..arguments[1] ) != 1 ) then return end
player:ConCommand( "gmod_toolmode "..arguments[1] )
local activeWep = player:GetActiveWeapon()
local isTool = (activeWep && activeWep:IsValid() && activeWep:GetClass() == "gmod_tool")
-- Switch weapons
player:SelectWeapon( "gmod_tool")
-- Get the weapon and send a fake deploy command
local wep = player:GetWeapon("gmod_tool")
if (wep:IsValid()) then
-- Hmmmmm???
if ( !isTool ) then
wep.wheelModel = nil
end
-- Holster the old 'tool'
if ( wep.Holster ) then
wep:Holster()
end
wep.Mode = arguments[1]
-- Deplot the new
if ( wep.Deploy ) then
wep:Deploy()
end
end
end
concommand.Add( "gmod_tool", CC_GMOD_Tool, nil, nil, { FCVAR_SERVER_CAN_EXECUTE } )
| gpl-2.0 |
swichers/LootSounds | Libs/AceEvent-3.0/AceEvent-3.0.lua | 50 | 4772 | --- AceEvent-3.0 provides event registration and secure dispatching.
-- All dispatching is done using **CallbackHandler-1.0**. AceEvent is a simple wrapper around
-- CallbackHandler, and dispatches all game events or addon message to the registrees.
--
-- **AceEvent-3.0** can be embeded into your addon, either explicitly by calling AceEvent:Embed(MyAddon) or by
-- specifying it as an embeded library in your AceAddon. All functions will be available on your addon object
-- and can be accessed directly, without having to explicitly call AceEvent itself.\\
-- It is recommended to embed AceEvent, otherwise you'll have to specify a custom `self` on all calls you
-- make into AceEvent.
-- @class file
-- @name AceEvent-3.0
-- @release $Id: AceEvent-3.0.lua 975 2010-10-23 11:26:18Z nevcairiel $
local MAJOR, MINOR = "AceEvent-3.0", 3
local AceEvent = LibStub:NewLibrary(MAJOR, MINOR)
if not AceEvent then return end
-- Lua APIs
local pairs = pairs
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
AceEvent.frame = AceEvent.frame or CreateFrame("Frame", "AceEvent30Frame") -- our event frame
AceEvent.embeds = AceEvent.embeds or {} -- what objects embed this lib
-- APIs and registry for blizzard events, using CallbackHandler lib
if not AceEvent.events then
AceEvent.events = CallbackHandler:New(AceEvent,
"RegisterEvent", "UnregisterEvent", "UnregisterAllEvents")
end
function AceEvent.events:OnUsed(target, eventname)
AceEvent.frame:RegisterEvent(eventname)
end
function AceEvent.events:OnUnused(target, eventname)
AceEvent.frame:UnregisterEvent(eventname)
end
-- APIs and registry for IPC messages, using CallbackHandler lib
if not AceEvent.messages then
AceEvent.messages = CallbackHandler:New(AceEvent,
"RegisterMessage", "UnregisterMessage", "UnregisterAllMessages"
)
AceEvent.SendMessage = AceEvent.messages.Fire
end
--- embedding and embed handling
local mixins = {
"RegisterEvent", "UnregisterEvent",
"RegisterMessage", "UnregisterMessage",
"SendMessage",
"UnregisterAllEvents", "UnregisterAllMessages",
}
--- Register for a Blizzard Event.
-- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied)
-- Any arguments to the event will be passed on after that.
-- @name AceEvent:RegisterEvent
-- @class function
-- @paramsig event[, callback [, arg]]
-- @param event The event to register for
-- @param callback The callback function to call when the event is triggered (funcref or method, defaults to a method with the event name)
-- @param arg An optional argument to pass to the callback function
--- Unregister an event.
-- @name AceEvent:UnregisterEvent
-- @class function
-- @paramsig event
-- @param event The event to unregister
--- Register for a custom AceEvent-internal message.
-- The callback will be called with the optional `arg` as the first argument (if supplied), and the event name as the second (or first, if no arg was supplied)
-- Any arguments to the event will be passed on after that.
-- @name AceEvent:RegisterMessage
-- @class function
-- @paramsig message[, callback [, arg]]
-- @param message The message to register for
-- @param callback The callback function to call when the message is triggered (funcref or method, defaults to a method with the event name)
-- @param arg An optional argument to pass to the callback function
--- Unregister a message
-- @name AceEvent:UnregisterMessage
-- @class function
-- @paramsig message
-- @param message The message to unregister
--- Send a message over the AceEvent-3.0 internal message system to other addons registered for this message.
-- @name AceEvent:SendMessage
-- @class function
-- @paramsig message, ...
-- @param message The message to send
-- @param ... Any arguments to the message
-- Embeds AceEvent into the target object making the functions from the mixins list available on target:..
-- @param target target object to embed AceEvent in
function AceEvent:Embed(target)
for k, v in pairs(mixins) do
target[v] = self[v]
end
self.embeds[target] = true
return target
end
-- AceEvent:OnEmbedDisable( target )
-- target (object) - target object that is being disabled
--
-- Unregister all events messages etc when the target disables.
-- this method should be called by the target manually or by an addon framework
function AceEvent:OnEmbedDisable(target)
target:UnregisterAllEvents()
target:UnregisterAllMessages()
end
-- Script to fire blizzard events into the event listeners
local events = AceEvent.events
AceEvent.frame:SetScript("OnEvent", function(this, event, ...)
events:Fire(event, ...)
end)
--- Finally: upgrade our old embeds
for target, v in pairs(AceEvent.embeds) do
AceEvent:Embed(target)
end
| apache-2.0 |
alastair-robertson/awesome | lib/awful/rules.lua | 2 | 15523 | ---------------------------------------------------------------------------
--- Apply rules to clients at startup.
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @release @AWESOME_VERSION@
-- @module awful.rules
---------------------------------------------------------------------------
-- Grab environment we need
local client = client
local awesome = awesome
local screen = screen
local table = table
local type = type
local ipairs = ipairs
local pairs = pairs
local atag = require("awful.tag")
local util = require("awful.util")
local a_place = require("awful.placement")
local protected_call = require("gears.protected_call")
local rules = {}
--[[--
This is the global rules table.
You should fill this table with your rule and properties to apply.
For example, if you want to set xterm maximized at startup, you can add:
{ rule = { class = "xterm" },
properties = { maximized_vertical = true, maximized_horizontal = true } }
If you want to set mplayer floating at startup, you can add:
{ rule = { name = "MPlayer" },
properties = { floating = true } }
If you want to put Firefox on a specific tag at startup, you can add:
{ rule = { instance = "firefox" },
properties = { tag = mytagobject } }
Alternatively, you can specify the tag by name:
{ rule = { instance = "firefox" },
properties = { tag = "3" } }
If you want to put Thunderbird on a specific screen at startup, use:
{ rule = { instance = "Thunderbird" },
properties = { screen = 1 } }
Assuming that your X11 server supports the RandR extension, you can also specify
the screen by name:
{ rule = { instance = "Thunderbird" },
properties = { screen = "VGA1" } }
If you want to put Emacs on a specific tag at startup, and immediately switch
to that tag you can add:
{ rule = { class = "Emacs" },
properties = { tag = mytagobject, switchtotag = true } }
If you want to apply a custom callback to execute when a rule matched,
for example to pause playing music from mpd when you start dosbox, you
can add:
{ rule = { class = "dosbox" },
callback = function(c)
awful.spawn('mpc pause')
end }
Note that all "rule" entries need to match. If any of the entry does not
match, the rule won't be applied.
If a client matches multiple rules, they are applied in the order they are
put in this global rules table. If the value of a rule is a string, then the
match function is used to determine if the client matches the rule.
If the value of a property is a function, that function gets called and
function's return value is used for the property.
To match multiple clients to a rule one need to use slightly different
syntax:
{ rule_any = { class = { "MPlayer", "Nitrogen" }, instance = { "xterm" } },
properties = { floating = true } }
To match multiple clients with an exception one can couple `rules.except` or
`rules.except_any` with the rules:
{ rule = { class = "Firefox" },
except = { instance = "Navigator" },
properties = {floating = true},
},
{ rule_any = { class = { "Pidgin", "Xchat" } },
except_any = { role = { "conversation" } },
properties = { tag = "1" }
}
{ rule = {},
except_any = { class = { "Firefox", "Vim" } },
properties = { floating = true }
}
]]--
rules.rules = {}
--- Check if a client matches a rule.
-- @client c The client.
-- @tab rule The rule to check.
-- @treturn bool True if it matches, false otherwise.
function rules.match(c, rule)
if not rule then return false end
for field, value in pairs(rule) do
if c[field] then
if type(c[field]) == "string" then
if not c[field]:match(value) and c[field] ~= value then
return false
end
elseif c[field] ~= value then
return false
end
else
return false
end
end
return true
end
--- Check if a client matches any part of a rule.
-- @client c The client.
-- @tab rule The rule to check.
-- @treturn bool True if at least one rule is matched, false otherwise.
function rules.match_any(c, rule)
if not rule then return false end
for field, values in pairs(rule) do
if c[field] then
for _, value in ipairs(values) do
if c[field] == value then
return true
elseif type(c[field]) == "string" and c[field]:match(value) then
return true
end
end
end
end
return false
end
--- Does a given rule entry match a client?
-- @client c The client.
-- @tab entry Rule entry (with keys `rule`, `rule_any`, `except` and/or
-- `except_any`).
-- @treturn bool
function rules.matches(c, entry)
return (rules.match(c, entry.rule) or rules.match_any(c, entry.rule_any)) and
(not rules.match(c, entry.except) and not rules.match_any(c, entry.except_any))
end
--- Get list of matching rules for a client.
-- @client c The client.
-- @tab _rules The rules to check. List with "rule", "rule_any", "except" and
-- "except_any" keys.
-- @treturn table The list of matched rules.
function rules.matching_rules(c, _rules)
local result = {}
for _, entry in ipairs(_rules) do
if (rules.matches(c, entry)) then
table.insert(result, entry)
end
end
return result
end
--- Check if a client matches a given set of rules.
-- @client c The client.
-- @tab _rules The rules to check. List of tables with `rule`, `rule_any`,
-- `except` and `except_any` keys.
-- @treturn bool True if at least one rule is matched, false otherwise.
function rules.matches_list(c, _rules)
for _, entry in ipairs(_rules) do
if (rules.matches(c, entry)) then
return true
end
end
return false
end
--- Apply awful.rules.rules to a client.
-- @client c The client.
function rules.apply(c)
local props = {}
local callbacks = {}
for _, entry in ipairs(rules.matching_rules(c, rules.rules)) do
if entry.properties then
for property, value in pairs(entry.properties) do
props[property] = value
end
end
if entry.callback then
table.insert(callbacks, entry.callback)
end
end
rules.execute(c, props, callbacks)
end
local function add_to_tag(c, t)
if not t then return end
local tags = c:tags()
table.insert(tags, t)
c:tags(tags)
end
--- Extra rules properties.
--
-- These properties are used in the rules only and are not sent to the client
-- afterward.
--
-- To add a new properties, just do:
--
-- function awful.rules.extra_properties.my_new_property(c, value, props)
-- -- do something
-- end
--
-- By default, the table has the following functions:
--
-- * geometry
-- * switchtotag
--
-- @tfield table awful.rules.extra_properties
rules.extra_properties = {}
--- Extra high priority properties.
--
-- Some properties, such as anything related to tags, geometry or focus, will
-- cause a race condition if set in the main property section. This is why
-- they have a section for them.
--
-- To add a new properties, just do:
--
-- function awful.rules.high_priority_properties.my_new_property(c, value, props)
-- -- do something
-- end
--
-- By default, the table has the following functions:
--
-- * tag
-- * new_tag
--
-- @tfield table awful.rules.high_priority_properties
rules.high_priority_properties = {}
rules.delayed_properties = {}
local force_ignore = {
titlebars_enabled=true, focus=true, screen=true, x=true,
y=true, width=true, height=true, geometry=true,placement=true,
border_width=true,floating=true,size_hints_honor=true
}
function rules.high_priority_properties.tag(c, value)
if value then
if type(value) == "string" then
value = atag.find_by_name(c.screen, value)
end
c:tags{ value }
end
end
function rules.delayed_properties.switchtotag(c, value)
if not value then return end
local selected_tags = {}
for _,v in ipairs(c.screen.selected_tags) do
selected_tags[v] = true
end
local tags = c:tags()
for _, t in ipairs(tags) do
t.selected = true
selected_tags[t] = nil
end
for t in pairs(selected_tags) do
t.selected = false
end
end
function rules.extra_properties.geometry(c, _, props)
local cur_geo = c:geometry()
local new_geo = type(props.geometry) == "function"
and props.geometry(c, props) or props.geometry or {}
for _, v in ipairs {"x", "y", "width", "height"} do
new_geo[v] = type(props[v]) == "function" and props[v](c, props)
or props[v] or new_geo[v] or cur_geo[v]
end
c:geometry(new_geo) --TODO use request::geometry
end
--- Create a new tag based on a rule.
-- @tparam client c The client
-- @tparam boolean|function|string value The value.
-- @treturn tag The new tag
function rules.high_priority_properties.new_tag(c, value)
local ty = type(value)
local t = nil
if ty == "boolean" then
-- Create a new tag named after the client class
t = atag.add(c.class or "N/A", {screen=c.screen, volatile=true})
elseif ty == "string" then
-- Create a tag named after "value"
t = atag.add(value, {screen=c.screen, volatile=true})
elseif ty == "table" then
-- Assume a table of tags properties
t = atag.add(value.name or c.class or "N/A", value)
else
assert(false)
end
add_to_tag(c, t)
return t
end
function rules.extra_properties.placement(c, value)
-- Avoid problems
if awesome.startup and
(c.size_hints.user_position or c.size_hints.program_position) then
return
end
local ty = type(value)
local args = {
honor_workarea = true,
honor_padding = true
}
if ty == "function" or (ty == "table" and
getmetatable(value) and getmetatable(value).__call
) then
value(c, args)
elseif ty == "string" and a_place[value] then
a_place[value](c, args)
end
end
function rules.extra_properties.tags(c, value)
local current = c:tags()
c:tags(util.table.merge(current, value))
end
--- Apply properties and callbacks to a client.
-- @client c The client.
-- @tab props Properties to apply.
-- @tab[opt] callbacks Callbacks to apply.
function rules.execute(c, props, callbacks)
-- This has to be done first, as it will impact geometry related props.
if props.titlebars_enabled then
c:emit_signal("request::titlebars", "rules", {properties=props})
end
-- Border width will also cause geometry related properties to fail
if props.border_width then
c.border_width = type(props.border_width) == "function" and
props.border_width(c, props) or props.border_width
end
-- Size hints will be re-applied when setting width/height unless it is
-- disabled first
if props.size_hints_honor ~= nil then
c.size_hints_honor = type(props.size_hints_honor) == "function" and props.size_hints_honor(c,props)
or props.size_hints_honor
end
-- Geometry will only work if floating is true, otherwise the "saved"
-- geometry will be restored.
if props.floating ~= nil then
c.floating = type(props.floating) == "function" and props.floating(c,props)
or props.floating
end
-- Before requesting a tag, make sure the screen is right
if props.screen then
c.screen = type(props.screen) == "function" and screen[props.screen(c,props)]
or screen[props.screen]
end
-- Some properties need to be handled first. For example, many properties
-- depend that the client is tagged, this isn't yet the case.
for prop, handler in pairs(rules.high_priority_properties) do
local value = props[prop]
if value ~= nil then
if type(value) == "function" then
value = value(c, props)
end
handler(c, value)
end
end
-- By default, rc.lua use no_overlap+no_offscreen placement. This has to
-- be executed before x/y/width/height/geometry as it would otherwise
-- always override the user specified position with the default rule.
if props.placement then
-- It may be a function, so this one doesn't execute it like others
rules.extra_properties.placement(c, props.placement, props)
end
-- Make sure the tag is selected before the main rules are called.
-- Otherwise properties like "urgent" or "focus" may fail because they
-- will be overiden by various callbacks.
-- Previously, this was done in a second client.manage callback, but caused
-- a race condition where the order the require() would change the output.
c:emit_signal("request::tag", nil, {reason="rules"})
-- By default, rc.lua use no_overlap+no_offscreen placement. This has to
-- be executed before x/y/width/height/geometry as it would otherwise
-- always override the user specified position with the default rule.
if props.placement then
-- It may be a function, so this one doesn't execute it like others
rules.extra_properties.placement(c, props.placement, props)
end
-- Now that the tags and screen are set, handle the geometry
if props.height or props.width or props.x or props.y or props.geometry then
rules.extra_properties.geometry(c, nil, props)
end
-- As most race conditions should now have been avoided, apply the remaining
-- properties.
for property, value in pairs(props) do
if property ~= "focus" and type(value) == "function" then
value = value(c, props)
end
local ignore = rules.high_priority_properties[property] or
rules.delayed_properties[property] or force_ignore[property]
if not ignore then
if rules.extra_properties[property] then
rules.extra_properties[property](c, value)
elseif type(c[property]) == "function" then
c[property](c, value)
else
c[property] = value
end
end
end
-- Apply all callbacks.
if callbacks then
for _, callback in pairs(callbacks) do
protected_call(callback, c)
end
end
-- Apply the delayed properties
for prop, handler in pairs(rules.delayed_properties) do
if not force_ignore[prop] then
local value = props[prop]
if value ~= nil then
if type(value) == "function" then
value = value(c, props)
end
handler(c, value, props)
end
end
end
-- Do this at last so we do not erase things done by the focus signal.
if props.focus and (type(props.focus) ~= "function" or props.focus(c)) then
c:emit_signal('request::activate', "rules", {raise=true})
end
end
function rules.completed_with_payload_callback(c, props)
rules.execute(c, props, type(props.callback) == "function" and
{props.callback} or props.callback )
end
client.connect_signal("spawn::completed_with_payload", rules.completed_with_payload_callback)
client.connect_signal("manage", rules.apply)
return rules
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
alexandergall/snabbswitch | src/lib/yang/value.lua | 6 | 5402 | -- Use of this source code is governed by the Apache 2.0 license; see
-- COPYING.
module(..., package.seeall)
local util = require("lib.yang.util")
local ipv4 = require("lib.protocol.ipv4")
local ipv6 = require("lib.protocol.ipv6")
local ffi = require("ffi")
local bit = require("bit")
local ethernet = require("lib.protocol.ethernet")
local ipv4_pton, ipv4_ntop = util.ipv4_pton, util.ipv4_ntop
types = {}
local function integer_type(ctype)
local ret = {ctype=ctype}
local min, max = ffi.new(ctype, 0), ffi.new(ctype, -1)
if max < 0 then
-- A signed type. Hackily rely on unsigned types having 'u'
-- prefix.
max = ffi.new(ctype, bit.rshift(ffi.new('u'..ctype, max), 1))
min = max - max - max - 1
end
function ret.parse(str, what)
return util.tointeger(str, what, min, max)
end
function ret.tostring(val)
local str = tostring(val)
if str:match("ULL") then return str:sub(1, -4)
elseif str:match("LL") then return str:sub(1, -3)
else return str end
end
return ret
end
types.int8 = integer_type('int8_t')
types.int16 = integer_type('int16_t')
types.int32 = integer_type('int32_t')
types.int64 = integer_type('int64_t')
types.uint8 = integer_type('uint8_t')
types.uint16 = integer_type('uint16_t')
types.uint32 = integer_type('uint32_t')
types.uint64 = integer_type('uint64_t')
local function unimplemented(type_name)
local ret = {}
function ret.parse(str, what)
error('unimplemented '..type_name..' when parsing '..what)
end
function ret.tostring(val)
return tostring(val)
end
return ret
end
types.binary = unimplemented('binary')
types.bits = unimplemented('bits')
types.boolean = {ctype='bool'}
function types.boolean.parse(str, what)
local str = assert(str, 'missing value for '..what)
if str == 'true' then return true end
if str == 'false' then return false end
error('bad boolean value: '..str)
end
function types.boolean.tostring(val)
return tostring(val)
end
-- FIXME: We lose precision by representing a decimal64 as a double.
types.decimal64 = {ctype='double'}
function types.decimal64.parse(str, what)
local str = assert(str, 'missing value for '..what)
return assert(tonumber(str), 'not a number: '..str)
end
function types.decimal64.tostring(val)
-- FIXME: Make sure we are not given too many digits after the
-- decimal point.
return tostring(val)
end
types.empty = {}
function types.empty.parse (str, what)
return assert(str == nil, "not empty value for "..what)
end
function types.empty.tostring (val)
return ""
end
types.identityref = {}
function types.identityref.parse(str, what)
-- References are expanded in the validation phase.
return assert(str, 'missing value for '..what)
end
function types.identityref.tostring(val)
return val
end
types['instance-identifier'] = unimplemented('instance-identifier')
types.leafref = {}
function types.leafref.parse(str, what)
return assert(str, 'missing value for '..what)
end
function types.leafref.tostring(val)
return val
end
types.string = {}
function types.string.parse(str, what)
return assert(str, 'missing value for '..what)
end
function types.string.tostring(val)
return val
end
types.enumeration = {}
function types.enumeration.parse(str, what)
return assert(str, 'missing value for '..what)
end
function types.enumeration.tostring(val)
return val
end
types.union = unimplemented('union')
types['ipv4-address'] = {
ctype = 'uint32_t',
parse = function(str, what) return ipv4_pton(str) end,
tostring = function(val) return ipv4_ntop(val) end
}
types['legacy-ipv4-address'] = {
ctype = 'uint8_t[4]',
parse = function(str, what) return assert(ipv4:pton(str)) end,
tostring = function(val) return ipv4:ntop(val) end
}
types['ipv6-address'] = {
ctype = 'uint8_t[16]',
parse = function(str, what) return assert(ipv6:pton(str)) end,
tostring = function(val) return ipv6:ntop(val) end
}
types['mac-address'] = {
ctype = 'uint8_t[6]',
parse = function(str, what) return assert(ethernet:pton(str)) end,
tostring = function(val) return ethernet:ntop(val) end
}
types['ipv4-prefix'] = {
ctype = 'struct { uint32_t prefix; uint8_t len; }',
parse = function(str, what)
local prefix, len = str:match('^([^/]+)/(.*)$')
return { prefix=ipv4_pton(prefix), len=util.tointeger(len, nil, 1, 32) }
end,
tostring = function(val) return ipv4_ntop(val.prefix)..'/'..tostring(val.len) end
}
types['ipv6-prefix'] = {
ctype = 'struct { uint8_t prefix[16]; uint8_t len; }',
parse = function(str, what)
local prefix, len = str:match('^([^/]+)/(.*)$')
return { assert(ipv6:pton(prefix)), util.tointeger(len, nil, 1, 128) }
end,
tostring = function(val) return ipv6:ntop(val[1])..'/'..tostring(val[2]) end
}
function selftest()
assert(types['uint8'].parse('0') == 0)
assert(types['uint8'].parse('255') == 255)
assert(not pcall(types['uint8'].parse, '256'))
assert(types['int8'].parse('-128') == -128)
assert(types['int8'].parse('0') == 0)
assert(types['int8'].parse('127') == 127)
assert(not pcall(types['int8'].parse, '128'))
local ip = types['ipv4-prefix'].parse('10.0.0.1/8')
assert(types['ipv4-prefix'].tostring(ip) == '10.0.0.1/8')
local ip = types['ipv6-prefix'].parse('fc00::1/64')
assert(types['ipv6-prefix'].tostring(ip) == 'fc00::1/64')
end
| apache-2.0 |
Xandaros/Starfall | lua/starfall/libs_sh/builtins.lua | 1 | 12191 | -------------------------------------------------------------------------------
-- Builtins.
-- Functions built-in to the default environment
-------------------------------------------------------------------------------
local dgetmeta = debug.getmetatable
--- Built in values. These don't need to be loaded; they are in the default environment.
-- @name builtin
-- @shared
-- @class library
-- @libtbl SF.DefaultEnvironment
-- ------------------------- Lua Ports ------------------------- --
-- This part is messy because of LuaDoc stuff.
local function pascalToCamel ( t, r )
local r = r or {}
for k, v in pairs( t ) do
k = k:gsub( "^%l", string.lower )
r[ k ] = v
end
return r
end
--- Same as Lua's tostring
-- @name SF.DefaultEnvironment.tostring
-- @class function
-- @param obj
-- @return obj as string
SF.DefaultEnvironment.tostring = tostring
--- Same as Lua's tonumber
-- @name SF.DefaultEnvironment.tonumber
-- @class function
-- @param obj
-- @return obj as number
SF.DefaultEnvironment.tonumber = tonumber
--- Same as Lua's ipairs
-- @name SF.DefaultEnvironment.ipairs
-- @class function
-- @param tbl Table to iterate over
-- @return Iterator function
-- @return Table tbl
-- @return 0 as current index
SF.DefaultEnvironment.ipairs = ipairs
--- Same as Lua's pairs
-- @name SF.DefaultEnvironment.pairs
-- @class function
-- @param tbl Table to iterate over
-- @return Iterator function
-- @return Table tbl
-- @return nil as current index
SF.DefaultEnvironment.pairs = pairs
--- Same as Lua's type
-- @name SF.DefaultEnvironment.type
-- @class function
-- @param obj Object to get type of
-- @return The name of the object's type.
SF.DefaultEnvironment.type = function ( obj )
local tp = getmetatable( obj )
return type( tp ) == "string" and tp or type( obj )
end
--- Same as Lua's next
-- @name SF.DefaultEnvironment.next
-- @class function
-- @param tbl Table to get the next key-value pair of
-- @param k Previous key (can be nil)
-- @return Key or nil
-- @return Value or nil
SF.DefaultEnvironment.next = next
--- Same as Lua's assert.
-- @name SF.DefaultEnvironment.assert
-- @class function
-- @param condition
-- @param msg
SF.DefaultEnvironment.assert = function ( condition, msg ) if not condition then SF.throw( msg or "assertion failed!", 2 ) end end
--- Same as Lua's unpack
-- @name SF.DefaultEnvironment.unpack
-- @class function
-- @param tbl
-- @return Elements of tbl
SF.DefaultEnvironment.unpack = unpack
--- Same as Lua's setmetatable. Doesn't work on most internal metatables
-- @name SF.DefaultEnvironment.setmetatable
-- @class function
-- @param tbl The table to set the metatable of
-- @param meta The metatable to use
-- @return tbl with metatable set to meta
SF.DefaultEnvironment.setmetatable = setmetatable
--- Same as Lua's getmetatable. Doesn't work on most internal metatables
-- @param tbl Table to get metatable of
-- @return The metatable of tbl
SF.DefaultEnvironment.getmetatable = function( tbl )
SF.CheckType( tbl, "table" )
return getmetatable( tbl )
end
--- Constant that denotes whether the code is executed on the client
-- @name SF.DefaultEnvironment.CLIENT
-- @class field
SF.DefaultEnvironment.CLIENT = CLIENT
--- Constant that denotes whether the code is executed on the server
-- @name SF.DefaultEnvironment.SERVER
-- @class field
SF.DefaultEnvironment.SERVER = SERVER
--- Returns the current count for this Think's CPU Time.
-- This value increases as more executions are done, may not be exactly as you want.
-- If used on screens, will show 0 if only rendering is done. Operations must be done in the Think loop for them to be counted.
-- @return Current quota used this Think
function SF.DefaultEnvironment.quotaUsed ()
return SF.instance.cpuTime.current
end
--- Gets the Average CPU Time in the buffer
-- @return Average CPU Time of the buffer.
function SF.DefaultEnvironment.quotaAverage ()
return SF.instance.cpuTime:getBufferAverage()
end
--- Gets the CPU Time max.
-- CPU Time is stored in a buffer of N elements, if the average of this exceeds quotaMax, the chip will error.
-- @return Max SysTime allowed to take for execution of the chip in a Think.
function SF.DefaultEnvironment.quotaMax ()
return SF.instance.context.cpuTime.getMax()
end
-- The below modules have the Gmod functions removed (the ones that begin with a capital letter),
-- as requested by Divran
-- Filters Gmod Lua files based on Garry's naming convention.
local function filterGmodLua ( lib, original, gm )
original = original or {}
gm = gm or {}
for name, func in pairs( lib ) do
if name:match( "^[A-Z]" ) then
gm[ name ] = func
else
original[ name ] = func
end
end
return original, gm
end
-- String library
local string_methods, string_metatable = SF.Typedef( "Library: string" )
filterGmodLua( string, string_methods )
string_metatable.__newindex = function () end
--- Lua's (not GLua's) string library
-- @name SF.DefaultEnvironment.string
-- @class table
SF.DefaultEnvironment.string = setmetatable( {}, string_metatable )
-- Math library
local math_methods, math_metatable = SF.Typedef( "Library: math" )
filterGmodLua( math, math_methods )
math_metatable.__newindex = function () end
math_methods.clamp = math.Clamp
math_methods.round = math.Round
math_methods.randfloat = math.Rand
math_methods.calcBSplineN = nil
--- Lua's ( not GLua's ) math library, plus clamp, round, and randfloat
-- @name SF.DefaultEnvironment.math
-- @class table
SF.DefaultEnvironment.math = setmetatable( {}, math_metatable )
local os_methods, os_metatable = SF.Typedef( "Library: os" )
filterGmodLua( os, os_methods )
os_metatable.__newindex = function () end
--- GLua's os library. http://wiki.garrysmod.com/page/Category:os
-- @name SF.DefaultEnvironment.os
-- @class table
SF.DefaultEnvironment.os = setmetatable( {}, os_metatable )
local table_methods, table_metatable = SF.Typedef( "Library: table" )
filterGmodLua( table,table_methods )
table_metatable.__newindex = function () end
--- Lua's (not GLua's) table library
-- @name SF.DefaultEnvironment.table
-- @class table
SF.DefaultEnvironment.table = setmetatable( {}, table_metatable )
-- ------------------------- Functions ------------------------- --
--- Gets a list of all libraries
-- @return Table containing the names of each available library
function SF.DefaultEnvironment.getLibraries ()
local ret = {}
for k,v in pairs( SF.Libraries.libraries ) do
ret[ #ret + 1 ] = k
end
return ret
end
if SERVER then
--- Prints a message to the player's chat.
-- @shared
-- @param ... Values to print
function SF.DefaultEnvironment.print ( ... )
local str = ""
local tbl = { ... }
for i = 1, #tbl do str = str .. tostring( tbl[ i ] ) .. ( i == #tbl and "" or "\t" ) end
SF.instance.player:ChatPrint( str )
end
else
-- Prints a message to the player's chat.
function SF.DefaultEnvironment.print ( ... )
if SF.instance.player ~= LocalPlayer() then return end
local str = ""
local tbl = { ... }
for i = 1 , #tbl do str = str .. tostring( tbl[ i ] ) .. ( i == #tbl and "" or "\t" ) end
LocalPlayer():ChatPrint( str )
end
end
local function printTableX ( target, t, indent, alreadyprinted )
for k,v in SF.DefaultEnvironment.pairs( t ) do
if SF.GetType( v ) == "table" and not alreadyprinted[ v ] then
alreadyprinted[ v ] = true
target:ChatPrint( string.rep( "\t", indent ) .. tostring( k ) .. ":" )
printTableX( target, v, indent + 1, alreadyprinted )
else
target:ChatPrint( string.rep( "\t", indent ) .. tostring( k ) .. "\t=\t" .. tostring( v ) )
end
end
end
--- Prints a table to player's chat
-- @param tbl Table to print
function SF.DefaultEnvironment.printTable ( tbl )
if CLIENT and SF.instance.player ~= LocalPlayer() then return end
SF.CheckType( tbl, "table" )
printTableX( ( SERVER and SF.instance.player or LocalPlayer() ), tbl, 0, { t = true } )
end
--- Runs an included script and caches the result.
-- Works pretty much like standard Lua require()
-- @param file The file to include. Make sure to --@include it
-- @return Return value of the script
function SF.DefaultEnvironment.require (file)
SF.CheckType( file, "string" )
local loaded = SF.instance.data.reqloaded
if not loaded then
loaded = {}
SF.instance.data.reqloaded = loaded
end
if loaded[ file ] then
return loaded[ file ]
else
local func = SF.instance.scripts[ file ]
if not func then SF.throw( "Can't find file '" .. file .. "' ( Did you forget to --@include it? )", 2 ) end
loaded[ file ] = func() or true
return loaded[ file ]
end
end
--- Runs an included script, but does not cache the result.
-- Pretty much like standard Lua dofile()
-- @param file The file to include. Make sure to --@include it
-- @return Return value of the script
function SF.DefaultEnvironment.dofile ( file )
SF.CheckType( file, "string" )
local func = SF.instance.scripts[ file ]
if not func then SF.throw( "Can't find file '" .. file .. "' ( Did you forget to --@include it? )", 2 ) end
return func()
end
--- GLua's loadstring
-- Works like loadstring, except that it executes by default in the main environment
-- @param str String to execute
-- @return Function of str
function SF.DefaultEnvironment.loadstring ( str )
local func = CompileString( str, "SF: " .. tostring( SF.instance.env ), false )
-- CompileString returns an error as a string, better check before setfenv
if type( func ) == "function" then
return setfenv( func, SF.instance.env )
end
return func
end
--- Lua's setfenv
-- Works like setfenv, but is restricted on functions
-- @param func Function to change environment of
-- @param tbl New environment
-- @return func with environment set to tbl
function SF.DefaultEnvironment.setfenv ( func, tbl )
if type( func ) ~= "function" then SF.throw( "Main Thread is protected!", 2 ) end
return setfenv( func, tbl )
end
--- Simple version of Lua's getfenv
-- Returns the current environment
-- @return Current environment
function SF.DefaultEnvironment.getfenv ()
return getfenv()
end
--- Try to execute a function and catch possible exceptions
-- Similar to xpcall, but a bit more in-depth
-- @param func Function to execute
-- @param catch Function to execute in case func fails
function SF.DefaultEnvironment.try ( func, catch )
local ok, err = pcall( func )
if ok then return end
if type( err ) == "table" then
if err.uncatchable then
error( err )
end
end
catch( err )
end
--- Throws an exception
-- @param msg Message
-- @param level Which level in the stacktrace to blame. Defaults to one of invalid
-- @param uncatchable Makes this exception uncatchable
function SF.DefaultEnvironment.throw ( msg, level, uncatchable )
local info = debug.getinfo( 1 + ( level or 1 ), "Sl" )
local filename = info.short_src:match( "^SF:(.*)$" )
if not filename then
info = debug.getinfo( 2, "Sl" )
filename = info.short_src:match( "^SF:(.*)$" )
end
local err = {
uncatchable = false,
file = filename,
line = info.currentline,
message = msg,
uncatchable = uncatchable
}
error( err )
end
--- Throws a raw exception.
-- @param msg Exception message
function SF.DefaultEnvironment.error ( msg )
error( msg or "an unspecified error occured", 2 )
end
--- Execute a console command
-- @param cmd Command to execute
function SF.DefaultEnvironment.concmd ( cmd )
if CLIENT and SF.instance.player ~= LocalPlayer() then return end -- only execute on owner of screen
SF.CheckType( cmd, "string" )
SF.instance.player:ConCommand( cmd )
end
-- ------------------------- Restrictions ------------------------- --
-- Restricts access to builtin type's metatables
local _R = debug.getregistry()
local function restrict( instance, hook, name, ok, err )
_R.Vector.__metatable = "Vector"
_R.Angle.__metatable = "Angle"
_R.VMatrix.__metatable = "VMatrix"
end
local function unrestrict( instance, hook, name, ok, err )
_R.Vector.__metatable = nil
_R.Angle.__metatable = nil
_R.VMatrix.__metatable = nil
end
SF.Libraries.AddHook( "prepare", restrict )
SF.Libraries.AddHook( "cleanup", unrestrict )
-- ------------------------- Hook Documentation ------------------------- --
--- Think hook. Called once per game tick
-- @name think
-- @class hook
-- @shared
| bsd-3-clause |
Vermeille/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 |
Feilkin/cyberpunk | engine/tools/navmesher/outfile.lua | 1 | 160529 | return {
height = 100,
layers = { {
data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 178, 178, 178, 178, 121, 178, 121, 121, 121, 0, 121, 178, 121, 121, 121, 121, 178, 178, 121, 178, 178, 178, 178, 178, 121, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 121, 178, 178, 121, 121, 121, 121, 178, 178, 0, 121, 121, 121, 121, 121, 178, 121, 121, 121, 121, 178, 178, 178, 178, 121, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 178, 121, 178, 178, 178, 121, 178, 121, 121, 121, 0, 178, 178, 178, 178, 178, 178, 178, 178, 121, 0, 121, 121, 121, 121, 178, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 178, 121, 121, 121, 178, 121, 178, 178, 178, 121, 121, 121, 178, 178, 178, 121, 178, 121, 178, 0, 121, 178, 178, 178, 121, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 178, 121, 178, 178, 178, 178, 121, 121, 121, 178, 121, 178, 178, 121, 121, 178, 121, 121, 178, 178, 0, 121, 178, 121, 178, 178, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 178, 178, 121, 178, 121, 121, 178, 178, 121, 121, 121, 121, 121,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, 0, 0, 0, 0, 0, 0, 0, 0, 178, 178, 121, 0, 0, 0, 0, 0, 0, 0, 0, 178, 178, 0, 0, 0, 0, 0, 0, 178, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 178, 121, 121, 121, 178, 121, 178, 178, 178, 121, 121, 178, 178, 121, 121, 178, 121, 178, 121, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 178, 178, 121, 121, 178, 178, 178, 178, 178, 178, 178, 121, 121, 178, 121, 178, 121, 178, 121, 178, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 178, 0, 0, 0, 0, 0, 0, 0, 0, 178, 178, 121, 0, 178, 178, 121, 178, 178, 178, 121, 178, 121, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 121, 121, 121, 178, 178, 178, 121, 121, 121, 178, 178, 178, 121, 121, 178, 178, 121, 178, 121, 178, 121, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 178, 178, 178, 121, 121, 178, 121, 178, 121, 178, 178, 178, 0, 121, 121, 121, 121, 178, 178, 178, 178, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 121, 178, 178, 178, 178, 178, 121, 178, 178, 178, 121, 121, 121, 121, 121, 178, 178, 121, 178, 178, 121, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 178, 121, 121, 178, 178, 121, 178, 121, 178, 121, 121, 178, 121, 178, 121, 178, 121, 121, 121, 121, 121, 121, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 178, 178, 121, 178, 178, 178, 178, 121, 178, 178, 121, 121, 178, 121, 121, 121, 121, 121, 178, 178, 178, 178, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 121, 178, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 178, 178, 121, 178, 121, 178, 121, 178, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
encoding = "lua",
height = 100,
name = "floors",
offsetx = 0,
offsety = 0,
opacity = 1,
properties = {},
type = "tilelayer",
visible = true,
width = 100,
x = 0,
y = 0
}, {
data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 715, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 775, 713, 713, 713, 713, 713, 713, 713, 713, 713, 775, 713, 713, 713, 713, 713, 713, 716, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 771, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 771, 0, 0, 0, 0, 0, 0, 0, 0, 0, 771, 0, 0, 0, 0, 0, 0, 771, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 491, 492, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1644, 1645, 1645, 1645, 1645, 1645, 1645, 1645, 1645, 1646, 0, 1644, 1645, 1645, 1645, 1645, 1645, 1645, 1645, 1646, 0, 0, 0, 1701, 1703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1701, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1703, 0, 1701, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1703, 0, 0, 0, 1701, 1703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1701, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1703, 0, 1701, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1703, 0, 0, 0, 1701, 1703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1701, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1703, 0, 1701, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1703, 0, 0, 0, 1701, 1703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1701, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1703, 0, 1701, 1702, 1702, 1702, 1702, 1702, 1702, 1702, 1703, 0, 0, 0, 1701, 1703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1758, 1759, 1759, 1759, 1702, 1702, 1759, 1759, 1759, 1760, 0, 1758, 1759, 1759, 1759, 1702, 1702, 1759, 1759, 1760, 0, 0, 0, 1701, 1703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 0, 0, 0, 1701, 1703, 0, 0, 0, 0, 0, 0, 1701, 1703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1701, 1702, 1645, 1645, 1645, 1645, 1645, 1645, 1645, 1645, 1645, 1702, 1702, 1645, 1645, 1645, 1645, 1645, 1645, 1702, 1703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1758, 1759, 1759, 1759, 1759, 1759, 1759, 1759, 1759, 1759, 1759, 1702, 1702, 1759, 1759, 1759, 1759, 1759, 1759, 1759, 1760, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 659, 0, 659, 0, 659, 0, 659, 0, 0, 0, 0, 2154, 2154, 2154, 2154, 2154, 2154, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
encoding = "lua",
height = 100,
name = "prop2",
offsetx = 0,
offsety = 0,
opacity = 1,
properties = {},
type = "tilelayer",
visible = true,
width = 100,
x = 0,
y = 0
}, {
draworder = "topdown",
name = "objects",
objects = { {
gid = 324,
height = 16,
id = 1,
name = "",
properties = {
collidable = true,
openGID = 490
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1520,
y = 128
}, {
gid = 325,
height = 16,
id = 3,
name = "",
properties = {
collidable = true,
openGID = 491
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1536,
y = 128
}, {
gid = 148,
height = 16,
id = 4,
name = "",
properties = {
collidable = true,
openGID = 261
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1536,
y = 272
}, {
gid = 324,
height = 16,
id = 5,
name = "",
properties = {
collidable = true,
openGID = 490
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1392,
y = 128
}, {
gid = 325,
height = 16,
id = 6,
name = "",
properties = {
collidable = true,
openGID = 491
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1408,
y = 128
}, {
gid = 324,
height = 16,
id = 7,
name = "",
properties = {
collidable = true,
openGID = 490
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1216,
y = 128
}, {
gid = 325,
height = 16,
id = 8,
name = "",
properties = {
collidable = true,
openGID = 491
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1232,
y = 128
}, {
gid = 147,
height = 16,
id = 9,
name = "",
properties = {
collidable = true,
openGID = 261
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1472,
y = 224
}, {
gid = 147,
height = 16,
id = 10,
name = "",
properties = {
collidable = true,
openGID = 261
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1312,
y = 224
}, {
gid = 324,
height = 16,
id = 11,
name = "",
properties = {
collidable = true,
openGID = 490
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1392,
y = 272
}, {
gid = 325,
height = 16,
id = 12,
name = "",
properties = {
collidable = true,
openGID = 491
},
rotation = 0,
shape = "rectangle",
type = "door",
visible = true,
width = 16,
x = 1408,
y = 272
}, {
height = 16,
id = 13,
name = "playerSpawn",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = false,
width = 16,
x = 1520,
y = 32
}, {
height = 16,
id = 40,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1520,
y = 304
}, {
height = 16,
id = 41,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1536,
y = 304
}, {
height = 16,
id = 42,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1520,
y = 320
}, {
height = 16,
id = 43,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1536,
y = 320
}, {
height = 16,
id = 44,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1472,
y = 176
}, {
height = 16,
id = 45,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1280,
y = 64
}, {
height = 16,
id = 46,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1168,
y = 16
}, {
height = 16,
id = 47,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1232,
y = 288
}, {
height = 16,
id = 48,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1360,
y = 288
}, {
height = 16,
id = 49,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1232,
y = 160
}, {
height = 16,
id = 50,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1232,
y = 240
}, {
height = 16,
id = 51,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "enemySpawn",
visible = false,
width = 16,
x = 1440,
y = 80
}, {
gid = 1872,
height = 16,
id = 109,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1360,
y = 48
}, {
gid = 1872,
height = 16,
id = 110,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1376,
y = 48
}, {
gid = 1872,
height = 16,
id = 111,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1392,
y = 48
}, {
gid = 1872,
height = 16,
id = 112,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1408,
y = 48
}, {
gid = 1872,
height = 16,
id = 113,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1424,
y = 48
}, {
gid = 1873,
height = 16,
id = 114,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1360,
y = 80
}, {
gid = 1873,
height = 16,
id = 115,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1376,
y = 80
}, {
gid = 1873,
height = 16,
id = 116,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1392,
y = 80
}, {
gid = 1873,
height = 16,
id = 117,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1408,
y = 80
}, {
gid = 1873,
height = 16,
id = 118,
name = "",
properties = {
collidable = true,
objectHeight = 90
},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1424,
y = 80
} },
offsetx = 0,
offsety = 0,
opacity = 1,
properties = {},
type = "objectgroup",
visible = true
}, {
draworder = "topdown",
name = "collisions",
objects = { {
height = 16,
id = 14,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 448,
x = 1136,
y = 0
}, {
height = 128,
id = 16,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1584,
y = 0
}, {
height = 16,
id = 17,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 32,
x = 1552,
y = 112
}, {
height = 128,
id = 18,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1552,
y = 128
}, {
height = 16,
id = 19,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 48,
x = 1552,
y = 256
}, {
height = 112,
id = 20,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1584,
y = 272
}, {
height = 16,
id = 21,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 384,
x = 1200,
y = 368
}, {
height = 256,
id = 22,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1200,
y = 112
}, {
height = 16,
id = 23,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 176,
x = 1216,
y = 256
}, {
height = 16,
id = 24,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 112,
x = 1424,
y = 256
}, {
height = 96,
id = 25,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1424,
y = 272
}, {
height = 112,
id = 26,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1504,
y = 112
}, {
height = 16,
id = 27,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1488,
y = 208
}, {
height = 16,
id = 28,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 48,
x = 1424,
y = 208
}, {
height = 96,
id = 29,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1424,
y = 112
}, {
height = 16,
id = 30,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 64,
x = 1440,
y = 112
}, {
height = 96,
id = 31,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1472,
y = 16
}, {
height = 112,
id = 32,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1376,
y = 112
}, {
height = 16,
id = 33,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 48,
x = 1328,
y = 208
}, {
height = 16,
id = 34,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 64,
x = 1248,
y = 208
}, {
height = 80,
id = 35,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1248,
y = 128
}, {
height = 16,
id = 36,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 128,
x = 1248,
y = 112
}, {
height = 96,
id = 37,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1312,
y = 16
}, {
height = 112,
id = 38,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 16,
x = 1136,
y = 16
}, {
height = 16,
id = 39,
name = "",
properties = {},
rotation = 0,
shape = "rectangle",
type = "",
visible = true,
width = 48,
x = 1152,
y = 112
} },
offsetx = 0,
offsety = 0,
opacity = 1,
properties = {
collidable = true
},
type = "objectgroup",
visible = false
}, {
draworder = "topdown",
name = "navmesh",
objects = { {
height = 16,
id = 183,
properties = {
connectsTo = "184"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 1136,
x = 0,
y = 0
}, {
height = 1584,
id = 184,
properties = {
connectsTo = "183,214,215,216,217"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 1136,
x = 0,
y = 16
}, {
height = 96,
id = 185,
properties = {
connectsTo = "195"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 144,
x = 1328,
y = 16
}, {
height = 96,
id = 186,
properties = {
connectsTo = "191"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 96,
x = 1488,
y = 16
}, {
height = 96,
id = 187,
properties = {
connectsTo = "213"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 160,
x = 1152,
y = 16
}, {
height = 80,
id = 188,
properties = {
connectsTo = "208"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1264,
y = 128
}, {
height = 80,
id = 189,
properties = {
connectsTo = "208"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1328,
y = 128
}, {
height = 16,
id = 190,
properties = {
connectsTo = "192,203,204"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1472,
y = 208
}, {
height = 16,
id = 191,
properties = {
connectsTo = "186,198"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1520,
y = 112
}, {
height = 80,
id = 192,
properties = {
connectsTo = "190"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 64,
x = 1440,
y = 128
}, {
height = 80,
id = 193,
properties = {
connectsTo = "194,195"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1392,
y = 128
}, {
height = 16,
id = 194,
properties = {
connectsTo = "193,205,212,218"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1392,
y = 208
}, {
height = 16,
id = 195,
properties = {
connectsTo = "185,193"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1392,
y = 112
}, {
height = 32,
id = 196,
properties = {
connectsTo = "200,204,206"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1504,
y = 224
}, {
height = 32,
id = 197,
properties = {
connectsTo = "201,202"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1568,
y = 224
}, {
height = 80,
id = 198,
properties = {
connectsTo = "191,200"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1520,
y = 128
}, {
height = 80,
id = 199,
properties = {
connectsTo = "201,202"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1568,
y = 128
}, {
height = 16,
id = 200,
properties = {
connectsTo = "196,198"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1520,
y = 208
}, {
height = 16,
id = 201,
properties = {
connectsTo = "197,199,202"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1568,
y = 208
}, {
height = 128,
id = 202,
properties = {
connectsTo = "197,199,201"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1584,
y = 128
}, {
height = 32,
id = 203,
properties = {
connectsTo = "190,204,205"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1440,
y = 224
}, {
height = 32,
id = 204,
properties = {
connectsTo = "190,196,203"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1488,
y = 224
}, {
height = 32,
id = 205,
properties = {
connectsTo = "194,203,218"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1424,
y = 224
}, {
height = 16,
id = 206,
properties = {
connectsTo = "196,220,228,230"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1536,
y = 256
}, {
height = 128,
id = 207,
properties = {
connectsTo = "210,213"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1216,
y = 128
}, {
height = 128,
id = 208,
properties = {
connectsTo = "188,189,209,211"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1312,
y = 128
}, {
height = 32,
id = 209,
properties = {
connectsTo = "208,212"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1328,
y = 224
}, {
height = 32,
id = 210,
properties = {
connectsTo = "207,211"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1248,
y = 224
}, {
height = 32,
id = 211,
properties = {
connectsTo = "208,210"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1264,
y = 224
}, {
height = 32,
id = 212,
properties = {
connectsTo = "194,209,218"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1376,
y = 224
}, {
height = 16,
id = 213,
properties = {
connectsTo = "187,207"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1216,
y = 112
}, {
height = 128,
id = 214,
properties = {
connectsTo = "184,215"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 64,
x = 1136,
y = 128
}, {
height = 16,
id = 215,
properties = {
connectsTo = "184,214,216"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 64,
x = 1136,
y = 256
}, {
height = 96,
id = 216,
properties = {
connectsTo = "184,215,217"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 64,
x = 1136,
y = 272
}, {
height = 1232,
id = 217,
properties = {
connectsTo = "184,216,244"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 64,
x = 1136,
y = 368
}, {
height = 144,
id = 218,
properties = {
connectsTo = "194,205,212,242"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1392,
y = 224
}, {
height = 1216,
id = 219,
properties = {
connectsTo = "243,245"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1392,
y = 384
}, {
height = 96,
id = 220,
properties = {
connectsTo = "206,222,230"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1552,
y = 272
}, {
height = 1216,
id = 221,
properties = {
connectsTo = "223,231"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1552,
y = 384
}, {
height = 96,
id = 222,
properties = {
connectsTo = "220"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1568,
y = 272
}, {
height = 1216,
id = 223,
properties = {
connectsTo = "221,246"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1568,
y = 384
}, {
height = 96,
id = 224,
properties = {
connectsTo = "226"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1440,
y = 272
}, {
height = 1216,
id = 225,
properties = {
connectsTo = "227,245"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1440,
y = 384
}, {
height = 96,
id = 226,
properties = {
connectsTo = "224,228"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1488,
y = 272
}, {
height = 1216,
id = 227,
properties = {
connectsTo = "225,229"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1488,
y = 384
}, {
height = 96,
id = 228,
properties = {
connectsTo = "206,226,230"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1504,
y = 272
}, {
height = 1216,
id = 229,
properties = {
connectsTo = "227,231"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1504,
y = 384
}, {
height = 96,
id = 230,
properties = {
connectsTo = "206,220,228"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1536,
y = 272
}, {
height = 1216,
id = 231,
properties = {
connectsTo = "221,229"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1536,
y = 384
}, {
height = 96,
id = 232,
properties = {
connectsTo = "238"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1216,
y = 272
}, {
height = 1216,
id = 233,
properties = {
connectsTo = "239,244"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 32,
x = 1216,
y = 384
}, {
height = 96,
id = 234,
properties = {
connectsTo = "236,240"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1312,
y = 272
}, {
height = 1216,
id = 235,
properties = {
connectsTo = "237,241"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1312,
y = 384
}, {
height = 96,
id = 236,
properties = {
connectsTo = "234,242"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1328,
y = 272
}, {
height = 1216,
id = 237,
properties = {
connectsTo = "235,243"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1328,
y = 384
}, {
height = 96,
id = 238,
properties = {
connectsTo = "232,240"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1248,
y = 272
}, {
height = 1216,
id = 239,
properties = {
connectsTo = "233,241"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1248,
y = 384
}, {
height = 96,
id = 240,
properties = {
connectsTo = "234,238"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1264,
y = 272
}, {
height = 1216,
id = 241,
properties = {
connectsTo = "235,239"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 48,
x = 1264,
y = 384
}, {
height = 96,
id = 242,
properties = {
connectsTo = "218,236"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1376,
y = 272
}, {
height = 1216,
id = 243,
properties = {
connectsTo = "219,237"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1376,
y = 384
}, {
height = 1216,
id = 244,
properties = {
connectsTo = "217,233"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1200,
y = 384
}, {
height = 1216,
id = 245,
properties = {
connectsTo = "219,225"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1424,
y = 384
}, {
height = 1216,
id = 246,
properties = {
connectsTo = "223"
},
rotation = 0,
shape = "rectangle",
type = "navmesh",
width = 16,
x = 1584,
y = 384
} },
offsetx = 0,
offsety = 0,
opacity = 1,
properties = {},
type = "objectgroup",
visible = false
} },
luaversion = "5.1",
nextobjectid = 247,
orientation = "orthogonal",
properties = {},
renderorder = "right-down",
tiledversion = "0.17.1",
tileheight = 16,
tilesets = { {
firstgid = 1,
image = "../tilesets/roguelikeSheet_transparent.png",
imageheight = 526,
imagewidth = 968,
margin = 0,
name = "roguelikeSheet_transparent",
properties = {},
spacing = 1,
terrains = {},
tilecount = 1767,
tileheight = 16,
tileoffset = {
x = 0,
y = 0
},
tiles = {},
tilewidth = 16
}, {
firstgid = 1768,
image = "../tilesets/roguelikeIndoor_transparent.png",
imageheight = 305,
imagewidth = 457,
margin = 0,
name = "roguelikeIndoor_transparent",
properties = {},
spacing = 1,
terrains = {},
tilecount = 468,
tileheight = 16,
tileoffset = {
x = 0,
y = 0
},
tiles = {},
tilewidth = 16
} },
tilewidth = 16,
version = "1.1",
width = 100
}
| mit |
xponen/Zero-K | scripts/cormak.lua | 1 | 10255 | include 'constants.lua'
local base = piece 'base'
local pelvis = piece 'pelvis'
local torso = piece 'torso'
local emit = piece 'emit'
local fire = piece 'fire'
local Lleg = piece 'lleg'
local Rleg = piece 'rleg'
local lowerLleg = piece 'lowerlleg'
local lowerRleg = piece 'lowerrleg'
local Lfoot = piece 'lfoot'
local Rfoot = piece 'rfoot'
local l_gun = piece 'l_gun'
local r_gun = piece 'r_gun'
local smokePiece = {torso}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Signal definitions
local SIG_WALK = 1
local SIG_AIM = 2
local SIG_ACTIVATE = 8
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetUnitWeaponState = Spring.GetUnitWeaponState
local spSetUnitWeaponState = Spring.SetUnitWeaponState
local spGetGameFrame = Spring.GetGameFrame
local waveWeaponDef = WeaponDefNames["cormak_blast"]
local WAVE_RELOAD = math.ceil( waveWeaponDef.reload * Game.gameSpeed ) -- 27
local WAVE_TIMEOUT = math.ceil( waveWeaponDef.damageAreaOfEffect / waveWeaponDef.explosionSpeed )* (1000 / Game.gameSpeed) + 200 -- empirically maximum delay of damage was (damageAreaOfEffect / explosionSpeed) - 4 frames
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function Walk()
Signal(SIG_WALK)
SetSignalMask(SIG_WALK)
while true do
Move( torso , y_axis, 0.000000 )
Turn( Rleg , x_axis, 0 )
Turn( lowerRleg , x_axis, 0 )
Turn( Rfoot , x_axis, 0 )
Turn( Lleg , x_axis, 0 )
Turn( lowerLleg , x_axis, 0 )
Turn( Lfoot , x_axis, 0 )
Sleep(67)
Move( torso , y_axis, 0.300000 )
Turn( Rleg , x_axis, math.rad(-10.000000) )
Turn( lowerRleg , x_axis, math.rad(-20.000000) )
Turn( Rfoot , x_axis, math.rad(20.000000) )
Turn( Lleg , x_axis, math.rad(10.000000) )
Turn( lowerLleg , x_axis, math.rad(20.000000) )
Turn( Lfoot , x_axis, math.rad(-20.000000) )
Sleep(67)
Move( torso , y_axis, 0.700000 )
Turn( Rleg , x_axis, math.rad(-20.000000) )
Turn( lowerRleg , x_axis, math.rad(-30.005495) )
Turn( Rfoot , x_axis, math.rad(30.005495) )
Turn( lowerLleg , x_axis, math.rad(20.000000) )
Turn( Lfoot , x_axis, math.rad(-20.000000) )
Sleep(67)
Move( torso , y_axis, 0.300000 )
Turn( Rleg , x_axis, math.rad(-30.005495) )
Turn( lowerRleg , x_axis, math.rad(-20.000000) )
Turn( Rfoot , x_axis, math.rad(40.005495) )
Turn( lowerLleg , x_axis, math.rad(30.005495) )
Turn( Lfoot , x_axis, math.rad(-30.005495) )
Sleep(67)
Move( torso , y_axis, 0.000000 )
Turn( Rleg , x_axis, math.rad(-20.000000) )
Turn( lowerRleg , x_axis, math.rad(-10.000000) )
Turn( Rfoot , x_axis, math.rad(30.005495) )
Turn( lowerLleg , x_axis, math.rad(40.005495) )
Turn( Lfoot , x_axis, math.rad(-40.005495) )
Sleep(67)
Move( torso , y_axis, -0.100000 )
Turn( Rleg , x_axis, 0 )
Turn( lowerRleg , x_axis, 0 )
Turn( Rfoot , x_axis, 0 )
Turn( Lleg , x_axis, 0 )
Turn( lowerLleg , x_axis, 0 )
Turn( Lfoot , x_axis, 0 )
Sleep(67)
Move( torso , y_axis, -0.200000 )
Turn( Rleg , x_axis, math.rad(10.000000) )
Turn( lowerRleg , x_axis, math.rad(20.000000) )
Turn( Rfoot , x_axis, math.rad(-20.000000) )
Turn( Lleg , x_axis, math.rad(-10.000000) )
Turn( lowerLleg , x_axis, math.rad(-20.000000) )
Turn( Lfoot , x_axis, math.rad(20.000000) )
Sleep(67)
Move( torso , y_axis, -0.300000 )
Turn( lowerRleg , x_axis, math.rad(20.000000) )
Turn( Rfoot , x_axis, math.rad(-20.000000) )
Turn( Lleg , x_axis, math.rad(-20.000000) )
Turn( lowerLleg , x_axis, math.rad(-30.005495) )
Turn( Lfoot , x_axis, math.rad(30.005495) )
Sleep(67)
Move( torso , y_axis, -0.400000 )
Turn( lowerRleg , x_axis, math.rad(30.005495) )
Turn( Rfoot , x_axis, math.rad(-30.005495) )
Turn( Lleg , x_axis, math.rad(-30.005495) )
Turn( lowerLleg , x_axis, math.rad(-20.000000) )
Turn( Lfoot , x_axis, math.rad(40.005495) )
Sleep(67)
Move( torso , y_axis, -0.500000 )
Turn( lowerRleg , x_axis, math.rad(40.005495) )
Turn( Rfoot , x_axis, math.rad(-40.005495) )
Turn( Lleg , x_axis, math.rad(-20.000000) )
Turn( lowerLleg , x_axis, math.rad(-10.000000) )
Turn( Lfoot , x_axis, math.rad(30.005495) )
Sleep(67)
Move( torso , y_axis, 0.000000 )
Turn( lowerRleg , x_axis, 0, math.rad(200.000000) )
Turn( Rleg , x_axis, 0, math.rad(200.000000) )
Turn( Rfoot , x_axis, 0, math.rad(200.000000) )
Turn( Lleg , x_axis, 0 )
Turn( lowerLleg , x_axis, 0 )
Turn( Lfoot , x_axis, 0 )
Sleep(67)
end
end
function script.Create()
--Move( emit, y_axis, 20)
StartThread(SmokeUnit, smokePiece)
end
function AutoAttack_Thread()
Signal(SIG_ACTIVATE)
SetSignalMask(SIG_ACTIVATE)
while true do
Sleep(100)
local reloaded = select(2, spGetUnitWeaponState(unitID,3))
if reloaded then
local gameFrame = spGetGameFrame()
local reloadMult = GG.att_reload[unitID] or 1.0
local reloadFrame = gameFrame + WAVE_RELOAD / reloadMult
spSetUnitWeaponState(unitID, 3, {reloadFrame = reloadFrame} )
GG.PokeDecloakUnit(unitID,100)
EmitSfx( emit, UNIT_SFX1 )
EmitSfx( emit, DETO_W2 )
FireAnim()
end
end
end
function FireAnim()
local mspeed = 4
Move (l_gun, x_axis, 2, mspeed*3)
Move (r_gun, x_axis, -2, mspeed*3)
WaitForMove(l_gun, x_axis)
WaitForMove(r_gun, x_axis)
Sleep(1)
Move (l_gun, x_axis, 0, mspeed)
Move (r_gun, x_axis, 0, mspeed)
Sleep(1)
end
function script.Activate()
StartThread(AutoAttack_Thread)
end
function script.Deactivate()
Signal(SIG_ACTIVATE)
end
function script.StartMoving()
StartThread(Walk)
end
function script.StopMoving()
Signal(SIG_WALK)
end
function script.FireWeapon(num)
if num == 3 then
EmitSfx( emit, UNIT_SFX1 )
EmitSfx( emit, DETO_W2 )
FireAnim()
end
end
function script.AimFromWeapon(num)
return torso
end
function script.AimWeapon(num, heading, pitch)
return num == 3
end
function script.QueryWeapon(num)
return emit
end
local function Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity <= .25 then
Explode(base, sfxNone)
Explode(torso, sfxNone)
Explode(Rleg, sfxNone)
Explode(Lleg, sfxNone)
Explode(lowerRleg, sfxNone)
Explode(lowerLleg, sfxNone)
Explode(Rfoot, sfxNone)
Explode(Lfoot, sfxNone)
return 1
elseif severity <= .50 then
Explode(base, sfxNone)
Explode(torso, sfxNone)
Explode(Rleg, sfxNone)
Explode(Lleg, sfxNone)
Explode(lowerRleg, sfxNone)
Explode(lowerLleg, sfxNone)
Explode(Rfoot, sfxNone)
Explode(Lfoot, sfxNone)
return 1
elseif severity <= .99 then
Explode(base, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT )
Explode(torso, sfxNone)
Explode(Rleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT )
Explode(Lleg, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT )
Explode(lowerRleg, sfxNone)
Explode(lowerLleg, sfxNone)
Explode(Rfoot, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT )
Explode(Lfoot, sfxNone)
return 2
else
Explode(base, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT )
Explode(torso, sfxNone)
Explode(Rleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT )
Explode(Lleg, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT )
Explode(lowerRleg, sfxNone)
Explode(lowerLleg, sfxNone)
Explode(Rfoot, SFX.SHATTER + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE_ON_HIT )
Explode(Lfoot, sfxNone)
return 2
end
end
function script.Killed(recentDamage, maxHealth)
-- spawn debris etc.
local wreckLevel = Killed(recentDamage, maxHealth)
local ud = UnitDefs[unitDefID]
local x, y, z = Spring.GetUnitPosition(unitID)
-- hide unit
Spring.SetUnitNoSelect(unitID, true)
Spring.SetUnitNoDraw(unitID, true)
Spring.SetUnitNoMinimap(unitID, true)
Spring.SetUnitSensorRadius(unitID, "los", 0)
Spring.SetUnitSensorRadius(unitID, "airLos", 0)
Spring.MoveCtrl.Enable(unitID, true)
Spring.MoveCtrl.SetNoBlocking(unitID, true)
Spring.MoveCtrl.SetPosition(unitID, x, Spring.GetGroundHeight(x, z) - 1000, z)
-- spawn wreck
local wreckDef = FeatureDefNames[ud.wreckName]
while (wreckLevel > 1 and wreckDef) do
wreckDef = FeatureDefs[ wreckDef.deathFeatureID ]
wreckLevel = wreckLevel - 1
end
if (wreckDef) then
local heading = Spring.GetUnitHeading(unitID)
local teamID = Spring.GetUnitTeam(unitID)
local featureID = Spring.CreateFeature(wreckDef.id, x, y, z, heading, teamID)
Spring.SetFeatureResurrect(featureID, ud.name)
-- engine also sets speed and smokeTime for wrecks, but there are no lua functions for these
end
Sleep(WAVE_TIMEOUT) -- wait until all waves hit
return 10 -- don't spawn second wreck
end
if (Game.version:find('91.0') == 1) and (Game.version:find('91.0.1') == nil) then
script.Killed = function(recentDamage, maxHealth)
-- spawn debris etc.
local wreckLevel = Killed(recentDamage, maxHealth)
local ud = UnitDefs[unitDefID]
local x, y, z = Spring.GetUnitPosition(unitID)
-- hide unit
Spring.SetUnitNoSelect(unitID, true)
Spring.SetUnitNoDraw(unitID, true)
Spring.SetUnitNoMinimap(unitID, true)
Spring.SetUnitSensorRadius(unitID, "los", 0)
Spring.SetUnitSensorRadius(unitID, "airLos", 0)
Spring.MoveCtrl.Enable(unitID, true)
Spring.MoveCtrl.SetNoBlocking(unitID, true)
Spring.MoveCtrl.SetPosition(unitID, x, Spring.GetGroundHeight(x, z) - 1000, z)
-- spawn wreck
local wreckDef = FeatureDefNames[ ud.wreckName ]
while (wreckLevel > 1 and wreckDef) do
wreckDef = FeatureDefNames[ wreckDef.deathFeature ]
wreckLevel = wreckLevel - 1
end
if (wreckDef) then
local heading = Spring.GetUnitHeading(unitID)
local teamID = Spring.GetUnitTeam(unitID)
local featureID = Spring.CreateFeature(wreckDef.id, x, y, z, heading, teamID)
Spring.SetFeatureResurrect(featureID, ud.name)
-- engine also sets speed and smokeTime for wrecks, but there are no lua functions for these
end
Sleep(WAVE_TIMEOUT) -- wait until all waves hit
return 10 -- don't spawn second wreck
end
end
| gpl-2.0 |
DreamHacks/dreamdota | DreamWarcraft/Build Tools/MPQFixEngine/lua/json/decode/calls.lua | 3 | 3241 | --[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local lpeg = require("lpeg")
local tostring = tostring
local pairs, ipairs = pairs, ipairs
local next, type = next, type
local error = error
local util = require("json.decode.util")
local buildCall = require("json.util").buildCall
local getmetatable = getmetatable
module("json.decode.calls")
local defaultOptions = {
defs = nil,
-- By default, do not allow undefined calls to be de-serialized as call objects
allowUndefined = false
}
-- No real default-option handling needed...
default = nil
strict = nil
local isPattern
if lpeg.type then
function isPattern(value)
return lpeg.type(value) == 'pattern'
end
else
local metaAdd = getmetatable(lpeg.P("")).__add
function isPattern(value)
return getmetatable(value).__add == metaAdd
end
end
local function buildDefinedCaptures(argumentCapture, defs)
local callCapture
if not defs then return end
for name, func in pairs(defs) do
if type(name) ~= 'string' and not isPattern(name) then
error("Invalid functionCalls name: " .. tostring(name) .. " not a string or LPEG pattern")
end
-- Allow boolean or function to match up w/ encoding permissions
if type(func) ~= 'boolean' and type(func) ~= 'function' then
error("Invalid functionCalls item: " .. name .. " not a function")
end
local nameCallCapture
if type(name) == 'string' then
nameCallCapture = lpeg.P(name .. "(") * lpeg.Cc(name)
else
-- Name matcher expected to produce a capture
nameCallCapture = name * "("
end
-- Call func over nameCallCapture and value to permit function receiving name
-- Process 'func' if it is not a function
if type(func) == 'boolean' then
local allowed = func
func = function(name, ...)
if not allowed then
error("Function call on '" .. name .. "' not permitted")
end
return buildCall(name, ...)
end
else
local inner_func = func
func = function(...)
return (inner_func(...))
end
end
local newCapture = (nameCallCapture * argumentCapture) / func * ")"
if not callCapture then
callCapture = newCapture
else
callCapture = callCapture + newCapture
end
end
return callCapture
end
local function buildCapture(options)
if not options -- No ops, don't bother to parse
or not (options.defs and (nil ~= next(options.defs)) or options.allowUndefined) then
return nil
end
-- Allow zero or more arguments separated by commas
local value = lpeg.V(util.types.VALUE)
local argumentCapture = (value * (lpeg.P(",") * value)^0) + 0
local callCapture = buildDefinedCaptures(argumentCapture, options.defs)
if options.allowUndefined then
local function func(name, ...)
return buildCall(name, ...)
end
-- Identifier-type-match
local nameCallCapture = lpeg.C(util.identifier) * "("
local newCapture = (nameCallCapture * argumentCapture) / func * ")"
if not callCapture then
callCapture = newCapture
else
callCapture = callCapture + newCapture
end
end
return callCapture
end
function load_types(options, global_options, grammar)
local capture = buildCapture(options, global_options)
if capture then
util.append_grammar_item(grammar, "VALUE", capture)
end
end
| mit |
sullome/km-freeminer-mods | mods/hunger/init.lua | 2 | 2969 | hunger = {}
hunger.MAX = 8*60*60*100
hunger.conf = {
-- Order is important
[1] = {bound = 1*60*60*100, timer_limit = 5*60*100, text = "Вы очень голодны."},
[2] = {bound = 3*60*60*100, timer_limit = 20*60*100, text = "Вы немного голодны."},
[3] = {bound = 7*60*60*100, timer_limit = -1, text = "Вы сыты."},
[4] = {bound = 8*60*60*100, timer_limit = -1, text = "Вы очень сыты."},
}
hunger.timers = {}
function hunger.need_to_take(playername)
if minetest.check_player_privs(playername, {["don't starve"] = true})
or minetest.get_player_by_name(playername):is_chat_opened()
then
return false
else
return true
end
end
function hunger.set(player, count)
local inv = player:get_inventory()
inv:set_stack("hunger", 1,
ItemStack({
name = "hunger:counter",
count = 1,
metadata = count
})
)
return tonumber(inv:get_stack("hunger", 1):get_metadata())
end
function hunger.get(player)
local inv = player:get_inventory()
local counter = inv:get_stack("hunger", 1)
if not counter:get_name() then
inv:set_size("hunger", 1)
hunger.set(player, hunger.MAX)
return inv:get_stack("hunger", 1):get_metadata()
end
return counter:get_metadata()
end
function hunger.take(player)
local inv = player:get_inventory()
local count = tonumber(inv:get_stack("hunger", 1):get_metadata())
count = count - 1
return hunger.set(player, count)
end
function hunger.state(count)
for index, state in ipairs(hunger.conf) do
if count > state.bound then
return state
end
end
end
minetest.register_globalstep(function(dtime)
for k, player in pairs(minetest.get_connected_players()) do
local name = player:get_player_name()
if hunger.need_to_take(name) then
local count = hunger.take(player)
local state = hunger.state(count)
if state then
local timer = hunger.timers[name] or 0
timer = timer - 1
if timer < 0 then
hunger.timers[name] = state.timer_limit
elseif timer == 0 then
hunger.timers[name] = state.timer_limit
minetest.chat_send_player(name, state.text)
if state.callback then state.callback() end
else
hunger.timers[name] = timer
end
end
end
end
end)
minetest.register_craftitem("hunger:counter", {})
minetest.register_privilege("don't starve", {
description = "Не снижать значение сытости игрока",
})
minetest.register_on_joinplayer(function(player)
local inv = player:get_inventory()
if not inv:get_list("hunger") then
inv:set_size("hunger", 1)
hunger.set(player, hunger.MAX)
end
end)
| gpl-3.0 |
AnySDK/Sample_JSB | frameworks/js-bindings/cocos2d-x/plugin/luabindings/auto/api/FacebookAgent.lua | 16 | 1731 |
--------------------------------
-- @module FacebookAgent
-- @parent_module plugin
--------------------------------
-- brief Notifies the events system that the app has launched & logs an activatedApp event.
-- @function [parent=#FacebookAgent] activateApp
-- @param self
--------------------------------
-- brief get permissoin list
-- @function [parent=#FacebookAgent] getPermissionList
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- brief get UserID
-- @function [parent=#FacebookAgent] getUserID
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- brief log out
-- @function [parent=#FacebookAgent] logout
-- @param self
--------------------------------
--
-- @function [parent=#FacebookAgent] getSDKVersion
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- brief Check whether the user logined or not
-- @function [parent=#FacebookAgent] isLoggedIn
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- brief get AccessToken
-- @function [parent=#FacebookAgent] getAccessToken
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- Destroy singleton of FacebookAgent
-- @function [parent=#FacebookAgent] destroyInstance
-- @param self
--------------------------------
-- Get singleton of FacebookAgent
-- @function [parent=#FacebookAgent] getInstance
-- @param self
-- @return plugin::FacebookAgent#plugin::FacebookAgent ret (return value: cc.plugin::FacebookAgent)
return nil
| mit |
mortezamosavy999/monster | plugins/stats.lua | 458 | 4098 | -- Saves the number of messages from a user
-- Can check the number of messages with !stats
do
local NUM_MSG_MAX = 5
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end | gpl-2.0 |
anvilvapre/OpenRA | mods/ra/maps/monster-tank-madness/monster-tank-madness.lua | 10 | 14601 | AlliedUnits =
{
{ delay = 0, types = { "1tnk", "1tnk", "2tnk", "2tnk" } },
{ delay = DateTime.Seconds(3), types = { "e1", "e1", "e1", "e3", "e3" } },
{ delay = DateTime.Seconds(7), types = { "e6" } }
}
ReinforceBaseUnits = { "1tnk", "1tnk", "2tnk", "arty", "arty" }
CivilianEvacuees = { "c1", "c2", "c5", "c7", "c8" }
USSROutpostFlameTurrets = { FlameTurret1, FlameTurret2 }
ExplosiveBarrels = { ExplosiveBarrel1, ExplosiveBarrel2 }
SuperTanks = { stnk1, stnk2, stnk3 }
SuperTankMoveWaypoints = { HospitalSuperTankPoint, AlliedBaseBottomRight, DemitriTriggerAreaCenter, DemitriLZ }
SuperTankMove = 1
SuperTankHuntWaypoints = { SuperTankHuntWaypoint1, SuperTankHuntWaypoint2, SuperTankHuntWaypoint3, SuperTankHuntWaypoint4 }
SuperTankHunt = 1
SuperTankHuntCounter = 1
ExtractionHeli = "tran"
ExtractionWaypoint = CPos.New(DemitriLZ.Location.X, 0)
ExtractionLZ = DemitriLZ.Location
BeachTrigger = { CPos.New(19, 44), CPos.New(20, 44), CPos.New(21, 44), CPos.New(22, 44), CPos.New(22, 45), CPos.New(23, 45), CPos.New(22, 44), CPos.New(24, 45), CPos.New(24, 46), CPos.New(24, 47), CPos.New(25, 47), CPos.New(25, 48) }
DemitriAreaTrigger = { CPos.New(32, 98), CPos.New(32, 99), CPos.New(33, 99), CPos.New(33, 100), CPos.New(33, 101), CPos.New(33, 102), CPos.New(32, 102), CPos.New(32, 103) }
HospitalAreaTrigger = { CPos.New(43, 41), CPos.New(44, 41), CPos.New(45, 41), CPos.New(46, 41), CPos.New(46, 42), CPos.New(46, 43), CPos.New(46, 44), CPos.New(46, 45), CPos.New(46, 46), CPos.New(45, 46), CPos.New(44, 46), CPos.New(43, 46) }
EvacuateCivilians = function()
local evacuees = Reinforcements.Reinforce(neutral, CivilianEvacuees, { HospitalCivilianSpawnPoint.Location }, 0)
Trigger.OnAnyKilled(evacuees, function()
player.MarkFailedObjective(RescueCivilians)
end)
Trigger.OnAllRemovedFromWorld(evacuees, function()
player.MarkCompletedObjective(RescueCivilians)
end)
Utils.Do(evacuees, function(civ)
Trigger.OnIdle(civ, function()
if civ.Location == AlliedBaseEntryPoint.Location then
civ.Destroy()
else
civ.Move(AlliedBaseEntryPoint.Location)
end
end)
end)
end
SpawnAndMoveAlliedBaseUnits = function()
Media.PlaySpeechNotification(player, "ReinforcementsArrived")
Reinforcements.Reinforce(player, ReinforceBaseUnits, { AlliedBaseEntryPoint.Location, AlliedBaseMovePoint.Location }, 18)
end
SetupAlliedBase = function()
local alliedOutpost = Map.ActorsInBox(AlliedBaseTopLeft.CenterPosition, AlliedBaseBottomRight.CenterPosition,
function(self) return self.Owner == outpost end)
Media.PlaySoundNotification(player, "BaseSetup")
Utils.Do(alliedOutpost, function(building)
building.Owner = player
end)
AlliedBaseHarv.Owner = player
AlliedBaseHarv.FindResources()
FindDemitri = player.AddPrimaryObjective("Find Dr. Demitri. He is likely hiding in the village\n to the far south.")
InfiltrateRadarDome = player.AddPrimaryObjective("Reprogram the super tanks by sending a spy into\n the Soviet radar dome.")
DefendOutpost = player.AddSecondaryObjective("Defend and repair our outpost.")
player.MarkCompletedObjective(FindOutpost)
Trigger.AfterDelay(DateTime.Seconds(1), function() -- don't fail the Objective instantly
Trigger.OnAllRemovedFromWorld(alliedOutpost, function() player.MarkFailedObjective(DefendOutpost) end)
end)
Trigger.AfterDelay(DateTime.Minutes(1) + DateTime.Seconds(40), function()
if not SuperTankDomeIsInfiltrated then
SuperTankAttack = true
Utils.Do(SuperTanks, function(tnk)
if not tnk.IsDead then
Trigger.ClearAll(tnk)
Trigger.AfterDelay(0, function()
Trigger.OnIdle(tnk, function()
if SuperTankAttack then
if tnk.Location == SuperTankMoveWaypoints[SuperTankMove].Location then
SuperTankMove = SuperTankMove + 1
if SuperTankMove == 5 then
SuperTankAttack = false
end
else
tnk.AttackMove(SuperTankMoveWaypoints[SuperTankMove].Location, 2)
end
end
end)
end)
end
end)
end
end)
end
SendAlliedUnits = function()
InitObjectives()
Camera.Position = StartEntryPoint.CenterPosition
Media.PlaySpeechNotification(player, "ReinforcementsArrived")
Utils.Do(AlliedUnits, function(table)
Trigger.AfterDelay(table.delay, function()
local units = Reinforcements.Reinforce(player, table.types, { StartEntryPoint.Location, StartMovePoint.Location }, 18)
Utils.Do(units, function(unit)
if unit.Type == "e6" then
Engineer = unit
Trigger.OnKilled(unit, LandingPossible)
end
end)
end)
end)
Trigger.AfterDelay(DateTime.Seconds(1), function() InitialUnitsArrived = true end)
end
LandingPossible = function()
if not beachReached and (USSRSpen.IsDead or Engineer.IsDead) and LstProduced < 1 then
player.MarkFailedObjective(CrossRiver)
end
end
SuperTankDomeInfiltrated = function()
SuperTankAttack = true
Utils.Do(SuperTanks, function(tnk)
tnk.Owner = friendlyMadTanks
if not tnk.IsDead then
Trigger.ClearAll(tnk)
tnk.Stop()
if tnk.Location.Y > 61 then
SuperTankHunt = 4
SuperTankHuntCounter = -1
end
Trigger.AfterDelay(0, function()
Trigger.OnIdle(tnk, function()
if SuperTankAttack then
if tnk.Location == SuperTankHuntWaypoints[SuperTankHunt].Location then
SuperTankHunt = SuperTankHunt + SuperTankHuntCounter
if SuperTankHunt == 0 or SuperTankHunt == 5 then
SuperTankAttack = false
end
else
tnk.AttackMove(SuperTankHuntWaypoints[SuperTankHunt].Location, 2)
end
else
tnk.Hunt()
end
end)
end)
end
end)
player.MarkCompletedObjective(InfiltrateRadarDome)
Trigger.AfterDelay(DateTime.Minutes(3), SuperTanksDestruction)
ticked = DateTime.Minutes(3)
Trigger.AfterDelay(DateTime.Seconds(2), function()
Media.PlaySpeechNotification(player, "ControlCenterDeactivated")
Trigger.AfterDelay(DateTime.Seconds(4), function()
Media.DisplayMessage("In 3 minutes the super tanks will self-destruct.")
Media.PlaySpeechNotification(player, "WarningThreeMinutesRemaining")
end)
end)
end
SuperTanksDestruction = function()
local badGuys = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == badguy and self.HasProperty("Health") end)
Utils.Do(badGuys, function(unit)
unit.Kill()
end)
Utils.Do(SuperTanks, function(tnk)
if not tnk.IsDead then
local camera = Actor.Create("camera", true, { Owner = player, Location = tnk.Location })
Trigger.AfterDelay(DateTime.Seconds(3), camera.Destroy)
Trigger.ClearAll(tnk)
tnk.Kill()
end
end)
player.MarkCompletedObjective(DefendOutpost)
end
CreateDemitri = function()
local demitri = Actor.Create("demitri", true, { Owner = player, Location = DemitriChurchSpawnPoint.Location })
demitri.Move(DemitriTriggerAreaCenter.Location)
Media.PlaySpeechNotification(player, "TargetFreed")
EvacuateDemitri = player.AddPrimaryObjective("Evacuate Dr. Demitri with the helicopter waiting\n at our outpost.")
player.MarkCompletedObjective(FindDemitri)
local flarepos = CPos.New(DemitriLZ.Location.X, DemitriLZ.Location.Y - 1)
local demitriLZFlare = Actor.Create("flare", true, { Owner = player, Location = flarepos })
Trigger.AfterDelay(DateTime.Seconds(3), function() Media.PlaySpeechNotification(player, "SignalFlareNorth") end)
local demitriChinook = Reinforcements.ReinforceWithTransport(player, ExtractionHeli, nil, { ExtractionWaypoint, ExtractionLZ })[1]
Trigger.OnAnyKilled({ demitri, demitriChinook }, function()
player.MarkFailedObjective(EvacuateDemitri)
end)
Trigger.OnRemovedFromWorld(demitriChinook, function()
if not demitriChinook.IsDead then
Media.PlaySpeechNotification(player, "TargetRescued")
Trigger.AfterDelay(DateTime.Seconds(1), function() player.MarkCompletedObjective(EvacuateDemitri) end)
Trigger.AfterDelay(DateTime.Seconds(3), SpawnAndMoveAlliedBaseUnits)
end
end)
Trigger.OnRemovedFromWorld(demitri, function()
if not demitriChinook.IsDead and demitriChinook.HasPassengers then
demitriChinook.Move(ExtractionWaypoint)
Trigger.OnIdle(demitriChinook, demitriChinook.Destroy)
demitriLZFlare.Destroy()
end
end)
end
ticked = -1
Tick = function()
ussr.Resources = ussr.Resources - (0.01 * ussr.ResourceCapacity / 25)
if InitialUnitsArrived then -- don't fail the mission straight at the beginning
if not DemitriFound or not SuperTankDomeIsInfiltrated then
if player.HasNoRequiredUnits() then
player.MarkFailedObjective(EliminateSuperTanks)
end
end
end
if ticked > 0 then
UserInterface.SetMissionText("The super tanks self-destruct in " .. Utils.FormatTime(ticked), TimerColor)
ticked = ticked - 1
elseif ticked == 0 then
FinishTimer()
ticked = ticked - 1
end
end
FinishTimer = function()
for i = 0, 9, 1 do
local c = TimerColor
if i % 2 == 0 then
c = HSLColor.White
end
Trigger.AfterDelay(DateTime.Seconds(i), function() UserInterface.SetMissionText("The super tanks are destroyed!", c) end)
end
Trigger.AfterDelay(DateTime.Seconds(10), function() UserInterface.SetMissionText("") end)
end
SetupMission = function()
TestCamera = Actor.Create("camera" ,true , { Owner = player, Location = ProvingGroundsCameraPoint.Location })
Camera.Position = ProvingGroundsCameraPoint.CenterPosition
TimerColor = player.Color
Trigger.AfterDelay(DateTime.Seconds(12), function()
Media.PlaySpeechNotification(player, "StartGame")
Trigger.AfterDelay(DateTime.Seconds(2), SendAlliedUnits)
end)
end
InitPlayers = function()
player = Player.GetPlayer("Greece")
neutral = Player.GetPlayer("Neutral")
outpost = Player.GetPlayer("Outpost")
badguy = Player.GetPlayer("BadGuy")
ussr = Player.GetPlayer("USSR")
ukraine = Player.GetPlayer("Ukraine")
turkey = Player.GetPlayer("Turkey")
friendlyMadTanks = Player.GetPlayer("FriendlyMadTanks")
player.Cash = 0
ussr.Cash = 2000
Trigger.AfterDelay(0, function() badguy.Resources = badguy.ResourceCapacity * 0.75 end)
Trigger.OnCapture(USSROutpostSilo, function() -- getting money through capturing doesn't work
player.Cash = player.Cash + Utils.RandomInteger(1200, 1300)
end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
EliminateSuperTanks = player.AddPrimaryObjective("Eliminate these super tanks.")
CrossRiver = player.AddPrimaryObjective("Secure transport to the mainland.")
FindOutpost = player.AddPrimaryObjective("Find our outpost and start repairs on it.")
RescueCivilians = player.AddSecondaryObjective("Evacuate all civilians from the hospital.")
BadGuyObj = badguy.AddPrimaryObjective("Deny the destruction of the super tanks.")
USSRObj = ussr.AddPrimaryObjective("Deny the destruction of the super tanks.")
UkraineObj = ukraine.AddPrimaryObjective("Survive.")
TurkeyObj = turkey.AddPrimaryObjective("Destroy.")
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "MissionFailed")
ussr.MarkCompletedObjective(USSRObj)
badguy.MarkCompletedObjective(BadGuyObj)
ukraine.MarkCompletedObjective(UkraineObj)
turkey.MarkCompletedObjective(TurkeyObj)
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "MissionAccomplished")
Media.DisplayMessage("Dr. Demitri has been extracted and the super tanks have been dealt with.")
ussr.MarkFailedObjective(USSRObj)
badguy.MarkFailedObjective(BadGuyObj)
ukraine.MarkFailedObjective(UkraineObj)
turkey.MarkFailedObjective(TurkeyObj)
end)
end
InitTriggers = function()
Trigger.OnAllKilled(SuperTanks, function()
Trigger.AfterDelay(DateTime.Seconds(3), function() player.MarkCompletedObjective(EliminateSuperTanks) end)
end)
Trigger.OnKilled(SuperTankDome, function()
if not SuperTankDomeIsInfiltrated then
player.MarkFailedObjective(InfiltrateRadarDome)
end
end)
Trigger.OnInfiltrated(SuperTankDome, function()
if not SuperTankDomeIsInfiltrated then
SuperTankDomeIsInfiltrated = true
SuperTankDomeInfiltrated()
end
end)
Trigger.OnCapture(SuperTankDome, function()
if not SuperTankDomeIsInfiltrated then
SuperTankDomeIsInfiltrated = true
SuperTankDomeInfiltrated()
end
end)
Trigger.OnKilled(UkraineBarrel, function()
if not UkraineBuilding.IsDead then UkraineBuilding.Kill() end
end)
Trigger.OnAnyKilled(USSROutpostFlameTurrets, function()
Utils.Do(ExplosiveBarrels, function(barrel)
if not barrel.IsDead then barrel.Kill() end
end)
end)
Trigger.OnKilled(DemitriChurch, function()
if not DemitriFound then
player.MarkFailedObjective(FindDemitri)
end
end)
Trigger.OnKilled(Hospital, function()
if not HospitalEvacuated then
HospitalEvacuated = true
player.MarkFailedObjective(RescueCivilians)
end
end)
beachReached = false
Trigger.OnEnteredFootprint(BeachTrigger, function(a, id)
if not beachReached and a.Owner == player then
beachReached = true
Trigger.RemoveFootprintTrigger(id)
player.MarkCompletedObjective(CrossRiver)
end
end)
Trigger.OnPlayerDiscovered(outpost, function(_, discoverer)
if not outpostReached and discoverer == player then
outpostReached = true
SetupAlliedBase()
end
end)
Trigger.OnEnteredFootprint(DemitriAreaTrigger, function(a, id)
if not DemitriFound and a.Owner == player then
DemitriFound = true
Trigger.RemoveFootprintTrigger(id)
CreateDemitri()
end
end)
Trigger.OnEnteredFootprint(HospitalAreaTrigger, function(a, id)
if not HospitalEvacuated and a.Owner == player then
HospitalEvacuated = true
Trigger.RemoveFootprintTrigger(id)
EvacuateCivilians()
end
end)
local tanksLeft = 0
Trigger.OnExitedProximityTrigger(ProvingGroundsCameraPoint.CenterPosition, WDist.New(10 * 1024), function(a, id)
if a.Type == "5tnk" then
tanksLeft = tanksLeft + 1
if tanksLeft == 3 then
if TestCamera.IsInWorld then TestCamera.Destroy() end
Trigger.RemoveProximityTrigger(id)
end
end
end)
LstProduced = 0
Trigger.OnKilled(USSRSpen, LandingPossible)
Trigger.OnProduction(USSRSpen, function(self, produced)
if produced.Type == "lst" then
LstProduced = LstProduced + 1
Trigger.OnKilled(produced, function()
LstProduced = LstProduced - 1
LandingPossible()
end)
end
end)
end
WorldLoaded = function()
InitPlayers()
InitTriggers()
SetupMission()
end
| gpl-3.0 |
kernelsauce/turbo | examples/cookie.lua | 12 | 1061 | --- Turbo.lua Cookie usage example
--
-- Copyright 2013 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local turbo = require "turbo"
local CookieHandler = class("CookieHandler", turbo.web.RequestHandler)
function CookieHandler:get()
local counter = self:get_cookie("counter")
local new_count = counter and tonumber(counter) + 1 or 0
self:set_cookie("counter", new_count)
self:write("Cookie counter is at: " .. new_count)
end
turbo.web.Application({{"^/$", CookieHandler}}):listen(8888)
turbo.ioloop.instance():start()
| apache-2.0 |
kernelsauce/turbo | turbo/fs.lua | 12 | 2093 | --- Turbo.lua file system Module
--
-- Copyright 2013 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local ffi = require "ffi"
local syscall = require "turbo.syscall"
local fs = {}
--- File system constants
fs.NAME_MAX = 255
fs.PATH_MAX = 4096
--- Read out file metadata with a given path
function fs.stat(path, buf)
local stat_t = ffi.typeof("struct stat")
if not buf then buf = stat_t() end
local ret = ffi.C.syscall(syscall.SYS_stat, path, buf)
if ret == -1 then
return -1, ffi.string(ffi.C.strerror(ffi.errno()))
end
return buf
end
--- Check whether a given path is directory
function fs.is_file(path)
local buf, err = fs.stat(path, nil)
if buf == -1 then return false, err end
if bit.band(buf.st_mode, syscall.S_IFREG) == syscall.S_IFREG then
return true
else
return false
end
end
--- Check whether a given path is directory
function fs.is_dir(path)
local buf, err = fs.stat(path, nil)
if buf == -1 then return false, err end
if bit.band(buf.st_mode, syscall.S_IFDIR) == syscall.S_IFDIR then
return true
else
return false
end
end
function fs.glob(pattern)
local re = -1
glob_t = ffi.new("glob_t[1]")
re = ffi.C.glob(pattern, 0, nil, glob_t)
if re ~= 0 then
ffi.C.globfree(glob_t)
return nil
end
local files = {}
local i = 0
while i < glob_t[0].gl_pathc do
table.insert(files, ffi.string(glob_t[0].gl_pathv[i]))
i = i + 1
end
ffi.C.globfree(glob_t)
return files
end
return fs
| apache-2.0 |
DreamHacks/dreamdota | DreamWarcraft/Build Tools/MPQFixEngine/lua/oil/kernel/base/Connector.lua | 6 | 5381 | --------------------------------------------------------------------------------
------------------------------ ##### ## ------------------------------
------------------------------ ## ## # ## ------------------------------
------------------------------ ## ## ## ## ------------------------------
------------------------------ ## ## # ## ------------------------------
------------------------------ ##### ### ###### ------------------------------
-------------------------------- --------------------------------
----------------------- An Object Request Broker in Lua ------------------------
--------------------------------------------------------------------------------
-- Project: OiL - ORB in Lua --
-- Release: 0.5 --
-- Title : Client-side CORBA GIOP Protocol specific to IIOP --
-- Authors: Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
-- Notes: --
-- See section 15.7 of CORBA 3.0 specification. --
-- See section 13.6.10.3 of CORBA 3.0 specification for IIOP corbaloc. --
--------------------------------------------------------------------------------
-- channels:Facet
-- channel:object retieve(configs:table, [probe:boolean])
--
-- sockets:Receptacle
-- socket:object tcp()
-- input:table, output:table select([input:table], [output:table], [timeout:number])
--------------------------------------------------------------------------------
local next = next
local pairs = pairs
local setmetatable = setmetatable
local type = type
local tabop = require "loop.table"
local ObjectCache = require "loop.collection.ObjectCache"
local Wrapper = require "loop.object.Wrapper"
local Channels = require "oil.kernel.base.Channels"
local oo = require "oil.oo" --[[VERBOSE]] local verbose = require "oil.verbose"
module "oil.kernel.base.Connector"
oo.class(_M, Channels)
--------------------------------------------------------------------------------
-- connection management
LuaSocketOps = tabop.copy(Channels.LuaSocketOps)
CoSocketOps = tabop.copy(Channels.CoSocketOps)
function LuaSocketOps:close()
local ports = self.factory.cache[self.host]
ports[self.port] = nil
if next(ports) == nil then
self.factory.cache[self.host] = nil
end
return self.__object:close()
end
CoSocketOps.close = LuaSocketOps.close
function LuaSocketOps:reset() --[[VERBOSE]] verbose:channels("resetting channel (attempt to reconnect)")
self.__object:close()
local sockets = self.factory.sockets
local result, errmsg = sockets:tcp()
if result then
local socket = result
result, errmsg = socket:connect(self.host, self.port)
if result then
self.__object = socket
end
end
return result, errmsg
end
function CoSocketOps:reset() --[[VERBOSE]] verbose:channels("resetting channel (attempt to reconnect)")
self.__object:close()
local sockets = self.factory.sockets
local result, errmsg = sockets:tcp()
if result then
local socket = result
result, errmsg = socket:connect(self.host, self.port)
if result then
self.__object = socket.__object
end
end
return result, errmsg
end
local list = {}
function LuaSocketOps:probe()
list[1] = self.__object
return self.factory.sockets:select(list, nil, 0)[1] == list[1]
end
function CoSocketOps:probe()
local list = { self }
return self.factory.sockets:select(list, nil, 0)[1] == list[1]
end
--------------------------------------------------------------------------------
-- channel cache for reuse
SocketCache = oo.class{ __index = ObjectCache.__index, __mode = "v" }
function __init(self, object)
self = oo.rawnew(self, object)
--
-- cache of active channels
-- self.cache[host][port] == <channel to host:port>
--
self.cache = ObjectCache()
function self.cache.retrieve(_, host)
local cache = SocketCache()
function cache.retrieve(_, port)
local sockets = self.sockets
local socket, errmsg = sockets:tcp()
if socket then --[[VERBOSE]] verbose:channels("new socket to ",host,":",port)
local success
success, errmsg = socket:connect(host, port)
if success then
socket = self:setupsocket(socket)
socket.factory = self
socket.host = host
socket.port = port
return socket
else
self.except = "connection refused"
end
else
self.except = "too many open connections"
end
end
cache[cache.retrieve] = true -- avoid being collected as unused sockets
return cache
end
return self
end
--------------------------------------------------------------------------------
-- channel factory
function retrieve(self, profile) --[[VERBOSE]] verbose:channels("retrieve channel connected to ",profile.host,":",profile.port)
local channel = self.cache[profile.host][profile.port]
if channel then
return channel
else
return nil, self.except
end
end
| mit |
nwf/nodemcu-firmware | lua_modules/bh1750/bh1750_Example2.lua | 7 | 1765 | -- ***************************************************************************
-- BH1750 Example Program for ESP8266 with nodeMCU
-- BH1750 compatible tested 2015-1-30
--
-- Written by xiaohu
--
-- MIT license, http://opensource.org/licenses/MIT
-- ***************************************************************************
--Updata to Lelian
--Ps 需要改动的地方LW_GATEWAY(乐联的设备标示),USERKEY(乐联userkey)
--Ps You nees to rewrite the LW_GATEWAY(Lelian's Device ID),USERKEY(Lelian's userkey)
local bh1750 = require("bh1750")
local sda = 6 -- sda pin, GPIO12
local scl = 5 -- scl pin, GPIO14
local ServerIP
do
bh1750.init(sda, scl)
tmr.create():alarm(60000, tmr.ALARM_AUTO, function()
bh1750.read()
local l = bh1750.getlux()
--定义数据变量格式 Define the veriables formate
local PostData = "[{\"Name\":\"T\",\"Value\":\"" ..(l / 100).."."..(l % 100).."\"}]"
--创建一个TCP连接 Create a TCP Connection
local socket = net.createConnection(net.TCP, 0)
--域名解析IP地址并赋值 DNS...it
socket:dns("www.lewei50.com", function(_, ip)
ServerIP = ip
print("Connection IP:" .. ServerIP)
end)
--开始连接服务器 Connect the sever
socket:connect(80, ServerIP)
socket:on("connection", function() end)
--HTTP请求头定义 HTTP Head
socket:send("POST /api/V1/gateway/UpdateSensors/LW_GATEWAY HTTP/1.1\r\n" ..
"Host: www.lewei50.com\r\n" ..
"Content-Length: " .. string.len(PostData) .. "\r\n" ..
"userkey: USERKEY\r\n\r\n" ..
PostData .. "\r\n")
--HTTP响应内容 Print the HTTP response
socket:on("receive", function(sck, response) -- luacheck: no unused
print(response)
end)
end)
end
| mit |
qskycolor/wax | lib/stdlib/helpers/cache.lua | 19 | 1993 | wax.cache = {}
setmetatable(wax.cache, wax.cache)
-- Returns contents of cache keys
-- key: string # value for cache
-- maxAge: number (optional) # max age of file in seconds
function wax.cache.get(key, maxAge)
local path = wax.cache.pathFor(key)
if not wax.filesystem.isFile(path) then return nil end
if maxAge then
local fileAge = os.time() - wax.filesystem.attributes(path).modifiedAt
if fileAge > maxAge then
return nil
end
end
local success, result = pcall(function()
return NSKeyedUnarchiver:unarchiveObjectWithFile(path)
end)
if not success then -- Bad cache
puts("Error: Couldn't read cache with key %s", key)
wax.cache.clear(key)
return nil
else
return result
end
end
-- Creates a cache for the key with contents
-- key: string # value for the cache
-- contents: object # whatever is NSKeyedArchive compatible
function wax.cache.set(key, contents)
local path = wax.cache.pathFor(key)
if not contents then -- delete the value from the cache
wax.cache.clear(key)
else
local success = NSKeyedArchiver:archiveRootObject_toFile(contents, path)
if not success then puts("Couldn't archive cache '%s' to '%s'", key, path) end
end
end
function wax.cache.age(key)
local path = wax.cache.pathFor(key)
-- If there is no file, just send them back a really big age. Cleaner than
-- dealing with nils
if not wax.filesystem.isFile(path) then return wax.time.days(1000) end
local fileAge = os.time() - wax.filesystem.attributes(path).modifiedAt
return fileAge
end
-- Removes specific keys from cache
function wax.cache.clear(...)
for i, key in ipairs({...}) do
local path = wax.cache.pathFor(key)
wax.filesystem.delete(path)
end
end
-- Removes entire cache dir
function wax.cache.clearAll()
wax.filesystem.delete(NSCacheDirectory)
wax.filesystem.createDir(NSCacheDirectory)
end
function wax.cache.pathFor(key)
return NSCacheDirectory .. "/" .. wax.base64.encode(key)
end | mit |
DaanHaaz/love-base | scripts/libs/autobatch.lua | 1 | 5280 | --
-- autobatch.lua
--
-- Copyright (c) 2016 rxi
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the MIT license. See LICENSE for details.
--
local autobatch = { _version = "0.0.0" }
setmetatable(autobatch, { __index = love.graphics })
-- Use a local reference of love.graphics as love.graphics will be overwritten
-- with this module
local love_graphics = love.graphics
autobatch.threshold = 4
autobatch.batches = setmetatable( {}, { __mode = "k" } )
autobatch.pending = { image = nil, draws = 0 }
autobatch.color = { 255, 255, 255 }
autobatch.image = nil
local function switchActiveImage(img)
-- Draw and reset old image's spritebatch if we have one; if not we set love's
-- color state as the spritebatch's color state will be used instead
if autobatch.image then
local b = autobatch.batches[autobatch.image]
love_graphics.draw(b.sb)
b.sb:clear()
b.count = 0
else
love_graphics.setColor(255, 255, 255)
end
-- Activate spritebatch if image was not nil
if img then
local b = autobatch.batches[img]
-- Create batch if it doesn't exist
if not b then
b = {}
b.count = 0
b.capacity = 16
b.sb = love_graphics.newSpriteBatch(img, b.capacity, "stream")
autobatch.batches[img] = b
end
-- Init spritebatch's color
b.sb:setColor( unpack(autobatch.color) )
end
-- Set new image
autobatch.image = img
end
local function flushAndDraw(...)
autobatch.flush()
return love_graphics.draw(...)
end
function autobatch.draw(image, ...)
-- Only Textures (Image or Canvas) can be batched -- if the image is neither
-- of these then we draw normally instead
if not image:typeOf("Texture") then
return flushAndDraw(image, ...)
end
-- Check if the image already has a batch -- if it doesn't we check to see if
-- it's the pending image, and whether it's reached the draw count threshold;
-- if so we can switch to it as the active image and create a batch for it,
-- otherwise we just increment the count and draw it normally
if not autobatch.batches[image] then
if image == autobatch.pending.image then
autobatch.pending.draws = autobatch.pending.draws + 1
if autobatch.pending.draws < autobatch.threshold then
return flushAndDraw(image, ...)
end
else
autobatch.pending.image = image
autobatch.pending.draws = 1
return flushAndDraw(image, ...)
end
end
-- Reset pending image
autobatch.pending.image = nil
-- Switch active image if this isn't it
if image ~= autobatch.image then
switchActiveImage(image)
end
-- Get active batch
local b = autobatch.batches[autobatch.image]
-- Increase spritebatch capacity if we've reached it
if b.count == b.capacity then
b.capacity = b.capacity * 2
b.sb:setBufferSize(b.capacity)
end
-- Add to spritebatch
b.sb:add(...)
b.count = b.count + 1
end
function autobatch.setColor(r, g, b, a)
local t = autobatch.color
-- Exit early if color isn't different to the current color
if t[1] == r and t[2] == g and t[3] == b and t[4] == a then
return
end
-- Set active color
t[1], t[2], t[3], t[4] = r, g, b, a
-- Set active color on active spritebatch or in love.graphics if no
-- image is active
local b = autobatch.batches[autobatch.image]
if b then
b.sb:setColor( unpack(autobatch.color) )
else
love_graphics.setColor( unpack(autobatch.color) )
end
end
function autobatch.getColor()
return unpack(autobatch.color)
end
function autobatch.reset()
autobatch.flush()
autobatch.setColor(255, 255, 255, 255)
love_graphics.reset()
end
function autobatch.flush()
-- If we have an active image set switch from it to draw the active batch and
-- reset love's color to match our internal one
if autobatch.image then
switchActiveImage(nil)
love_graphics.setColor( unpack(autobatch.color) )
end
end
local function wrap(fn)
return function(...)
autobatch.flush()
return fn(...)
end
end
-- Initialise wrapper functions for all graphics functions which change the
-- state or draw to the screen, thus requiring that the autobatch be flushed
-- prior. reset() and setColor() are special cases handled above
local names = {
"arc",
"circle",
"clear",
"discard",
"ellipse",
"line",
"points",
"polygon",
"present",
"print",
"printf",
"rectangle",
"stencil",
"setBlendMode",
"setCanvas",
"setColorMask",
"setScissor",
"setShader",
"setStencilTest",
"origin",
"pop",
"push",
"rotate",
"scale",
"shear",
"translate",
}
for i, name in ipairs(names) do
autobatch[name] = wrap( love_graphics[name] )
end
-- Override love.graphics
love.graphics = autobatch
-- Override Canvas:renderTo() and Canvas:getPixel()
local mt = getmetatable( love_graphics.newCanvas(1, 1) )
local fn = mt.renderTo
mt.renderTo = function(self, fn)
local old = { autobatch.getCanvas() }
autobatch.setCanvas(self)
fn()
autobatch.setCanvas( unpack(old) )
end
mt.getPixel = wrap(mt.getPixel)
return autobatch | mit |
xponen/Zero-K | LuaRules/Configs/MetalSpots/haunteddowns.lua | 17 | 4541 | return {
spots = {
{x = 3240, z = 904, metal = 1.3},
{x = 7128, z = 4088, metal = 1.3},
{x = 3112, z = 3272, metal = 1.3},
{x = 8424, z = 4216, metal = 1.3},
{x = 4808, z = 1688, metal = 1.3},
{x = 312, z = 4888, metal = 1.3},
{x = 10056, z = 1384, metal = 1.3},
{x = 9336, z = 312, metal = 1.3},
{x = 10040, z = 216, metal = 1.3},
{x = 4056, z = 152, metal = 1.3},
{x = 296, z = 2568, metal = 1.3},
{x = 5464, z = 888, metal = 1.3},
{x = 4856, z = 824, metal = 1.3},
{x = 5448, z = 152, metal = 1.3},
{x = 200, z = 4952, metal = 1.3},
{x = 10088, z = 4968, metal = 1.3},
{x = 10072, z = 3960, metal = 1.3},
{x = 4792, z = 2872, metal = 1.3},
{x = 1816, z = 3096, metal = 1.3},
{x = 5464, z = 2184, metal = 1.3},
{x = 6088, z = 2168, metal = 1.3},
{x = 3064, z = 1848, metal = 1.3},
{x = 10072, z = 3768, metal = 1.3},
{x = 200, z = 2680, metal = 1.3},
{x = 4120, z = 3480, metal = 1.3},
{x = 6104, z = 4200, metal = 1.3},
{x = 1912, z = 4696, metal = 1.3},
{x = 200, z = 3752, metal = 1.3},
{x = 296, z = 1304, metal = 1.3},
{x = 5432, z = 4856, metal = 1.3},
{x = 6104, z = 936, metal = 1.3},
{x = 4728, z = 4168, metal = 1.3},
{x = 200, z = 1368, metal = 1.3},
{x = 4792, z = 2168, metal = 1.3},
{x = 7080, z = 824, metal = 1.3},
{x = 4152, z = 2168, metal = 1.3},
{x = 1912, z = 312, metal = 1.3},
{x = 4120, z = 888, metal = 1.3},
{x = 4824, z = 3432, metal = 1.3},
{x = 1896, z = 4184, metal = 1.3},
{x = 296, z = 248, metal = 1.3},
{x = 4104, z = 2920, metal = 1.3},
{x = 5448, z = 3512, metal = 1.3},
{x = 10072, z = 2632, metal = 1.3},
{x = 10072, z = 1208, metal = 1.3},
{x = 8392, z = 4920, metal = 1.3},
{x = 9960, z = 4888, metal = 1.3},
{x = 9944, z = 2584, metal = 1.3},
{x = 8360, z = 3224, metal = 1.3},
{x = 9352, z = 4840, metal = 1.3},
{x = 5464, z = 2904, metal = 1.3},
{x = 2984, z = 4760, metal = 1.3},
{x = 7064, z = 312, metal = 1.3},
{x = 10040, z = 344, metal = 1.3},
{x = 7080, z = 1928, metal = 1.3},
{x = 1880, z = 1880, metal = 1.3},
{x = 6088, z = 2904, metal = 1.3},
{x = 10088, z = 4840, metal = 1.3},
{x = 10072, z = 2504, metal = 1.3},
{x = 6136, z = 3512, metal = 1.3},
{x = 6136, z = 4824, metal = 1.3},
{x = 4024, z = 4024, metal = 1.3},
{x = 920, z = 4808, metal = 1.3},
{x = 9992, z = 1288, metal = 1.3},
{x = 7128, z = 4808, metal = 1.3},
{x = 6088, z = 1656, metal = 1.3},
{x = 6104, z = 296, metal = 1.3},
{x = 216, z = 4808, metal = 1.3},
{x = 904, z = 296, metal = 1.3},
{x = 296, z = 3864, metal = 1.3},
{x = 200, z = 3944, metal = 1.3},
{x = 9992, z = 3864, metal = 1.3},
{x = 3240, z = 4152, metal = 1.3},
{x = 4808, z = 4840, metal = 1.3},
{x = 4168, z = 1592, metal = 1.3},
{x = 8392, z = 296, metal = 1.3},
{x = 232, z = 1208, metal = 1.3},
{x = 1752, z = 888, metal = 1.3},
{x = 200, z = 168, metal = 1.3},
{x = 5448, z = 1688, metal = 1.3},
{x = 7080, z = 3160, metal = 1.3},
{x = 200, z = 2488, metal = 1.3},
{x = 4792, z = 184, metal = 1.3},
{x = 9944, z = 280, metal = 1.3},
{x = 3128, z = 424, metal = 1.3},
{x = 4120, z = 4856, metal = 1.3},
{x = 8344, z = 1896, metal = 1.3},
{x = 5496, z = 4280, metal = 1.3},
{x = 200, z = 296, metal = 1.3},
}
} | gpl-2.0 |
D3vMa3sTrO/superbot | plugins/helpall.lua | 1 | 9034 | --[[
_ _ _ _____ _____ ____ ____
/ \ / \ / \ | ____|___|_ _| /_\ \ / __ \ Đєⱴ 💀: @MaEsTrO_0
/ / \/ / \ / _ \ | _| / __| | | | |_\_/| | | | Đєⱴ 💀: @devmaestr0
/ / \ \/ \ \ / ___ \| |___\__ \ | | | | \ \| |__| | Đєⱴ ฿๏ͳ💀: @iqMaestroBot
/_/ \/ \_/_/ \_|_____|___/ |_| |_| \_\\____/ Đєⱴ ฿๏ͳ💀: @maestr0bot
Đєⱴ Ϲḫ₳ͷͷєℓ💀: @DevMaestro
—]]
do
function run(msg, matches)
if matches[1] == "الاوامر" and is_momod(msg) then
return "اهلا وسهلا بك ☠ "..msg.from.first_name.."\n"
.." ".."\n"
..[[
▫️ اهلا وسهلا عزيزي هناك 5 اوامر في بوت
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
▫️ م1 | لعرض اوامر الادمنيه و المدير🏌
▫️م2 | لعرض اوامر الميديا🏌
▫️ م3 | لعرض اوامر حماية 🏌
▫️م4 | لعرض اوامر بالتحذير🏌
▫️ م5 | لعرض اوامر المجموعه 🏌
▫️ م6 | لعرض اوامر المطورين 🏌
]].."\n"
.."☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ".."\n"
..'|☠| Ϲḫ₳ͷͷєℓ | @DevMaestro '..'\n'
------------------
elseif matches[1] == "م1" and is_momod(msg) then
return "اهلا وسهلا بك ☠ "..msg.from.first_name.."\n"
.." ".."\n"
..[[
☠ اوامر المشرفين في المجموعة ☠
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
▫️ رفع ادمن
▫️ لرفع ادمن رد + معرف
▫️ تنزيل ادمن
▫️ لرفع ادمن رد + معرف
▫️ رفع اداري
▫️ لرفع اداري رد + معرف
▫️ تنزيل اداري
▫️لرفع اداري رد + معرف
▫️ حظر
▫️ حظر عضو من المجموعه
▫️ الغاء حظر
▫️ الغاء الحظر عن عضو
▫️ منع + الكلمه
▫️ منع كلمه
▫️ الغاء منع + الكلمه
▫️ الغاء منع كلمه
▫️ قائمه المنع
▫️ اظهار الكلمات الممنوعه
▫️ تنظيف قائمه المنع
▫️ لمسح كل قائمه المنع
▫️ ايدي
▫️ عرض ايدي المجموعه
▫️ ايدي بالرد
▫️ عرض ايدي شخص
▫️ كتم
▫️ لكتم عضو رد + معرف + ايدي
▫️ المكتومين
▫️ لعرض قائمه المكتومين
▫️ ضع ترحيب
▫️ لوضع ترحيب للمجموعه
▫️ حذف الترحيب
▫️ لحذف الترحيب للمجموعه
]].."\n"
.."☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ".."\n"
..'|☠| Ϲḫ₳ͷͷєℓ | @DevMaestro '..'\n'
------------------
elseif matches[1] == "م2" and is_momod(msg) then
return "اهلا وسهلا بك ☠ "..msg.from.first_name.."\n"
.." ".."\n"
..[[
اوامـر تخص الميديا🏌
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
قفل 🔐 + الامر : للقفل 🏌
فتح🔓 + الامر : للفتح 🏌
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
▫️ الصوت 🔊
▫️ الصور 📸
▫️ الفيديو 🎥
▫️ المتحركه 🃏
▫️ الفايلات 📚
▫️ الدردشه🗯
▫️ التعديل📝
]].."\n"
.."☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ".."\n"
..'|☠| Ϲḫ₳ͷͷєℓ | @DevMaestro '..'\n'
------------------
elseif matches[1] == "م3" and is_momod(msg) then
return "اهلا وسهلا بك ☠ "..msg.from.first_name.."\n"
.." ".."\n"
..[[
☠اوامـــر تخص الحمايه☠
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
قفل🔐 + الامر : للقفل 🏌
فتح🔓 + الامر : للفتح 🏌
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
▫️ الانلاين 🔊
▫️الكلايش 🚯
▫️ التكرار 📑
▫️ الطرد ⚠️
▫️ العربيه 🆎
▫️ الجهات 📱
▫️ المعرف📌
▫️ التاك📑
▫️ الشارحه〽️
▫️ الاضافه👥
▫️ الروابط ♻️
▫️ البوتات 🤖
▫️ السمايل 😢
▫️ الملصقات 🔐
▫️ الاشعارات 🔔
▫️ اعاده توجيه↪️
▫️ الدخول🚶
▫️ الجماعيه 👥
]].."\n"
.."☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ".."\n"
..'|☠| Ϲḫ₳ͷͷєℓ | @DevMaestro '..'\n'
------------------
elseif matches[1] == "م4" and is_momod(msg) then
return "اهلا وسهلا بك ☠ "..msg.from.first_name.."\n"
.." ".."\n"
..[[
🏌 اوامـر تخص القفل والفتح 🏌
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
قفل 🔐+ الامر: للقفل 🏌
فتح 🔓+ الامر :للفتح 🏌
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
▫️ الروابط بالتحذير ⚠️
▫️ التوجيه بالتحذير ↪️
▫️ الصور بالتحذير📸
▫️ الصوت بالتحذير📣
▫️ الفيديو بالتحذير 🎥
▫️ الدردشه بالتحذير📑
▫️ المعرف بالتحذير📌
▫️ الشارحه بالتحذير〽️
▫️ الانلاين بالتحذير 📡
▫️ التاك بالتحذير 🌀
▫️ السمايل بالتحذير😢
▫️ الميديا بالتحذير⚠️
]].."\n"
.."☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ".."\n"
..'|☠| Ϲḫ₳ͷͷєℓ | @DevMaestro '..'\n'
------------------------
elseif matches[1] == "م5" and is_momod(msg) then
return "اهلا وسهلا بك ☠ "..msg.from.first_name.."\n"
.." ".."\n"
..[[
▫️- اوامــر تــخــص ادارة المجموعه🏌
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
▫️ ضع صوره
▫️ لوضع صوره
▫️ ضع قوانين
▫️لوضع قوانين
▫️ ضع وصف
▫️ لوضع وصف
▫️ضع اسم
▫️لوضع اسم
▫️ ضع معرف
▫️ لوضع معرف
▫️ ضع رابط
▫️ لخزن رابط المجموعه
▫️الرابط
▫️لعرض رابط المجموعه
▫️ معلوماتي
▫️ لعرض معلوماتك
▫️معلومات المجموعه
▫️لعرض معلومات المجموعه
▫️ اعدادت الوسائط
▫️ لاضهار الاعدادات الوسائط
]].."\n"
.."☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ".."\n"
..'|☠| Ϲḫ₳ͷͷєℓ | @DevMaestro '..'\n'
-----------------------
elseif matches[1] == "م6" and is_sudo(msg) then
return "اهلا وسهلا بك ☠ "..msg.from.first_name.."\n"
.." ".."\n"
..[[
▫️اوامر تخص المطورين 🕵
☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ
▫️تفعيل
▫️ لتفعيل البوت بالمجموعه
▫️ تعطيل
▫️لتعطيل البوت بالمجموعه
▫️ رفع المدير
▫️ لرفع المدير عن طريق الرد + معرف
▫️ وضع وقت + عدد الايام
▫️ لتفعيل البوت ع عدد الايام
▫️ الوقت
▫️ لمعرفت عدد ايام تفعيل البوت
▫️ اذاعه
▫️ لنشر شئ بكل مجموعات البوت
▫️زحلك
▫️ لطرد البوت من المجموعه
▫️جلب ملف + اسم الملف
▫️ لجلب ملف من سيرفر البوت
▫️ تفعيل + اسم الملف
▫️ لتفعيل ملف عن طريق البوت
▫️ تعطيل + اسم للملف
▫️ لتعطيل ملف عن طريق البوت
▫️ صنع مجموعه + الاسم
▫️ لصنع مجموعه بواسطه البوت
▫️ ترقيه سوبر
▫️لترقيه المجموعه بواسطه البوت
]].."\n"
.."☠›› ﴿❗️﴿ الم̷ـــِْاي̷سـஓـتـــروِْ﴾️❗️ ﴾ ‹‹☠ـ".."\n"
..'|☠| Ϲḫ₳ͷͷєℓ | @DevMaestro '..'\n'
------------------
end
end
return {
patterns = {
"^(الاوامر)",
"^(م1)",
"^(م2)",
"^(م3)",
"^(م4)",
"^(م5)",
"^(م6)",
"^[#!/](الاوامر)",
"^[#!/](م1)",
"^[#!/](م2)",
"^[#!/](م3)",
"^[#!/](م4)",
"^[#!/](م5)",
"^[#!/](م6)"
},
run = run
}
end
| gpl-2.0 |
alexandergall/snabbswitch | src/apps/lwaftr/lwaftr.lua | 2 | 47737 | module(..., package.seeall)
local bt = require("apps.lwaftr.binding_table")
local constants = require("apps.lwaftr.constants")
local lwdebug = require("apps.lwaftr.lwdebug")
local lwutil = require("apps.lwaftr.lwutil")
local checksum = require("lib.checksum")
local datagram = require("lib.protocol.datagram")
local ethernet = require("lib.protocol.ethernet")
local ipv4 = require("lib.protocol.ipv4")
local ipv6 = require("lib.protocol.ipv6")
local counter = require("core.counter")
local packet = require("core.packet")
local lib = require("core.lib")
local link = require("core.link")
local engine = require("core.app")
local bit = require("bit")
local ffi = require("ffi")
local alarms = require("lib.yang.alarms")
local CounterAlarm = alarms.CounterAlarm
local band, bnot = bit.band, bit.bnot
local rshift, lshift = bit.rshift, bit.lshift
local receive, transmit = link.receive, link.transmit
local rd16, wr16, rd32, wr32 = lwutil.rd16, lwutil.wr16, lwutil.rd32, lwutil.wr32
local ipv6_equals = lwutil.ipv6_equals
local is_ipv4, is_ipv6 = lwutil.is_ipv4, lwutil.is_ipv6
local htons, ntohs, ntohl = lib.htons, lib.ntohs, lib.ntohl
local is_ipv4_fragment, is_ipv6_fragment = lwutil.is_ipv4_fragment, lwutil.is_ipv6_fragment
local S = require("syscall")
-- Note whether an IPv4 packet is actually coming from the internet, or from
-- a b4 and hairpinned to be re-encapsulated in another IPv6 packet.
local PKT_FROM_INET = 1
local PKT_HAIRPINNED = 2
local debug = lib.getenv("LWAFTR_DEBUG")
local ethernet_header_t = ffi.typeof([[
struct {
uint8_t dhost[6];
uint8_t shost[6];
uint16_t type;
uint8_t payload[0];
}
]])
local ipv4_header_t = ffi.typeof [[
struct {
uint8_t version_and_ihl; // version:4, ihl:4
uint8_t dscp_and_ecn; // dscp:6, ecn:2
uint16_t total_length;
uint16_t id;
uint16_t flags_and_fragment_offset; // flags:3, fragment_offset:13
uint8_t ttl;
uint8_t protocol;
uint16_t checksum;
uint8_t src_ip[4];
uint8_t dst_ip[4];
} __attribute__((packed))
]]
local ipv6_header_t = ffi.typeof([[
struct {
uint32_t v_tc_fl; // version:4, traffic class:8, flow label:20
uint16_t payload_length;
uint8_t next_header;
uint8_t hop_limit;
uint8_t src_ip[16];
uint8_t dst_ip[16];
} __attribute__((packed))
]])
local ipv6_pseudo_header_t = ffi.typeof[[
struct {
char src_ip[16];
char dst_ip[16];
uint32_t payload_length;
uint32_t next_header;
} __attribute__((packed))
]]
local icmp_header_t = ffi.typeof [[
struct {
uint8_t type;
uint8_t code;
int16_t checksum;
} __attribute__((packed))
]]
local ethernet_header_ptr_t = ffi.typeof("$*", ethernet_header_t)
local ethernet_header_size = ffi.sizeof(ethernet_header_t)
local ipv4_header_ptr_t = ffi.typeof("$*", ipv4_header_t)
local ipv4_header_size = ffi.sizeof(ipv4_header_t)
local ipv6_header_ptr_t = ffi.typeof("$*", ipv6_header_t)
local ipv6_header_size = ffi.sizeof(ipv6_header_t)
local ipv6_header_ptr_t = ffi.typeof("$*", ipv6_header_t)
local ipv6_header_size = ffi.sizeof(ipv6_header_t)
local icmp_header_t = ffi.typeof("$*", icmp_header_t)
local icmp_header_size = ffi.sizeof(icmp_header_t)
local ipv6_pseudo_header_size = ffi.sizeof(ipv6_pseudo_header_t)
-- Local bindings for constants that are used in the hot path of the
-- data plane. Not having them here is a 1-2% performance penalty.
local n_ethertype_ipv4 = constants.n_ethertype_ipv4
local n_ethertype_ipv6 = constants.n_ethertype_ipv6
local function get_ethernet_payload(pkt)
return pkt.data + ethernet_header_size
end
local function get_ethernet_payload_length(pkt)
return pkt.length - ethernet_header_size
end
local o_ipv4_checksum = constants.o_ipv4_checksum
local o_ipv4_dscp_and_ecn = constants.o_ipv4_dscp_and_ecn
local o_ipv4_dst_addr = constants.o_ipv4_dst_addr
local o_ipv4_flags = constants.o_ipv4_flags
local o_ipv4_proto = constants.o_ipv4_proto
local o_ipv4_src_addr = constants.o_ipv4_src_addr
local o_ipv4_total_length = constants.o_ipv4_total_length
local o_ipv4_ttl = constants.o_ipv4_ttl
local function get_ipv4_header_length(ptr)
local ver_and_ihl = ptr[0]
return lshift(band(ver_and_ihl, 0xf), 2)
end
local function get_ipv4_total_length(ptr)
return ntohs(rd16(ptr + o_ipv4_total_length))
end
local function get_ipv4_src_address_ptr(ptr)
return ptr + o_ipv4_src_addr
end
local function get_ipv4_dst_address_ptr(ptr)
return ptr + o_ipv4_dst_addr
end
local function get_ipv4_src_address(ptr)
return ntohl(rd32(get_ipv4_src_address_ptr(ptr)))
end
local function get_ipv4_dst_address(ptr)
return ntohl(rd32(get_ipv4_dst_address_ptr(ptr)))
end
local function get_ipv4_proto(ptr)
return ptr[o_ipv4_proto]
end
local function get_ipv4_flags(ptr)
return ptr[o_ipv4_flags]
end
local function get_ipv4_dscp_and_ecn(ptr)
return ptr[o_ipv4_dscp_and_ecn]
end
local function get_ipv4_payload(ptr)
return ptr + get_ipv4_header_length(ptr)
end
local function get_ipv4_payload_src_port(ptr)
-- Assumes that the packet is TCP or UDP.
return ntohs(rd16(get_ipv4_payload(ptr)))
end
local function get_ipv4_payload_dst_port(ptr)
-- Assumes that the packet is TCP or UDP.
return ntohs(rd16(get_ipv4_payload(ptr) + 2))
end
local ipv6_fixed_header_size = constants.ipv6_fixed_header_size
local o_ipv6_dst_addr = constants.o_ipv6_dst_addr
local o_ipv6_next_header = constants.o_ipv6_next_header
local o_ipv6_src_addr = constants.o_ipv6_src_addr
local function get_ipv6_src_address(ptr)
return ptr + o_ipv6_src_addr
end
local function get_ipv6_dst_address(ptr)
return ptr + o_ipv6_dst_addr
end
local function get_ipv6_next_header(ptr)
return ptr[o_ipv6_next_header]
end
local function get_ipv6_payload(ptr)
-- FIXME: Deal with multiple IPv6 headers?
return ptr + ipv6_fixed_header_size
end
local proto_icmp = constants.proto_icmp
local proto_icmpv6 = constants.proto_icmpv6
local proto_ipv4 = constants.proto_ipv4
local function get_icmp_type(ptr)
return ptr[0]
end
local function get_icmp_code(ptr)
return ptr[1]
end
local function get_icmpv4_echo_identifier(ptr)
return ntohs(rd16(ptr + constants.o_icmpv4_echo_identifier))
end
local function get_icmp_mtu(ptr)
local next_hop_mtu_offset = 6
return ntohs(rd16(ptr + next_hop_mtu_offset))
end
local function get_icmp_payload(ptr)
return ptr + constants.icmp_base_size
end
local function write_ethernet_header(pkt, ether_type)
local h = ffi.cast(ethernet_header_ptr_t, pkt.data)
ffi.fill(h.shost, 6, 0)
ffi.fill(h.dhost, 6, 0)
h.type = ether_type
end
local function prepend_ethernet_header(pkt, ether_type)
pkt = packet.shiftright(pkt, ethernet_header_size)
write_ethernet_header(pkt, ether_type)
return pkt
end
local function write_ipv6_header(ptr, src, dst, tc, flow_label, next_header, payload_length)
local h = ffi.cast(ipv6_header_ptr_t, ptr)
h.v_tc_fl = 0
lib.bitfield(32, h, 'v_tc_fl', 0, 4, 6) -- IPv6 Version
lib.bitfield(32, h, 'v_tc_fl', 4, 8, tc) -- Traffic class
lib.bitfield(32, h, 'v_tc_fl', 12, 20, flow_label) -- Flow label
h.payload_length = htons(payload_length)
h.next_header = next_header
h.hop_limit = constants.default_ttl
h.src_ip = src
h.dst_ip = dst
end
local function calculate_icmp_payload_size(dst_pkt, initial_pkt, max_size, config)
local original_bytes_to_skip = ethernet_header_size
if config.extra_payload_offset then
original_bytes_to_skip = original_bytes_to_skip + config.extra_payload_offset
end
local payload_size = initial_pkt.length - original_bytes_to_skip
local non_payload_bytes = dst_pkt.length + constants.icmp_base_size
local full_pkt_size = payload_size + non_payload_bytes
if full_pkt_size > max_size + ethernet_header_size then
full_pkt_size = max_size + ethernet_header_size
payload_size = full_pkt_size - non_payload_bytes
end
return payload_size, original_bytes_to_skip, non_payload_bytes
end
-- Write ICMP data to the end of a packet
-- Config must contain code and type
-- Config may contain a 'next_hop_mtu' setting.
local function write_icmp(dst_pkt, initial_pkt, max_size, base_checksum, config)
local payload_size, original_bytes_to_skip, non_payload_bytes =
calculate_icmp_payload_size(dst_pkt, initial_pkt, max_size, config)
local off = dst_pkt.length
dst_pkt.data[off] = config.type
dst_pkt.data[off + 1] = config.code
wr16(dst_pkt.data + off + 2, 0) -- checksum
wr32(dst_pkt.data + off + 4, 0) -- Reserved
if config.next_hop_mtu then
wr16(dst_pkt.data + off + 6, htons(config.next_hop_mtu))
end
local dest = dst_pkt.data + non_payload_bytes
ffi.C.memmove(dest, initial_pkt.data + original_bytes_to_skip, payload_size)
local icmp_bytes = constants.icmp_base_size + payload_size
local icmp_start = dst_pkt.data + dst_pkt.length
local csum = checksum.ipsum(icmp_start, icmp_bytes, base_checksum)
wr16(dst_pkt.data + off + 2, htons(csum))
dst_pkt.length = dst_pkt.length + icmp_bytes
end
local function to_datagram(pkt)
return datagram:new(pkt)
end
-- initial_pkt is the one to embed (a subset of) in the ICMP payload
function new_icmpv4_packet(from_ip, to_ip, initial_pkt, config)
local new_pkt = packet.allocate()
local dgram = to_datagram(new_pkt)
local ipv4_header = ipv4:new({ttl = constants.default_ttl,
protocol = constants.proto_icmp,
src = from_ip, dst = to_ip})
dgram:push(ipv4_header)
new_pkt = dgram:packet()
ipv4_header:free()
new_pkt = prepend_ethernet_header(new_pkt, n_ethertype_ipv4)
-- Generate RFC 1812 ICMPv4 packets, which carry as much payload as they can,
-- rather than RFC 792 packets, which only carry the original IPv4 header + 8 octets
write_icmp(new_pkt, initial_pkt, constants.max_icmpv4_packet_size, 0, config)
-- Fix up the IPv4 total length and checksum
local new_ipv4_len = new_pkt.length - ethernet_header_size
local ip_tl_p = new_pkt.data + ethernet_header_size + constants.o_ipv4_total_length
wr16(ip_tl_p, ntohs(new_ipv4_len))
local ip_checksum_p = new_pkt.data + ethernet_header_size + constants.o_ipv4_checksum
wr16(ip_checksum_p, 0) -- zero out the checksum before recomputing
local csum = checksum.ipsum(new_pkt.data + ethernet_header_size, new_ipv4_len, 0)
wr16(ip_checksum_p, htons(csum))
return new_pkt
end
function new_icmpv6_packet(from_ip, to_ip, initial_pkt, config)
local new_pkt = packet.allocate()
local dgram = to_datagram(new_pkt)
local ipv6_header = ipv6:new({hop_limit = constants.default_ttl,
next_header = constants.proto_icmpv6,
src = from_ip, dst = to_ip})
dgram:push(ipv6_header)
new_pkt = prepend_ethernet_header(dgram:packet(), n_ethertype_ipv6)
local max_size = constants.max_icmpv6_packet_size
local ph_len = calculate_icmp_payload_size(new_pkt, initial_pkt, max_size, config) + constants.icmp_base_size
local ph = ipv6_header:pseudo_header(ph_len, constants.proto_icmpv6)
local ph_csum = checksum.ipsum(ffi.cast("uint8_t*", ph), ffi.sizeof(ph), 0)
ph_csum = band(bnot(ph_csum), 0xffff)
write_icmp(new_pkt, initial_pkt, max_size, ph_csum, config)
local new_ipv6_len = new_pkt.length - (constants.ipv6_fixed_header_size + ethernet_header_size)
local ip_pl_p = new_pkt.data + ethernet_header_size + constants.o_ipv6_payload_len
wr16(ip_pl_p, ntohs(new_ipv6_len))
ipv6_header:free()
return new_pkt
end
-- This function converts between IPv4-as-host-uint32 and IPv4 as
-- uint8_t[4]. It's a stopgap measure; really the rest of the code
-- should be converted to use IPv4-as-host-uint32.
local function convert_ipv4(addr)
local str = require('lib.yang.util').ipv4_ntop(addr)
return require('lib.protocol.ipv4'):pton(str)
end
local function drop(pkt)
packet.free(pkt)
end
local function select_instance(conf)
local function table_merge(t1, t2)
local ret = {}
for k,v in pairs(t1) do ret[k] = v end
for k,v in pairs(t2) do ret[k] = v end
return ret
end
local device, id, queue = lwutil.parse_instance(conf)
conf.softwire_config.external_interface = table_merge(
conf.softwire_config.external_interface, queue.external_interface)
conf.softwire_config.internal_interface = table_merge(
conf.softwire_config.internal_interface, queue.internal_interface)
return conf
end
LwAftr = { yang_schema = 'snabb-softwire-v2' }
-- Fields:
-- - direction: "in", "out", "hairpin", "drop";
-- If "direction" is "drop":
-- - reason: reasons for dropping;
-- - protocol+version: "icmpv4", "icmpv6", "ipv4", "ipv6";
-- - size: "bytes", "packets".
LwAftr.shm = {
["drop-all-ipv4-iface-bytes"] = {counter},
["drop-all-ipv4-iface-packets"] = {counter},
["drop-all-ipv6-iface-bytes"] = {counter},
["drop-all-ipv6-iface-packets"] = {counter},
["drop-bad-checksum-icmpv4-bytes"] = {counter},
["drop-bad-checksum-icmpv4-packets"] = {counter},
["drop-in-by-policy-icmpv4-bytes"] = {counter},
["drop-in-by-policy-icmpv4-packets"] = {counter},
["drop-in-by-policy-icmpv6-bytes"] = {counter},
["drop-in-by-policy-icmpv6-packets"] = {counter},
["drop-in-by-rfc7596-icmpv4-bytes"] = {counter},
["drop-in-by-rfc7596-icmpv4-packets"] = {counter},
["drop-ipv4-frag-disabled"] = {counter},
["drop-ipv6-frag-disabled"] = {counter},
["drop-misplaced-not-ipv4-bytes"] = {counter},
["drop-misplaced-not-ipv4-packets"] = {counter},
["drop-misplaced-not-ipv6-bytes"] = {counter},
["drop-misplaced-not-ipv6-packets"] = {counter},
["drop-no-dest-softwire-ipv4-bytes"] = {counter},
["drop-no-dest-softwire-ipv4-packets"] = {counter},
["drop-no-source-softwire-ipv6-bytes"] = {counter},
["drop-no-source-softwire-ipv6-packets"] = {counter},
["drop-out-by-policy-icmpv4-packets"] = {counter},
["drop-out-by-policy-icmpv6-packets"] = {counter},
["drop-over-mtu-but-dont-fragment-ipv4-bytes"] = {counter},
["drop-over-mtu-but-dont-fragment-ipv4-packets"] = {counter},
["drop-over-rate-limit-icmpv6-bytes"] = {counter},
["drop-over-rate-limit-icmpv6-packets"] = {counter},
["drop-over-time-but-not-hop-limit-icmpv6-bytes"] = {counter},
["drop-over-time-but-not-hop-limit-icmpv6-packets"] = {counter},
["drop-too-big-type-but-not-code-icmpv6-bytes"] = {counter},
["drop-too-big-type-but-not-code-icmpv6-packets"] = {counter},
["drop-ttl-zero-ipv4-bytes"] = {counter},
["drop-ttl-zero-ipv4-packets"] = {counter},
["drop-unknown-protocol-icmpv6-bytes"] = {counter},
["drop-unknown-protocol-icmpv6-packets"] = {counter},
["drop-unknown-protocol-ipv6-bytes"] = {counter},
["drop-unknown-protocol-ipv6-packets"] = {counter},
["hairpin-ipv4-bytes"] = {counter},
["hairpin-ipv4-packets"] = {counter},
["ingress-packet-drops"] = {counter},
["in-ipv4-bytes"] = {counter},
["in-ipv4-packets"] = {counter},
["in-ipv6-bytes"] = {counter},
["in-ipv6-packets"] = {counter},
["out-icmpv4-bytes"] = {counter},
["out-icmpv4-packets"] = {counter},
["out-icmpv6-bytes"] = {counter},
["out-icmpv6-packets"] = {counter},
["out-ipv4-bytes"] = {counter},
["out-ipv4-packets"] = {counter},
["out-ipv6-bytes"] = {counter},
["out-ipv6-packets"] = {counter},
}
function LwAftr:new(conf)
if conf.debug then debug = true end
local o = setmetatable({}, {__index=LwAftr})
conf = select_instance(conf).softwire_config
o.conf = conf
o.binding_table = bt.load(conf.binding_table)
o.inet_lookup_queue = bt.BTLookupQueue.new(o.binding_table)
o.hairpin_lookup_queue = bt.BTLookupQueue.new(o.binding_table)
o.icmpv4_error_count = 0
o.icmpv4_error_rate_limit_start = 0
o.icmpv6_error_count = 0
o.icmpv6_error_rate_limit_start = 0
alarms.add_to_inventory(
{alarm_type_id='bad-ipv4-softwires-matches'},
{resource=tostring(S.getpid()), has_clear=true,
description="lwAFTR's bad matching softwires due to not found destination "..
"address for IPv4 packets"})
alarms.add_to_inventory(
{alarm_type_id='bad-ipv6-softwires-matches'},
{resource=tostring(S.getpid()), has_clear=true,
description="lwAFTR's bad matching softwires due to not found source"..
"address for IPv6 packets"})
local bad_ipv4_softwire_matches = alarms.declare_alarm(
{resource=tostring(S.getpid()), alarm_type_id='bad-ipv4-softwires-matches'},
{perceived_severity = 'major',
alarm_text = "lwAFTR's bad softwires matches due to non matching destination"..
"address for incoming packets (IPv4) has reached over 100,000 softwires "..
"binding-table. Please review your lwAFTR's configuration binding-table."})
local bad_ipv6_softwire_matches = alarms.declare_alarm(
{resource=tostring(S.getpid()), alarm_type_id='bad-ipv6-softwires-matches'},
{perceived_severity = 'major',
alarm_text = "lwAFTR's bad softwires matches due to non matching source "..
"address for outgoing packets (IPv6) has reached over 100,000 softwires "..
"binding-table. Please review your lwAFTR's configuration binding-table."})
o.bad_ipv4_softwire_matches_alarm = CounterAlarm.new(bad_ipv4_softwire_matches,
5, 1e5, o, 'drop-no-dest-softwire-ipv4-packets')
o.bad_ipv6_softwire_matches_alarm = CounterAlarm.new(bad_ipv6_softwire_matches,
5, 1e5, o, 'drop-no-source-softwire-ipv6-packets')
if debug then lwdebug.pp(conf) end
return o
end
-- The following two methods are called by lib.ptree.worker in reaction
-- to binding table changes, via
-- lib/ptree/support/snabb-softwire-v2.lua.
function LwAftr:add_softwire_entry(entry_blob)
self.binding_table:add_softwire_entry(entry_blob)
end
function LwAftr:remove_softwire_entry(entry_key_blob)
self.binding_table:remove_softwire_entry(entry_key_blob)
end
local function decrement_ttl(pkt)
local ipv4_header = get_ethernet_payload(pkt)
local chksum = bnot(ntohs(rd16(ipv4_header + o_ipv4_checksum)))
local old_ttl = ipv4_header[o_ipv4_ttl]
if old_ttl == 0 then return 0 end
local new_ttl = band(old_ttl - 1, 0xff)
ipv4_header[o_ipv4_ttl] = new_ttl
-- Now fix up the checksum. o_ipv4_ttl is the first byte in the
-- 16-bit big-endian word, so the difference to the overall sum is
-- multiplied by 0xff.
chksum = chksum + lshift(new_ttl - old_ttl, 8)
-- Now do the one's complement 16-bit addition of the 16-bit words of
-- the checksum, which necessarily is a 32-bit value. Two carry
-- iterations will suffice.
chksum = band(chksum, 0xffff) + rshift(chksum, 16)
chksum = band(chksum, 0xffff) + rshift(chksum, 16)
wr16(ipv4_header + o_ipv4_checksum, htons(bnot(chksum)))
return new_ttl
end
function LwAftr:ipv4_in_binding_table (ip)
return self.binding_table:is_managed_ipv4_address(ip)
end
function LwAftr:transmit_icmpv6_reply (pkt)
local now = tonumber(engine.now())
-- Reset if elapsed time reached.
local rate_limiting = self.conf.internal_interface.error_rate_limiting
if now - self.icmpv6_error_rate_limit_start >= rate_limiting.period then
self.icmpv6_error_rate_limit_start = now
self.icmpv6_error_count = 0
end
-- Send packet if limit not reached.
if self.icmpv6_error_count < rate_limiting.packets then
self.icmpv6_error_count = self.icmpv6_error_count + 1
counter.add(self.shm["out-icmpv6-bytes"], pkt.length)
counter.add(self.shm["out-icmpv6-packets"])
counter.add(self.shm["out-ipv6-bytes"], pkt.length)
counter.add(self.shm["out-ipv6-packets"])
return transmit(self.o6, pkt)
else
counter.add(self.shm["drop-over-rate-limit-icmpv6-bytes"], pkt.length)
counter.add(self.shm["drop-over-rate-limit-icmpv6-packets"])
return drop(pkt)
end
end
function LwAftr:drop_ipv4(pkt, pkt_src_link)
if pkt_src_link == PKT_FROM_INET then
counter.add(self.shm["drop-all-ipv4-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv4-iface-packets"])
elseif pkt_src_link == PKT_HAIRPINNED then
-- B4s emit packets with no IPv6 extension headers.
local orig_packet_len = pkt.length + ipv6_fixed_header_size
counter.add(self.shm["drop-all-ipv6-iface-bytes"], orig_packet_len)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
else
assert(false, "Programming error, bad pkt_src_link: " .. pkt_src_link)
end
return drop(pkt)
end
function LwAftr:transmit_icmpv4_reply(pkt, orig_pkt, orig_pkt_link)
local now = tonumber(engine.now())
-- Reset if elapsed time reached.
local rate_limiting = self.conf.external_interface.error_rate_limiting
if now - self.icmpv4_error_rate_limit_start >= rate_limiting.period then
self.icmpv4_error_rate_limit_start = now
self.icmpv4_error_count = 0
end
-- Origin packet is always dropped.
if orig_pkt_link then
self:drop_ipv4(orig_pkt, orig_pkt_link)
else
drop(orig_pkt)
end
-- Send packet if limit not reached.
if self.icmpv4_error_count < rate_limiting.packets then
self.icmpv4_error_count = self.icmpv4_error_count + 1
counter.add(self.shm["out-icmpv4-bytes"], pkt.length)
counter.add(self.shm["out-icmpv4-packets"])
-- Only locally generated error packets are handled here. We transmit
-- them right away, instead of calling transmit_ipv4, because they are
-- never hairpinned and should not be counted by the "out-ipv4" counter.
-- However, they should be tunneled if the error is to be sent to a host
-- behind a B4, whether or not hairpinning is enabled; this is not hairpinning.
-- ... and the tunneling should happen via the 'hairpinning' queue, to make
-- sure counters are handled appropriately, despite this not being hairpinning.
-- This avoids having phantom incoming IPv4 packets.
local ipv4_header = get_ethernet_payload(pkt)
local dst_ip = get_ipv4_dst_address(ipv4_header)
if self:ipv4_in_binding_table(dst_ip) then
return transmit(self.input.hairpin_in, pkt)
else
counter.add(self.shm["out-ipv4-bytes"], pkt.length)
counter.add(self.shm["out-ipv4-packets"])
return transmit(self.o4, pkt)
end
else
return drop(pkt)
end
end
-- Hairpinned packets need to be handled quite carefully. We've decided they:
-- * should increment hairpin-ipv4-bytes and hairpin-ipv4-packets
-- * should increment [in|out]-ipv6-[bytes|packets]
-- * should NOT increment [in|out]-ipv4-[bytes|packets]
-- The latter is because decapsulating and re-encapsulating them via IPv4
-- packets is an internal implementation detail that DOES NOT go out over
-- physical wires.
-- Not incrementing out-ipv4-bytes and out-ipv4-packets is straightforward.
-- Not incrementing in-ipv4-[bytes|packets] is harder. The easy way would be
-- to add extra flags and conditionals, but it's expected that a high enough
-- percentage of traffic might be hairpinned that this could be problematic,
-- (and a nightmare as soon as we add any kind of parallelism)
-- so instead we speculatively decrement the counters here.
-- It is assumed that any packet we transmit to self.input.v4 will not
-- be dropped before the in-ipv4-[bytes|packets] counters are incremented;
-- I *think* this approach bypasses using the physical NIC but am not
-- absolutely certain.
function LwAftr:transmit_ipv4(pkt)
local ipv4_header = get_ethernet_payload(pkt)
local dst_ip = get_ipv4_dst_address(ipv4_header)
if (self.conf.internal_interface.hairpinning and
self:ipv4_in_binding_table(dst_ip)) then
-- The destination address is managed by the lwAFTR, so we need to
-- hairpin this packet. Enqueue on the IPv4 interface, as if it
-- came from the internet.
counter.add(self.shm["hairpin-ipv4-bytes"], pkt.length)
counter.add(self.shm["hairpin-ipv4-packets"])
return transmit(self.input.hairpin_in, pkt)
else
counter.add(self.shm["out-ipv4-bytes"], pkt.length)
counter.add(self.shm["out-ipv4-packets"])
return transmit(self.o4, pkt)
end
end
-- ICMPv4 type 3 code 1, as per RFC 7596.
-- The target IPv4 address + port is not in the table.
function LwAftr:drop_ipv4_packet_to_unreachable_host(pkt, pkt_src_link)
counter.add(self.shm["drop-no-dest-softwire-ipv4-bytes"], pkt.length)
counter.add(self.shm["drop-no-dest-softwire-ipv4-packets"])
if not self.conf.external_interface.generate_icmp_errors then
-- ICMP error messages off by policy; silently drop.
-- Not counting bytes because we do not even generate the packets.
counter.add(self.shm["drop-out-by-policy-icmpv4-packets"])
return self:drop_ipv4(pkt, pkt_src_link)
end
if get_ipv4_proto(get_ethernet_payload(pkt)) == proto_icmp then
-- RFC 7596 section 8.1 requires us to silently drop incoming
-- ICMPv4 messages that don't match the binding table.
counter.add(self.shm["drop-in-by-rfc7596-icmpv4-bytes"], pkt.length)
counter.add(self.shm["drop-in-by-rfc7596-icmpv4-packets"])
return self:drop_ipv4(pkt, pkt_src_link)
end
local ipv4_header = get_ethernet_payload(pkt)
local to_ip = get_ipv4_src_address_ptr(ipv4_header)
local icmp_config = {
type = constants.icmpv4_dst_unreachable,
code = constants.icmpv4_host_unreachable,
}
local icmp_dis = new_icmpv4_packet(
convert_ipv4(self.conf.external_interface.ip),
to_ip, pkt, icmp_config)
return self:transmit_icmpv4_reply(icmp_dis, pkt, pkt_src_link)
end
-- ICMPv6 type 1 code 5, as per RFC 7596.
-- The source (ipv6, ipv4, port) tuple is not in the table.
function LwAftr:drop_ipv6_packet_from_bad_softwire(pkt, br_addr)
if not self.conf.internal_interface.generate_icmp_errors then
-- ICMP error messages off by policy; silently drop.
-- Not counting bytes because we do not even generate the packets.
counter.add(self.shm["drop-out-by-policy-icmpv6-packets"])
return drop(pkt)
end
local ipv6_header = get_ethernet_payload(pkt)
local orig_src_addr_icmp_dst = get_ipv6_src_address(ipv6_header)
-- If br_addr is specified, use that as the source addr. Otherwise, send it
-- back from the IPv6 address it was sent to.
local icmpv6_src_addr = br_addr or get_ipv6_dst_address(ipv6_header)
local icmp_config = {type = constants.icmpv6_dst_unreachable,
code = constants.icmpv6_failed_ingress_egress_policy,
}
local b4fail_icmp = new_icmpv6_packet(
icmpv6_src_addr, orig_src_addr_icmp_dst, pkt, icmp_config)
drop(pkt)
self:transmit_icmpv6_reply(b4fail_icmp)
end
function LwAftr:encapsulating_packet_with_df_flag_would_exceed_mtu(pkt)
local payload_length = get_ethernet_payload_length(pkt)
local mtu = self.conf.internal_interface.mtu
if payload_length + ipv6_fixed_header_size <= mtu then
-- Packet will not exceed MTU.
return false
end
-- The result would exceed the IPv6 MTU; signal an error via ICMPv4 if
-- the IPv4 fragment has the DF flag.
return band(get_ipv4_flags(get_ethernet_payload(pkt)), 0x40) == 0x40
end
function LwAftr:cannot_fragment_df_packet_error(pkt)
-- According to RFC 791, the original packet must be discarded.
-- Return a packet with ICMP(3, 4) and the appropriate MTU
-- as per https://tools.ietf.org/html/rfc2473#section-7.2
if debug then lwdebug.print_pkt(pkt) end
-- The ICMP packet should be set back to the packet's source.
local dst_ip = get_ipv4_src_address_ptr(get_ethernet_payload(pkt))
local mtu = self.conf.internal_interface.mtu
local icmp_config = {
type = constants.icmpv4_dst_unreachable,
code = constants.icmpv4_datagram_too_big_df,
extra_payload_offset = 0,
next_hop_mtu = mtu - constants.ipv6_fixed_header_size,
}
return new_icmpv4_packet(
convert_ipv4(self.conf.external_interface.ip),
dst_ip, pkt, icmp_config)
end
function LwAftr:encapsulate_and_transmit(pkt, ipv6_dst, ipv6_src, pkt_src_link)
-- Do not encapsulate packets that now have a ttl of zero or wrapped around
local ttl = decrement_ttl(pkt)
if ttl == 0 then
counter.add(self.shm["drop-ttl-zero-ipv4-bytes"], pkt.length)
counter.add(self.shm["drop-ttl-zero-ipv4-packets"])
if not self.conf.external_interface.generate_icmp_errors then
-- Not counting bytes because we do not even generate the packets.
counter.add(self.shm["drop-out-by-policy-icmpv4-packets"])
return self:drop_ipv4(pkt, pkt_src_link)
end
local ipv4_header = get_ethernet_payload(pkt)
local dst_ip = get_ipv4_src_address_ptr(ipv4_header)
local icmp_config = {type = constants.icmpv4_time_exceeded,
code = constants.icmpv4_ttl_exceeded_in_transit,
}
local reply = new_icmpv4_packet(
convert_ipv4(self.conf.external_interface.ip),
dst_ip, pkt, icmp_config)
return self:transmit_icmpv4_reply(reply, pkt, pkt_src_link)
end
if debug then print("ipv6", ipv6_src, ipv6_dst) end
if self:encapsulating_packet_with_df_flag_would_exceed_mtu(pkt) then
counter.add(self.shm["drop-over-mtu-but-dont-fragment-ipv4-bytes"], pkt.length)
counter.add(self.shm["drop-over-mtu-but-dont-fragment-ipv4-packets"])
if not self.conf.external_interface.generate_icmp_errors then
-- Not counting bytes because we do not even generate the packets.
counter.add(self.shm["drop-out-by-policy-icmpv4-packets"])
return self:drop_ipv4(pkt, pkt_src_link)
end
local reply = self:cannot_fragment_df_packet_error(pkt)
return self:transmit_icmpv4_reply(reply, pkt, pkt_src_link)
end
local payload_length = get_ethernet_payload_length(pkt)
local l3_header = get_ethernet_payload(pkt)
local traffic_class = get_ipv4_dscp_and_ecn(l3_header)
local flow_label = self.conf.internal_interface.flow_label
-- Note that this may invalidate any pointer into pkt.data. Be warned!
pkt = packet.shiftright(pkt, ipv6_header_size)
write_ethernet_header(pkt, n_ethertype_ipv6)
-- Fetch possibly-moved L3 header location.
l3_header = get_ethernet_payload(pkt)
write_ipv6_header(l3_header, ipv6_src, ipv6_dst, traffic_class,
flow_label, proto_ipv4, payload_length)
if debug then
print("encapsulated packet:")
lwdebug.print_pkt(pkt)
end
counter.add(self.shm["out-ipv6-bytes"], pkt.length)
counter.add(self.shm["out-ipv6-packets"])
return transmit(self.o6, pkt)
end
function LwAftr:flush_encapsulation()
local lq = self.inet_lookup_queue
lq:process_queue()
for n = 0, lq.length - 1 do
local pkt, ipv6_dst, ipv6_src = lq:get_lookup(n)
if ipv6_dst then
self:encapsulate_and_transmit(pkt, ipv6_dst, ipv6_src, PKT_FROM_INET)
else
-- Lookup failed.
if debug then print("lookup failed") end
self:drop_ipv4_packet_to_unreachable_host(pkt, PKT_FROM_INET)
end
end
lq:reset_queue()
end
function LwAftr:flush_hairpin()
local lq = self.hairpin_lookup_queue
lq:process_queue()
for n = 0, lq.length - 1 do
local pkt, ipv6_dst, ipv6_src = lq:get_lookup(n)
if ipv6_dst then
self:encapsulate_and_transmit(pkt, ipv6_dst, ipv6_src, PKT_HAIRPINNED)
else
-- Lookup failed. This can happen even with hairpinned packets, if
-- the binding table changes between destination lookups.
-- Count the original IPv6 packet as dropped, not the hairpinned one.
if debug then print("lookup failed") end
self:drop_ipv4_packet_to_unreachable_host(pkt, PKT_HAIRPINNED)
end
end
lq:reset_queue()
end
function LwAftr:enqueue_encapsulation(pkt, ipv4, port, pkt_src_link)
if pkt_src_link == PKT_FROM_INET then
if self.inet_lookup_queue:enqueue_lookup(pkt, ipv4, port) then
-- Flush the queue right away if enough packets are queued up already.
self:flush_encapsulation()
end
else
assert(pkt_src_link == PKT_HAIRPINNED)
if self.hairpin_lookup_queue:enqueue_lookup(pkt, ipv4, port) then
-- Flush the queue right away if enough packets are queued up already.
self:flush_hairpin()
end
end
end
function LwAftr:icmpv4_incoming(pkt, pkt_src_link)
local ipv4_header = get_ethernet_payload(pkt)
local ipv4_header_size = get_ipv4_header_length(ipv4_header)
local icmp_header = get_ipv4_payload(ipv4_header)
local icmp_type = get_icmp_type(icmp_header)
-- RFC 7596 is silent on whether to validate echo request/reply checksums.
-- ICMP checksums SHOULD be validated according to RFC 5508.
-- Choose to verify the echo reply/request ones too.
-- Note: the lwaftr SHOULD NOT validate the transport checksum of the embedded packet.
-- Were it to nonetheless do so, RFC 4884 extension headers MUST NOT
-- be taken into account when validating the checksum
local icmp_bytes = get_ipv4_total_length(ipv4_header) - ipv4_header_size
if checksum.ipsum(icmp_header, icmp_bytes, 0) ~= 0 then
-- Silently drop the packet, as per RFC 5508
counter.add(self.shm["drop-bad-checksum-icmpv4-bytes"], pkt.length)
counter.add(self.shm["drop-bad-checksum-icmpv4-packets"])
return self:drop_ipv4(pkt, pkt_src_link)
end
local ipv4_dst = get_ipv4_dst_address(ipv4_header)
local port
-- checksum was ok
if icmp_type == constants.icmpv4_echo_request then
-- For an incoming ping from the IPv4 internet, assume port == 0
-- for the purposes of looking up a softwire in the binding table.
-- This will allow ping to a B4 on an IPv4 without port sharing.
-- It also has the nice property of causing a drop if the IPv4 has
-- any reserved ports.
--
-- RFC 7596 section 8.1 seems to suggest that we should use the
-- echo identifier for this purpose, but that only makes sense for
-- echo requests originating from a B4, to identify the softwire
-- of the source. It can't identify a destination softwire. This
-- makes sense because you can't really "ping" a port-restricted
-- IPv4 address.
port = 0
elseif icmp_type == constants.icmpv4_echo_reply then
-- A reply to a ping that originally issued from a subscriber on
-- the B4 side; the B4 set the port in the echo identifier, as per
-- RFC 7596, section 8.1, so use that to look up the destination
-- softwire.
port = get_icmpv4_echo_identifier(icmp_header)
else
-- As per REQ-3, use the ip address embedded in the ICMP payload,
-- assuming that the payload is shaped like TCP or UDP with the
-- ports first.
local embedded_ipv4_header = get_icmp_payload(icmp_header)
port = get_ipv4_payload_src_port(embedded_ipv4_header)
end
return self:enqueue_encapsulation(pkt, ipv4_dst, port, pkt_src_link)
end
-- The incoming packet is a complete one with ethernet headers.
-- FIXME: Verify that the total_length declared in the packet is correct.
function LwAftr:from_inet(pkt, pkt_src_link)
-- Check incoming ICMP -first-, because it has different binding table lookup logic
-- than other protocols.
local ipv4_header = get_ethernet_payload(pkt)
if get_ipv4_proto(ipv4_header) == proto_icmp then
if not self.conf.external_interface.allow_incoming_icmp then
counter.add(self.shm["drop-in-by-policy-icmpv4-bytes"], pkt.length)
counter.add(self.shm["drop-in-by-policy-icmpv4-packets"])
return self:drop_ipv4(pkt, pkt_src_link)
else
return self:icmpv4_incoming(pkt, pkt_src_link)
end
end
-- If fragmentation support is enabled, the lwAFTR never receives fragments.
-- If it does, fragment support is disabled and it should drop them.
if is_ipv4_fragment(pkt) then
counter.add(self.shm["drop-ipv4-frag-disabled"])
return self:drop_ipv4(pkt, pkt_src_link)
end
-- It's not incoming ICMP. Assume we can find ports in the IPv4
-- payload, as in TCP and UDP. We could check strictly for TCP/UDP,
-- but that would filter out similarly-shaped protocols like SCTP, so
-- we optimistically assume that the incoming traffic has the right
-- shape.
local dst_ip = get_ipv4_dst_address(ipv4_header)
local dst_port = get_ipv4_payload_dst_port(ipv4_header)
return self:enqueue_encapsulation(pkt, dst_ip, dst_port, pkt_src_link)
end
function LwAftr:tunnel_unreachable(pkt, code, next_hop_mtu)
local ipv6_header = get_ethernet_payload(pkt)
local icmp_header = get_ipv6_payload(ipv6_header)
local embedded_ipv6_header = get_icmp_payload(icmp_header)
local embedded_ipv4_header = get_ipv6_payload(embedded_ipv6_header)
local icmp_config = {type = constants.icmpv4_dst_unreachable,
code = code,
extra_payload_offset = embedded_ipv4_header - ipv6_header,
next_hop_mtu = next_hop_mtu
}
local dst_ip = get_ipv4_src_address_ptr(embedded_ipv4_header)
local icmp_reply = new_icmpv4_packet(
convert_ipv4(self.conf.external_interface.ip),
dst_ip, pkt, icmp_config)
return icmp_reply
end
-- FIXME: Verify that the softwire is in the the binding table.
function LwAftr:icmpv6_incoming(pkt)
local ipv6_header = get_ethernet_payload(pkt)
local icmp_header = get_ipv6_payload(ipv6_header)
local icmp_type = get_icmp_type(icmp_header)
local icmp_code = get_icmp_code(icmp_header)
if icmp_type == constants.icmpv6_packet_too_big then
if icmp_code ~= constants.icmpv6_code_packet_too_big then
-- Invalid code.
counter.add(self.shm["drop-too-big-type-but-not-code-icmpv6-bytes"],
pkt.length)
counter.add(self.shm["drop-too-big-type-but-not-code-icmpv6-packets"])
counter.add(self.shm["drop-all-ipv6-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
return drop(pkt)
end
local mtu = get_icmp_mtu(icmp_header) - constants.ipv6_fixed_header_size
local reply = self:tunnel_unreachable(pkt,
constants.icmpv4_datagram_too_big_df,
mtu)
return self:transmit_icmpv4_reply(reply, pkt)
-- Take advantage of having already checked for 'packet too big' (2), and
-- unreachable node/hop limit exceeded/paramater problem being 1, 3, 4 respectively
elseif icmp_type <= constants.icmpv6_parameter_problem then
-- If the time limit was exceeded, require it was a hop limit code
if icmp_type == constants.icmpv6_time_limit_exceeded then
if icmp_code ~= constants.icmpv6_hop_limit_exceeded then
counter.add(self.shm[
"drop-over-time-but-not-hop-limit-icmpv6-bytes"], pkt.length)
counter.add(
self.shm["drop-over-time-but-not-hop-limit-icmpv6-packets"])
counter.add(self.shm["drop-all-ipv6-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
return drop(pkt)
end
end
-- Accept all unreachable or parameter problem codes
local reply = self:tunnel_unreachable(pkt,
constants.icmpv4_host_unreachable)
return self:transmit_icmpv4_reply(reply, pkt)
else
-- No other types of ICMPv6, including echo request/reply, are
-- handled.
counter.add(self.shm["drop-unknown-protocol-icmpv6-bytes"], pkt.length)
counter.add(self.shm["drop-unknown-protocol-icmpv6-packets"])
counter.add(self.shm["drop-all-ipv6-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
return drop(pkt)
end
end
function LwAftr:flush_decapsulation()
local lq = self.inet_lookup_queue
lq:process_queue()
for n = 0, lq.length - 1 do
local pkt, b4_addr, br_addr = lq:get_lookup(n)
local ipv6_header = get_ethernet_payload(pkt)
if (b4_addr
and ipv6_equals(get_ipv6_src_address(ipv6_header), b4_addr)
and ipv6_equals(get_ipv6_dst_address(ipv6_header), br_addr)) then
-- Source softwire is valid; decapsulate and forward.
-- Note that this may invalidate any pointer into pkt.data. Be warned!
pkt = packet.shiftleft(pkt, ipv6_fixed_header_size)
write_ethernet_header(pkt, n_ethertype_ipv4)
self:transmit_ipv4(pkt)
else
counter.add(self.shm["drop-no-source-softwire-ipv6-bytes"], pkt.length)
counter.add(self.shm["drop-no-source-softwire-ipv6-packets"])
counter.add(self.shm["drop-all-ipv6-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
self:drop_ipv6_packet_from_bad_softwire(pkt, br_addr)
end
end
lq:reset_queue()
end
function LwAftr:enqueue_decapsulation(pkt, ipv4, port)
if self.inet_lookup_queue:enqueue_lookup(pkt, ipv4, port) then
-- Flush the queue right away if enough packets are queued up already.
self:flush_decapsulation()
end
end
-- FIXME: Verify that the packet length is big enough?
function LwAftr:from_b4(pkt)
-- If fragmentation support is enabled, the lwAFTR never receives fragments.
-- If it does, fragment support is disabled and it should drop them.
if is_ipv6_fragment(pkt) then
counter.add(self.shm["drop-ipv6-frag-disabled"])
counter.add(self.shm["drop-all-ipv6-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
return drop(pkt)
end
local ipv6_header = get_ethernet_payload(pkt)
local proto = get_ipv6_next_header(ipv6_header)
if proto ~= proto_ipv4 then
if proto == proto_icmpv6 then
if not self.conf.internal_interface.allow_incoming_icmp then
counter.add(self.shm["drop-in-by-policy-icmpv6-bytes"], pkt.length)
counter.add(self.shm["drop-in-by-policy-icmpv6-packets"])
counter.add(self.shm["drop-all-ipv6-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
return drop(pkt)
else
return self:icmpv6_incoming(pkt)
end
else
-- Drop packet with unknown protocol.
counter.add(self.shm["drop-unknown-protocol-ipv6-bytes"], pkt.length)
counter.add(self.shm["drop-unknown-protocol-ipv6-packets"])
counter.add(self.shm["drop-all-ipv6-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
return drop(pkt)
end
end
local tunneled_ipv4_header = get_ipv6_payload(ipv6_header)
local port
if get_ipv4_proto(tunneled_ipv4_header) == proto_icmp then
local icmp_header = get_ipv4_payload(tunneled_ipv4_header)
local icmp_type = get_icmp_type(icmp_header)
if icmp_type == constants.icmpv4_echo_request then
-- A ping going out from the B4 to the internet; the B4 will
-- encode a port in its range into the echo identifier, as per
-- RFC 7596 section 8.
port = get_icmpv4_echo_identifier(icmp_header)
elseif icmp_type == constants.icmpv4_echo_reply then
-- A reply to a ping, coming from the B4. Only B4s whose
-- softwire is associated with port 0 are pingable. See
-- icmpv4_incoming for more discussion.
port = 0
else
-- Otherwise it's an error in response to a non-ICMP packet,
-- routed to the B4 via the ports in IPv4 payload. Extract
-- these ports from the embedded packet fragment in the ICMP
-- payload.
local embedded_ipv4_header = get_icmp_payload(icmp_header)
port = get_ipv4_payload_src_port(embedded_ipv4_header)
end
else
-- It's not ICMP. Assume we can find ports in the IPv4 payload,
-- as in TCP and UDP. We could check strictly for TCP/UDP, but
-- that would filter out similarly-shaped protocols like SCTP, so
-- we optimistically assume that the incoming traffic has the
-- right shape.
port = get_ipv4_payload_src_port(tunneled_ipv4_header)
end
local ipv4 = get_ipv4_src_address(tunneled_ipv4_header)
return self:enqueue_decapsulation(pkt, ipv4, port)
end
function LwAftr:push ()
local i4, i6, ih = self.input.v4, self.input.v6, self.input.hairpin_in
local o4, o6 = self.output.v4, self.output.v6
self.o4, self.o6 = o4, o6
self.bad_ipv4_softwire_matches_alarm:check()
self.bad_ipv6_softwire_matches_alarm:check()
for _ = 1, link.nreadable(i6) do
-- Decapsulate incoming IPv6 packets from the B4 interface and
-- push them out the V4 link, unless they need hairpinning, in
-- which case enqueue them on the hairpinning incoming link.
-- Drop anything that's not IPv6.
local pkt = receive(i6)
if is_ipv6(pkt) then
counter.add(self.shm["in-ipv6-bytes"], pkt.length)
counter.add(self.shm["in-ipv6-packets"])
self:from_b4(pkt)
else
counter.add(self.shm["drop-misplaced-not-ipv6-bytes"], pkt.length)
counter.add(self.shm["drop-misplaced-not-ipv6-packets"])
counter.add(self.shm["drop-all-ipv6-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv6-iface-packets"])
drop(pkt)
end
end
self:flush_decapsulation()
for _ = 1, link.nreadable(i4) do
-- Encapsulate incoming IPv4 packets, excluding hairpinned
-- packets. Drop anything that's not IPv4.
local pkt = receive(i4)
if is_ipv4(pkt) then
counter.add(self.shm["in-ipv4-bytes"], pkt.length)
counter.add(self.shm["in-ipv4-packets"])
self:from_inet(pkt, PKT_FROM_INET)
else
counter.add(self.shm["drop-misplaced-not-ipv4-bytes"], pkt.length)
counter.add(self.shm["drop-misplaced-not-ipv4-packets"])
-- It's guaranteed to not be hairpinned.
counter.add(self.shm["drop-all-ipv4-iface-bytes"], pkt.length)
counter.add(self.shm["drop-all-ipv4-iface-packets"])
drop(pkt)
end
end
self:flush_encapsulation()
for _ = 1, link.nreadable(ih) do
-- Encapsulate hairpinned packet.
local pkt = receive(ih)
-- To reach this link, it has to have come through the lwaftr, so it
-- is certainly IPv4. It was already counted, no more counter updates.
self:from_inet(pkt, PKT_HAIRPINNED)
end
self:flush_hairpin()
end
| apache-2.0 |
Paradokz/BadRotations | System/engines/HealingEngine.lua | 3 | 21447 | --[[---------------------------------------------------------------------------------------------------
-----------------------------------------Bubba's Healing Engine--------------------------------------]]
if not metaTable1 then
-- localizing the commonly used functions while inside loops
local getDistance,tinsert,tremove,UnitGUID,UnitClass,UnitIsUnit = getDistance,tinsert,tremove,UnitGUID,UnitClass,UnitIsUnit
local UnitDebuff,UnitExists,UnitHealth,UnitHealthMax = UnitDebuff,UnitExists,UnitHealth,UnitHealthMax
local GetSpellInfo,GetTime,UnitDebuffID,getBuffStacks = GetSpellInfo,GetTime,UnitDebuffID,getBuffStacks
br.friend = {} -- This is our main Table that the world will see
memberSetup = {} -- This is one of our MetaTables that will be the default user/contructor
memberSetup.cache = { } -- This is for the cache Table to check against
metaTable1 = {} -- This will be the MetaTable attached to our Main Table that the world will see
metaTable1.__call = function(_, ...) -- (_, forceRetable, excludePets, onlyInRange) [Not Implemented]
local group = IsInRaid() and "raid" or "party" -- Determining if the UnitID will be raid or party based
local groupSize = IsInRaid() and GetNumGroupMembers() or GetNumGroupMembers() - 1 -- If in raid, we check the entire raid. If in party, we remove one from max to account for the player.
if group == "party" then tinsert(br.friend, memberSetup:new("player")) end -- We are creating a new User for player if in a Group
for i=1, groupSize do -- start of the loop to read throught the party/raid
local groupUnit = group..i
local groupMember = memberSetup:new(groupUnit)
if groupMember then tinsert(br.friend, groupMember) end -- Inserting a newly created Unit into the Main Frame
end
end
metaTable1.__index = {-- Setting the Metamethod of Index for our Main Table
name = "Healing Table",
author = "Bubba",
}
-- Creating a default Unit to default to on a check
memberSetup.__index = {
name = "noob",
hp = 100,
unit = "noob",
role = "NOOB",
range = false,
guid = 0,
guidsh = 0,
class = "NONE",
}
-- If ever somebody enters or leaves the raid, wipe the entire Table
local updateHealingTable = CreateFrame("frame", nil)
updateHealingTable:RegisterEvent("GROUP_ROSTER_UPDATE")
updateHealingTable:SetScript("OnEvent", function()
table.wipe(br.friend)
table.wipe(memberSetup.cache)
SetupTables()
end)
-- This is for those NPC units that need healing. Compare them against our list of Unit ID's
local function SpecialHealUnit(tar)
for i=1, #novaEngineTables.SpecialHealUnitList do
if getGUID(tar) == novaEngineTables.SpecialHealUnitList[i] then
return true
end
end
end
-- We are checking if the user has a Debuff we either can not or don't want to heal them
local function CheckBadDebuff(tar)
for i=1, #novaEngineTables.BadDebuffList do
if UnitDebuff(tar, GetSpellInfo(novaEngineTables.BadDebuffList[i])) or UnitBuff(tar, GetSpellInfo(novaEngineTables.BadDebuffList[i])) then
return false
end
end
return true
end
-- This is for NPC units we do not want to heal. Compare to list in collections.
local function CheckSkipNPC(tar)
local npcId = (getGUID(tar))
for i=1, #novaEngineTables.skipNPC do
if npcId == novaEngineTables.skipNPC[i] then
return true
end
end
return false
end
local function CheckCreatureType(tar)
local CreatureTypeList = {"Critter", "Totem", "Non-combat Pet", "Wild Pet"}
for i=1, #CreatureTypeList do
if UnitCreatureType(tar) == CreatureTypeList[i] then return false end
end
if not UnitIsBattlePet(tar) and not UnitIsWildBattlePet(tar) then return true else return false end
end
-- Verifying the target is a Valid Healing target
function HealCheck(tar)
if ((UnitIsVisible(tar)
and not UnitIsCharmed(tar)
and UnitReaction("player",tar) > 4
and not UnitIsDeadOrGhost(tar)
and UnitIsConnected(tar)
and UnitInPhase(tar))
or novaEngineTables.SpecialHealUnitList[tonumber(select(2,getGUID(tar)))] ~= nil or (getOptionCheck("Heal Pets") == true and UnitIsOtherPlayersPet(tar) or UnitGUID(tar) == UnitGUID("pet")))
and CheckBadDebuff(tar)
and CheckCreatureType(tar)
and getLineOfSight("player", tar)
and UnitInPhase(tar)
then return true
else return false end
end
function memberSetup:new(unit)
-- Seeing if we have already cached this unit before
if memberSetup.cache[getGUID(unit)] then return false end
local o = {}
setmetatable(o, memberSetup)
if unit and type(unit) == "string" then
o.unit = unit
end
-- This is the function for Dispel checking built into the player itself.
function o:Dispel()
for i = 1, #novaEngineTables.DispelID do
if UnitDebuff(o.unit,GetSpellInfo(novaEngineTables.DispelID[i].id)) ~= nil and novaEngineTables.DispelID[i].id ~= nil then
if select(4,UnitDebuff(o.unit,GetSpellInfo(novaEngineTables.DispelID[i].id))) >= novaEngineTables.DispelID[i].stacks
and (isChecked("Dispel delay") and
(getDebuffDuration(o.unit, novaEngineTables.DispelID[i].id) - getDebuffRemain(o.unit, novaEngineTables.DispelID[i].id)) > (getDebuffDuration(o.unit, novaEngineTables.DispelID[i].id) * (math.random(getValue("Dispel delay")-2, getValue("Dispel delay")+2)/100) ))then -- Dispel Delay
if novaEngineTables.DispelID[i].range ~= nil then
if #getAllies(o.unit,novaEngineTables.DispelID[i].range) > 1 then
return false
end
end
return true
end
end
end
return false
end
-- We are checking the HP of the person through their own function.
function o:CalcHP()
-- Place out of range players at the end of the list -- replaced range to 40 as we should be using lib range
if not UnitInRange(o.unit) and getDistance(o.unit) > 40 and not UnitIsUnit("player", o.unit) then
return 250,250,250
end
-- Place Dead players at the end of the list
if HealCheck(o.unit) ~= true then
return 250,250,250
end
-- incoming heals
local incomingheals
if getOptionCheck("Incoming Heals") == true and UnitGetIncomingHeals(o.unit,"player") ~= nil then
incomingheals = UnitGetIncomingHeals(o.unit,"player")
else
incomingheals = 0
end
-- absorbs
local nAbsorbs
if getOptionCheck("No Absorbs") ~= true then
nAbsorbs = (UnitGetTotalAbsorbs(o.unit)*0.25)
else
nAbsorbs = 0
end
-- calc base + absorbs + incomings
local PercentWithIncoming = 100 * ( UnitHealth(o.unit) + incomingheals + nAbsorbs ) / UnitHealthMax(o.unit)
-- Using the group role assigned to the Unit
if o.role == "TANK" then
PercentWithIncoming = PercentWithIncoming - 5
end
-- Using Dispel Check to see if we should give bonus weight
if o.dispel then
PercentWithIncoming = PercentWithIncoming - 2
end
-- Using threat to remove 3% to all tanking units
if o.threat == 3 then
PercentWithIncoming = PercentWithIncoming - 3
end
-- Tank in Proving Grounds
if o.guidsh == 72218 then
PercentWithIncoming = PercentWithIncoming - 5
end
local ActualWithIncoming = ( UnitHealthMax(o.unit) - ( UnitHealth(o.unit) + incomingheals ) )
-- Malkorok shields logic
local SpecificHPBuffs = {
{buff = 142865,value = select(15,UnitDebuffID(o.unit,142865))}, -- Strong Ancient Barrier (Green)
{buff = 142864,value = select(15,UnitDebuffID(o.unit,142864))}, -- Ancient Barrier (Yellow)
{buff = 142863,value = select(15,UnitDebuffID(o.unit,142863))}, -- Weak Ancient Barrier (Red)
}
if UnitDebuffID(o.unit, 142861) then -- If Miasma found
for i = 1,#SpecificHPBuffs do -- start iteration
if UnitDebuffID(o.unit, SpecificHPBuffs[i].buff) ~= nil then -- if buff found
if SpecificHPBuffs[i].value ~= nil then
PercentWithIncoming = 100 + (SpecificHPBuffs[i].value/UnitHealthMax(o.unit)*100) -- we set its amount + 100 to make sure its within 50-100 range
break
end
end
end
PercentWithIncoming = PercentWithIncoming/2 -- no mather what as long as we are on miasma buff our life is cut in half so unshielded ends up 0-50
end
-- Tyrant Velhair Aura logic
if UnitDebuffID(o.unit, 179986) then -- If Aura of Contempt found
max_percentage = select(15,UnitAura("boss1",GetSpellInfo(179986))) -- find current reduction % in healing
if max_percentage then
PercentWithIncoming = (PercentWithIncoming/max_percentage)* 100 -- Calculate Actual HP % after reduction
end
end
-- Debuffs HP compensation
local HpDebuffs = novaEngineTables.SpecificHPDebuffs
for i = 1, #HpDebuffs do
local _,_,_,count,_,_,_,_,_,_,spellID = UnitDebuffID(o.unit,HpDebuffs[i].debuff)
if spellID ~= nil and (HpDebuffs[i].stacks == nil or (count and count >= HpDebuffs[i].stacks)) then
PercentWithIncoming = PercentWithIncoming - HpDebuffs[i].value
break
end
end
if getOptionCheck("Blacklist") == true and br.data.blackList ~= nil then
for i = 1, #br.data.blackList do
if o.guid == br.data.blackList[i].guid then
PercentWithIncoming,ActualWithIncoming,nAbsorbs = PercentWithIncoming + getValue("Blacklist"),ActualWithIncoming + getValue("Blacklist"),nAbsorbs + getValue("Blacklist")
break
end
end
end
return PercentWithIncoming,ActualWithIncoming,nAbsorbs
end
-- returns unit GUID
function o:nGUID()
local nShortHand = ""
if GetUnitExists(unit) then
targetGUID = UnitGUID(unit)
nShortHand = UnitGUID(unit):sub(-5)
end
return targetGUID, nShortHand
end
-- Returns unit class
function o:GetClass()
if UnitGroupRolesAssigned(o.unit) == "NONE" then
if UnitIsUnit("player",o.unit) then
return UnitClass("player")
end
if novaEngineTables.roleTable[UnitName(o.unit)] ~= nil then
return novaEngineTables.roleTable[UnitName(o.unit)].class
end
else
return UnitClass(o.unit)
end
end
-- return unit role
function o:GetRole()
if UnitGroupRolesAssigned(o.unit) == "NONE" then
-- if we already have a role defined we dont scan
if novaEngineTables.roleTable[UnitName(o.unit)] ~= nil then
return novaEngineTables.roleTable[UnitName(o.unit)].role
end
else
return UnitGroupRolesAssigned(o.unit)
end
end
-- sets actual position of unit in engine, shouldnt refresh more than once/sec
function o:GetPosition()
if GetUnitIsVisible(o.unit) then
o.refresh = GetTime()
local x,y,z = GetObjectPosition(o.unit)
x = math.ceil(x*100)/100
y = math.ceil(y*100)/100
z = math.ceil(z*100)/100
return x,y,z
else
return 0,0,0
end
end
-- Group Number of Player: getUnitGroupNumber(1)
function o:getUnitGroupNumber()
-- check if in raid
if IsInRaid() and UnitInRaid(o.unit) ~= nil then
return select(3,GetRaidRosterInfo(UnitInRaid(o.unit)))
end
return 0
end
-- Unit distance to player
function o:getUnitDistance()
if UnitIsUnit("player",o.unit) then return 0 end
return getDistance("player",o.unit)
end
-- Updating the values of the Unit
function o:UpdateUnit()
if br.data.settings[br.selectedSpec].toggles["isDebugging"] == true then
local startTime, duration
local debugprofilestop = debugprofilestop
-- assign Name of unit
startTime = debugprofilestop()
o.name = UnitName(o.unit)
br.debug.cpu.healingEngine.UnitName = br.debug.cpu.healingEngine.UnitName + debugprofilestop()-startTime
-- assign real GUID of unit
startTime = debugprofilestop()
o.guid = o:nGUID()
br.debug.cpu.healingEngine.nGUID = br.debug.cpu.healingEngine.nGUID + debugprofilestop()-startTime
-- assign unit role
startTime = debugprofilestop()
o.role = o:GetRole()
br.debug.cpu.healingEngine.GetRole = br.debug.cpu.healingEngine.GetRole + debugprofilestop()-startTime
-- subgroup number
startTime = debugprofilestop()
o.subgroup = o:getUnitGroupNumber()
br.debug.cpu.healingEngine.getUnitGroupNumber = br.debug.cpu.healingEngine.getUnitGroupNumber+ debugprofilestop()-startTime
-- Short GUID of unit for the SetupTable
o.guidsh = select(2, o:nGUID())
-- set to true if unit should be dispelled
startTime = debugprofilestop()
o.dispel = o:Dispel(o.unit)
br.debug.cpu.healingEngine.Dispel = br.debug.cpu.healingEngine.Dispel + debugprofilestop()-startTime
-- distance to player
startTime = debugprofilestop()
o.distance = o:getUnitDistance()
br.debug.cpu.healingEngine.getUnitDistance = br.debug.cpu.healingEngine.getUnitDistance + debugprofilestop()-startTime
-- Unit's threat situation(1-4)
startTime = debugprofilestop()
o.threat = UnitThreatSituation(o.unit)
br.debug.cpu.healingEngine.UnitThreatSituation = br.debug.cpu.healingEngine.UnitThreatSituation + debugprofilestop()-startTime
-- Unit HP absolute
startTime = debugprofilestop()
o.hpabs = UnitHealth(o.unit)
br.debug.cpu.healingEngine.UnitHealth = br.debug.cpu.healingEngine.UnitHealth + debugprofilestop()-startTime
-- Unit HP missing absolute
startTime = debugprofilestop()
o.hpmissing = UnitHealthMax(o.unit) - UnitHealth(o.unit)
br.debug.cpu.healingEngine.hpMissing = br.debug.cpu.healingEngine.hpMissing + debugprofilestop()-startTime
-- Unit HP
startTime = debugprofilestop()
o.hp = o:CalcHP()
o.absorb = select(3, o:CalcHP())
br.debug.cpu.healingEngine.absorb = br.debug.cpu.healingEngine.absorb + debugprofilestop()-startTime
-- Target's target
o.target = tostring(o.unit).."target"
-- Unit Class
startTime = debugprofilestop()
o.class = o:GetClass()
br.debug.cpu.healingEngine.GetClass = br.debug.cpu.healingEngine.GetClass + debugprofilestop()-startTime
-- Unit is player
startTime = debugprofilestop()
o.isPlayer = UnitIsPlayer(o.unit)
br.debug.cpu.healingEngine.UnitIsPlayer = br.debug.cpu.healingEngine.UnitIsPlayer + debugprofilestop()-startTime
-- precise unit position
startTime = debugprofilestop()
if o.refresh == nil or o.refresh < GetTime() - 1 then
o.x,o.y,o.z = o:GetPosition()
end
br.debug.cpu.healingEngine.GetPosition = br.debug.cpu.healingEngine.GetPosition + debugprofilestop()-startTime
--debug
startTime = debugprofilestop()
o.hp, _, o.absorb = o:CalcHP()
br.debug.cpu.healingEngine.absorbANDhp = br.debug.cpu.healingEngine.absorbANDhp + debugprofilestop()-startTime
else
-- assign Name of unit
o.name = UnitName(o.unit)
-- assign real GUID of unit and Short GUID of unit for the SetupTable
o.guid, o.guidsh = o:nGUID()
-- assign unit role
o.role = o:GetRole()
-- subgroup number
o.subgroup = o:getUnitGroupNumber()
-- set to true if unit should be dispelled
o.dispel = o:Dispel(o.unit)
-- distance to player
o.distance = o:getUnitDistance()
-- Unit's threat situation(1-4)
o.threat = UnitThreatSituation(o.unit)
-- Unit HP absolute
o.hpabs = UnitHealth(o.unit)
-- Unit HP missing absolute
o.hpmissing = UnitHealthMax(o.unit) - UnitHealth(o.unit)
-- Unit HP and Absorb
o.hp, _, o.absorb = o:CalcHP()
-- Target's target
o.target = tostring(o.unit).."target"
-- Unit Class
o.class = o:GetClass()
-- Unit is player
o.isPlayer = UnitIsPlayer(o.unit)
-- precise unit position
if o.refresh == nil or o.refresh < GetTime() - 1 then
o.x,o.y,o.z = o:GetPosition()
end
end
-- add unit to setup cache
memberSetup.cache[select(2, getGUID(o.unit))] = o -- Add unit to SetupTable
end
-- Adding the user and functions we just created to this cached version in case we need it again
-- This will also serve as a good check for if the unit is already in the table easily
--Print(UnitName(unit), select(2, getGUID(unit)))
memberSetup.cache[select(2, o:nGUID())] = o
return o
end
-- Setting up the tables on either Wipe or Initial Setup
function SetupTables() -- Creating the cache (we use this to check if some1 is already in the table)
setmetatable(br.friend, metaTable1) -- Set the metaTable of Main to Meta
function br.friend:Update()
local refreshTimer = 0.666
if br.friendTableTimer == nil or br.friendTableTimer <= GetTime() - refreshTimer then
br.friendTableTimer = GetTime()
-- Print("HEAL PULSE: "..GetTime()) -- debug Print to check update time
-- This is for special situations, IE world healing or NPC healing in encounters
local selectedMode,SpecialTargets = getOptionValue("Special Heal"), {}
if getOptionCheck("Special Heal") == true then
if selectedMode == 1 then
SpecialTargets = { "target" }
elseif selectedMode == 2 then
SpecialTargets = { "target","mouseover","focus" }
elseif selectedMode == 3 then
SpecialTargets = { "target","mouseover" }
else
SpecialTargets = { "target","focus" }
end
end
for p=1, #SpecialTargets do
-- Checking if Unit Exists and it's possible to heal them
if GetUnitExists(SpecialTargets[p]) and HealCheck(SpecialTargets[p]) and not CheckSkipNPC(SpecialTargets[p]) then
if not memberSetup.cache[select(2, getGUID(SpecialTargets[p]))] then
local SpecialCase = memberSetup:new(SpecialTargets[p])
if SpecialCase then
-- Creating a new user, if not already tabled, will return with the User
for j=1, #br.friend do
if br.friend[j].unit == SpecialTargets[p] then
-- Now we add the Unit we just created to the Main Table
for k,v in pairs(memberSetup.cache) do
if br.friend[j].guidsh == k then
memberSetup.cache[k] = nil
end
end
tremove(br.friend, j)
break
end
end
end
tinsert(br.friend, SpecialCase)
novaEngineTables.SavedSpecialTargets[SpecialTargets[p]] = select(2,getGUID(SpecialTargets[p]))
end
end
end
for p=1, #SpecialTargets do
local removedTarget = false
for j=1, #br.friend do
-- Trying to find a case of the unit inside the Main Table to remove
if br.friend[j].unit == SpecialTargets[p] and (br.friend[j].guid ~= 0 and br.friend[j].guid ~= UnitGUID(SpecialTargets[p])) then
tremove(br.friend, j)
removedTarget = true
break
end
end
if removedTarget == true then
for k,v in pairs(memberSetup.cache) do
-- Now we're trying to find that unit in the Cache table to remove
if SpecialTargets[p] == v.unit then
memberSetup.cache[k] = nil
end
end
end
end
for i=1, #br.friend do
-- We are updating all of the User Info (Health/Range/Name)
br.friend[i]:UpdateUnit()
end
-- We are sorting by Health first
table.sort(br.friend, function(x,y)
return x.hp < y.hp
end)
-- Sorting with the Role
if getOptionCheck("Sorting with Role") then
table.sort(br.friend, function(x,y)
if x.role and y.role then return x.role > y.role
elseif x.role then return true
elseif y.role then return false end
end)
end
if getOptionCheck("Special Priority") == true then
if GetUnitExists("focus") and memberSetup.cache[select(2, getGUID("focus"))] then
table.sort(br.friend, function(x)
if x.unit == "focus" then
return true
else
return false
end
end)
end
if GetUnitExists("target") and memberSetup.cache[select(2, getGUID("target"))] then
table.sort(br.friend, function(x)
if x.unit == "target" then
return true
else
return false
end
end)
end
if GetUnitExists("mouseover") and memberSetup.cache[select(2, getGUID("mouseover"))] then
table.sort(br.friend, function(x)
if x.unit == "mouseover" then
return true
else
return false
end
end)
end
end
if pulseNovaDebugTimer == nil or pulseNovaDebugTimer <= GetTime() then
pulseNovaDebugTimer = GetTime() + 0.5
pulseNovaDebug()
end
-- update these frames to current br.friend values via a pulse in nova engine
end -- timer capsule
end
-- We are creating the initial Main Table
br.friend()
end
-- We are setting up the Tables for the first time
SetupTables()
end
| gpl-3.0 |
xponen/Zero-K | units/corbhmth.lua | 1 | 5825 | unitDef = {
unitname = [[corbhmth]],
name = [[Behemoth]],
description = [[Plasma Battery - Requires 50 Power]],
acceleration = 0,
activateWhenBuilt = true,
brakeRate = 0,
buildAngle = 8192,
buildCostEnergy = 2500,
buildCostMetal = 2500,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 8,
buildingGroundDecalSizeY = 8,
buildingGroundDecalType = [[corbhmth_aoplane.dds]],
buildPic = [[CORBHMTH.png]],
buildTime = 2500,
canAttack = true,
canstop = [[1]],
category = [[SINK]],
corpse = [[DEAD]],
customParams = {
description_de = [[Plasmabatterie - Benötigt ein angeschlossenes Stromnetz von 50 Energie, um feuern zu können.]],
description_pl = [[Bateria plazmowa]],
helptext = [[The Behemoth offers long-range artillery/counter-artillery capability, making it excellent for area denial. It is not designed as a defense turret, and will go down if attacked directly.]],
helptext_de = [[Der Behemoth besitzt eine weitreichende (Erwiderungs-)Artilleriefähigkeit, um Zugang zu größeren Arealen zu verhindern. Er wurde nicht als Verteidigungsturm entwickelt und wird bei direktem Angriff in die Knie gezwungen.]],
helptext_pl = [[Behemoth to bateria (przeciw-)artyleryjska. Swietnie radzi sobie z zabezpieczaniem terytorium, jednak latwo go zniszczyc bezposrednio. Aby strzelac, musi znajdowac sie w sieci energetycznej o mocy co najmniej 50 energii.]],
keeptooltip = [[any string I want]],
neededlink = 50,
pylonrange = 50,
},
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 5,
footprintZ = 5,
highTrajectory = 2,
iconType = [[staticarty]],
idleAutoHeal = 5,
idleTime = 1800,
mass = 605,
maxDamage = 3750,
maxSlope = 18,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
noAutoFire = false,
noChaseCategory = [[FIXEDWING LAND SHIP SATELLITE SWIM GUNSHIP SUB HOVER]],
objectName = [[corbhmth.s3o]],
onoffable = false,
script = [[corbhmth.lua]],
seismicSignature = 4,
selfDestructAs = [[LARGE_BUILDINGEX]],
sfxtypes = {
explosiongenerators = {
[[custom:LARGE_MUZZLE_FLASH_FX]],
},
},
side = [[CORE]],
sightDistance = 660,
smoothAnim = true,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[ooooo ooooo ooooo ooooo ooooo]],
weapons = {
{
def = [[PLASMA]],
badTargetCategory = [[GUNSHIP]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]],
},
},
weaponDefs = {
PLASMA = {
name = [[Long-Range Plasma Battery]],
areaOfEffect = 192,
avoidFeature = false,
avoidGround = false,
burst = 3,
burstRate = 0.16,
craterBoost = 1,
craterMult = 2,
damage = {
default = 600,
planes = 600,
subs = 30,
},
edgeEffectiveness = 0.5,
explosionGenerator = [[custom:330rlexplode]],
fireStarter = 120,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
mygravity = 0.1,
range = 1850,
reloadtime = 10,
soundHit = [[explosion/ex_large4]],
soundStart = [[explosion/ex_large5]],
sprayangle = 1024,
startsmoke = [[1]],
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 400,
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Behemoth]],
blocking = true,
category = [[corpses]],
damage = 3750,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 5,
footprintZ = 5,
height = [[20]],
hitdensity = [[100]],
metal = 1000,
object = [[corbhmth_dead.s3o]],
reclaimable = true,
reclaimTime = 1000,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Behemoth]],
blocking = false,
category = [[heaps]],
damage = 3750,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 5,
footprintZ = 5,
height = [[4]],
hitdensity = [[100]],
metal = 500,
object = [[debris4x4b.s3o]],
reclaimable = true,
reclaimTime = 500,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ corbhmth = unitDef })
| gpl-2.0 |
MRAHS/UBTEST | plugins/face.lua | 641 | 3073 | local https = require("ssl.https")
local ltn12 = require "ltn12"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function request(imageUrl)
local api_key = mashape.api_key
if api_key:isempty() then
return nil, 'Configure your Mashape API Key'
end
local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?"
local parameters = "attribute=gender%2Cage%2Crace"
parameters = parameters .. "&url="..(URL.escape(imageUrl) or "")
local url = api..parameters
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "Accept: application/json"
}
print(url)
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return "", code end
local body = table.concat(respbody)
return body, code
end
local function parseData(data)
local jsonBody = json:decode(data)
local response = ""
if jsonBody.error ~= nil then
if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then
response = response .. "The image is too big. Provide a smaller image."
elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then
response = response .. "Is that a valid url for an image?"
else
response = response .. jsonBody.error
end
elseif jsonBody.face == nil or #jsonBody.face == 0 then
response = response .. "No faces found"
else
response = response .. #jsonBody.face .." face(s) found:\n\n"
for k,face in pairs(jsonBody.face) do
local raceP = ""
if face.attribute.race.confidence > 85.0 then
raceP = face.attribute.race.value:lower()
elseif face.attribute.race.confidence > 50.0 then
raceP = "(probably "..face.attribute.race.value:lower()..")"
else
raceP = "(posibly "..face.attribute.race.value:lower()..")"
end
if face.attribute.gender.confidence > 85.0 then
response = response .. "There is a "
else
response = response .. "There may be a "
end
response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " "
response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n"
end
end
return response
end
local function run(msg, matches)
--return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg')
local data, code = request(matches[1])
if code ~= 200 then return "There was an error. "..code end
return parseData(data)
end
return {
description = "Who is in that photo?",
usage = {
"!face [url]",
"!recognise [url]"
},
patterns = {
"^!face (.*)$",
"^!recognise (.*)$"
},
run = run
}
| gpl-2.0 |
nifty-site-manager/nsm | LuaJIT/dynasm/dasm_arm64.lua | 1 | 35195 | ------------------------------------------------------------------------------
-- DynASM ARM64 module.
--
-- Copyright (C) 2005-2021 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "arm",
description = "DynASM ARM64 module",
version = "1.4.0",
vernum = 10400,
release = "2015-10-18",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, setmetatable, rawget = assert, setmetatable, rawget
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub
local concat, sort, insert = table.concat, table.sort, table.insert
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local ror, tohex = bit.ror, bit.tohex
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM", "IMM6", "IMM12", "IMM13W", "IMM13X", "IMML",
"VREG",
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
------------------------------------------------------------------------------
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n <= 0x000fffff then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
if n <= 0x000fffff then
insert(actlist, pos+1, n)
n = map_action.ESC * 0x10000
end
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end
local n = next_global
if n > 2047 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=20,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=20,next_global-1 do
out:write(" ", prefix, t[i], ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=20,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
-- Ext. register name -> int. name.
local map_archdef = { xzr = "@x31", wzr = "@w31", lr = "x30", }
-- Int. register name -> ext. name.
local map_reg_rev = { ["@x31"] = "xzr", ["@w31"] = "wzr", x30 = "lr", }
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
return map_reg_rev[s] or s
end
local map_shift = { lsl = 0, lsr = 1, asr = 2, }
local map_extend = {
uxtb = 0, uxth = 1, uxtw = 2, uxtx = 3,
sxtb = 4, sxth = 5, sxtw = 6, sxtx = 7,
}
local map_cond = {
eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7,
hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14,
hs = 2, lo = 3,
}
------------------------------------------------------------------------------
local parse_reg_type
local function parse_reg(expr, shift)
if not expr then werror("expected register name") end
local tname, ovreg = match(expr, "^([%w_]+):(@?%l%d+)$")
if not tname then
tname, ovreg = match(expr, "^([%w_]+):(R[xwqdshb]%b())$")
end
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local ok31, rt, r = match(expr, "^(@?)([xwqdshb])([123]?[0-9])$")
if r then
r = tonumber(r)
if r <= 30 or (r == 31 and ok31 ~= "" or (rt ~= "w" and rt ~= "x")) then
if not parse_reg_type then
parse_reg_type = rt
elseif parse_reg_type ~= rt then
werror("register size mismatch")
end
return shl(r, shift), tp
end
end
local vrt, vreg = match(expr, "^R([xwqdshb])(%b())$")
if vreg then
if not parse_reg_type then
parse_reg_type = vrt
elseif parse_reg_type ~= vrt then
werror("register size mismatch")
end
if shift then waction("VREG", shift, vreg) end
return 0
end
werror("bad register name `"..expr.."'")
end
local function parse_reg_base(expr)
if expr == "sp" then return 0x3e0 end
local base, tp = parse_reg(expr, 5)
if parse_reg_type ~= "x" then werror("bad register type") end
parse_reg_type = false
return base, tp
end
local parse_ctx = {}
local loadenv = setfenv and function(s)
local code = loadstring(s, "")
if code then setfenv(code, parse_ctx) end
return code
end or function(s)
return load(s, "", nil, parse_ctx)
end
-- Try to parse simple arithmetic, too, since some basic ops are aliases.
local function parse_number(n)
local x = tonumber(n)
if x then return x end
local code = loadenv("return "..n)
if code then
local ok, y = pcall(code)
if ok then return y end
end
return nil
end
local function parse_imm(imm, bits, shift, scale, signed)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm)
return 0
end
end
local function parse_imm12(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
if shr(n, 12) == 0 then
return shl(n, 10)
elseif band(n, 0xff000fff) == 0 then
return shr(n, 2) + 0x00400000
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM12", 0, imm)
return 0
end
end
local function parse_imm13(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
local r64 = parse_reg_type == "x"
if n and n % 1 == 0 and n >= 0 and n <= 0xffffffff then
local inv = false
if band(n, 1) == 1 then n = bit.bnot(n); inv = true end
local t = {}
for i=1,32 do t[i] = band(n, 1); n = shr(n, 1) end
local b = table.concat(t)
b = b..(r64 and (inv and "1" or "0"):rep(32) or b)
local p0, p1, p0a, p1a = b:match("^(0+)(1+)(0*)(1*)")
if p0 then
local w = p1a == "" and (r64 and 64 or 32) or #p1+#p0a
if band(w, w-1) == 0 and b == b:sub(1, w):rep(64/w) then
local s = band(-2*w, 0x3f) - 1
if w == 64 then s = s + 0x1000 end
if inv then
return shl(w-#p1-#p0, 16) + shl(s+w-#p1, 10)
else
return shl(w-#p0, 16) + shl(s+#p1, 10)
end
end
end
werror("out of range immediate `"..imm.."'")
elseif r64 then
waction("IMM13X", 0, format("(unsigned int)(%s)", imm))
actargs[#actargs+1] = format("(unsigned int)((unsigned long long)(%s)>>32)", imm)
return 0
else
waction("IMM13W", 0, imm)
return 0
end
end
local function parse_imm6(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
if n >= 0 and n <= 63 then
return shl(band(n, 0x1f), 19) + (n >= 32 and 0x80000000 or 0)
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM6", 0, imm)
return 0
end
end
local function parse_imm_load(imm, scale)
local n = parse_number(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n and m >= 0 and m < 0x1000 then
return shl(m, 10) + 0x01000000 -- Scaled, unsigned 12 bit offset.
elseif n >= -256 and n < 256 then
return shl(band(n, 511), 12) -- Unscaled, signed 9 bit offset.
end
werror("out of range immediate `"..imm.."'")
else
waction("IMML", scale, imm)
return 0
end
end
local function parse_fpimm(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = parse_number(imm)
if n then
local m, e = math.frexp(n)
local s, e2 = 0, band(e-2, 7)
if m < 0 then m = -m; s = 0x00100000 end
m = m*32-16
if m % 1 == 0 and m >= 0 and m <= 15 and sar(shl(e2, 29), 29)+2 == e then
return s + shl(e2, 17) + shl(m, 13)
end
werror("out of range immediate `"..imm.."'")
else
werror("NYI fpimm action")
end
end
local function parse_shift(expr)
local s, s2 = match(expr, "^(%S+)%s*(.*)$")
s = map_shift[s]
if not s then werror("expected shift operand") end
return parse_imm(s2, 6, 10, 0, false) + shl(s, 22)
end
local function parse_lslx16(expr)
local n = match(expr, "^lsl%s*#(%d+)$")
n = tonumber(n)
if not n then werror("expected shift operand") end
if band(n, parse_reg_type == "x" and 0xffffffcf or 0xffffffef) ~= 0 then
werror("bad shift amount")
end
return shl(n, 17)
end
local function parse_extend(expr)
local s, s2 = match(expr, "^(%S+)%s*(.*)$")
if s == "lsl" then
s = parse_reg_type == "x" and 3 or 2
else
s = map_extend[s]
end
if not s then werror("expected extend operand") end
return (s2 == "" and 0 or parse_imm(s2, 3, 10, 0, false)) + shl(s, 13)
end
local function parse_cond(expr, inv)
local c = map_cond[expr]
if not c then werror("expected condition operand") end
return shl(bit.bxor(c, inv), 12)
end
local function parse_load(params, nparams, n, op)
if params[n+2] then werror("too many operands") end
local scale = shr(op, 30)
local pn, p2 = params[n], params[n+1]
local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$")
if not p1 then
if not p2 then
local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local base, tp = parse_reg_base(reg)
if tp then
waction("IMML", scale, format(tp.ctypefmt, tailr))
return op + base
end
end
end
werror("expected address operand")
end
if p2 then
if wb == "!" then werror("bad use of '!'") end
op = op + parse_reg_base(p1) + parse_imm(p2, 9, 12, 0, true) + 0x400
elseif wb == "!" then
local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$")
if not p1a then werror("bad use of '!'") end
op = op + parse_reg_base(p1a) + parse_imm(p2a, 9, 12, 0, true) + 0xc00
else
local p1a, p2a = match(p1, "^([^,%s]*)%s*(.*)$")
op = op + parse_reg_base(p1a)
if p2a ~= "" then
local imm = match(p2a, "^,%s*#(.*)$")
if imm then
op = op + parse_imm_load(imm, scale)
else
local p2b, p3b, p3s = match(p2a, "^,%s*([^,%s]*)%s*,?%s*(%S*)%s*(.*)$")
op = op + parse_reg(p2b, 16) + 0x00200800
if parse_reg_type ~= "x" and parse_reg_type ~= "w" then
werror("bad index register type")
end
if p3b == "" then
if parse_reg_type ~= "x" then werror("bad index register type") end
op = op + 0x6000
else
if p3s == "" or p3s == "#0" then
elseif p3s == "#"..scale then
op = op + 0x1000
else
werror("bad scale")
end
if parse_reg_type == "x" then
if p3b == "lsl" and p3s ~= "" then op = op + 0x6000
elseif p3b == "sxtx" then op = op + 0xe000
else
werror("bad extend/shift specifier")
end
else
if p3b == "uxtw" then op = op + 0x4000
elseif p3b == "sxtw" then op = op + 0xc000
else
werror("bad extend/shift specifier")
end
end
end
end
else
if wb == "!" then werror("bad use of '!'") end
op = op + 0x01000000
end
end
return op
end
local function parse_load_pair(params, nparams, n, op)
if params[n+2] then werror("too many operands") end
local pn, p2 = params[n], params[n+1]
local scale = shr(op, 30) == 0 and 2 or 3
local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$")
if not p1 then
if not p2 then
local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local base, tp = parse_reg_base(reg)
if tp then
waction("IMM", 32768+7*32+15+scale*1024, format(tp.ctypefmt, tailr))
return op + base + 0x01000000
end
end
end
werror("expected address operand")
end
if p2 then
if wb == "!" then werror("bad use of '!'") end
op = op + 0x00800000
else
local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$")
if p1a then p1, p2 = p1a, p2a else p2 = "#0" end
op = op + (wb == "!" and 0x01800000 or 0x01000000)
end
return op + parse_reg_base(p1) + parse_imm(p2, 7, 15, scale, true)
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
local function branch_type(op)
if band(op, 0x7c000000) == 0x14000000 then return 0 -- B, BL
elseif shr(op, 24) == 0x54 or band(op, 0x7e000000) == 0x34000000 or
band(op, 0x3b000000) == 0x18000000 then
return 0x800 -- B.cond, CBZ, CBNZ, LDR* literal
elseif band(op, 0x7e000000) == 0x36000000 then return 0x1000 -- TBZ, TBNZ
elseif band(op, 0x9f000000) == 0x10000000 then return 0x2000 -- ADR
elseif band(op, 0x9f000000) == band(0x90000000) then return 0x3000 -- ADRP
else
assert(false, "unknown branch type")
end
end
------------------------------------------------------------------------------
local map_op, op_template
local function op_alias(opname, f)
return function(params, nparams)
if not params then return "-> "..opname:sub(1, -3) end
f(params, nparams)
op_template(params, map_op[opname], nparams)
end
end
local function alias_bfx(p)
p[4] = "#("..p[3]:sub(2)..")+("..p[4]:sub(2)..")-1"
end
local function alias_bfiz(p)
parse_reg(p[1], 0)
if parse_reg_type == "w" then
p[3] = "#-("..p[3]:sub(2)..")%32"
p[4] = "#("..p[4]:sub(2)..")-1"
else
p[3] = "#-("..p[3]:sub(2)..")%64"
p[4] = "#("..p[4]:sub(2)..")-1"
end
end
local alias_lslimm = op_alias("ubfm_4", function(p)
parse_reg(p[1], 0)
local sh = p[3]:sub(2)
if parse_reg_type == "w" then
p[3] = "#-("..sh..")%32"
p[4] = "#31-("..sh..")"
else
p[3] = "#-("..sh..")%64"
p[4] = "#63-("..sh..")"
end
end)
-- Template strings for ARM instructions.
map_op = {
-- Basic data processing instructions.
add_3 = "0b000000DNMg|11000000pDpNIg|8b206000pDpNMx",
add_4 = "0b000000DNMSg|0b200000DNMXg|8b200000pDpNMXx|8b200000pDpNxMwX",
adds_3 = "2b000000DNMg|31000000DpNIg|ab206000DpNMx",
adds_4 = "2b000000DNMSg|2b200000DNMXg|ab200000DpNMXx|ab200000DpNxMwX",
cmn_2 = "2b00001fNMg|3100001fpNIg|ab20601fpNMx",
cmn_3 = "2b00001fNMSg|2b20001fNMXg|ab20001fpNMXx|ab20001fpNxMwX",
sub_3 = "4b000000DNMg|51000000pDpNIg|cb206000pDpNMx",
sub_4 = "4b000000DNMSg|4b200000DNMXg|cb200000pDpNMXx|cb200000pDpNxMwX",
subs_3 = "6b000000DNMg|71000000DpNIg|eb206000DpNMx",
subs_4 = "6b000000DNMSg|6b200000DNMXg|eb200000DpNMXx|eb200000DpNxMwX",
cmp_2 = "6b00001fNMg|7100001fpNIg|eb20601fpNMx",
cmp_3 = "6b00001fNMSg|6b20001fNMXg|eb20001fpNMXx|eb20001fpNxMwX",
neg_2 = "4b0003e0DMg",
neg_3 = "4b0003e0DMSg",
negs_2 = "6b0003e0DMg",
negs_3 = "6b0003e0DMSg",
adc_3 = "1a000000DNMg",
adcs_3 = "3a000000DNMg",
sbc_3 = "5a000000DNMg",
sbcs_3 = "7a000000DNMg",
ngc_2 = "5a0003e0DMg",
ngcs_2 = "7a0003e0DMg",
and_3 = "0a000000DNMg|12000000pDNig",
and_4 = "0a000000DNMSg",
orr_3 = "2a000000DNMg|32000000pDNig",
orr_4 = "2a000000DNMSg",
eor_3 = "4a000000DNMg|52000000pDNig",
eor_4 = "4a000000DNMSg",
ands_3 = "6a000000DNMg|72000000DNig",
ands_4 = "6a000000DNMSg",
tst_2 = "6a00001fNMg|7200001fNig",
tst_3 = "6a00001fNMSg",
bic_3 = "0a200000DNMg",
bic_4 = "0a200000DNMSg",
orn_3 = "2a200000DNMg",
orn_4 = "2a200000DNMSg",
eon_3 = "4a200000DNMg",
eon_4 = "4a200000DNMSg",
bics_3 = "6a200000DNMg",
bics_4 = "6a200000DNMSg",
movn_2 = "12800000DWg",
movn_3 = "12800000DWRg",
movz_2 = "52800000DWg",
movz_3 = "52800000DWRg",
movk_2 = "72800000DWg",
movk_3 = "72800000DWRg",
-- TODO: this doesn't cover all valid immediates for mov reg, #imm.
mov_2 = "2a0003e0DMg|52800000DW|320003e0pDig|11000000pDpNg",
mov_3 = "2a0003e0DMSg",
mvn_2 = "2a2003e0DMg",
mvn_3 = "2a2003e0DMSg",
adr_2 = "10000000DBx",
adrp_2 = "90000000DBx",
csel_4 = "1a800000DNMCg",
csinc_4 = "1a800400DNMCg",
csinv_4 = "5a800000DNMCg",
csneg_4 = "5a800400DNMCg",
cset_2 = "1a9f07e0Dcg",
csetm_2 = "5a9f03e0Dcg",
cinc_3 = "1a800400DNmcg",
cinv_3 = "5a800000DNmcg",
cneg_3 = "5a800400DNmcg",
ccmn_4 = "3a400000NMVCg|3a400800N5VCg",
ccmp_4 = "7a400000NMVCg|7a400800N5VCg",
madd_4 = "1b000000DNMAg",
msub_4 = "1b008000DNMAg",
mul_3 = "1b007c00DNMg",
mneg_3 = "1b00fc00DNMg",
smaddl_4 = "9b200000DxNMwAx",
smsubl_4 = "9b208000DxNMwAx",
smull_3 = "9b207c00DxNMw",
smnegl_3 = "9b20fc00DxNMw",
smulh_3 = "9b407c00DNMx",
umaddl_4 = "9ba00000DxNMwAx",
umsubl_4 = "9ba08000DxNMwAx",
umull_3 = "9ba07c00DxNMw",
umnegl_3 = "9ba0fc00DxNMw",
umulh_3 = "9bc07c00DNMx",
udiv_3 = "1ac00800DNMg",
sdiv_3 = "1ac00c00DNMg",
-- Bit operations.
sbfm_4 = "13000000DN12w|93400000DN12x",
bfm_4 = "33000000DN12w|b3400000DN12x",
ubfm_4 = "53000000DN12w|d3400000DN12x",
extr_4 = "13800000DNM2w|93c00000DNM2x",
sxtb_2 = "13001c00DNw|93401c00DNx",
sxth_2 = "13003c00DNw|93403c00DNx",
sxtw_2 = "93407c00DxNw",
uxtb_2 = "53001c00DNw",
uxth_2 = "53003c00DNw",
sbfx_4 = op_alias("sbfm_4", alias_bfx),
bfxil_4 = op_alias("bfm_4", alias_bfx),
ubfx_4 = op_alias("ubfm_4", alias_bfx),
sbfiz_4 = op_alias("sbfm_4", alias_bfiz),
bfi_4 = op_alias("bfm_4", alias_bfiz),
ubfiz_4 = op_alias("ubfm_4", alias_bfiz),
lsl_3 = function(params, nparams)
if params and params[3]:byte() == 35 then
return alias_lslimm(params, nparams)
else
return op_template(params, "1ac02000DNMg", nparams)
end
end,
lsr_3 = "1ac02400DNMg|53007c00DN1w|d340fc00DN1x",
asr_3 = "1ac02800DNMg|13007c00DN1w|9340fc00DN1x",
ror_3 = "1ac02c00DNMg|13800000DNm2w|93c00000DNm2x",
clz_2 = "5ac01000DNg",
cls_2 = "5ac01400DNg",
rbit_2 = "5ac00000DNg",
rev_2 = "5ac00800DNw|dac00c00DNx",
rev16_2 = "5ac00400DNg",
rev32_2 = "dac00800DNx",
-- Loads and stores.
["strb_*"] = "38000000DwL",
["ldrb_*"] = "38400000DwL",
["ldrsb_*"] = "38c00000DwL|38800000DxL",
["strh_*"] = "78000000DwL",
["ldrh_*"] = "78400000DwL",
["ldrsh_*"] = "78c00000DwL|78800000DxL",
["str_*"] = "b8000000DwL|f8000000DxL|bc000000DsL|fc000000DdL",
["ldr_*"] = "18000000DwB|58000000DxB|1c000000DsB|5c000000DdB|b8400000DwL|f8400000DxL|bc400000DsL|fc400000DdL",
["ldrsw_*"] = "98000000DxB|b8800000DxL",
-- NOTE: ldur etc. are handled by ldr et al.
["stp_*"] = "28000000DAwP|a8000000DAxP|2c000000DAsP|6c000000DAdP",
["ldp_*"] = "28400000DAwP|a8400000DAxP|2c400000DAsP|6c400000DAdP",
["ldpsw_*"] = "68400000DAxP",
-- Branches.
b_1 = "14000000B",
bl_1 = "94000000B",
blr_1 = "d63f0000Nx",
br_1 = "d61f0000Nx",
ret_0 = "d65f03c0",
ret_1 = "d65f0000Nx",
-- b.cond is added below.
cbz_2 = "34000000DBg",
cbnz_2 = "35000000DBg",
tbz_3 = "36000000DTBw|36000000DTBx",
tbnz_3 = "37000000DTBw|37000000DTBx",
-- Miscellaneous instructions.
-- TODO: hlt, hvc, smc, svc, eret, dcps[123], drps, mrs, msr
-- TODO: sys, sysl, ic, dc, at, tlbi
-- TODO: hint, yield, wfe, wfi, sev, sevl
-- TODO: clrex, dsb, dmb, isb
nop_0 = "d503201f",
brk_0 = "d4200000",
brk_1 = "d4200000W",
-- Floating point instructions.
fmov_2 = "1e204000DNf|1e260000DwNs|1e270000DsNw|9e660000DxNd|9e670000DdNx|1e201000DFf",
fabs_2 = "1e20c000DNf",
fneg_2 = "1e214000DNf",
fsqrt_2 = "1e21c000DNf",
fcvt_2 = "1e22c000DdNs|1e624000DsNd",
-- TODO: half-precision and fixed-point conversions.
fcvtas_2 = "1e240000DwNs|9e240000DxNs|1e640000DwNd|9e640000DxNd",
fcvtau_2 = "1e250000DwNs|9e250000DxNs|1e650000DwNd|9e650000DxNd",
fcvtms_2 = "1e300000DwNs|9e300000DxNs|1e700000DwNd|9e700000DxNd",
fcvtmu_2 = "1e310000DwNs|9e310000DxNs|1e710000DwNd|9e710000DxNd",
fcvtns_2 = "1e200000DwNs|9e200000DxNs|1e600000DwNd|9e600000DxNd",
fcvtnu_2 = "1e210000DwNs|9e210000DxNs|1e610000DwNd|9e610000DxNd",
fcvtps_2 = "1e280000DwNs|9e280000DxNs|1e680000DwNd|9e680000DxNd",
fcvtpu_2 = "1e290000DwNs|9e290000DxNs|1e690000DwNd|9e690000DxNd",
fcvtzs_2 = "1e380000DwNs|9e380000DxNs|1e780000DwNd|9e780000DxNd",
fcvtzu_2 = "1e390000DwNs|9e390000DxNs|1e790000DwNd|9e790000DxNd",
scvtf_2 = "1e220000DsNw|9e220000DsNx|1e620000DdNw|9e620000DdNx",
ucvtf_2 = "1e230000DsNw|9e230000DsNx|1e630000DdNw|9e630000DdNx",
frintn_2 = "1e244000DNf",
frintp_2 = "1e24c000DNf",
frintm_2 = "1e254000DNf",
frintz_2 = "1e25c000DNf",
frinta_2 = "1e264000DNf",
frintx_2 = "1e274000DNf",
frinti_2 = "1e27c000DNf",
fadd_3 = "1e202800DNMf",
fsub_3 = "1e203800DNMf",
fmul_3 = "1e200800DNMf",
fnmul_3 = "1e208800DNMf",
fdiv_3 = "1e201800DNMf",
fmadd_4 = "1f000000DNMAf",
fmsub_4 = "1f008000DNMAf",
fnmadd_4 = "1f200000DNMAf",
fnmsub_4 = "1f208000DNMAf",
fmax_3 = "1e204800DNMf",
fmaxnm_3 = "1e206800DNMf",
fmin_3 = "1e205800DNMf",
fminnm_3 = "1e207800DNMf",
fcmp_2 = "1e202000NMf|1e202008NZf",
fcmpe_2 = "1e202010NMf|1e202018NZf",
fccmp_4 = "1e200400NMVCf",
fccmpe_4 = "1e200410NMVCf",
fcsel_4 = "1e200c00DNMCf",
-- TODO: crc32*, aes*, sha*, pmull
-- TODO: SIMD instructions.
}
for cond,c in pairs(map_cond) do
map_op["b"..cond.."_1"] = tohex(0x54000000+c).."B"
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
local function parse_template(params, template, nparams, pos)
local op = tonumber(sub(template, 1, 8), 16)
local n = 1
local rtt = {}
parse_reg_type = false
-- Process each character.
for p in gmatch(sub(template, 9), ".") do
local q = params[n]
if p == "D" then
op = op + parse_reg(q, 0); n = n + 1
elseif p == "N" then
op = op + parse_reg(q, 5); n = n + 1
elseif p == "M" then
op = op + parse_reg(q, 16); n = n + 1
elseif p == "A" then
op = op + parse_reg(q, 10); n = n + 1
elseif p == "m" then
op = op + parse_reg(params[n-1], 16)
elseif p == "p" then
if q == "sp" then params[n] = "@x31" end
elseif p == "g" then
if parse_reg_type == "x" then
op = op + 0x80000000
elseif parse_reg_type ~= "w" then
werror("bad register type")
end
parse_reg_type = false
elseif p == "f" then
if parse_reg_type == "d" then
op = op + 0x00400000
elseif parse_reg_type ~= "s" then
werror("bad register type")
end
parse_reg_type = false
elseif p == "x" or p == "w" or p == "d" or p == "s" then
if parse_reg_type ~= p then
werror("register size mismatch")
end
parse_reg_type = false
elseif p == "L" then
op = parse_load(params, nparams, n, op)
elseif p == "P" then
op = parse_load_pair(params, nparams, n, op)
elseif p == "B" then
local mode, v, s = parse_label(q, false); n = n + 1
local m = branch_type(op)
waction("REL_"..mode, v+m, s, 1)
elseif p == "I" then
op = op + parse_imm12(q); n = n + 1
elseif p == "i" then
op = op + parse_imm13(q); n = n + 1
elseif p == "W" then
op = op + parse_imm(q, 16, 5, 0, false); n = n + 1
elseif p == "T" then
op = op + parse_imm6(q); n = n + 1
elseif p == "1" then
op = op + parse_imm(q, 6, 16, 0, false); n = n + 1
elseif p == "2" then
op = op + parse_imm(q, 6, 10, 0, false); n = n + 1
elseif p == "5" then
op = op + parse_imm(q, 5, 16, 0, false); n = n + 1
elseif p == "V" then
op = op + parse_imm(q, 4, 0, 0, false); n = n + 1
elseif p == "F" then
op = op + parse_fpimm(q); n = n + 1
elseif p == "Z" then
if q ~= "#0" and q ~= "#0.0" then werror("expected zero immediate") end
n = n + 1
elseif p == "S" then
op = op + parse_shift(q); n = n + 1
elseif p == "X" then
op = op + parse_extend(q); n = n + 1
elseif p == "R" then
op = op + parse_lslx16(q); n = n + 1
elseif p == "C" then
op = op + parse_cond(q, 0); n = n + 1
elseif p == "c" then
op = op + parse_cond(q, 1); n = n + 1
else
assert(false)
end
end
wputpos(pos, op)
end
function op_template(params, template, nparams)
if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 3 positions.
if secpos+3 > maxsecpos then wflush() end
local pos = wpos()
local lpos, apos, spos = #actlist, #actargs, secpos
local ok, err
for t in gmatch(template, "[^|]+") do
ok, err = pcall(parse_template, params, t, nparams, pos)
if ok then return end
secpos = spos
actlist[lpos+1] = nil
actlist[lpos+2] = nil
actlist[lpos+3] = nil
actargs[apos+1] = nil
actargs[apos+2] = nil
actargs[apos+3] = nil
end
error(err, 0)
end
map_op[".template__"] = op_template
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1])
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION", num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = map_coreop })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| mit |
xponen/Zero-K | LuaUI/Widgets/chili/Controls/font.lua | 17 | 6639 | --//=============================================================================
Font = Object:Inherit{
classname = 'font',
font = "FreeSansBold.otf",
size = 12,
outlineWidth = 3,
outlineWeight = 3,
shadow = false,
outline = false,
color = {1,1,1,1},
outlineColor = {0,0,0,1},
autoOutlineColor = true,
}
local this = Font
local inherited = this.inherited
--//=============================================================================
function Font:New(obj)
obj = inherited.New(self,obj)
--// Load the font
obj:_LoadFont()
return obj
end
function Font:Dispose(...)
if (not self.disposed) then
FontHandler.UnloadFont(self._font)
end
inherited.Dispose(self,...)
end
--//=============================================================================
function Font:_LoadFont()
local oldfont = self._font
self._font = FontHandler.LoadFont(self.font,self.size,self.outlineWidth,self.outlineWeight)
--// do this after LoadFont because it can happen that LoadFont returns the same font again
--// but if we Unload our old one before, the gc could collect it before, so the engine would have to reload it again
FontHandler.UnloadFont(oldfont)
end
--//=============================================================================
local function NotEqual(v1, v2)
local t1 = type(v1)
local t2 = type(v2)
if (t1 ~= t2) then
return true
end
local isindexable = (t=="table")or(t=="metatable")or(t=="userdata")
if (not isindexable) then
return (t1 ~= t2)
end
for i,v in pairs(v1) do
if (v ~= v2[i]) then
return true
end
end
for i,v in pairs(v2) do
if (v ~= v1[i]) then
return true
end
end
end
do
--// Create some Set... methods (e.g. SetColor, SetSize, SetFont, ...)
local params = {
font = true,
size = true,
outlineWidth = true,
outlineWeight = true,
shadow = false,
outline = false,
color = false,
outlineColor = false,
autoOutlineColor = false,
}
for param,recreateFont in pairs(params) do
local paramWithUpperCase = param:gsub("^%l", string.upper)
local funcname = "Set" .. paramWithUpperCase
Font[funcname] = function(self,value,...)
local t = type(value)
local oldValue = self[param]
if (t == "table") then
self[param] = table.shallowcopy(value)
else
local to = type(self[param])
if (to == "table") then
--// this allows :SetColor(r,g,b,a) and :SetColor({r,g,b,a})
local newtable = {value,...}
table.merge(newtable,self[param])
self[param] = newtable
else
self[param] = value
end
end
local p = self.parent
if (recreateFont) then
self:_LoadFont()
if (p) then
p:RequestRealign()
end
else
if (p)and NotEqual(oldValue, self[param]) then
p:Invalidate()
end
end
end
end
params = nil
end
--//=============================================================================
function Font:GetLineHeight(size)
return self._font.lineheight * (size or self.size)
end
function Font:GetAscenderHeight(size)
local font = self._font
return (font.lineheight + font.descender) * (size or self.size)
end
function Font:GetTextWidth(text, size)
return (self._font):GetTextWidth(text) * (size or self.size)
end
function Font:GetTextHeight(text, size)
if (not size) then size = self.size end
local h,descender,numlines = (self._font):GetTextHeight(text)
return h*size, descender*size, numlines
end
function Font:WrapText(text, width, height, size)
if (not size) then size = self.size end
if (height < 1.5 * self._font.lineheight)or(width < size) then
return text --//workaround for a bug in <=80.5.2
end
return (self._font):WrapText(text,width,height,size)
end
--//=============================================================================
function Font:AdjustPosToAlignment(x, y, width, height, align, valign)
local extra = ''
--// vertical alignment
if valign == "center" then
y = y + height/2
extra = 'v'
elseif valign == "top" then
extra = 't'
elseif valign == "bottom" then
y = y + height
extra = 'b'
elseif valign == "linecenter" then
y = y + (height / 2) + (1 + self._font.descender) * self.size / 2
extra = 'x'
else
--// ascender
extra = 'a'
end
--FIXME add baseline 'd'
--// horizontal alignment
if align == "left" then
--do nothing
elseif align == "center" then
x = x + width/2
extra = extra .. 'c'
elseif align == "right" then
x = x + width
extra = extra .. 'r'
end
return x,y,extra
end
local function _GetExtra(align, valign)
local extra = ''
--// vertical alignment
if valign == "center" then
extra = 'v'
elseif valign == "top" then
extra = 't'
elseif valign == "bottom" then
extra = 'b'
else
--// ascender
extra = 'a'
end
--// horizontal alignment
if align == "left" then
--do nothing
elseif align == "center" then
extra = extra .. 'c'
elseif align == "right" then
extra = extra .. 'r'
end
return extra
end
--//=============================================================================
function Font:Draw(text, x, y, align, valign)
if (not text) then
return
end
local font = self._font
local extra = _GetExtra(align, valign)
if self.outline then
extra = extra .. 'o'
elseif self.shadow then
extra = extra .. 's'
end
gl.PushMatrix()
gl.Scale(1,-1,1)
font:Begin()
font:SetTextColor(self.color)
font:SetOutlineColor(self.outlineColor)
font:SetAutoOutlineColor(self.autoOutlineColor)
font:Print(text, x, -y, self.size, extra)
font:End()
gl.PopMatrix()
end
function Font:DrawInBox(text, x, y, w, h, align, valign)
if (not text) then
return
end
local font = self._font
local x,y,extra = self:AdjustPosToAlignment(x, y, w, h, align, valign)
if self.outline then
extra = extra .. 'o'
elseif self.shadow then
extra = extra .. 's'
end
y = y + 1 --// FIXME: if this isn't done some chars as 'R' get truncated at the top
gl.PushMatrix()
gl.Scale(1,-1,1)
font:Begin()
font:SetTextColor(self.color)
font:SetOutlineColor(self.outlineColor)
font:SetAutoOutlineColor(self.autoOutlineColor)
font:Print(text, x, -y, self.size, extra)
font:End()
gl.PopMatrix()
end
Font.Print = Font.Draw
Font.PrintInBox = Font.DrawInBox
--//=============================================================================
| gpl-2.0 |
lambd0x/Awesome-wm-Funtoo-GreenInfinity | awesome/vicious/widgets/cpu_freebsd.lua | 4 | 1758 | -- {{{ Grab environment
local helpers = require("vicious.helpers")
local tonumber = tonumber
local setmetatable = setmetatable
local math = { floor = math.floor }
local string = { gmatch = string.gmatch }
-- }}}
-- Cpu: provides CPU usage for all available CPUs/cores
-- vicious.widgets.cpu_freebsd
local cpu_freebsd = {}
-- Initialize function tables
local cpu_total = {}
local cpu_idle = {}
-- {{{ CPU widget type
local function worker(format)
local cp_times = helpers.sysctl("kern.cp_times")
local matches = {}
local tmp_total = {}
local tmp_idle = {}
local tmp_usage = {}
-- Read input data
for v in string.gmatch(cp_times, "([%d]+)") do
table.insert(matches, v)
end
-- Set first value of function tables
if #cpu_total == 0 then -- check for empty table
for i = 1, #matches / 5 + 1 do
cpu_total[i] = 0
cpu_idle[i] = 0
end
end
for i = 1, #matches / 5 + 1 do
tmp_total[i] = 0
tmp_idle[i] = 0
tmp_usage[i] = 0
end
-- CPU usage
for i, v in ipairs(matches) do
local index = math.floor((i-1) / 5) + 2 -- current cpu
tmp_total[1] = tmp_total[1] + v
tmp_total[index] = tmp_total[index] + v
if (i-1) % 5 == 4 then
tmp_idle[1] = tmp_idle[1] + v
tmp_idle[index] = tmp_idle[index] + v
end
end
for i = 1, #tmp_usage do
tmp_usage[i] = tmp_total[i] - cpu_total[i]
tmp_usage[i] = math.floor((tmp_usage[i] - (tmp_idle[i] - cpu_idle[i])) / tmp_usage[i] * 100)
end
cpu_total = tmp_total
cpu_idle = tmp_idle
return tmp_usage
end
-- }}}
return setmetatable(cpu_freebsd, { __call = function(_, ...) return worker(...) end })
| gpl-2.0 |
nwf/nodemcu-firmware | app/lua53/host/tests/math.lua | 7 | 24284 | -- $Id: math.lua,v 1.78 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice in file all.lua
print("testing numbers and math lib")
local minint = math.mininteger
local maxint = math.maxinteger
local intbits = math.floor(math.log(maxint, 2) + 0.5) + 1
assert((1 << intbits) == 0)
assert(minint == 1 << (intbits - 1))
assert(maxint == minint - 1)
-- number of bits in the mantissa of a floating-point number
local floatbits = 24
do
local p = 2.0^floatbits
while p < p + 1.0 do
p = p * 2.0
floatbits = floatbits + 1
end
end
local function isNaN (x)
return (x ~= x)
end
assert(isNaN(0/0))
assert(not isNaN(1/0))
do
local x = 2.0^floatbits
assert(x > x - 1.0 and x == x + 1.0)
print(string.format("%d-bit integers, %d-bit (mantissa) floats",
intbits, floatbits))
end
assert(math.type(0) == "integer" and math.type(0.0) == "float"
and math.type("10") == nil)
local function checkerror (msg, f, ...)
local s, err = pcall(f, ...)
assert(not s and string.find(err, msg))
end
local msgf2i = "number.* has no integer representation"
-- float equality
function eq (a,b,limit)
if not limit then
if floatbits >= 50 then limit = 1E-11
else limit = 1E-5
end
end
-- a == b needed for +inf/-inf
return a == b or math.abs(a-b) <= limit
end
-- equality with types
function eqT (a,b)
return a == b and math.type(a) == math.type(b)
end
-- basic float notation
assert(0e12 == 0 and .0 == 0 and 0. == 0 and .2e2 == 20 and 2.E-1 == 0.2)
do
local a,b,c = "2", " 3e0 ", " 10 "
assert(a+b == 5 and -b == -3 and b+"2" == 5 and "10"-c == 0)
assert(type(a) == 'string' and type(b) == 'string' and type(c) == 'string')
assert(a == "2" and b == " 3e0 " and c == " 10 " and -c == -" 10 ")
assert(c%a == 0 and a^b == 08)
a = 0
assert(a == -a and 0 == -0)
end
do
local x = -1
local mz = 0/x -- minus zero
t = {[0] = 10, 20, 30, 40, 50}
assert(t[mz] == t[0] and t[-0] == t[0])
end
do -- tests for 'modf'
local a,b = math.modf(3.5)
assert(a == 3.0 and b == 0.5)
a,b = math.modf(-2.5)
assert(a == -2.0 and b == -0.5)
a,b = math.modf(-3e23)
assert(a == -3e23 and b == 0.0)
a,b = math.modf(3e35)
assert(a == 3e35 and b == 0.0)
a,b = math.modf(-1/0) -- -inf
assert(a == -1/0 and b == 0.0)
a,b = math.modf(1/0) -- inf
assert(a == 1/0 and b == 0.0)
a,b = math.modf(0/0) -- NaN
assert(isNaN(a) and isNaN(b))
a,b = math.modf(3) -- integer argument
assert(eqT(a, 3) and eqT(b, 0.0))
a,b = math.modf(minint)
assert(eqT(a, minint) and eqT(b, 0.0))
end
assert(math.huge > 10e30)
assert(-math.huge < -10e30)
-- integer arithmetic
assert(minint < minint + 1)
assert(maxint - 1 < maxint)
assert(0 - minint == minint)
assert(minint * minint == 0)
assert(maxint * maxint * maxint == maxint)
-- testing floor division and conversions
for _, i in pairs{-16, -15, -3, -2, -1, 0, 1, 2, 3, 15} do
for _, j in pairs{-16, -15, -3, -2, -1, 1, 2, 3, 15} do
for _, ti in pairs{0, 0.0} do -- try 'i' as integer and as float
for _, tj in pairs{0, 0.0} do -- try 'j' as integer and as float
local x = i + ti
local y = j + tj
assert(i//j == math.floor(i/j))
end
end
end
end
assert(1//0.0 == 1/0)
assert(-1 // 0.0 == -1/0)
assert(eqT(3.5 // 1.5, 2.0))
assert(eqT(3.5 // -1.5, -3.0))
assert(maxint // maxint == 1)
assert(maxint // 1 == maxint)
assert((maxint - 1) // maxint == 0)
assert(maxint // (maxint - 1) == 1)
assert(minint // minint == 1)
assert(minint // minint == 1)
assert((minint + 1) // minint == 0)
assert(minint // (minint + 1) == 1)
assert(minint // 1 == minint)
assert(minint // -1 == -minint)
assert(minint // -2 == 2^(intbits - 2))
assert(maxint // -1 == -maxint)
-- negative exponents
do
assert(2^-3 == 1 / 2^3)
assert(eq((-3)^-3, 1 / (-3)^3))
for i = -3, 3 do -- variables avoid constant folding
for j = -3, 3 do
-- domain errors (0^(-n)) are not portable
if not _port or i ~= 0 or j > 0 then
assert(eq(i^j, 1 / i^(-j)))
end
end
end
end
-- comparison between floats and integers (border cases)
if floatbits < intbits then
assert(2.0^floatbits == (1 << floatbits))
assert(2.0^floatbits - 1.0 == (1 << floatbits) - 1.0)
assert(2.0^floatbits - 1.0 ~= (1 << floatbits))
-- float is rounded, int is not
assert(2.0^floatbits + 1.0 ~= (1 << floatbits) + 1)
else -- floats can express all integers with full accuracy
assert(maxint == maxint + 0.0)
assert(maxint - 1 == maxint - 1.0)
assert(minint + 1 == minint + 1.0)
assert(maxint ~= maxint - 1.0)
end
assert(maxint + 0.0 == 2.0^(intbits - 1) - 1.0)
assert(minint + 0.0 == minint)
assert(minint + 0.0 == -2.0^(intbits - 1))
-- order between floats and integers
assert(1 < 1.1); assert(not (1 < 0.9))
assert(1 <= 1.1); assert(not (1 <= 0.9))
assert(-1 < -0.9); assert(not (-1 < -1.1))
assert(1 <= 1.1); assert(not (-1 <= -1.1))
assert(-1 < -0.9); assert(not (-1 < -1.1))
assert(-1 <= -0.9); assert(not (-1 <= -1.1))
assert(minint <= minint + 0.0)
assert(minint + 0.0 <= minint)
assert(not (minint < minint + 0.0))
assert(not (minint + 0.0 < minint))
assert(maxint < minint * -1.0)
assert(maxint <= minint * -1.0)
do
local fmaxi1 = 2^(intbits - 1)
assert(maxint < fmaxi1)
assert(maxint <= fmaxi1)
assert(not (fmaxi1 <= maxint))
assert(minint <= -2^(intbits - 1))
assert(-2^(intbits - 1) <= minint)
end
if floatbits < intbits then
print("testing order (floats cannot represent all integers)")
local fmax = 2^floatbits
local ifmax = fmax | 0
assert(fmax < ifmax + 1)
assert(fmax - 1 < ifmax)
assert(-(fmax - 1) > -ifmax)
assert(not (fmax <= ifmax - 1))
assert(-fmax > -(ifmax + 1))
assert(not (-fmax >= -(ifmax - 1)))
assert(fmax/2 - 0.5 < ifmax//2)
assert(-(fmax/2 - 0.5) > -ifmax//2)
assert(maxint < 2^intbits)
assert(minint > -2^intbits)
assert(maxint <= 2^intbits)
assert(minint >= -2^intbits)
else
print("testing order (floats can represent all integers)")
assert(maxint < maxint + 1.0)
assert(maxint < maxint + 0.5)
assert(maxint - 1.0 < maxint)
assert(maxint - 0.5 < maxint)
assert(not (maxint + 0.0 < maxint))
assert(maxint + 0.0 <= maxint)
assert(not (maxint < maxint + 0.0))
assert(maxint + 0.0 <= maxint)
assert(maxint <= maxint + 0.0)
assert(not (maxint + 1.0 <= maxint))
assert(not (maxint + 0.5 <= maxint))
assert(not (maxint <= maxint - 1.0))
assert(not (maxint <= maxint - 0.5))
assert(minint < minint + 1.0)
assert(minint < minint + 0.5)
assert(minint <= minint + 0.5)
assert(minint - 1.0 < minint)
assert(minint - 1.0 <= minint)
assert(not (minint + 0.0 < minint))
assert(not (minint + 0.5 < minint))
assert(not (minint < minint + 0.0))
assert(minint + 0.0 <= minint)
assert(minint <= minint + 0.0)
assert(not (minint + 1.0 <= minint))
assert(not (minint + 0.5 <= minint))
assert(not (minint <= minint - 1.0))
end
do
local NaN = 0/0
assert(not (NaN < 0))
assert(not (NaN > minint))
assert(not (NaN <= -9))
assert(not (NaN <= maxint))
assert(not (NaN < maxint))
assert(not (minint <= NaN))
assert(not (minint < NaN))
end
-- avoiding errors at compile time
local function checkcompt (msg, code)
checkerror(msg, assert(load(code)))
end
checkcompt("divide by zero", "return 2 // 0")
checkcompt(msgf2i, "return 2.3 >> 0")
checkcompt(msgf2i, ("return 2.0^%d & 1"):format(intbits - 1))
checkcompt("field 'huge'", "return math.huge << 1")
checkcompt(msgf2i, ("return 1 | 2.0^%d"):format(intbits - 1))
checkcompt(msgf2i, "return 2.3 ~ '0.0'")
-- testing overflow errors when converting from float to integer (runtime)
local function f2i (x) return x | x end
checkerror(msgf2i, f2i, math.huge) -- +inf
checkerror(msgf2i, f2i, -math.huge) -- -inf
checkerror(msgf2i, f2i, 0/0) -- NaN
if floatbits < intbits then
-- conversion tests when float cannot represent all integers
assert(maxint + 1.0 == maxint + 0.0)
assert(minint - 1.0 == minint + 0.0)
checkerror(msgf2i, f2i, maxint + 0.0)
assert(f2i(2.0^(intbits - 2)) == 1 << (intbits - 2))
assert(f2i(-2.0^(intbits - 2)) == -(1 << (intbits - 2)))
assert((2.0^(floatbits - 1) + 1.0) // 1 == (1 << (floatbits - 1)) + 1)
-- maximum integer representable as a float
local mf = maxint - (1 << (floatbits - intbits)) + 1
assert(f2i(mf + 0.0) == mf) -- OK up to here
mf = mf + 1
assert(f2i(mf + 0.0) ~= mf) -- no more representable
else
-- conversion tests when float can represent all integers
assert(maxint + 1.0 > maxint)
assert(minint - 1.0 < minint)
assert(f2i(maxint + 0.0) == maxint)
checkerror("no integer rep", f2i, maxint + 1.0)
checkerror("no integer rep", f2i, minint - 1.0)
end
-- 'minint' should be representable as a float no matter the precision
assert(f2i(minint + 0.0) == minint)
-- testing numeric strings
assert("2" + 1 == 3)
assert("2 " + 1 == 3)
assert(" -2 " + 1 == -1)
assert(" -0xa " + 1 == -9)
-- Literal integer Overflows (new behavior in 5.3.3)
do
-- no overflows
assert(eqT(tonumber(tostring(maxint)), maxint))
assert(eqT(tonumber(tostring(minint)), minint))
-- add 1 to last digit as a string (it cannot be 9...)
local function incd (n)
local s = string.format("%d", n)
s = string.gsub(s, "%d$", function (d)
assert(d ~= '9')
return string.char(string.byte(d) + 1)
end)
return s
end
-- 'tonumber' with overflow by 1
assert(eqT(tonumber(incd(maxint)), maxint + 1.0))
assert(eqT(tonumber(incd(minint)), minint - 1.0))
-- large numbers
assert(eqT(tonumber("1"..string.rep("0", 30)), 1e30))
assert(eqT(tonumber("-1"..string.rep("0", 30)), -1e30))
-- hexa format still wraps around
assert(eqT(tonumber("0x1"..string.rep("0", 30)), 0))
-- lexer in the limits
assert(minint == load("return " .. minint)())
assert(eqT(maxint, load("return " .. maxint)()))
assert(eqT(10000000000000000000000.0, 10000000000000000000000))
assert(eqT(-10000000000000000000000.0, -10000000000000000000000))
end
-- testing 'tonumber'
-- 'tonumber' with numbers
assert(tonumber(3.4) == 3.4)
assert(eqT(tonumber(3), 3))
assert(eqT(tonumber(maxint), maxint) and eqT(tonumber(minint), minint))
assert(tonumber(1/0) == 1/0)
-- 'tonumber' with strings
assert(tonumber("0") == 0)
assert(tonumber("") == nil)
assert(tonumber(" ") == nil)
assert(tonumber("-") == nil)
assert(tonumber(" -0x ") == nil)
assert(tonumber{} == nil)
assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and
tonumber'.01' == 0.01 and tonumber'-1.' == -1 and
tonumber'+1.' == 1)
assert(tonumber'+ 0.01' == nil and tonumber'+.e1' == nil and
tonumber'1e' == nil and tonumber'1.0e+' == nil and
tonumber'.' == nil)
assert(tonumber('-012') == -010-2)
assert(tonumber('-1.2e2') == - - -120)
assert(tonumber("0xffffffffffff") == (1 << (4*12)) - 1)
assert(tonumber("0x"..string.rep("f", (intbits//4))) == -1)
assert(tonumber("-0x"..string.rep("f", (intbits//4))) == 1)
-- testing 'tonumber' with base
assert(tonumber(' 001010 ', 2) == 10)
assert(tonumber(' 001010 ', 10) == 001010)
assert(tonumber(' -1010 ', 2) == -10)
assert(tonumber('10', 36) == 36)
assert(tonumber(' -10 ', 36) == -36)
assert(tonumber(' +1Z ', 36) == 36 + 35)
assert(tonumber(' -1z ', 36) == -36 + -35)
assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15)))))))
assert(tonumber(string.rep('1', (intbits - 2)), 2) + 1 == 2^(intbits - 2))
assert(tonumber('ffffFFFF', 16)+1 == (1 << 32))
assert(tonumber('0ffffFFFF', 16)+1 == (1 << 32))
assert(tonumber('-0ffffffFFFF', 16) - 1 == -(1 << 40))
for i = 2,36 do
local i2 = i * i
local i10 = i2 * i2 * i2 * i2 * i2 -- i^10
assert(tonumber('\t10000000000\t', i) == i10)
end
if not _soft then
-- tests with very long numerals
assert(tonumber("0x"..string.rep("f", 13)..".0") == 2.0^(4*13) - 1)
assert(tonumber("0x"..string.rep("f", 150)..".0") == 2.0^(4*150) - 1)
assert(tonumber("0x"..string.rep("f", 300)..".0") == 2.0^(4*300) - 1)
assert(tonumber("0x"..string.rep("f", 500)..".0") == 2.0^(4*500) - 1)
assert(tonumber('0x3.' .. string.rep('0', 1000)) == 3)
assert(tonumber('0x' .. string.rep('0', 1000) .. 'a') == 10)
assert(tonumber('0x0.' .. string.rep('0', 13).."1") == 2.0^(-4*14))
assert(tonumber('0x0.' .. string.rep('0', 150).."1") == 2.0^(-4*151))
assert(tonumber('0x0.' .. string.rep('0', 300).."1") == 2.0^(-4*301))
assert(tonumber('0x0.' .. string.rep('0', 500).."1") == 2.0^(-4*501))
assert(tonumber('0xe03' .. string.rep('0', 1000) .. 'p-4000') == 3587.0)
assert(tonumber('0x.' .. string.rep('0', 1000) .. '74p4004') == 0x7.4)
end
-- testing 'tonumber' for invalid formats
local function f (...)
if select('#', ...) == 1 then
return (...)
else
return "***"
end
end
assert(f(tonumber('fFfa', 15)) == nil)
assert(f(tonumber('099', 8)) == nil)
assert(f(tonumber('1\0', 2)) == nil)
assert(f(tonumber('', 8)) == nil)
assert(f(tonumber(' ', 9)) == nil)
assert(f(tonumber(' ', 9)) == nil)
assert(f(tonumber('0xf', 10)) == nil)
assert(f(tonumber('inf')) == nil)
assert(f(tonumber(' INF ')) == nil)
assert(f(tonumber('Nan')) == nil)
assert(f(tonumber('nan')) == nil)
assert(f(tonumber(' ')) == nil)
assert(f(tonumber('')) == nil)
assert(f(tonumber('1 a')) == nil)
assert(f(tonumber('1 a', 2)) == nil)
assert(f(tonumber('1\0')) == nil)
assert(f(tonumber('1 \0')) == nil)
assert(f(tonumber('1\0 ')) == nil)
assert(f(tonumber('e1')) == nil)
assert(f(tonumber('e 1')) == nil)
assert(f(tonumber(' 3.4.5 ')) == nil)
-- testing 'tonumber' for invalid hexadecimal formats
assert(tonumber('0x') == nil)
assert(tonumber('x') == nil)
assert(tonumber('x3') == nil)
assert(tonumber('0x3.3.3') == nil) -- two decimal points
assert(tonumber('00x2') == nil)
assert(tonumber('0x 2') == nil)
assert(tonumber('0 x2') == nil)
assert(tonumber('23x') == nil)
assert(tonumber('- 0xaa') == nil)
assert(tonumber('-0xaaP ') == nil) -- no exponent
assert(tonumber('0x0.51p') == nil)
assert(tonumber('0x5p+-2') == nil)
-- testing hexadecimal numerals
assert(0x10 == 16 and 0xfff == 2^12 - 1 and 0XFB == 251)
assert(0x0p12 == 0 and 0x.0p-3 == 0)
assert(0xFFFFFFFF == (1 << 32) - 1)
assert(tonumber('+0x2') == 2)
assert(tonumber('-0xaA') == -170)
assert(tonumber('-0xffFFFfff') == -(1 << 32) + 1)
-- possible confusion with decimal exponent
assert(0E+1 == 0 and 0xE+1 == 15 and 0xe-1 == 13)
-- floating hexas
assert(tonumber(' 0x2.5 ') == 0x25/16)
assert(tonumber(' -0x2.5 ') == -0x25/16)
assert(tonumber(' +0x0.51p+8 ') == 0x51)
assert(0x.FfffFFFF == 1 - '0x.00000001')
assert('0xA.a' + 0 == 10 + 10/16)
assert(0xa.aP4 == 0XAA)
assert(0x4P-2 == 1)
assert(0x1.1 == '0x1.' + '+0x.1')
assert(0Xabcdef.0 == 0x.ABCDEFp+24)
assert(1.1 == 1.+.1)
assert(100.0 == 1E2 and .01 == 1e-2)
assert(1111111111 - 1111111110 == 1000.00e-03)
assert(1.1 == '1.'+'.1')
assert(tonumber'1111111111' - tonumber'1111111110' ==
tonumber" +0.001e+3 \n\t")
assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31)
assert(0.123456 > 0.123455)
assert(tonumber('+1.23E18') == 1.23*10.0^18)
-- testing order operators
assert(not(1<1) and (1<2) and not(2<1))
assert(not('a'<'a') and ('a'<'b') and not('b'<'a'))
assert((1<=1) and (1<=2) and not(2<=1))
assert(('a'<='a') and ('a'<='b') and not('b'<='a'))
assert(not(1>1) and not(1>2) and (2>1))
assert(not('a'>'a') and not('a'>'b') and ('b'>'a'))
assert((1>=1) and not(1>=2) and (2>=1))
assert(('a'>='a') and not('a'>='b') and ('b'>='a'))
assert(1.3 < 1.4 and 1.3 <= 1.4 and not (1.3 < 1.3) and 1.3 <= 1.3)
-- testing mod operator
assert(eqT(-4 % 3, 2))
assert(eqT(4 % -3, -2))
assert(eqT(-4.0 % 3, 2.0))
assert(eqT(4 % -3.0, -2.0))
assert(math.pi - math.pi % 1 == 3)
assert(math.pi - math.pi % 0.001 == 3.141)
assert(eqT(minint % minint, 0))
assert(eqT(maxint % maxint, 0))
assert((minint + 1) % minint == minint + 1)
assert((maxint - 1) % maxint == maxint - 1)
assert(minint % maxint == maxint - 1)
assert(minint % -1 == 0)
assert(minint % -2 == 0)
assert(maxint % -2 == -1)
-- non-portable tests because Windows C library cannot compute
-- fmod(1, huge) correctly
if not _port then
local function anan (x) assert(isNaN(x)) end -- assert Not a Number
anan(0.0 % 0)
anan(1.3 % 0)
anan(math.huge % 1)
anan(math.huge % 1e30)
anan(-math.huge % 1e30)
anan(-math.huge % -1e30)
assert(1 % math.huge == 1)
assert(1e30 % math.huge == 1e30)
assert(1e30 % -math.huge == -math.huge)
assert(-1 % math.huge == math.huge)
assert(-1 % -math.huge == -1)
end
-- testing unsigned comparisons
assert(math.ult(3, 4))
assert(not math.ult(4, 4))
assert(math.ult(-2, -1))
assert(math.ult(2, -1))
assert(not math.ult(-2, -2))
assert(math.ult(maxint, minint))
assert(not math.ult(minint, maxint))
assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1))
assert(eq(math.tan(math.pi/4), 1))
assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0))
assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and
eq(math.asin(1), math.pi/2))
assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2))
assert(math.abs(-10.43) == 10.43)
assert(eqT(math.abs(minint), minint))
assert(eqT(math.abs(maxint), maxint))
assert(eqT(math.abs(-maxint), maxint))
assert(eq(math.atan(1,0), math.pi/2))
assert(math.fmod(10,3) == 1)
assert(eq(math.sqrt(10)^2, 10))
assert(eq(math.log(2, 10), math.log(2)/math.log(10)))
assert(eq(math.log(2, 2), 1))
assert(eq(math.log(9, 3), 2))
assert(eq(math.exp(0), 1))
assert(eq(math.sin(10), math.sin(10%(2*math.pi))))
assert(tonumber(' 1.3e-2 ') == 1.3e-2)
assert(tonumber(' -1.00000000000001 ') == -1.00000000000001)
-- testing constant limits
-- 2^23 = 8388608
assert(8388609 + -8388609 == 0)
assert(8388608 + -8388608 == 0)
assert(8388607 + -8388607 == 0)
do -- testing floor & ceil
assert(eqT(math.floor(3.4), 3))
assert(eqT(math.ceil(3.4), 4))
assert(eqT(math.floor(-3.4), -4))
assert(eqT(math.ceil(-3.4), -3))
assert(eqT(math.floor(maxint), maxint))
assert(eqT(math.ceil(maxint), maxint))
assert(eqT(math.floor(minint), minint))
assert(eqT(math.floor(minint + 0.0), minint))
assert(eqT(math.ceil(minint), minint))
assert(eqT(math.ceil(minint + 0.0), minint))
assert(math.floor(1e50) == 1e50)
assert(math.ceil(1e50) == 1e50)
assert(math.floor(-1e50) == -1e50)
assert(math.ceil(-1e50) == -1e50)
for _, p in pairs{31,32,63,64} do
assert(math.floor(2^p) == 2^p)
assert(math.floor(2^p + 0.5) == 2^p)
assert(math.ceil(2^p) == 2^p)
assert(math.ceil(2^p - 0.5) == 2^p)
end
checkerror("number expected", math.floor, {})
checkerror("number expected", math.ceil, print)
assert(eqT(math.tointeger(minint), minint))
assert(eqT(math.tointeger(minint .. ""), minint))
assert(eqT(math.tointeger(maxint), maxint))
assert(eqT(math.tointeger(maxint .. ""), maxint))
assert(eqT(math.tointeger(minint + 0.0), minint))
assert(math.tointeger(0.0 - minint) == nil)
assert(math.tointeger(math.pi) == nil)
assert(math.tointeger(-math.pi) == nil)
assert(math.floor(math.huge) == math.huge)
assert(math.ceil(math.huge) == math.huge)
assert(math.tointeger(math.huge) == nil)
assert(math.floor(-math.huge) == -math.huge)
assert(math.ceil(-math.huge) == -math.huge)
assert(math.tointeger(-math.huge) == nil)
assert(math.tointeger("34.0") == 34)
assert(math.tointeger("34.3") == nil)
assert(math.tointeger({}) == nil)
assert(math.tointeger(0/0) == nil) -- NaN
end
-- testing fmod for integers
for i = -6, 6 do
for j = -6, 6 do
if j ~= 0 then
local mi = math.fmod(i, j)
local mf = math.fmod(i + 0.0, j)
assert(mi == mf)
assert(math.type(mi) == 'integer' and math.type(mf) == 'float')
if (i >= 0 and j >= 0) or (i <= 0 and j <= 0) or mi == 0 then
assert(eqT(mi, i % j))
end
end
end
end
assert(eqT(math.fmod(minint, minint), 0))
assert(eqT(math.fmod(maxint, maxint), 0))
assert(eqT(math.fmod(minint + 1, minint), minint + 1))
assert(eqT(math.fmod(maxint - 1, maxint), maxint - 1))
checkerror("zero", math.fmod, 3, 0)
do -- testing max/min
checkerror("value expected", math.max)
checkerror("value expected", math.min)
assert(eqT(math.max(3), 3))
assert(eqT(math.max(3, 5, 9, 1), 9))
assert(math.max(maxint, 10e60) == 10e60)
assert(eqT(math.max(minint, minint + 1), minint + 1))
assert(eqT(math.min(3), 3))
assert(eqT(math.min(3, 5, 9, 1), 1))
assert(math.min(3.2, 5.9, -9.2, 1.1) == -9.2)
assert(math.min(1.9, 1.7, 1.72) == 1.7)
assert(math.min(-10e60, minint) == -10e60)
assert(eqT(math.min(maxint, maxint - 1), maxint - 1))
assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2))
end
-- testing implicit convertions
local a,b = '10', '20'
assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20)
assert(a == '10' and b == '20')
do
print("testing -0 and NaN")
local mz, z = -0.0, 0.0
assert(mz == z)
assert(1/mz < 0 and 0 < 1/z)
local a = {[mz] = 1}
assert(a[z] == 1 and a[mz] == 1)
a[z] = 2
assert(a[z] == 2 and a[mz] == 2)
local inf = math.huge * 2 + 1
mz, z = -1/inf, 1/inf
assert(mz == z)
assert(1/mz < 0 and 0 < 1/z)
local NaN = inf - inf
assert(NaN ~= NaN)
assert(not (NaN < NaN))
assert(not (NaN <= NaN))
assert(not (NaN > NaN))
assert(not (NaN >= NaN))
assert(not (0 < NaN) and not (NaN < 0))
local NaN1 = 0/0
assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN))
local a = {}
assert(not pcall(rawset, a, NaN, 1))
assert(a[NaN] == nil)
a[1] = 1
assert(not pcall(rawset, a, NaN, 1))
assert(a[NaN] == nil)
-- strings with same binary representation as 0.0 (might create problems
-- for constant manipulation in the pre-compiler)
local a1, a2, a3, a4, a5 = 0, 0, "\0\0\0\0\0\0\0\0", 0, "\0\0\0\0\0\0\0\0"
assert(a1 == a2 and a2 == a4 and a1 ~= a3)
assert(a3 == a5)
end
print("testing 'math.random'")
math.randomseed(0)
do -- test random for floats
local max = -math.huge
local min = math.huge
for i = 0, 20000 do
local t = math.random()
assert(0 <= t and t < 1)
max = math.max(max, t)
min = math.min(min, t)
if eq(max, 1, 0.001) and eq(min, 0, 0.001) then
goto ok
end
end
-- loop ended without satisfing condition
assert(false)
::ok::
end
do
local function aux (p, lim) -- test random for small intervals
local x1, x2
if #p == 1 then x1 = 1; x2 = p[1]
else x1 = p[1]; x2 = p[2]
end
local mark = {}; local count = 0 -- to check that all values appeared
for i = 0, lim or 2000 do
local t = math.random(table.unpack(p))
assert(x1 <= t and t <= x2)
if not mark[t] then -- new value
mark[t] = true
count = count + 1
end
if count == x2 - x1 + 1 then -- all values appeared; OK
goto ok
end
end
-- loop ended without satisfing condition
assert(false)
::ok::
end
aux({-10,0})
aux({6})
aux({-10, 10})
aux({minint, minint})
aux({maxint, maxint})
aux({minint, minint + 9})
aux({maxint - 3, maxint})
end
do
local function aux(p1, p2) -- test random for large intervals
local max = minint
local min = maxint
local n = 200
local mark = {}; local count = 0 -- to count how many different values
for _ = 1, n do
local t = math.random(p1, p2)
max = math.max(max, t)
min = math.min(min, t)
if not mark[t] then -- new value
mark[t] = true
count = count + 1
end
end
-- at least 80% of values are different
assert(count >= n * 0.8)
-- min and max not too far from formal min and max
local diff = (p2 - p1) // 8
assert(min < p1 + diff and max > p2 - diff)
end
aux(0, maxint)
aux(1, maxint)
aux(minint, -1)
aux(minint // 2, maxint // 2)
end
for i=1,100 do
assert(math.random(maxint) > 0)
assert(math.random(minint, -1) < 0)
end
assert(not pcall(math.random, 1, 2, 3)) -- too many arguments
-- empty interval
assert(not pcall(math.random, minint + 1, minint))
assert(not pcall(math.random, maxint, maxint - 1))
assert(not pcall(math.random, maxint, minint))
-- interval too large
assert(not pcall(math.random, minint, 0))
assert(not pcall(math.random, -1, maxint))
assert(not pcall(math.random, minint // 2, maxint // 2 + 1))
print('OK')
| mit |
Canaan-Creative/luci | applications/luci-statistics/luasrc/model/cbi/luci_statistics/iwinfo.lua | 78 | 1089 | --[[
Luci configuration model for statistics - collectd interface plugin configuration
(c) 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local m, s, o
m = Map("luci_statistics",
translate("Wireless iwinfo Plugin Configuration"),
translate("The iwinfo plugin collects statistics about wireless signal strength, noise and quality."))
s = m:section(NamedSection, "collectd_iwinfo", "luci_statistics")
o = s:option(Flag, "enable", translate("Enable this plugin"))
o.default = 0
o = s:option(Value, "Interfaces", translate("Monitor interfaces"),
translate("Leave unselected to automatically determine interfaces to monitor."))
o.template = "cbi/network_ifacelist"
o.widget = "checkbox"
o.nocreate = true
o:depends("enable", 1)
o = s:option(Flag, "IgnoreSelected", translate("Monitor all except specified"))
o.default = 0
o:depends("enable", 1)
return m
| apache-2.0 |
Elanis/SciFi-Pack-Addon-Gamemode | gamemodes/scifipack/entities/weapons/gmod_tool/cl_viewscreen.lua | 3 | 2076 |
local matScreen = Material( "models/weapons/v_toolgun/screen" )
local txBackground = surface.GetTextureID( "models/weapons/v_toolgun/screen_bg" )
-- GetRenderTarget returns the texture if it exists, or creates it if it doesn't
local RTTexture = GetRenderTarget( "GModToolgunScreen", 256, 256 )
surface.CreateFont( "GModToolScreen", {
font = "Helvetica",
size = 60,
weight = 900
} )
local function DrawScrollingText( text, y, texwide )
local w, h = surface.GetTextSize( text )
w = w + 64
y = y - h / 2 -- Center text to y position
local x = RealTime() * 250 % w * -1
while ( x < texwide ) do
surface.SetTextColor( 0, 0, 0, 255 )
surface.SetTextPos( x + 3, y + 3 )
surface.DrawText( text )
surface.SetTextColor( 255, 255, 255, 255 )
surface.SetTextPos( x, y )
surface.DrawText( text )
x = x + w
end
end
--[[---------------------------------------------------------
We use this opportunity to draw to the toolmode
screen's rendertarget texture.
-----------------------------------------------------------]]
function SWEP:RenderScreen()
local TEX_SIZE = 256
local mode = GetConVarString( "gmod_toolmode" )
local oldW = ScrW()
local oldH = ScrH()
-- Set the material of the screen to our render target
matScreen:SetTexture( "$basetexture", RTTexture )
local OldRT = render.GetRenderTarget()
-- Set up our view for drawing to the texture
render.SetRenderTarget( RTTexture )
render.SetViewPort( 0, 0, TEX_SIZE, TEX_SIZE )
cam.Start2D()
-- Background
surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetTexture( txBackground )
surface.DrawTexturedRect( 0, 0, TEX_SIZE, TEX_SIZE )
-- Give our toolmode the opportunity to override the drawing
if ( self:GetToolObject() && self:GetToolObject().DrawToolScreen ) then
self:GetToolObject():DrawToolScreen( TEX_SIZE, TEX_SIZE )
else
surface.SetFont( "GModToolScreen" )
DrawScrollingText( "#tool." .. mode .. ".name", 104, TEX_SIZE )
end
cam.End2D()
render.SetRenderTarget( OldRT )
render.SetViewPort( 0, 0, oldW, oldH )
end
| gpl-2.0 |
xponen/Zero-K | units/armsonar.lua | 1 | 3870 | unitDef = {
unitname = [[armsonar]],
name = [[Sonar Station]],
description = [[Locates Water Units]],
acceleration = 0,
activateWhenBuilt = true,
bmcode = [[0]],
brakeRate = 0,
buildAngle = 8192,
buildCostEnergy = 40,
buildCostMetal = 40,
builder = false,
buildPic = [[ARMSONAR.png]],
buildTime = 40,
canAttack = false,
category = [[UNARMED FLOAT]],
corpse = [[DEAD]],
energyUse = 0.5,
explodeAs = [[SMALL_BUILDINGEX]],
floater = true,
footprintX = 2,
footprintZ = 2,
iconType = [[sonar]],
idleAutoHeal = 5,
idleTime = 1800,
mass = 104,
maxangledif1 = [[1]],
maxDamage = 300,
maxSlope = 18,
maxVelocity = 0,
minCloakDistance = 150,
minWaterDepth = 10,
noAutoFire = false,
objectName = [[novasonar.s3o]],
onoffable = true,
seismicSignature = 4,
selfDestructAs = [[SMALL_BUILDINGEX]],
side = [[ARM]],
sightDistance = 500,
smoothAnim = true,
sonarDistance = 600,
TEDClass = [[WATER]],
turnRate = 0,
waterLine = 0,
workerTime = 0,
yardMap = [[oooo]],
customParams = {
description_de = [[Ortet Einheiten unter Wasser]],
description_pl = [[Wykrywa Jednostki Podwodne]],
helptext = [[The docile Sonar Station provides one of the few means of locating underwater targets.]],
helptext_de = [[Das Sonar ortet nach dem Echoprinzip von Radaranlagen feindliche Einheiten unter Wasser. Dazu strahlen sie selbst ein Signal aus und empfangen das entsprechende Echo, aus dessen Laufzeit auf die Entfernung zu den Einheiten geschlossen wird.]],
helptext_pl = [[Sonar jest odpowiednikiem radaru dzia³aj¹cym pod wod¹. Jest niezbêdny do wykrywania (a zatem i niszczenia) okrêtów podwodnych i amfibii nieprzyjaciela.]],
},
featureDefs = {
DEAD = {
description = [[Wreckage - Sonar Station]],
blocking = false,
category = [[corpses]],
damage = 300,
energy = 0,
featureDead = [[DEAD2]],
footprintX = 2,
footprintZ = 2,
height = [[4]],
hitdensity = [[100]],
metal = 16,
object = [[novasonar_dead.s3o]],
reclaimable = true,
reclaimTime = 16,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
DEAD2 = {
description = [[Debris - Sonar Station]],
blocking = false,
category = [[heaps]],
damage = 300,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 2,
footprintZ = 2,
hitdensity = [[100]],
metal = 16,
object = [[debris2x2a.s3o]],
reclaimable = true,
reclaimTime = 16,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Sonar Station]],
blocking = false,
category = [[heaps]],
damage = 300,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 2,
footprintZ = 2,
hitdensity = [[100]],
metal = 8,
object = [[debris2x2a.s3o]],
reclaimable = true,
reclaimTime = 8,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ armsonar = unitDef })
| gpl-2.0 |
xponen/Zero-K | units/gorg.lua | 2 | 12594 | unitDef = {
unitname = [[gorg]],
name = [[Jugglenaut]],
description = [[Heavy Assault Strider]],
acceleration = 0.0552,
brakeRate = 0.1375,
buildCostEnergy = 12000,
buildCostMetal = 12000,
builder = false,
buildPic = [[GORG.png]],
buildTime = 12000,
canAttack = true,
canManualFire = true,
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 -5 0]],
collisionVolumeScales = [[70 60 65]],
collisionVolumeTest = 1,
collisionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
description_fr = [[Mechwarrior d'Assaut]],
description_de = [[Schwerer Sturmroboter]],
description_pl = [[Ciezki bot szturmowy]],
helptext = [[The Jugglenaut is the big daddy to the Sumo. Where its smaller cousin sported the exotic disruptor beams, the Jugg is even more bizzare with its three gravity guns and a standard laser cannon complementing a negative gravity core that can be activated to lift up and throw nearby units. This beast is slow and expensive, but seemingly impervious to enemy fire.]],
helptext_fr = [[Le Jugglenaut est un quadrip?de lourd et lent, mais ?xtr?mement solide. Il est ?quip? de deux canons laser ? haute fr?quence, et d'un double laser anti gravit? de technologie Newton. Il d?cole les unit?s ennemies du sol et les ?jecte en arri?re tout en les bombardant de ses tirs. Difficilement arr?table, voire la silhouette d'un Juggernaut ? l'horizon est une des pires chose que l'on puisse apercevoir.]],
helptext_de = [[Der Jugglenaut ist der große Bruder des Sumos. Er besitzt im Gegensatz zu diesem keinen exotischen Heat Ray, sondern drei nicht weniger verrückte Gravitationskanonen und eine einfache Laserkanone. Dieses Biest ist langsam und teuer, aber scheinbar völlig unbeeindruckt vom feindlichen Feuer.]],
helptext_pl = [[Jugglenaut to starszy brat Sumo, ktory takze uzywa egzotycznych broni - jest wyposazony w dzialka grawitacyjne i rdzen grawitacyjny, ktory mozna aktywowac, aby podniesc okoliczne jednostki i rzucic nimi. Ponadto jego wytrzymalosc nie ma sobie rownych.]],
extradrawrange = 260,
modelradius = [[30]],
},
explodeAs = [[ESTOR_BUILDINGEX]],
footprintX = 4,
footprintZ = 4,
iconType = [[t3special]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
mass = 1848,
maxDamage = 100000,
maxSlope = 36,
maxVelocity = 0.8325,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT4]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]],
objectName = [[GORG]],
pieceTrailCEGRange = 1,
pieceTrailCEGTag = [[trail_huge]],
seismicSignature = 4,
selfDestructAs = [[ESTOR_BUILDINGEX]],
sfxtypes = {
explosiongenerators = {
[[custom:BEAMWEAPON_MUZZLE_RED]],
},
},
--script = [[gorg.lua]],
side = [[CORE]],
sightDistance = 650,
smoothAnim = true,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[juggle]],
trackWidth = 64,
turnRate = 233,
workerTime = 0,
weapons = {
{
def = [[LASER]],
badTargetCategory = [[FIXEDWING]],
mainDir = [[0 0 1]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[GRAVITY_NEG]],
badTargetCategory = [[FIXEDWING]],
mainDir = [[0.2 0 1]],
maxAngleDif = 150,
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
},
{
def = [[GRAVITY_NEG_SPECIAL]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[GRAVITY_NEG]],
badTargetCategory = [[FIXEDWING]],
mainDir = [[0 0 1]],
maxAngleDif = 150,
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
},
{
def = [[GRAVITY_NEG]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING HOVER SWIM LAND SHIP GUNSHIP]],
},
--{
-- def = [[GRASER]],
--},
},
weaponDefs = {
GRAVITY_NEG = {
name = [[Attractive Gravity]],
areaOfEffect = 8,
avoidFriendly = false,
burst = 6,
burstrate = 0.01,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
impulse = [[-125]],
},
damage = {
default = 0.001,
planes = 0.001,
subs = 5E-05,
},
duration = 0.0333,
endsmoke = [[0]],
explosionGenerator = [[custom:NONE]],
impactOnly = true,
intensity = 0.7,
interceptedByShieldType = 0,
noSelfDamage = true,
projectiles = 2,
proximityPriority = -15,
range = 550,
reloadtime = 0.2,
renderType = 4,
rgbColor = [[0 0 1]],
rgbColor2 = [[1 0.5 1]],
size = 2,
soundStart = [[weapon/gravity_fire]],
soundTrigger = true,
startsmoke = [[0]],
thickness = 4,
tolerance = 5000,
turret = true,
weaponTimer = 0.1,
weaponType = [[LaserCannon]],
weaponVelocity = 2750,
},
GRAVITY_NEG_SPECIAL = {
name = [[Psychic Tank Float]],
accuracy = 10,
alphaDecay = 0.7,
areaOfEffect = 2,
avoidFeature = false,
avoidFriendly = false,
collideEnemy = false,
collideFeature = false,
collideFriendly = false,
collideGround = false,
collideNeutral = false,
burnblow = true,
craterBoost = 0.15,
craterMult = 0.3,
commandFire = true,
customParams = {
massliftthrow = [[1]],
},
damage = {
default = 0.01,
},
edgeEffectiveness = 0.5,
explosionGenerator = [[custom:GRAV]],
lineOfSight = true,
noSelfDamage = true,
projectiles = 1,
range = 550,
reloadtime = 40,
renderType = 4,
rgbColor = [[1 0.95 0.4]],
separation = 1.5,
size = 0,
stages = 1,
targetMoveError = 0,
tolerance = 5000,
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 550,
},
LASER = {
name = [[Heavy Laser Blaster]],
areaOfEffect = 24,
canattackground = true,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 40,
planes = 40,
subs = 2,
},
duration = 0.04,
explosionGenerator = [[custom:BEAMWEAPON_HIT_RED]],
fireStarter = 30,
heightMod = 1,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
range = 430,
reloadtime = 0.17,
rgbColor = [[1 0 0]],
soundHit = [[weapon/laser/lasercannon_hit]],
soundStart = [[weapon/laser/heavylaser_fire2]],
sweepfire = false,
targetMoveError = 0.1,
thickness = 4,
tolerance = 10000,
turret = true,
weaponType = [[LaserCannon]],
weaponVelocity = 1720,
},
FAKELASER = {
name = [[Laser]],
areaOfEffect = 8,
avoidFeature = false,
collideFriendly = false,
coreThickness = 0,
craterBoost = 0,
craterMult = 0,
damage = {
default = -0.001,
subs = -0.001,
},
duration = 0.02,
explosionGenerator = [[custom:NONE]],
fireStarter = 0,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 1,
range = 400,
reloadtime = 8,
rgbColor = [[0 0 0]],
soundTrigger = true,
targetMoveError = 0.2,
thickness = 0.001,
tolerance = 0,
turret = true,
weaponType = [[LaserCannon]],
weaponVelocity = 2300,
},
GRASER = {
name = [[Light Graser]],
areaOfEffect = 8,
beamTime = 0.01,
beamttl = 6,
canAttackGround = false,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 20,
planes = 20,
subs = 1,
},
explosionGenerator = [[custom:flash1green]],
fireStarter = 120,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 3.5,
minIntensity = 1,
range = 430,
reloadtime = 1,
rgbColor = [[0.1 1 0.3]],
soundStart = [[weapon/laser/laser_burn10]],
soundTrigger = true,
sweepfire = true,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 3,
tolerance = 18000,
turret = true,
weaponType = [[BeamLaser]],
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Jugglenaut]],
blocking = true,
category = [[corpses]],
damage = 100000,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 4,
footprintZ = 4,
height = [[8]],
hitdensity = [[100]],
metal = 4800,
object = [[GORG_DEAD]],
reclaimable = true,
reclaimTime = 4800,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Jugglenaut]],
blocking = false,
category = [[heaps]],
damage = 100000,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 4,
footprintZ = 4,
height = [[2]],
hitdensity = [[100]],
metal = 2400,
object = [[debris4x4a.s3o]],
reclaimable = true,
reclaimTime = 2400,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ gorg = unitDef })
| gpl-2.0 |
hashbang/hashvtt | lib/timer.lua | 27 | 6224 | --[[
Copyright (c) 2010-2013 Matthias Richter
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.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local Timer = {}
Timer.__index = Timer
local function _nothing_() end
function Timer:update(dt)
local to_remove = {}
for handle, delay in pairs(self.functions) do
delay = delay - dt
if delay <= 0 then
to_remove[#to_remove+1] = handle
end
self.functions[handle] = delay
handle.func(dt, delay)
end
for _,handle in ipairs(to_remove) do
self.functions[handle] = nil
handle.after(handle.after)
end
end
function Timer:do_for(delay, func, after)
local handle = {func = func, after = after or _nothing_}
self.functions[handle] = delay
return handle
end
function Timer:add(delay, func)
return self:do_for(delay, _nothing_, func)
end
function Timer:addPeriodic(delay, func, count)
local count, handle = count or math.huge -- exploit below: math.huge - 1 = math.huge
handle = self:add(delay, function(f)
if func(func) == false then return end
count = count - 1
if count > 0 then
self.functions[handle] = delay
end
end)
return handle
end
function Timer:cancel(handle)
self.functions[handle] = nil
end
function Timer:clear()
self.functions = {}
end
Timer.tween = setmetatable({
-- helper functions
out = function(f) -- 'rotates' a function
return function(s, ...) return 1 - f(1-s, ...) end
end,
chain = function(f1, f2) -- concatenates two functions
return function(s, ...) return (s < .5 and f1(2*s, ...) or 1 + f2(2*s-1, ...)) * .5 end
end,
-- useful tweening functions
linear = function(s) return s end,
quad = function(s) return s*s end,
cubic = function(s) return s*s*s end,
quart = function(s) return s*s*s*s end,
quint = function(s) return s*s*s*s*s end,
sine = function(s) return 1-math.cos(s*math.pi/2) end,
expo = function(s) return 2^(10*(s-1)) end,
circ = function(s) return 1 - math.sqrt(1-s*s) end,
back = function(s,bounciness)
bounciness = bounciness or 1.70158
return s*s*((bounciness+1)*s - bounciness)
end,
bounce = function(s) -- magic numbers ahead
local a,b = 7.5625, 1/2.75
return math.min(a*s^2, a*(s-1.5*b)^2 + .75, a*(s-2.25*b)^2 + .9375, a*(s-2.625*b)^2 + .984375)
end,
elastic = function(s, amp, period)
amp, period = amp and math.max(1, amp) or 1, period or .3
return (-amp * math.sin(2*math.pi/period * (s-1) - math.asin(1/amp))) * 2^(10*(s-1))
end,
}, {
-- register new tween
__call = function(tween, self, len, subject, target, method, after, ...)
-- recursively collects fields that are defined in both subject and target into a flat list
local function tween_collect_payload(subject, target, out)
for k,v in pairs(target) do
local ref = subject[k]
assert(type(v) == type(ref), 'Type mismatch in field "'..k..'".')
if type(v) == 'table' then
tween_collect_payload(ref, v, out)
else
local ok, delta = pcall(function() return (v-ref)*1 end)
assert(ok, 'Field "'..k..'" does not support arithmetic operations')
out[#out+1] = {subject, k, delta}
end
end
return out
end
method = tween[method or 'linear'] -- see __index
local payload, t, args = tween_collect_payload(subject, target, {}), 0, {...}
local last_s = 0
return self:do_for(len, function(dt)
t = t + dt
local s = method(math.min(1, t/len), unpack(args))
local ds = s - last_s
last_s = s
for _, info in ipairs(payload) do
local ref, key, delta = unpack(info)
ref[key] = ref[key] + delta * ds
end
end, after)
end,
-- fetches function and generated compositions for method `key`
__index = function(tweens, key)
if type(key) == 'function' then return key end
assert(type(key) == 'string', 'Method must be function or string.')
if rawget(tweens, key) then return rawget(tweens, key) end
local function construct(pattern, f)
local method = rawget(tweens, key:match(pattern))
if method then return f(method) end
return nil
end
local out, chain = rawget(tweens,'out'), rawget(tweens,'chain')
return construct('^in%-([^-]+)$', function(...) return ... end)
or construct('^out%-([^-]+)$', out)
or construct('^in%-out%-([^-]+)$', function(f) return chain(f, out(f)) end)
or construct('^out%-in%-([^-]+)$', function(f) return chain(out(f), f) end)
or error('Unknown interpolation method: ' .. key)
end})
-- the module
local function new()
local timer = setmetatable({functions = {}, tween = Timer.tween}, Timer)
return setmetatable({
new = new,
update = function(...) return timer:update(...) end,
do_for = function(...) return timer:do_for(...) end,
add = function(...) return timer:add(...) end,
addPeriodic = function(...) return timer:addPeriodic(...) end,
cancel = function(...) return timer:cancel(...) end,
clear = function(...) return timer:clear(...) end,
tween = setmetatable({}, {
__index = Timer.tween,
__newindex = function(_,k,v) Timer.tween[k] = v end,
__call = function(t,...) return timer:tween(...) end,
})
}, {__call = new})
end
return new()
| mit |
warriorhero/black_wolf_2016 | plugins/stats.lua | 236 | 3989 | 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/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..chat_id,"./groups/"..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 |
alexandergall/snabbswitch | src/program/packetblaster/lwaftr/lwaftr.lua | 6 | 14456 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local engine = require("core.app")
local config = require("core.config")
local timer = require("core.timer")
local pci = require("lib.hardware.pci")
local ethernet = require("lib.protocol.ethernet")
local ipv4 = require("lib.protocol.ipv4")
local ipv6 = require("lib.protocol.ipv6")
local main = require("core.main")
local S = require("syscall")
local B4Gen = require("program.packetblaster.lwaftr.lib").B4Gen
local InetGen = require("program.packetblaster.lwaftr.lib").InetGen
local Interleave = require("program.packetblaster.lwaftr.lib").Interleave
local Tap = require("apps.tap.tap").Tap
local vlan = require("apps.vlan.vlan")
local arp = require("apps.ipv4.arp")
local ndp = require("apps.lwaftr.ndp")
local V4V6 = require("apps.lwaftr.V4V6")
local raw = require("apps.socket.raw")
local pcap = require("apps.pcap.pcap")
local VhostUser = require("apps.vhost.vhost_user").VhostUser
local lib = require("core.lib")
local usage = require("program.packetblaster.lwaftr.README_inc")
local long_opts = {
pci = "p", -- PCI address
tap = "t", -- tap interface
int = "i", -- Linux network interface, e.g. eth0
sock = "k", -- socket name for virtio
duration = "D", -- terminate after n seconds
verbose = "V", -- verbose, display stats
help = "h", -- display help text
size = "S", -- frame size list (defaults to IMIX)
src_mac = "s", -- source ethernet address
dst_mac = "d", -- destination ethernet address
src_mac4 = 1, -- source ethernet address for IPv4 traffic
dst_mac4 = 1, -- destination ethernet address for IPv4 traffic
src_mac6 = 1, -- source ethernet address for IPv6 traffic
dst_mac6 = 1, -- destination ethernet address for IPv6 traffic
vlan = "v", -- VLAN id
vlan4 = 1, -- VLAN id for IPv4 traffic
vlan6 = 1, -- VLAN id for IPv6 traffic
b4 = "b", -- B4 start IPv6_address,IPv4_address,port
aftr = "a", -- fix AFTR public IPv6_address
ipv4 = "I", -- fix public IPv4 address
count = "c", -- how many b4 clients to simulate
rate = "r", -- rate in MPPS (0 => listen only)
v4only = "4", -- generate only public IPv4 traffic
v6only = "6", -- generate only public IPv6 encapsulated traffic
pcap = "o" -- output packet to the pcap file
}
local function dir_exists(path)
local stat = S.stat(path)
return stat and stat.isdir
end
function run (args)
local opt = {}
local duration
local c = config.new()
function opt.D (arg)
duration = assert(tonumber(arg), "duration is not a number!")
end
local verbose
function opt.V (arg)
verbose = true
end
function opt.h (arg)
print(usage)
main.exit(0)
end
local sizes = { 64, 64, 64, 64, 64, 64, 64, 594, 594, 594, 1464 }
function opt.S (arg)
sizes = {}
for size in string.gmatch(arg, "%d+") do
sizes[#sizes + 1] = assert(tonumber(size), "size not a number: "..size)
end
end
local v4_src_mac = "00:00:00:00:00:00"
function opt.src_mac4 (arg) v4_src_mac = arg end
local v6_src_mac = "00:00:00:00:00:00"
function opt.src_mac6 (arg) v6_src_mac = arg end
function opt.s (arg) opt.src_mac4(arg); opt.src_mac6(arg) end
local v4_dst_mac = "00:00:00:00:00:00"
function opt.dst_mac4 (arg) v4_dst_mac = arg end
local v6_dst_mac = "00:00:00:00:00:00"
function opt.dst_mac6 (arg) v6_dst_mac = arg end
function opt.d (arg) opt.dst_mac4(arg); opt.dst_mac6(arg) end
local b4_ipv6, b4_ipv4, b4_port = "2001:db8::", "10.0.0.0", 1024
function opt.b (arg)
for s in string.gmatch(arg, "[%w.:]+") do
if string.find(s, ":") then
b4_ipv6 = s
elseif string.find(s, '.',1,true) then
b4_ipv4 = s
else
b4_port = assert(tonumber(s), string.format("UDP port %s is not a number!", s))
end
end
end
local public_ipv4 = "8.8.8.8"
function opt.I (arg) public_ipv4 = arg end
local aftr_ipv6 = "2001:db8:ffff::100"
function opt.a (arg) aftr_ipv6 = arg end
local count = 1
function opt.c (arg)
count = assert(tonumber(arg), "count is not a number!")
end
local rate = 1
function opt.r (arg)
rate = assert(tonumber(arg), "rate is not a number!")
end
local target
local pciaddr
function opt.p (arg)
pciaddr = arg
target = pciaddr
end
local tap_interface
function opt.t (arg)
tap_interface = arg
target = tap_interface
end
local int_interface
function opt.i (arg)
int_interface = arg
target = int_interface
end
local sock_interface
function opt.k (arg)
sock_interface = arg
target = sock_interface
end
local v4, v6 = true, true
function opt.v4 () v6 = false end
opt["4"] = opt.v4
function opt.v6 () v4 = false end
opt["6"] = opt.v6
local v4_vlan
function opt.vlan4 (arg)
v4_vlan = assert(tonumber(arg), "vlan is not a number!")
end
local v6_vlan
function opt.vlan6 (arg)
v6_vlan = assert(tonumber(arg), "vlan is not a number!")
end
function opt.v (arg) opt.vlan4(arg); opt.vlan6(arg) end
local pcap_file, single_pass = nil, false
function opt.o (arg)
pcap_file = arg
target = pcap_file
single_pass = true
rate = 1/0
end
args = lib.dogetopt(args, opt, "VD:hS:s:a:d:b:iI:c:r:46p:v:o:t:i:k:", long_opts)
for _,s in ipairs(sizes) do
if s < 18 + (v4_vlan and v6_vlan and 4 or 0) + 20 + 8 then
error("Minimum frame size is 46 bytes (18 ethernet+CRC, 20 IPv4, and 8 UDP)")
end
end
if not target then
print("either --pci, --tap, --sock, --int or --pcap are required parameters")
main.exit(1)
end
print(string.format("packetblaster lwaftr: Sending %d clients at %.3f MPPS to %s", count, rate, target))
print()
if not (v4 or v6) then
-- Assume that -4 -6 means both instead of neither.
v4, v6 = true, true
end
local v4_input, v4_output, v6_input, v6_output
local function finish_vlan(input, output, tag)
if not tag then return input, output end
-- Add and remove the common vlan tag.
config.app(c, "untag", vlan.Untagger, {tag=tag})
config.app(c, "tag", vlan.Tagger, {tag=tag})
config.link(c, "tag.output -> " .. input)
config.link(c, input .. " -> untag.input")
return 'tag.input', 'untag.output'
end
local function finish_v4(input, output)
assert(v4)
-- Stamp output with the MAC and make an ARP responder.
local tester_ip = ipv4:pton('1.2.3.4')
local next_ip = nil -- Assume we have a static dst mac.
config.app(c, "arp", arp.ARP,
{ self_ip = tester_ip,
self_mac = ethernet:pton(v4_src_mac),
next_mac = ethernet:pton(v4_dst_mac),
next_ip = next_ip })
config.link(c, output .. ' -> arp.south')
config.link(c, 'arp.south -> ' .. input)
return 'arp.north', 'arp.north'
end
local function finish_v6(input, output)
assert(v6)
-- Stamp output with the MAC and make an NDP responder.
local tester_ip = ipv6:pton('2001:DB8::1')
local next_ip = nil -- Assume we have a static dst mac.
config.app(c, "ndp", ndp.NDP,
{ self_ip = tester_ip,
self_mac = ethernet:pton(v6_src_mac),
next_mac = ethernet:pton(v6_dst_mac),
next_ip = next_ip })
config.link(c, output .. ' -> ndp.south')
config.link(c, 'ndp.south -> ' .. input)
return 'ndp.north', 'ndp.north'
end
local function split(input, output)
assert(v4 and v6)
if v4_vlan ~= v6_vlan then
-- Split based on vlan.
config.app(c, "vmux", vlan.VlanMux, {})
config.link(c, output .. ' -> vmux.trunk')
config.link(c, 'vmux.trunk -> ' .. input)
local v4_link = v4_vlan and 'vmux.vlan'..v4_vlan or 'vmux.native'
v4_input, v4_output = finish_v4(v4_link, v4_link)
local v6_link = v6_vlan and 'vmux.vlan'..v6_vlan or 'vmux.native'
v6_input, v6_output = finish_v6(v6_link, v6_link)
else
input, output = finish_vlan(input, output, v4_vlan)
-- Split based on ethertype.
config.app(c, "mux", V4V6.V4V6, {})
config.app(c, "join", Interleave, {})
v4_input, v4_output = finish_v4('join.v4', 'mux.v4')
v6_input, v6_output = finish_v6('join.v6', 'mux.v6')
config.link(c, output .. " -> mux.input")
config.link(c, "join.output -> " .. input)
end
end
local function maybe_split(input, output)
if v4 and v6 then
split(input, output)
elseif v4 then
input, output = finish_vlan(input, output, v4_vlan)
v4_input, v4_output = finish_v4(input, output)
else
input, output = finish_vlan(input, output, v6_vlan)
v6_input, v6_output = finish_v6(input, output)
end
end
if tap_interface then
if dir_exists(("/sys/devices/virtual/net/%s"):format(tap_interface)) then
config.app(c, "tap", Tap, tap_interface)
else
print(string.format("tap interface %s doesn't exist", tap_interface))
main.exit(1)
end
maybe_split("tap.input", "tap.output")
elseif pciaddr then
local device_info = pci.device_info(pciaddr)
if v4_vlan then
print(string.format("IPv4 vlan set to %d", v4_vlan))
end
if v6_vlan then
print(string.format("IPv6 vlan set to %d", v6_vlan))
end
if not device_info then
fatal(("Couldn't find device info for PCI or tap device %s"):format(pciaddr))
end
if v4 and v6 then
if v4_vlan == v6_vlan and v4_src_mac == v6_src_mac then
config.app(c, "nic", require(device_info.driver).driver,
{pciaddr = pciaddr, vmdq = true, macaddr = v4_src_mac,
mtu = 9500, vlan = v4_vlan})
maybe_split("nic."..device_info.rx, "nic."..device_info.tx)
else
config.app(c, "v4nic", require(device_info.driver).driver,
{pciaddr = pciaddr, vmdq = true, macaddr = v4_src_mac,
mtu = 9500, vlan = v4_vlan})
v4_input, v4_output = finish_v4("v4nic."..device_info.rx,
"v4nic."..device_info.tx)
config.app(c, "v6nic", require(device_info.driver).driver,
{pciaddr = pciaddr, vmdq = true, macaddr = v6_src_mac,
mtu = 9500, vlan = v6_vlan})
v6_input, v6_output = finish_v6("v6nic."..device_info.rx,
"v6nic."..device_info.tx)
end
elseif v4 then
config.app(c, "nic", require(device_info.driver).driver,
{pciaddr = pciaddr, vmdq = true, macaddr = v4_src_mac,
mtu = 9500, vlan = v4_vlan})
v4_input, v4_output = finish_v4("nic."..device_info.rx,
"nic."..device_info.tx)
else
config.app(c, "nic", require(device_info.driver).driver,
{pciaddr = pciaddr, vmdq = true, macaddr = v6_src_mac,
mtu = 9500, vlan = v6_vlan})
v6_input, v6_output = finish_v6("nic."..device_info.rx,
"nic."..device_info.tx)
end
elseif int_interface then
config.app(c, "int", raw.RawSocket, int_interface)
maybe_split("int.rx", "int.tx")
elseif sock_interface then
config.app(c, "virtio", VhostUser, { socket_path=sock_interface } )
maybe_split("virtio.rx", "virtio.tx")
else
config.app(c, "pcap", pcap.PcapWriter, pcap_file)
maybe_split("pcap.input", "pcap.output")
end
if v4 then
print()
print(string.format("IPv4: %s:12345 > %s:%d", public_ipv4, b4_ipv4, b4_port))
print(" destination IPv4 and Port adjusted per client")
print("IPv4 frame sizes: " .. table.concat(sizes,","))
local rate = v6 and rate/2 or rate
config.app(c, "inetgen", InetGen, {
sizes = sizes, rate = rate, count = count, single_pass = single_pass,
b4_ipv4 = b4_ipv4, b4_port = b4_port, public_ipv4 = public_ipv4,
frame_overhead = v4_vlan and 4 or 0})
if v6_output then
config.link(c, v6_output .. " -> inetgen.input")
end
config.link(c, "inetgen.output -> " .. v4_input)
end
if v6 then
print()
print(string.format("IPv6: %s > %s: %s:%d > %s:12345", b4_ipv6, aftr_ipv6, b4_ipv4, b4_port, public_ipv4))
print(" source IPv6 and source IPv4/Port adjusted per client")
local sizes_ipv6 = {}
for i,size in ipairs(sizes) do sizes_ipv6[i] = size + 40 end
print("IPv6 frame sizes: " .. table.concat(sizes_ipv6,","))
local rate = v4 and rate/2 or rate
config.app(c, "b4gen", B4Gen, {
sizes = sizes, rate = rate, count = count, single_pass = single_pass,
b4_ipv6 = b4_ipv6, aftr_ipv6 = aftr_ipv6,
b4_ipv4 = b4_ipv4, b4_port = b4_port, public_ipv4 = public_ipv4,
frame_overhead = v6_vlan and 4 or 0})
if v4_output then
config.link(c, v4_output .. " -> b4gen.input")
end
config.link(c, "b4gen.output -> " .. v6_input)
end
engine.busywait = true
engine.configure(c)
if verbose then
print ("enabling verbose")
local fn = function ()
print("Transmissions (last 1 sec):")
engine.report_apps()
end
local t = timer.new("report", fn, 1e9, 'repeating')
timer.activate(t)
end
local done
if duration then
done = lib.timeout(duration)
else
local b4gen = engine.app_table.b4gen
local inetgen = engine.app_table.inetgen
print (b4gen, inetgen)
function done()
return ((not b4gen) or b4gen:done()) and ((not inetgen) or inetgen:done())
end
end
engine.main({done=done})
end
| apache-2.0 |
jjimenezg93/ai-pathfinding | moai/src/lua-modules/moai/url.lua | 4 | 1345 | --==============================================================
-- Copyright (c) 2010-2011 Zipline Games, Inc.
-- All Rights Reserved.
-- http://getmoai.com
--==============================================================
----------------------------------------------------------------
-- url.lua - version 1.0 Beta
----------------------------------------------------------------
module ( ..., package.seeall )
----------------------------------------------------------------
-- escapes a url string and returns the new string
----------------------------------------------------------------
function escape ( str )
if str then
-- convert line endings
str = string.gsub ( str, "\n", "\r\n" )
-- escape all special characters
str = string.gsub ( str, "([^%w ])",
function ( c )
return string.format ( "%%%02X", string.byte ( c ))
end
)
-- convert spaces to "+" symbols
str = string.gsub ( str, " ", "+" )
end
return str
end
----------------------------------------------------------------
-- converts a Lua table into a url encoded string of parameters
----------------------------------------------------------------
function encode ( t )
local s = ""
for k,v in pairs ( t ) do
s = s .. "&" .. escape ( k ) .. "=" .. escape ( v )
end
return string.sub ( s, 2 ) -- remove first '&'
end
| mit |
Vermeille/kong | kong/plugins/ldap-auth/access.lua | 3 | 3848 | local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local cache = require "kong.tools.database_cache"
local ldap = require "kong.plugins.ldap-auth.ldap"
local match = string.match
local ngx_log = ngx.log
local request = ngx.req
local ngx_error = ngx.ERR
local ngx_debug = ngx.DEBUG
local decode_base64 = ngx.decode_base64
local ngx_socket_tcp = ngx.socket.tcp
local tostring = tostring
local AUTHORIZATION = "authorization"
local PROXY_AUTHORIZATION = "proxy-authorization"
local _M = {}
local function retrieve_credentials(authorization_header_value, conf)
local username, password
if authorization_header_value then
local cred = match(authorization_header_value, "%s*[ldap|LDAP]%s+(.*)")
if cred ~= nil then
local decoded_cred = decode_base64(cred)
username, password = match(decoded_cred, "(.+):(.+)")
end
end
return username, password
end
local function ldap_authenticate(given_username, given_password, conf)
local is_authenticated
local error, suppressed_err, ok
local who = conf.attribute.."="..given_username..","..conf.base_dn
local sock = ngx_socket_tcp()
sock:settimeout(conf.timeout)
ok, error = sock:connect(conf.ldap_host, conf.ldap_port)
if not ok then
ngx_log(ngx_error, "[ldap-auth] failed to connect to "..conf.ldap_host..":"..tostring(conf.ldap_port)..": ", error)
return responses.send_HTTP_INTERNAL_SERVER_ERROR(error)
end
if conf.start_tls then
local success, error = ldap.start_tls(sock)
if not success then
return false, error
end
local _, error = sock:sslhandshake(true, conf.ldap_host, conf.verify_ldap_host)
if error ~= nil then
return false, "failed to do SSL handshake with "..conf.ldap_host..":"..tostring(conf.ldap_port)..": ".. error
end
end
is_authenticated, error = ldap.bind_request(sock, who, given_password)
ok, suppressed_err = sock:setkeepalive(conf.keepalive)
if not ok then
ngx_log(ngx_error, "[ldap-auth] failed to keepalive to "..conf.ldap_host..":"..tostring(conf.ldap_port)..": ", suppressed_err)
end
return is_authenticated, error
end
local function authenticate(conf, given_credentials)
local given_username, given_password = retrieve_credentials(given_credentials)
if given_username == nil then
return false
end
local credential = cache.get_or_set(cache.ldap_credential_key(given_username), function()
ngx_log(ngx_debug, "[ldap-auth] authenticating user against LDAP server: "..conf.ldap_host..":"..conf.ldap_port)
local ok, err = ldap_authenticate(given_username, given_password, conf)
if err ~= nil then ngx_log(ngx_error, err) end
if not ok then
return nil
end
return {username = given_username, password = given_password}
end, conf.cache_ttl)
return credential and credential.password == given_password, credential
end
function _M.execute(conf)
local authorization_value = request.get_headers()[AUTHORIZATION]
local proxy_authorization_value = request.get_headers()[PROXY_AUTHORIZATION]
-- If both headers are missing, return 401
if not (authorization_value or proxy_authorization_value) then
ngx.header["WWW-Authenticate"] = 'LDAP realm="kong"'
return responses.send_HTTP_UNAUTHORIZED()
end
local is_authorized, credential = authenticate(conf, proxy_authorization_value)
if not is_authorized then
is_authorized, credential = authenticate(conf, authorization_value)
end
if not is_authorized then
return responses.send_HTTP_FORBIDDEN("Invalid authentication credentials")
end
if conf.hide_credentials then
request.clear_header(AUTHORIZATION)
request.clear_header(PROXY_AUTHORIZATION)
end
request.set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username)
ngx.ctx.authenticated_credential = credential
end
return _M
| apache-2.0 |
anvilvapre/OpenRA | mods/ra/maps/soviet-01/soviet01.lua | 28 | 2150 | Yaks = { "yak", "yak", "yak" }
Airfields = { Airfield1, Airfield2, Airfield3 }
InsertYaks = function()
local i = 1
Utils.Do(Yaks, function(yakType)
local start = YakEntry.CenterPosition + WVec.New(0, (i - 1) * 1536, Actor.CruiseAltitude(yakType))
local dest = StartJeep.Location + CVec.New(0, 2 * i)
local yak = Actor.Create(yakType, true, { CenterPosition = start, Owner = player, Facing = (Map.CenterOfCell(dest) - start).Facing })
yak.Move(dest)
yak.ReturnToBase(Airfields[i])
i = i + 1
end)
end
JeepDemolishingBridge = function()
StartJeep.Move(StartJeepMovePoint.Location)
Trigger.OnIdle(StartJeep, function()
Trigger.ClearAll(StartJeep)
if not BridgeBarrel.IsDead then
BridgeBarrel.Kill()
end
local bridge = Map.ActorsInBox(BridgeWaypoint.CenterPosition, Airfield1.CenterPosition,
function(self) return self.Type == "bridge1" end)[1]
if not bridge.IsDead then
bridge.Kill()
end
end)
end
WorldLoaded = function()
player = Player.GetPlayer("USSR")
france = Player.GetPlayer("France")
germany = Player.GetPlayer("Germany")
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
VillageRaidObjective = player.AddPrimaryObjective("Raze the village.")
Trigger.OnAllRemovedFromWorld(Airfields, function()
player.MarkFailedObjective(VillageRaidObjective)
end)
JeepDemolishingBridge()
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "MissionAccomplished")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "MissionFailed")
end)
Trigger.AfterDelay(DateTime.Seconds(2), InsertYaks)
end
Tick = function()
if france.HasNoRequiredUnits() and germany.HasNoRequiredUnits() then
player.MarkCompletedObjective(VillageRaidObjective)
end
end
| gpl-3.0 |
pjulien/flatbuffers | tests/namespace_test/NamespaceC/TableInC.lua | 12 | 1513 | -- automatically generated by the FlatBuffers compiler, do not modify
-- namespace: NamespaceC
local flatbuffers = require('flatbuffers')
local TableInC = {} -- the module
local TableInC_mt = {} -- the class metatable
function TableInC.New()
local o = {}
setmetatable(o, {__index = TableInC_mt})
return o
end
function TableInC.GetRootAsTableInC(buf, offset)
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = TableInC.New()
o:Init(buf, n + offset)
return o
end
function TableInC_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function TableInC_mt:ReferToA1()
local o = self.view:Offset(4)
if o ~= 0 then
local x = self.view:Indirect(o + self.view.pos)
local obj = require('NamespaceA.TableInFirstNS').New()
obj:Init(self.view.bytes, x)
return obj
end
end
function TableInC_mt:ReferToA2()
local o = self.view:Offset(6)
if o ~= 0 then
local x = self.view:Indirect(o + self.view.pos)
local obj = require('NamespaceA.SecondTableInA').New()
obj:Init(self.view.bytes, x)
return obj
end
end
function TableInC.Start(builder) builder:StartObject(2) end
function TableInC.AddReferToA1(builder, referToA1) builder:PrependUOffsetTRelativeSlot(0, referToA1, 0) end
function TableInC.AddReferToA2(builder, referToA2) builder:PrependUOffsetTRelativeSlot(1, referToA2, 0) end
function TableInC.End(builder) return builder:EndObject() end
return TableInC -- return the module | apache-2.0 |
Schaka/gladdy | Modules/Auras.lua | 1 | 14168 | local pairs = pairs
local GetSpellInfo = GetSpellInfo
local CreateFrame = CreateFrame
local Gladdy = LibStub("Gladdy")
local L = Gladdy.L
local Auras = Gladdy:NewModule("Auras", nil, {
auraFontSize = 16,
auraFontColor = {r = 1, g = 1, b = 0, a = 1}
})
function Auras:Initialise()
self.frames = {}
self.auras = self:GetAuraList()
self:RegisterMessage("AURA_GAIN")
self:RegisterMessage("AURA_FADE")
self:RegisterMessage("UNIT_DEATH", "AURA_FADE")
end
function Auras:CreateFrame(unit)
local auraFrame = CreateFrame("Frame", nil, Gladdy.buttons[unit])
local classIcon = Gladdy.modules.Classicon.frames[unit]
auraFrame:ClearAllPoints()
auraFrame:SetAllPoints(classIcon)
auraFrame:SetScript("OnUpdate", function(self, elapsed)
if (self.active) then
if (self.timeLeft <= 0) then
Auras:AURA_FADE(unit)
else
self.timeLeft = self.timeLeft - elapsed
self.text:SetFormattedText("%.1f", self.timeLeft)
end
end
end)
auraFrame.icon = auraFrame:CreateTexture(nil, "ARTWORK")
auraFrame.icon:SetAllPoints(auraFrame)
auraFrame.text = auraFrame:CreateFontString(nil, "OVERLAY")
auraFrame.text:SetFont(Gladdy.LSM:Fetch("font"), Gladdy.db.auraFontSize)
auraFrame.text:SetTextColor(Gladdy.db.auraFontColor.r, Gladdy.db.auraFontColor.g, Gladdy.db.auraFontColor.b, Gladdy.db.auraFontColor.a)
auraFrame.text:SetShadowOffset(1, -1)
auraFrame.text:SetShadowColor(0, 0, 0, 1)
auraFrame.text:SetJustifyH("CENTER")
auraFrame.text:SetPoint("CENTER")
self.frames[unit] = auraFrame
self:ResetUnit(unit)
end
function Auras:UpdateFrame(unit)
local auraFrame = self.frames[unit]
if (not auraFrame) then return end
local classIcon = Gladdy.modules.Classicon.frames[unit]
auraFrame:SetWidth(classIcon:GetWidth())
auraFrame:SetHeight(classIcon:GetHeight())
auraFrame:SetAllPoints(classIcon)
auraFrame.text:SetFont(Gladdy.LSM:Fetch("font"), Gladdy.db.auraFontSize)
auraFrame.text:SetTextColor(Gladdy.db.auraFontColor.r, Gladdy.db.auraFontColor.g, Gladdy.db.auraFontColor.b, Gladdy.db.auraFontColor.a)
end
function Auras:ResetUnit(unit)
self:AURA_FADE(unit)
end
function Auras:Test(unit)
local aura, _, icon
if (unit == "arena1") then
aura, _, icon = GetSpellInfo(12826)
elseif (unit == "arena3") then
aura, _, icon = GetSpellInfo(31224)
end
if (aura) then
self:AURA_GAIN(unit, aura, icon, self.auras[aura].duration, self.auras[aura].priority)
end
end
function Auras:AURA_GAIN(unit, aura, icon, duration, priority)
local auraFrame = self.frames[unit]
if (not auraFrame) then return end
if (auraFrame.priority and auraFrame.priority > priority) then
return
end
auraFrame.name = aura
auraFrame.timeLeft = duration
auraFrame.priority = priority
auraFrame.icon:SetTexture(icon)
auraFrame.active = true
end
function Auras:AURA_FADE(unit)
local auraFrame = self.frames[unit]
if (not auraFrame) then return end
auraFrame.active = false
auraFrame.name = nil
auraFrame.timeLeft = 0
auraFrame.priority = nil
auraFrame.icon:SetTexture("")
auraFrame.text:SetText("")
end
local function option(params)
local defaults = {
get = function(info)
local key = info.arg or info[#info]
return Gladdy.dbi.profile[key]
end,
set = function(info, value)
local key = info.arg or info[#info]
Gladdy.dbi.profile[key] = value
Gladdy:UpdateFrame()
end,
}
for k, v in pairs(params) do
defaults[k] = v
end
return defaults
end
local function colorOption(params)
local defaults = {
get = function(info)
local key = info.arg or info[#info]
return Gladdy.dbi.profile[key].r, Gladdy.dbi.profile[key].g, Gladdy.dbi.profile[key].b, Gladdy.dbi.profile[key].a
end,
set = function(info, r, g, b ,a)
local key = info.arg or info[#info]
Gladdy.dbi.profile[key].r, Gladdy.dbi.profile[key].g, Gladdy.dbi.profile[key].b, Gladdy.dbi.profile[key].a = r, g, b, a
Gladdy:UpdateFrame()
end,
}
for k, v in pairs(params) do
defaults[k] = v
end
return defaults
end
function Auras:GetOptions()
return {
auraFontColor = colorOption({
type = "color",
name = L["Font color"],
desc = L["Color of the text"],
order = 4,
hasAlpha = true,
}),
auraFontSize = option({
type = "range",
name = L["Font size"],
desc = L["Size of the text"],
order = 5,
min = 1,
max = 20,
}),
}
end
function Auras:GetAuraList()
return {
-- Cyclone
[GetSpellInfo(33786)] = {
track = "debuff",
duration = 6,
priority = 40,
},
-- Hibername
[GetSpellInfo(18658)] = {
track = "debuff",
duration = 10,
priority = 40,
magic = true,
},
-- Entangling Roots
[GetSpellInfo(26989)] = {
track = "debuff",
duration = 10,
priority = 30,
onDamage = true,
magic = true,
root = true,
},
-- Feral Charge
[GetSpellInfo(16979)] = {
track = "debuff",
duration = 4,
priority = 30,
root = true,
},
-- Bash
[GetSpellInfo(8983)] = {
track = "debuff",
duration = 4,
priority = 30,
},
-- Pounce
[GetSpellInfo(9005)] = {
track = "debuff",
duration = 3,
priority = 40,
},
-- Maim
[GetSpellInfo(22570)] = {
track = "debuff",
duration = 6,
priority = 40,
incapacite = true,
},
-- Innervate
[GetSpellInfo(29166)] = {
track = "buff",
duration = 20,
priority = 10,
},
-- Freezing Trap Effect
[GetSpellInfo(14309)] = {
track = "debuff",
duration = 10,
priority = 40,
onDamage = true,
magic = true,
},
-- Wyvern Sting
[GetSpellInfo(19386)] = {
track = "debuff",
duration = 10,
priority = 40,
onDamage = true,
poison = true,
sleep = true,
},
-- Scatter Shot
[GetSpellInfo(19503)] = {
track = "debuff",
duration = 4,
priority = 40,
onDamage = true,
},
-- Silencing Shot
[GetSpellInfo(34490)] = {
track = "debuff",
duration = 3,
priority = 15,
magic = true,
},
-- Intimidation
[GetSpellInfo(19577)] = {
track = "debuff",
duration = 2,
priority = 40,
},
-- The Beast Within
[GetSpellInfo(34692)] = {
track = "buff",
duration = 18,
priority = 20,
},
-- Polymorph
[GetSpellInfo(12826)] = {
track = "debuff",
duration = 10,
priority = 40,
onDamage = true,
magic = true,
},
-- Dragon's Breath
[GetSpellInfo(31661)] = {
track = "debuff",
duration = 3,
priority = 40,
onDamage = true,
magic = true,
},
-- Frost Nova
[GetSpellInfo(27088)] = {
track = "debuff",
duration = 8,
priority = 30,
onDamage = true,
magic = true,
root = true,
},
-- Freeze (Water Elemental)
[GetSpellInfo(33395)] = {
track = "debuff",
duration = 8,
priority = 30,
onDamage = true,
magic = true,
root = true,
},
-- Counterspell - Silence
[GetSpellInfo(18469)] = {
track = "debuff",
duration = 4,
priority = 15,
magic = true,
},
-- Ice Block
[GetSpellInfo(45438)] = {
track = "buff",
duration = 10,
priority = 20,
},
-- Hammer of Justice
[GetSpellInfo(10308)] = {
track = "debuff",
duration = 6,
priority = 40,
magic = true,
},
-- Repentance
[GetSpellInfo(20066)] = {
track = "debuff",
duration = 6,
priority = 40,
onDamage = true,
magic = true,
incapacite = true,
},
-- Blessing of Protection
[GetSpellInfo(10278)] = {
track = "buff",
duration = 10,
priority = 10,
},
-- Blessing of Freedom
[GetSpellInfo(1044)] = {
track = "buff",
duration = 14,
priority = 10,
},
-- Divine Shield
[GetSpellInfo(642)] = {
track = "buff",
duration = 12,
priority = 20,
},
-- Psychic Scream
[GetSpellInfo(8122)] = {
track = "debuff",
duration = 8,
priority = 40,
onDamage = true,
fear = true,
magic = true,
},
-- Chastise
[GetSpellInfo(44047)] = {
track = "debuff",
duration = 8,
priority = 30,
root = true,
},
-- Mind Control
[GetSpellInfo(605)] = {
track = "debuff",
duration = 10,
priority = 40,
magic = true,
},
-- Silence
[GetSpellInfo(15487)] = {
track = "debuff",
duration = 5,
priority = 15,
magic = true,
},
-- Pain Suppression
[GetSpellInfo(33206)] = {
track = "buff",
duration = 8,
priority = 10,
},
-- Sap
[GetSpellInfo(6770)] = {
track = "debuff",
duration = 10,
priority = 40,
onDamage = true,
incapacite = true,
},
-- Blind
[GetSpellInfo(2094)] = {
track = "debuff",
duration = 10,
priority = 40,
onDamage = true,
},
-- Cheap Shot
[GetSpellInfo(1833)] = {
track = "debuff",
duration = 4,
priority = 40,
},
-- Kidney Shot
[GetSpellInfo(8643)] = {
track = "debuff",
duration = 6,
priority = 40,
},
-- Gouge
[GetSpellInfo(1776)] = {
track = "debuff",
duration = 4,
priority = 40,
onDamage = true,
incapacite = true,
},
-- Kick - Silence
[GetSpellInfo(18425)] = {
track = "debuff",
duration = 2,
priority = 15,
},
-- Garrote - Silence
[GetSpellInfo(1330)] = {
track = "debuff",
duration = 3,
priority = 15,
},
-- Cloak of Shadows
[GetSpellInfo(31224)] = {
track = "buff",
duration = 5,
priority = 20,
},
-- Fear
[GetSpellInfo(5782)] = {
track = "debuff",
duration = 10,
priority = 40,
onDamage = true,
fear = true,
magic = true,
},
-- Death Coil
[GetSpellInfo(27223)] = {
track = "debuff",
duration = 3,
priority = 40,
},
-- Shadowfury
[GetSpellInfo(30283)] = {
track = "debuff",
duration = 2,
priority = 40,
magic = true,
},
-- Seduction (Succubus)
[GetSpellInfo(6358)] = {
track = "debuff",
duration = 10,
priority = 40,
onDamage = true,
fear = true,
magic = true,
},
-- Howl of Terror
[GetSpellInfo(5484)] = {
track = "debuff",
duration = 8,
priority = 40,
onDamage = true,
fear = true,
magic = true,
},
-- Spell Lock (Felhunter)
[GetSpellInfo(24259)] = {
track = "debuff",
duration = 3,
priority = 15,
magic = true,
},
-- Unstable Affliction
[GetSpellInfo(31117)] = {
track = "debuff",
duration = 5,
priority = 15,
magic = true,
},
-- Intimidating Shout
[GetSpellInfo(5246)] = {
track = "debuff",
duration = 8,
priority = 15,
onDamage = true,
fear = true,
},
-- Concussion Blow
[GetSpellInfo(12809)] = {
track = "debuff",
duration = 5,
priority = 40,
},
-- Intercept Stun
[GetSpellInfo(25274)] = {
track = "debuff",
duration = 3,
priority = 40,
},
-- Spell Reflection
[GetSpellInfo(23920)] = {
track = "buff",
duration = 5,
priority = 10,
},
-- War Stomp
[GetSpellInfo(20549)] = {
track = "debuff",
duration = 2,
priority = 40,
},
-- Arcane Torrent
[GetSpellInfo(28730)] = {
track = "debuff",
duration = 2,
priority = 15,
magic = true,
},
}
end | mit |
jackywgw/ntopng_test | scripts/lua/inc/change_user_password_form.lua | 10 | 2983 | print [[
<style type='text/css'>
.largegroup {
width:500px
}
</style>
<div id="password_dialog" tabindex="-1" >
<h3 id="password_dialog_label">Change ]] print(_SESSION["user"]) print [[ Password <span id="password_dialog_title"></span></h3>
<div id="password_alert_placeholder"></div>
<script>
password_alert = function() {}
password_alert.error = function(message) { $('#password_alert_placeholder').html('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>' + message + '</div>');
}
password_alert.success = function(message) { $('#password_alert_placeholder').html('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">x</button>' + message + '</div>'); }
</script>
<form id="form_password_reset" class="form-horizontal" method="get" action="password_reset.lua">
]]
print('<input id="csrf" name="csrf" type="hidden" value="'..ntop.getRandomCSRFValue()..'" />\n')
local user = ""
if (_COOKIE["user"] ~= nil) then
user = _COOKIE["user"]
end
print('<input id="password_dialog_username" type="hidden" name="username" value="' ..user.. '" />')
print [[
<div class="input-group">
<div class="input-group">
<label for="" class="control-label">Old Password</label>
<div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span>
<input id="old_password_input" type="password" name="old_password" value="" class="form-control">
</div>
</div>
<div class="input-group">
<label for="" class="control-label">New Password</label>
<div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span>
<input id="new_password_input" type="password" name="new_password" value="" class="form-control">
</div>
</div>
<div class="input-group">
<label for="" class="control-label">Confirm New Password</label>
<div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span>
<input id="confirm_new_password_input" type="password" name="confirm_new_password" value="" class="form-control">
</div>
</div>
<div class="input-group"> </div>
<button id="password_reset_submit" class="btn btn-primary btn-block">Change Password</button>
</div>
</form>
]]
print [[<script>
var frmpassreset = $('#form_password_reset');
frmpassreset.submit(function () {
$.ajax({
type: frmpassreset.attr('method'),
url: frmpassreset.attr('action'),
data: frmpassreset.serialize(),
success: function (data) {
var response = jQuery.parseJSON(data);
if (response.result == 0) {
password_alert.success(response.message);
}
else {
password_alert.error(response.message);
}
$("old_password_input").text("");
$("new_password_input").text("");
$("confirm_new_password_input").text("");
}
});
return false;
});
</script>
</div>
</div> <!-- personal password_dialog -->
]]
| gpl-3.0 |
DavidIngraham/ardupilot | libraries/AP_Scripting/examples/protected_call.lua | 22 | 1154 | -- this shows how to protect against faults in your scripts
-- you can wrap your update() call (or any other call) in a pcall()
-- which catches errors, allowing you to take an appropriate action
-- example main loop function
function update()
local t = 0.001 * millis():tofloat()
gcs:send_text(0, string.format("TICK %.1fs", t))
if math.floor(t) % 10 == 0 then
-- deliberately make a bad call to cause a fault, asking for the 6th GPS status
-- as this is done inside a pcall() the error will be caught instead of stopping the script
local status = gps:status(5)
end
end
-- wrapper around update(). This calls update() at 5Hz,
-- and if update faults then an error is displayed, but the script is not
-- stopped
function protected_wrapper()
local success, err = pcall(update)
if not success then
gcs:send_text(0, "Internal Error: " .. err)
-- when we fault we run the update function again after 1s, slowing it
-- down a bit so we don't flood the console with errors
return protected_wrapper, 1000
end
return protected_wrapper, 200
end
-- start running update loop
return protected_wrapper()
| gpl-3.0 |
DigitalVeer/Lua-Snippets | FunctionalProgrammingLua.lua | 2 | 1307 | local Signal = {
meta = {}
}
insert = table.insert
local SignalLibrary = {
Event = function (name)
return function(callPerWait)
local Bool = Instance.new("BoolValue"); Bool.Value = false;
return { ["connect"] = function() Bool.Value = true end,
["Wait"] = coroutine.wrap(function()
local orig = Bool.Value;
while not rawequal(not orig,Bool.Value) and wait() do
callPerWait()
end
return true;
end)(), ["disconnect"] = function() Bool.Value = false end, ["EventType"] = name}
end
end,
}
function SignalLibrary:get(func,...)
--return function(...)
if func == nil then
local kys,vls = {},{}
for i,v in pairs(self) do
insert(kys,i)
insert(vls,v)
end
return self,kys,vls;
else
func(self)
end
--end
end
function Signal.new(dataType)
return function(vals)
return function(passIn)
local kvAr = {}
assert(#dataType==#vals,"Error: Need Key per Value")
for ind,val in pairs(dataType) do
kvAr[dataType[ind]] = vals[ind]
end
return setmetatable(kvAr, {
__index = function(s,k)
if k=="get" then
return passIn.get or SignalLibrary.get
elseif k=="connect" then
return SignalLibrary["Event"]
elseif k == "set" then
end
end,
__newindex = function() return "nop" end,
})
end
end
end
return Signal
| mit |
Poyer/Anchor-BoT | plugins/qr.lua | 637 | 1730 | --[[
* qr plugin uses:
* - http://goqr.me/api/doc/create-qr-code/
* psykomantis
]]
local function get_hex(str)
local colors = {
red = "f00",
blue = "00f",
green = "0f0",
yellow = "ff0",
purple = "f0f",
white = "fff",
black = "000",
gray = "ccc"
}
for color, value in pairs(colors) do
if color == str then
return value
end
end
return str
end
local function qr(receiver, text, color, bgcolor)
local url = "http://api.qrserver.com/v1/create-qr-code/?"
.."size=600x600" --fixed size otherways it's low detailed
.."&data="..URL.escape(text:trim())
if color then
url = url.."&color="..get_hex(color)
end
if bgcolor then
url = url.."&bgcolor="..get_hex(bgcolor)
end
local response, code, headers = http.request(url)
if code ~= 200 then
return "Oops! Error: " .. code
end
if #response > 0 then
send_photo_from_url(receiver, url)
return
end
return "Oops! Something strange happened :("
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local color
local back
if #matches > 1 then
text = matches[3]
color = matches[2]
back = matches[1]
end
return qr(receiver, text, color, back)
end
return {
description = {"qr code plugin for telegram, given a text it returns the qr code"},
usage = {
"!qr [text]",
'!qr "[background color]" "[data color]" [text]\n'
.."Color through text: red|green|blue|purple|black|white|gray\n"
.."Colors through hex notation: (\"a56729\" is brown)\n"
.."Or colors through decimals: (\"255-192-203\" is pink)"
},
patterns = {
'^!qr "(%w+)" "(%w+)" (.+)$',
"^!qr (.+)$"
},
run = run
} | gpl-2.0 |
mortezamosavy999/monster | plugins/qr.lua | 637 | 1730 | --[[
* qr plugin uses:
* - http://goqr.me/api/doc/create-qr-code/
* psykomantis
]]
local function get_hex(str)
local colors = {
red = "f00",
blue = "00f",
green = "0f0",
yellow = "ff0",
purple = "f0f",
white = "fff",
black = "000",
gray = "ccc"
}
for color, value in pairs(colors) do
if color == str then
return value
end
end
return str
end
local function qr(receiver, text, color, bgcolor)
local url = "http://api.qrserver.com/v1/create-qr-code/?"
.."size=600x600" --fixed size otherways it's low detailed
.."&data="..URL.escape(text:trim())
if color then
url = url.."&color="..get_hex(color)
end
if bgcolor then
url = url.."&bgcolor="..get_hex(bgcolor)
end
local response, code, headers = http.request(url)
if code ~= 200 then
return "Oops! Error: " .. code
end
if #response > 0 then
send_photo_from_url(receiver, url)
return
end
return "Oops! Something strange happened :("
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local color
local back
if #matches > 1 then
text = matches[3]
color = matches[2]
back = matches[1]
end
return qr(receiver, text, color, back)
end
return {
description = {"qr code plugin for telegram, given a text it returns the qr code"},
usage = {
"!qr [text]",
'!qr "[background color]" "[data color]" [text]\n'
.."Color through text: red|green|blue|purple|black|white|gray\n"
.."Colors through hex notation: (\"a56729\" is brown)\n"
.."Or colors through decimals: (\"255-192-203\" is pink)"
},
patterns = {
'^!qr "(%w+)" "(%w+)" (.+)$',
"^!qr (.+)$"
},
run = run
} | gpl-2.0 |
xponen/Zero-K | LuaUI/Widgets/gfx_outline.lua | 1 | 10198 | -- $Id: gfx_outline.lua 3171 2008-11-06 09:06:29Z det $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: gfx_outline.lua
-- brief: Displays a nice cartoon like outline around units
-- author: jK
--
-- Copyright (C) 2007.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Outline",
desc = "Displays a nice cartoon like outline around units.",
author = "jK",
date = "Dec 06, 2007",
license = "GNU GPL, v2 or later",
layer = -10,
enabled = false -- loaded by default?
}
end
options_path = 'Settings/Graphics/Unit Visibility/Outline'
options = {
thickness = {
name = 'Outline Thickness',
desc = 'How thick the outline appears around objects',
type = 'number',
min = 0.4, max = 1, step = 0.01,
value = 1,
},
}
local thickness = 1
local function OnchangeFunc()
thickness = options.thickness.value
end
for key,option in pairs(options) do
option.OnChange = OnchangeFunc
end
OnchangeFunc()
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--//textures
local offscreentex
local depthtex
local blurtex
--//shader
local depthShader
local blurShader_h
local blurShader_v
local uniformScreenXY, uniformScreenX, uniformScreenY
--// geometric
local vsx, vsy = 0,0
local resChanged = false
--// display lists
local enter2d,leave2d
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local GL_DEPTH_BITS = 0x0D56
local GL_DEPTH_COMPONENT = 0x1902
local GL_DEPTH_COMPONENT16 = 0x81A5
local GL_DEPTH_COMPONENT24 = 0x81A6
local GL_DEPTH_COMPONENT32 = 0x81A7
--// speed ups
local ALL_UNITS = Spring.ALL_UNITS
local GetUnitHealth = Spring.GetUnitHealth
local GetVisibleUnits = Spring.GetVisibleUnits
local GL_MODELVIEW = GL.MODELVIEW
local GL_PROJECTION = GL.PROJECTION
local GL_COLOR_BUFFER_BIT = GL.COLOR_BUFFER_BIT
local glUnit = gl.Unit
local glCopyToTexture = gl.CopyToTexture
local glRenderToTexture = gl.RenderToTexture
local glCallList = gl.CallList
local glUseShader = gl.UseShader
local glUniform = gl.Uniform
local glUniformInt = gl.UniformInt
local glClear = gl.Clear
local glTexRect = gl.TexRect
local glColor = gl.Color
local glTexture = gl.Texture
local glResetMatrices = gl.ResetMatrices
local glMatrixMode = gl.MatrixMode
local glPushMatrix = gl.PushMatrix
local glLoadIdentity = gl.LoadIdentity
local glPopMatrix = gl.PopMatrix
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--tables
local unbuiltUnits = {}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
vsx, vsy = widgetHandler:GetViewSizes()
depthShader = gl.CreateShader({
fragment = [[
uniform sampler2D tex0;
uniform vec2 screenXY;
void main(void)
{
vec2 texCoord = vec2( gl_FragCoord.x/screenXY.x , gl_FragCoord.y/screenXY.y );
float depth = texture2D(tex0, texCoord ).z;
if (depth <= gl_FragCoord.z) {
discard;
}
gl_FragColor = gl_Color;
}
]],
uniformInt = {
tex0 = 0,
},
uniform = {
screenXY = {vsx,vsy},
},
})
blurShader_h = gl.CreateShader({
fragment = [[
uniform sampler2D tex0;
uniform int screenX;
const vec2 kernel = vec2(0.6,0.7);
void main(void) {
vec2 texCoord = vec2(gl_TextureMatrix[0] * gl_TexCoord[0]);
gl_FragColor = vec4(0.0);
int i;
int n = 1;
float pixelsize = 1.0/float(screenX);
for(i = 1; i < 3; ++i){
gl_FragColor += kernel[n] * texture2D(tex0, vec2(texCoord.s + i*pixelsize,texCoord.t) );
--n;
}
gl_FragColor += texture2D(tex0, texCoord );
n = 0;
for(i = -2; i < 0; ++i){
gl_FragColor += kernel[n] * texture2D(tex0, vec2(texCoord.s + i*pixelsize,texCoord.t) );
++n;
}
}
]],
uniformInt = {
tex0 = 0,
screenX = vsx,
},
})
blurShader_v = gl.CreateShader({
fragment = [[ uniform sampler2D tex0;
uniform int screenY;
const vec2 kernel = vec2(0.6,0.7);
void main(void) {
vec2 texCoord = vec2(gl_TextureMatrix[0] * gl_TexCoord[0]);
gl_FragColor = vec4(0.0);
int i;
int n = 1;
float pixelsize = 1.0/float(screenY);
for(i = 0; i < 2; ++i){
gl_FragColor += kernel[n] * texture2D(tex0, vec2(texCoord.s,texCoord.t + i*pixelsize) );
--n;
}
gl_FragColor += texture2D(tex0, texCoord );
n = 0;
for(i = -2; i < 0; ++i){
gl_FragColor += kernel[n] * texture2D(tex0, vec2(texCoord.s,texCoord.t + i*pixelsize) );
++n;
}
}
]],
uniformInt = {
tex0 = 0,
screenY = vsy,
},
})
if (depthShader == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo widget: depthcheck shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
if (blurShader_h == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo widget: hblur shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
if (blurShader_v == nil) then
Spring.Log(widget:GetInfo().name, LOG.ERROR, "Halo widget: vblur shader error: "..gl.GetShaderLog())
widgetHandler:RemoveWidget()
return false
end
uniformScreenXY = gl.GetUniformLocation(depthShader, 'screenXY')
uniformScreenX = gl.GetUniformLocation(blurShader_h, 'screenX')
uniformScreenY = gl.GetUniformLocation(blurShader_v, 'screenY')
self:ViewResize(widgetHandler:GetViewSizes())
enter2d = gl.CreateList(function()
glUseShader(0)
glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity()
glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity()
end)
leave2d = gl.CreateList(function()
glMatrixMode(GL_PROJECTION); glPopMatrix()
glMatrixMode(GL_MODELVIEW); glPopMatrix()
glTexture(false)
glUseShader(0)
end)
end
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
gl.DeleteTexture(depthtex or 0)
gl.DeleteTextureFBO(offscreentex or 0)
gl.DeleteTextureFBO(blurtex or 0)
depthtex = gl.CreateTexture(vsx,vsy, {
border = false,
format = GL_DEPTH_COMPONENT24,
min_filter = GL.NEAREST,
mag_filter = GL.NEAREST,
})
offscreentex = gl.CreateTexture(vsx,vsy, {
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP,
wrap_t = GL.CLAMP,
fbo = true,
fboDepth = true,
})
blurtex = gl.CreateTexture(vsx,vsy, {
border = false,
min_filter = GL.LINEAR,
mag_filter = GL.LINEAR,
wrap_s = GL.CLAMP,
wrap_t = GL.CLAMP,
fbo = true,
})
resChanged = true
end
function widget:Shutdown()
gl.DeleteTexture(depthtex)
if (gl.DeleteTextureFBO) then
gl.DeleteTextureFBO(offscreentex)
gl.DeleteTextureFBO(blurtex)
end
if (gl.DeleteShader) then
gl.DeleteShader(depthShader or 0)
gl.DeleteShader(blurShader_h or 0)
gl.DeleteShader(blurShader_v or 0)
end
gl.DeleteList(enter2d)
gl.DeleteList(leave2d)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function DrawVisibleUnits()
if (Spring.GetGameFrame() % 15 == 0) then
checknow = true
end
local visibleUnits = GetVisibleUnits(ALL_UNITS,nil,false)
for i=1,#visibleUnits do
if checknow then
local unitProgress = select(5, GetUnitHealth(visibleUnits[i]))
if unitProgress == nil or unitProgress >= 1 then
unbuiltUnits[visibleUnits[i]] = nil
else
unbuiltUnits[visibleUnits[i]] = true
end
end
if not unbuiltUnits[visibleUnits[i]] then
glUnit(visibleUnits[i],true)
end
end
end
local MyDrawVisibleUnits = function()
glClear(GL_COLOR_BUFFER_BIT,0,0,0,0)
glPushMatrix()
glResetMatrices()
glColor(0,0,0,thickness)
DrawVisibleUnits()
glColor(1,1,1,1)
glPopMatrix()
end
local blur_h = function()
glClear(GL_COLOR_BUFFER_BIT,0,0,0,0)
glUseShader(blurShader_h)
glTexRect(-1-0.5/vsx,1+0.5/vsy,1+0.5/vsx,-1-0.5/vsy)
end
local blur_v = function()
glClear(GL_COLOR_BUFFER_BIT,0,0,0,0)
glUseShader(blurShader_v)
glTexRect(-1-0.5/vsx,1+0.5/vsy,1+0.5/vsx,-1-0.5/vsy)
end
function widget:DrawWorldPreUnit()
glCopyToTexture(depthtex, 0, 0, 0, 0, vsx, vsy)
glTexture(depthtex)
if (resChanged) then
resChanged = false
if (vsx==1) or (vsy==1) then return end
glUseShader(depthShader)
glUniform(uniformScreenXY, vsx,vsy )
glUseShader(blurShader_h)
glUniformInt(uniformScreenX, vsx )
glUseShader(blurShader_v)
glUniformInt(uniformScreenY, vsy )
end
glUseShader(depthShader)
glRenderToTexture(offscreentex,MyDrawVisibleUnits)
glTexture(offscreentex)
glRenderToTexture(blurtex, blur_h)
glTexture(blurtex)
glRenderToTexture(offscreentex, blur_v)
glCallList(enter2d)
glTexture(offscreentex)
glTexRect(-1-0.5/vsx,1+0.5/vsy,1+0.5/vsx,-1-0.5/vsy)
glCallList(leave2d)
end
function widget:UnitCreated(unitID)
unbuiltUnits[unitID] = true
end
function widget:UnitDestroyed(unitID)
unbuiltUnits[unitID] = nil
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
alexandergall/snabbswitch | src/lib/lpm/lpm.lua | 9 | 3780 | module(..., package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lib = require("core.lib")
ffi.cdef([[
void free(void *ptr);
void *malloc(int size);
]])
LPM = {}
function LPM:new()
return setmetatable({ alloc_map = {} }, { __index = self })
end
function LPM:alloc (name, ctype, count, idx)
local idx = idx or 0
idx = idx - 1
local heap = {}
local count = count or 0
local function realloc (size)
if size == 0 then size = 1 end
local bytes = ffi.sizeof(ctype) * size
local ptr_t = ffi.typeof("$*", ctype)
local ptr = assert(C.malloc(bytes))
ffi.fill(ptr, bytes)
ptr = ffi.cast(ptr_t, ptr)
if self[name] then
ffi.copy(ptr, self[name], ffi.sizeof(ctype) * count)
end
self[name] = ffi.gc(ptr, C.free)
count = size
end
self[name .. "_type"] = function() return ctype end
self[name .. "_length"] = function() return count end
self[name .. "_free"] = function(self, idx) table.insert(heap, idx) end
self[name .. "_grow"] = function(self, factor) realloc(count * (factor or 2)) end
self[name .. "_load"] = function(self, ptr, bytelength)
count = bytelength / ffi.sizeof(ctype)
self[name] = ptr
realloc(count)
end
self[name .. "_store"] = function(self, ptr)
local bytes = ffi.sizeof(ctype) * count
ffi.copy(ptr, self[name], bytes)
return bytes
end
self[name .. "_new"] = function()
if table.getn(heap) == 0 then
if idx + 1 == count then
realloc(count * 2)
end
idx = idx + 1
return idx
else
return table.remove(heap)
end
end
if count > 0 then
realloc(count)
end
return self
end
function LPM:alloc_store(bytes)
local bytes = ffi.cast("uint8_t *", bytes)
for _,k in pairs(self.alloc_storable) do
local lenptr = ffi.cast("uint64_t *", bytes)
lenptr[0] = self[k .. "_store"](self, bytes + ffi.sizeof("uint64_t"))
bytes = bytes + lenptr[0] + ffi.sizeof("uint64_t")
end
end
function LPM:alloc_load(bytes)
local bytes = ffi.cast("uint8_t *", bytes)
for _,k in pairs(self.alloc_storable) do
local lenptr = ffi.cast("uint64_t *", bytes)
self[k .. "_load"](self, bytes + ffi.sizeof("uint64_t"), lenptr[0])
bytes = bytes + lenptr[0] + ffi.sizeof("uint64_t")
end
end
function selftest ()
local s = LPM:new()
s:alloc("test", ffi.typeof("uint64_t"), 2)
assert(s:test_new() == 0)
assert(s:test_new() == 1)
assert(s:test_new() == 2)
assert(s:test_new() == 3)
assert(s:test_new() == 4)
assert(s:test_new() == 5)
assert(s:test_new() == 6)
s:test_free(4)
s:test_free(3)
s:test_free(2)
s:test_free(5)
assert(s:test_new() == 5)
assert(s:test_new() == 2)
assert(s:test_new() == 3)
assert(s:test_new() == 4)
assert(s:test_new() == 7)
assert(s:test_type() == ffi.typeof("uint64_t"))
assert(s:test_length() == 8)
for i = 0, 7 do s.test[i] = i end
s:test_grow()
for i =0,7 do assert(s.test[i] == i) end
assert(s:test_length() == 16)
s:test_grow(3)
assert(s:test_length() == 48)
local ptr = C.malloc(1024 * 1024)
local tab = {}
local ents = { "t1", "t2", "t3", "t4" }
for i=1,3 do
tab[i] = LPM:new()
tab[i].alloc_storable = ents
tab[i]:alloc("t1", ffi.typeof("uint8_t"), 16)
tab[i]:alloc("t2", ffi.typeof("uint16_t"), 16)
tab[i]:alloc("t3", ffi.typeof("uint32_t"), 16)
tab[i]:alloc("t4", ffi.typeof("uint64_t"), 16)
end
for _, t in pairs(ents) do
for j=0,127 do
tab[1][t][ tab[1][t.."_new"]() ] = math.random(206)
end
end
tab[1]:alloc_store(ptr)
tab[2]:alloc_load(ptr)
for _, t in pairs(ents) do
for j=0,127 do
assert(tab[1][t][j] == tab[2][t][j])
end
end
C.free(ptr)
end
| apache-2.0 |
DreamHacks/dreamdota | DreamWarcraft/Build Tools/MPQFixEngine/lua/socket.lua | 146 | 4061 | -----------------------------------------------------------------------------
-- LuaSocket helper module
-- Author: Diego Nehab
-- RCS ID: $Id: socket.lua,v 1.22 2005/11/22 08:33:29 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local math = require("math")
local socket = require("socket.core")
module("socket")
-----------------------------------------------------------------------------
-- Exported auxiliar functions
-----------------------------------------------------------------------------
function connect(address, port, laddress, lport)
local sock, err = socket.tcp()
if not sock then return nil, err end
if laddress then
local res, err = sock:bind(laddress, lport, -1)
if not res then return nil, err end
end
local res, err = sock:connect(address, port)
if not res then return nil, err end
return sock
end
function bind(host, port, backlog)
local sock, err = socket.tcp()
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
local res, err = sock:bind(host, port)
if not res then return nil, err end
res, err = sock:listen(backlog)
if not res then return nil, err end
return sock
end
try = newtry()
function choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
else return f(opt1, opt2) end
end
end
-----------------------------------------------------------------------------
-- Socket sources and sinks, conforming to LTN12
-----------------------------------------------------------------------------
-- create namespaces inside LuaSocket namespace
sourcet = {}
sinkt = {}
BLOCKSIZE = 2048
sinkt["close-when-done"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then
sock:close()
return 1
else return sock:send(chunk) end
end
})
end
sinkt["keep-open"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if chunk then return sock:send(chunk)
else return 1 end
end
})
end
sinkt["default"] = sinkt["keep-open"]
sink = choose(sinkt)
sourcet["by-length"] = function(sock, length)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if length <= 0 then return nil end
local size = math.min(socket.BLOCKSIZE, length)
local chunk, err = sock:receive(size)
if err then return nil, err end
length = length - string.len(chunk)
return chunk
end
})
end
sourcet["until-closed"] = function(sock)
local done
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if done then return nil end
local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
if not err then return chunk
elseif err == "closed" then
sock:close()
done = 1
return partial
else return nil, err end
end
})
end
sourcet["default"] = sourcet["until-closed"]
source = choose(sourcet)
| mit |
harvardnlp/NAMAS | summary/util.lua | 9 | 1617 | --
-- Copyright (c) 2015, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Author: Alexander M Rush <srush@seas.harvard.edu>
-- Sumit Chopra <spchopra@fb.com>
-- Jason Weston <jase@fb.com>
-- The utility tool box
local util = {}
function util.string_shortfloat(t)
return string.format('%2.4g', t)
end
function util.shuffleTable(t)
local rand = math.random
local iterations = #t
local j
for i = iterations, 2, -1 do
j = rand(i)
t[i], t[j] = t[j], t[i]
end
end
function util.string_split(s, c)
if c==nil then c=' ' end
local t={}
while true do
local f=s:find(c)
if f==nil then
if s:len()>0 then
table.insert(t, s)
end
break
end
if f > 1 then
table.insert(t, s:sub(1,f-1))
end
s=s:sub(f+1,s:len())
end
return t
end
function util.add(tab, key)
local cur = tab
for i = 1, #key-1 do
local new_cur = cur[key[i]]
if new_cur == nil then
cur[key[i]] = {}
new_cur = cur[key[i]]
end
cur = new_cur
end
cur[key[#key]] = true
end
function util.has(tab, key)
local cur = tab
for i = 1, #key do
cur = cur[key[i]]
if cur == nil then
return false
end
end
return true
end
function util.isnan(x)
return x ~= x
end
return util
| bsd-3-clause |
Xandaros/Starfall | lua/starfall/libraries.lua | 1 | 2649 | ---------------------------------------------------------------------
-- SF Global Library management
---------------------------------------------------------------------
SF.Libraries = {}
SF.Libraries.libraries = {}
SF.Libraries.hooks = {}
--- Place to store local libraries
-- @name SF.Libraries.Local
-- @class table
SF.Libraries.Local = {}
--- Creates and registers a global library. The library will be accessible from any Starfall Instance, regardless of context.
-- This will automatically set __index and __metatable.
-- @param name The library name
function SF.Libraries.Register ( name )
local methods, metamethods = SF.Typedef( "Library: " .. name )
SF.Libraries.libraries[ name ] = metamethods
SF.DefaultEnvironment[ name ] = setmetatable( {}, metamethods )
return methods, metamethods
end
--- Creates and registers a local library. The library must be added to the context's
-- local libraries field.
function SF.Libraries.RegisterLocal ( name )
local methods, metamethods = SF.Typedef( "Library: " .. name )
SF.Libraries.Local[ name ] = metamethods
return methods, metamethods
end
--- Gets a global library by name
-- @param name The name of the library
-- @return A metatable proxy of the library
function SF.Libraries.Get ( name )
return SF.Libraries.libraries[ name ] and setmetatable( {}, SF.Libraries.libraries[ name ] )
end
--- Gets a local library by name
-- @param name The name of the library
-- @return The library (not a metatable proxy!)
function SF.Libraries.GetLocal ( name )
return SF.Libraries.Local[ name ]
end
--- Creates a table for use in SF.CreateContext containing all of the
-- local libraries in arr.
-- @param arr Array of local libraries to load
function SF.Libraries.CreateLocalTbl ( arr )
local tbl = {}
for i = 1, #arr do
local lib = arr[ i ]
tbl[ lib ] = SF.Libraries.Local[ lib ] or SF.throw( string.format( "Requested nonexistant library '%s'", lib ), 2 )
end
return tbl
end
--- Registers a library hook. These hooks are only available to SF libraries,
-- and are called by Libraries.CallHook.
-- @param hookname The name of the hook.
-- @param func The function to call
function SF.Libraries.AddHook ( hookname, func )
local hook = SF.Libraries.hooks[ hookname ]
if not hook then
hook = {}
SF.Libraries.hooks[ hookname ] = hook
end
hook[ #hook + 1 ] = func
end
--- Calls a library hook.
-- @param hookname The name of the hook.
-- @param ... The arguments to the functions that are called.
function SF.Libraries.CallHook ( hookname, ... )
local hook = SF.Libraries.hooks[ hookname ]
if not hook then return end
for i = 1, #hook do
hook[ i ]( ... )
end
end
| bsd-3-clause |
DreamHacks/dreamdota | DreamWarcraft/Build Tools/MPQFixEngine/lua/oil/arch/corba/client.lua | 6 | 1097 | local pairs = pairs
local port = require "oil.port"
local component = require "oil.component"
local arch = require "oil.arch" --[[VERBOSE]] local verbose = require "oil.verbose"
module "oil.arch.corba.client"
OperationRequester = component.Template{
requests = port.Facet,
codec = port.Receptacle,
profiler = port.HashReceptacle,
channels = port.HashReceptacle,
}
function assemble(components)
arch.start(components)
-- GIOP MAPPINGS
local IOPClientChannels = { [0] = ClientChannels }
-- REQUESTER
OperationRequester.codec = CDREncoder.codec
OperationRequester.pcall = BasicSystem.pcall -- to catch marshal errors
-- COMMUNICATION
for tag, ClientChannels in pairs(IOPClientChannels) do
ClientChannels.sockets = BasicSystem.sockets
OperationRequester.channels[tag] = ClientChannels.channels
end
-- REFERENCES
ObjectReferrer.requester = OperationRequester.requests
for tag, IORProfiler in pairs(IORProfilers) do
OperationRequester.profiler[0] = IIOPProfiler
end
arch.finish(components)
end
| mit |
link4all/20170920openwrt | own_files/mt7628/files_mifi_ss/usr/lib/lua/luci/model/cbi/Config4G.lua | 15 | 1437 | require("luci.sys")
m = Map("config4g", translate("4G/3G Config"), translate("Configure 4G/3G Parameter"))
s = m:section(TypedSection, "4G", "")
s.addremove = false
s.anonymous = true
enable = s:option(Flag, "enable", translate("Enable"), translate("Enable 4G"))
apn = s:option(Value, "apn", translate("APN"))
user = s:option(Value, "user", translate("Username"))
pass = s:option(Value, "password", translate("Password"))
pass.password = true
pincode = s:option(Value, "pincode", translate("PIN Code"), translate("Verify sim card pin if sim card is locked"))
auth = s:option(ListValue, "auth", translate("Authentication type"))
auth.default=0
auth.datatype="uinteger"
auth:value(0, "None")
auth:value(1, "Pap")
auth:value(2, "Chap")
auth:value(3, "MsChapV2")
networktype = s:option(ListValue, "networktype", translate("Network type"))
networktype.default=0
networktype.datatype="uinteger"
networktype:value(0, translate("auto"))
enable_dns = s:option(Flag, "enable_dns", translate("DNS server address"), translate("Default: Obtain DNS server address automatically"))
pri_nameserver = s:option(Value, "pri_nameserver", translate("Primary DNS"))
pri_nameserver:depends("enable_dns", "1")
sec_nameserver = s:option(Value, "sec_nameserver", translate("Secondary DNS"))
sec_nameserver:depends("enable_dns", "1")
local apply = luci.http.formvalue("cbi.apply")
if apply then
io.popen("/etc/init.d/config4g restart")
end
return m
| gpl-2.0 |
link4all/20170920openwrt | own_files/mt7628/files_zigbee/usr/lib/lua/luci/model/cbi/Config4G.lua | 15 | 1437 | require("luci.sys")
m = Map("config4g", translate("4G/3G Config"), translate("Configure 4G/3G Parameter"))
s = m:section(TypedSection, "4G", "")
s.addremove = false
s.anonymous = true
enable = s:option(Flag, "enable", translate("Enable"), translate("Enable 4G"))
apn = s:option(Value, "apn", translate("APN"))
user = s:option(Value, "user", translate("Username"))
pass = s:option(Value, "password", translate("Password"))
pass.password = true
pincode = s:option(Value, "pincode", translate("PIN Code"), translate("Verify sim card pin if sim card is locked"))
auth = s:option(ListValue, "auth", translate("Authentication type"))
auth.default=0
auth.datatype="uinteger"
auth:value(0, "None")
auth:value(1, "Pap")
auth:value(2, "Chap")
auth:value(3, "MsChapV2")
networktype = s:option(ListValue, "networktype", translate("Network type"))
networktype.default=0
networktype.datatype="uinteger"
networktype:value(0, translate("auto"))
enable_dns = s:option(Flag, "enable_dns", translate("DNS server address"), translate("Default: Obtain DNS server address automatically"))
pri_nameserver = s:option(Value, "pri_nameserver", translate("Primary DNS"))
pri_nameserver:depends("enable_dns", "1")
sec_nameserver = s:option(Value, "sec_nameserver", translate("Secondary DNS"))
sec_nameserver:depends("enable_dns", "1")
local apply = luci.http.formvalue("cbi.apply")
if apply then
io.popen("/etc/init.d/config4g restart")
end
return m
| gpl-2.0 |
nifty-site-manager/nsm | LuaJIT/src/jit/dis_ppc.lua | 6 | 20301 | ----------------------------------------------------------------------------
-- LuaJIT PPC disassembler module.
--
-- Copyright (C) 2005-2021 Mike Pall. All rights reserved.
-- Released under the MIT/X license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- It disassembles all common, non-privileged 32/64 bit PowerPC instructions
-- plus the e500 SPE instructions and some Cell/Xenon extensions.
--
-- NYI: VMX, VMX128
------------------------------------------------------------------------------
local type = type
local byte, format = string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local concat = table.concat
local bit = require("bit")
local band, bor, tohex = bit.band, bit.bor, bit.tohex
local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift
------------------------------------------------------------------------------
-- Primary and extended opcode maps
------------------------------------------------------------------------------
local map_crops = {
shift = 1, mask = 1023,
[0] = "mcrfXX",
[33] = "crnor|crnotCCC=", [129] = "crandcCCC",
[193] = "crxor|crclrCCC%", [225] = "crnandCCC",
[257] = "crandCCC", [289] = "creqv|crsetCCC%",
[417] = "crorcCCC", [449] = "cror|crmoveCCC=",
[16] = "b_lrKB", [528] = "b_ctrKB",
[150] = "isync",
}
local map_rlwinm = setmetatable({
shift = 0, mask = -1,
},
{ __index = function(t, x)
local rot = band(rshift(x, 11), 31)
local mb = band(rshift(x, 6), 31)
local me = band(rshift(x, 1), 31)
if mb == 0 and me == 31-rot then
return "slwiRR~A."
elseif me == 31 and mb == 32-rot then
return "srwiRR~-A."
else
return "rlwinmRR~AAA."
end
end
})
local map_rld = {
shift = 2, mask = 7,
[0] = "rldiclRR~HM.", "rldicrRR~HM.", "rldicRR~HM.", "rldimiRR~HM.",
{
shift = 1, mask = 1,
[0] = "rldclRR~RM.", "rldcrRR~RM.",
},
}
local map_ext = setmetatable({
shift = 1, mask = 1023,
[0] = "cmp_YLRR", [32] = "cmpl_YLRR",
[4] = "twARR", [68] = "tdARR",
[8] = "subfcRRR.", [40] = "subfRRR.",
[104] = "negRR.", [136] = "subfeRRR.",
[200] = "subfzeRR.", [232] = "subfmeRR.",
[520] = "subfcoRRR.", [552] = "subfoRRR.",
[616] = "negoRR.", [648] = "subfeoRRR.",
[712] = "subfzeoRR.", [744] = "subfmeoRR.",
[9] = "mulhduRRR.", [73] = "mulhdRRR.", [233] = "mulldRRR.",
[457] = "divduRRR.", [489] = "divdRRR.",
[745] = "mulldoRRR.",
[969] = "divduoRRR.", [1001] = "divdoRRR.",
[10] = "addcRRR.", [138] = "addeRRR.",
[202] = "addzeRR.", [234] = "addmeRR.", [266] = "addRRR.",
[522] = "addcoRRR.", [650] = "addeoRRR.",
[714] = "addzeoRR.", [746] = "addmeoRR.", [778] = "addoRRR.",
[11] = "mulhwuRRR.", [75] = "mulhwRRR.", [235] = "mullwRRR.",
[459] = "divwuRRR.", [491] = "divwRRR.",
[747] = "mullwoRRR.",
[971] = "divwouRRR.", [1003] = "divwoRRR.",
[15] = "iselltRRR", [47] = "iselgtRRR", [79] = "iseleqRRR",
[144] = { shift = 20, mask = 1, [0] = "mtcrfRZ~", "mtocrfRZ~", },
[19] = { shift = 20, mask = 1, [0] = "mfcrR", "mfocrfRZ", },
[371] = { shift = 11, mask = 1023, [392] = "mftbR", [424] = "mftbuR", },
[339] = {
shift = 11, mask = 1023,
[32] = "mferR", [256] = "mflrR", [288] = "mfctrR", [16] = "mfspefscrR",
},
[467] = {
shift = 11, mask = 1023,
[32] = "mtxerR", [256] = "mtlrR", [288] = "mtctrR", [16] = "mtspefscrR",
},
[20] = "lwarxRR0R", [84] = "ldarxRR0R",
[21] = "ldxRR0R", [53] = "lduxRRR",
[149] = "stdxRR0R", [181] = "stduxRRR",
[341] = "lwaxRR0R", [373] = "lwauxRRR",
[23] = "lwzxRR0R", [55] = "lwzuxRRR",
[87] = "lbzxRR0R", [119] = "lbzuxRRR",
[151] = "stwxRR0R", [183] = "stwuxRRR",
[215] = "stbxRR0R", [247] = "stbuxRRR",
[279] = "lhzxRR0R", [311] = "lhzuxRRR",
[343] = "lhaxRR0R", [375] = "lhauxRRR",
[407] = "sthxRR0R", [439] = "sthuxRRR",
[54] = "dcbst-R0R", [86] = "dcbf-R0R",
[150] = "stwcxRR0R.", [214] = "stdcxRR0R.",
[246] = "dcbtst-R0R", [278] = "dcbt-R0R",
[310] = "eciwxRR0R", [438] = "ecowxRR0R",
[470] = "dcbi-RR",
[598] = {
shift = 21, mask = 3,
[0] = "sync", "lwsync", "ptesync",
},
[758] = "dcba-RR",
[854] = "eieio", [982] = "icbi-R0R", [1014] = "dcbz-R0R",
[26] = "cntlzwRR~", [58] = "cntlzdRR~",
[122] = "popcntbRR~",
[154] = "prtywRR~", [186] = "prtydRR~",
[28] = "andRR~R.", [60] = "andcRR~R.", [124] = "nor|notRR~R=.",
[284] = "eqvRR~R.", [316] = "xorRR~R.",
[412] = "orcRR~R.", [444] = "or|mrRR~R=.", [476] = "nandRR~R.",
[508] = "cmpbRR~R",
[512] = "mcrxrX",
[532] = "ldbrxRR0R", [660] = "stdbrxRR0R",
[533] = "lswxRR0R", [597] = "lswiRR0A",
[661] = "stswxRR0R", [725] = "stswiRR0A",
[534] = "lwbrxRR0R", [662] = "stwbrxRR0R",
[790] = "lhbrxRR0R", [918] = "sthbrxRR0R",
[535] = "lfsxFR0R", [567] = "lfsuxFRR",
[599] = "lfdxFR0R", [631] = "lfduxFRR",
[663] = "stfsxFR0R", [695] = "stfsuxFRR",
[727] = "stfdxFR0R", [759] = "stfduxFR0R",
[855] = "lfiwaxFR0R",
[983] = "stfiwxFR0R",
[24] = "slwRR~R.",
[27] = "sldRR~R.", [536] = "srwRR~R.",
[792] = "srawRR~R.", [824] = "srawiRR~A.",
[794] = "sradRR~R.", [826] = "sradiRR~H.", [827] = "sradiRR~H.",
[922] = "extshRR~.", [954] = "extsbRR~.", [986] = "extswRR~.",
[539] = "srdRR~R.",
},
{ __index = function(t, x)
if band(x, 31) == 15 then return "iselRRRC" end
end
})
local map_ld = {
shift = 0, mask = 3,
[0] = "ldRRE", "lduRRE", "lwaRRE",
}
local map_std = {
shift = 0, mask = 3,
[0] = "stdRRE", "stduRRE",
}
local map_fps = {
shift = 5, mask = 1,
{
shift = 1, mask = 15,
[0] = false, false, "fdivsFFF.", false,
"fsubsFFF.", "faddsFFF.", "fsqrtsF-F.", false,
"fresF-F.", "fmulsFF-F.", "frsqrtesF-F.", false,
"fmsubsFFFF~.", "fmaddsFFFF~.", "fnmsubsFFFF~.", "fnmaddsFFFF~.",
}
}
local map_fpd = {
shift = 5, mask = 1,
[0] = {
shift = 1, mask = 1023,
[0] = "fcmpuXFF", [32] = "fcmpoXFF", [64] = "mcrfsXX",
[38] = "mtfsb1A.", [70] = "mtfsb0A.", [134] = "mtfsfiA>>-A>",
[8] = "fcpsgnFFF.", [40] = "fnegF-F.", [72] = "fmrF-F.",
[136] = "fnabsF-F.", [264] = "fabsF-F.",
[12] = "frspF-F.",
[14] = "fctiwF-F.", [15] = "fctiwzF-F.",
[583] = "mffsF.", [711] = "mtfsfZF.",
[392] = "frinF-F.", [424] = "frizF-F.",
[456] = "fripF-F.", [488] = "frimF-F.",
[814] = "fctidF-F.", [815] = "fctidzF-F.", [846] = "fcfidF-F.",
},
{
shift = 1, mask = 15,
[0] = false, false, "fdivFFF.", false,
"fsubFFF.", "faddFFF.", "fsqrtF-F.", "fselFFFF~.",
"freF-F.", "fmulFF-F.", "frsqrteF-F.", false,
"fmsubFFFF~.", "fmaddFFFF~.", "fnmsubFFFF~.", "fnmaddFFFF~.",
}
}
local map_spe = {
shift = 0, mask = 2047,
[512] = "evaddwRRR", [514] = "evaddiwRAR~",
[516] = "evsubwRRR~", [518] = "evsubiwRAR~",
[520] = "evabsRR", [521] = "evnegRR",
[522] = "evextsbRR", [523] = "evextshRR", [524] = "evrndwRR",
[525] = "evcntlzwRR", [526] = "evcntlswRR",
[527] = "brincRRR",
[529] = "evandRRR", [530] = "evandcRRR", [534] = "evxorRRR",
[535] = "evor|evmrRRR=", [536] = "evnor|evnotRRR=",
[537] = "eveqvRRR", [539] = "evorcRRR", [542] = "evnandRRR",
[544] = "evsrwuRRR", [545] = "evsrwsRRR",
[546] = "evsrwiuRRA", [547] = "evsrwisRRA",
[548] = "evslwRRR", [550] = "evslwiRRA",
[552] = "evrlwRRR", [553] = "evsplatiRS",
[554] = "evrlwiRRA", [555] = "evsplatfiRS",
[556] = "evmergehiRRR", [557] = "evmergeloRRR",
[558] = "evmergehiloRRR", [559] = "evmergelohiRRR",
[560] = "evcmpgtuYRR", [561] = "evcmpgtsYRR",
[562] = "evcmpltuYRR", [563] = "evcmpltsYRR",
[564] = "evcmpeqYRR",
[632] = "evselRRR", [633] = "evselRRRW",
[634] = "evselRRRW", [635] = "evselRRRW",
[636] = "evselRRRW", [637] = "evselRRRW",
[638] = "evselRRRW", [639] = "evselRRRW",
[640] = "evfsaddRRR", [641] = "evfssubRRR",
[644] = "evfsabsRR", [645] = "evfsnabsRR", [646] = "evfsnegRR",
[648] = "evfsmulRRR", [649] = "evfsdivRRR",
[652] = "evfscmpgtYRR", [653] = "evfscmpltYRR", [654] = "evfscmpeqYRR",
[656] = "evfscfuiR-R", [657] = "evfscfsiR-R",
[658] = "evfscfufR-R", [659] = "evfscfsfR-R",
[660] = "evfsctuiR-R", [661] = "evfsctsiR-R",
[662] = "evfsctufR-R", [663] = "evfsctsfR-R",
[664] = "evfsctuizR-R", [666] = "evfsctsizR-R",
[668] = "evfststgtYRR", [669] = "evfststltYRR", [670] = "evfststeqYRR",
[704] = "efsaddRRR", [705] = "efssubRRR",
[708] = "efsabsRR", [709] = "efsnabsRR", [710] = "efsnegRR",
[712] = "efsmulRRR", [713] = "efsdivRRR",
[716] = "efscmpgtYRR", [717] = "efscmpltYRR", [718] = "efscmpeqYRR",
[719] = "efscfdR-R",
[720] = "efscfuiR-R", [721] = "efscfsiR-R",
[722] = "efscfufR-R", [723] = "efscfsfR-R",
[724] = "efsctuiR-R", [725] = "efsctsiR-R",
[726] = "efsctufR-R", [727] = "efsctsfR-R",
[728] = "efsctuizR-R", [730] = "efsctsizR-R",
[732] = "efststgtYRR", [733] = "efststltYRR", [734] = "efststeqYRR",
[736] = "efdaddRRR", [737] = "efdsubRRR",
[738] = "efdcfuidR-R", [739] = "efdcfsidR-R",
[740] = "efdabsRR", [741] = "efdnabsRR", [742] = "efdnegRR",
[744] = "efdmulRRR", [745] = "efddivRRR",
[746] = "efdctuidzR-R", [747] = "efdctsidzR-R",
[748] = "efdcmpgtYRR", [749] = "efdcmpltYRR", [750] = "efdcmpeqYRR",
[751] = "efdcfsR-R",
[752] = "efdcfuiR-R", [753] = "efdcfsiR-R",
[754] = "efdcfufR-R", [755] = "efdcfsfR-R",
[756] = "efdctuiR-R", [757] = "efdctsiR-R",
[758] = "efdctufR-R", [759] = "efdctsfR-R",
[760] = "efdctuizR-R", [762] = "efdctsizR-R",
[764] = "efdtstgtYRR", [765] = "efdtstltYRR", [766] = "efdtsteqYRR",
[768] = "evlddxRR0R", [769] = "evlddRR8",
[770] = "evldwxRR0R", [771] = "evldwRR8",
[772] = "evldhxRR0R", [773] = "evldhRR8",
[776] = "evlhhesplatxRR0R", [777] = "evlhhesplatRR2",
[780] = "evlhhousplatxRR0R", [781] = "evlhhousplatRR2",
[782] = "evlhhossplatxRR0R", [783] = "evlhhossplatRR2",
[784] = "evlwhexRR0R", [785] = "evlwheRR4",
[788] = "evlwhouxRR0R", [789] = "evlwhouRR4",
[790] = "evlwhosxRR0R", [791] = "evlwhosRR4",
[792] = "evlwwsplatxRR0R", [793] = "evlwwsplatRR4",
[796] = "evlwhsplatxRR0R", [797] = "evlwhsplatRR4",
[800] = "evstddxRR0R", [801] = "evstddRR8",
[802] = "evstdwxRR0R", [803] = "evstdwRR8",
[804] = "evstdhxRR0R", [805] = "evstdhRR8",
[816] = "evstwhexRR0R", [817] = "evstwheRR4",
[820] = "evstwhoxRR0R", [821] = "evstwhoRR4",
[824] = "evstwwexRR0R", [825] = "evstwweRR4",
[828] = "evstwwoxRR0R", [829] = "evstwwoRR4",
[1027] = "evmhessfRRR", [1031] = "evmhossfRRR", [1032] = "evmheumiRRR",
[1033] = "evmhesmiRRR", [1035] = "evmhesmfRRR", [1036] = "evmhoumiRRR",
[1037] = "evmhosmiRRR", [1039] = "evmhosmfRRR", [1059] = "evmhessfaRRR",
[1063] = "evmhossfaRRR", [1064] = "evmheumiaRRR", [1065] = "evmhesmiaRRR",
[1067] = "evmhesmfaRRR", [1068] = "evmhoumiaRRR", [1069] = "evmhosmiaRRR",
[1071] = "evmhosmfaRRR", [1095] = "evmwhssfRRR", [1096] = "evmwlumiRRR",
[1100] = "evmwhumiRRR", [1101] = "evmwhsmiRRR", [1103] = "evmwhsmfRRR",
[1107] = "evmwssfRRR", [1112] = "evmwumiRRR", [1113] = "evmwsmiRRR",
[1115] = "evmwsmfRRR", [1127] = "evmwhssfaRRR", [1128] = "evmwlumiaRRR",
[1132] = "evmwhumiaRRR", [1133] = "evmwhsmiaRRR", [1135] = "evmwhsmfaRRR",
[1139] = "evmwssfaRRR", [1144] = "evmwumiaRRR", [1145] = "evmwsmiaRRR",
[1147] = "evmwsmfaRRR",
[1216] = "evaddusiaawRR", [1217] = "evaddssiaawRR",
[1218] = "evsubfusiaawRR", [1219] = "evsubfssiaawRR",
[1220] = "evmraRR",
[1222] = "evdivwsRRR", [1223] = "evdivwuRRR",
[1224] = "evaddumiaawRR", [1225] = "evaddsmiaawRR",
[1226] = "evsubfumiaawRR", [1227] = "evsubfsmiaawRR",
[1280] = "evmheusiaawRRR", [1281] = "evmhessiaawRRR",
[1283] = "evmhessfaawRRR", [1284] = "evmhousiaawRRR",
[1285] = "evmhossiaawRRR", [1287] = "evmhossfaawRRR",
[1288] = "evmheumiaawRRR", [1289] = "evmhesmiaawRRR",
[1291] = "evmhesmfaawRRR", [1292] = "evmhoumiaawRRR",
[1293] = "evmhosmiaawRRR", [1295] = "evmhosmfaawRRR",
[1320] = "evmhegumiaaRRR", [1321] = "evmhegsmiaaRRR",
[1323] = "evmhegsmfaaRRR", [1324] = "evmhogumiaaRRR",
[1325] = "evmhogsmiaaRRR", [1327] = "evmhogsmfaaRRR",
[1344] = "evmwlusiaawRRR", [1345] = "evmwlssiaawRRR",
[1352] = "evmwlumiaawRRR", [1353] = "evmwlsmiaawRRR",
[1363] = "evmwssfaaRRR", [1368] = "evmwumiaaRRR",
[1369] = "evmwsmiaaRRR", [1371] = "evmwsmfaaRRR",
[1408] = "evmheusianwRRR", [1409] = "evmhessianwRRR",
[1411] = "evmhessfanwRRR", [1412] = "evmhousianwRRR",
[1413] = "evmhossianwRRR", [1415] = "evmhossfanwRRR",
[1416] = "evmheumianwRRR", [1417] = "evmhesmianwRRR",
[1419] = "evmhesmfanwRRR", [1420] = "evmhoumianwRRR",
[1421] = "evmhosmianwRRR", [1423] = "evmhosmfanwRRR",
[1448] = "evmhegumianRRR", [1449] = "evmhegsmianRRR",
[1451] = "evmhegsmfanRRR", [1452] = "evmhogumianRRR",
[1453] = "evmhogsmianRRR", [1455] = "evmhogsmfanRRR",
[1472] = "evmwlusianwRRR", [1473] = "evmwlssianwRRR",
[1480] = "evmwlumianwRRR", [1481] = "evmwlsmianwRRR",
[1491] = "evmwssfanRRR", [1496] = "evmwumianRRR",
[1497] = "evmwsmianRRR", [1499] = "evmwsmfanRRR",
}
local map_pri = {
[0] = false, false, "tdiARI", "twiARI",
map_spe, false, false, "mulliRRI",
"subficRRI", false, "cmpl_iYLRU", "cmp_iYLRI",
"addicRRI", "addic.RRI", "addi|liRR0I", "addis|lisRR0I",
"b_KBJ", "sc", "bKJ", map_crops,
"rlwimiRR~AAA.", map_rlwinm, false, "rlwnmRR~RAA.",
"oriNRR~U", "orisRR~U", "xoriRR~U", "xorisRR~U",
"andi.RR~U", "andis.RR~U", map_rld, map_ext,
"lwzRRD", "lwzuRRD", "lbzRRD", "lbzuRRD",
"stwRRD", "stwuRRD", "stbRRD", "stbuRRD",
"lhzRRD", "lhzuRRD", "lhaRRD", "lhauRRD",
"sthRRD", "sthuRRD", "lmwRRD", "stmwRRD",
"lfsFRD", "lfsuFRD", "lfdFRD", "lfduFRD",
"stfsFRD", "stfsuFRD", "stfdFRD", "stfduFRD",
false, false, map_ld, map_fps,
false, false, map_std, map_fpd,
}
------------------------------------------------------------------------------
local map_gpr = {
[0] = "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
"r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
}
local map_cond = { [0] = "lt", "gt", "eq", "so", "ge", "le", "ne", "ns", }
-- Format a condition bit.
local function condfmt(cond)
if cond <= 3 then
return map_cond[band(cond, 3)]
else
return format("4*cr%d+%s", rshift(cond, 2), map_cond[band(cond, 3)])
end
end
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local pos = ctx.pos
local extra = ""
if ctx.rel then
local sym = ctx.symtab[ctx.rel]
if sym then extra = "\t->"..sym end
end
if ctx.hexdump > 0 then
ctx.out(format("%08x %s %-7s %s%s\n",
ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra))
else
ctx.out(format("%08x %-7s %s%s\n",
ctx.addr+pos, text, concat(operands, ", "), extra))
end
ctx.pos = pos + 4
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
return putop(ctx, ".long", { "0x"..tohex(ctx.op) })
end
-- Disassemble a single instruction.
local function disass_ins(ctx)
local pos = ctx.pos
local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
local op = bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3)
local operands = {}
local last = nil
local rs = 21
ctx.op = op
ctx.rel = nil
local opat = map_pri[rshift(b0, 2)]
while type(opat) ~= "string" do
if not opat then return unknown(ctx) end
opat = opat[band(rshift(op, opat.shift), opat.mask)]
end
local name, pat = match(opat, "^([a-z0-9_.]*)(.*)")
local altname, pat2 = match(pat, "|([a-z0-9_.]*)(.*)")
if altname then pat = pat2 end
for p in gmatch(pat, ".") do
local x = nil
if p == "R" then
x = map_gpr[band(rshift(op, rs), 31)]
rs = rs - 5
elseif p == "F" then
x = "f"..band(rshift(op, rs), 31)
rs = rs - 5
elseif p == "A" then
x = band(rshift(op, rs), 31)
rs = rs - 5
elseif p == "S" then
x = arshift(lshift(op, 27-rs), 27)
rs = rs - 5
elseif p == "I" then
x = arshift(lshift(op, 16), 16)
elseif p == "U" then
x = band(op, 0xffff)
elseif p == "D" or p == "E" then
local disp = arshift(lshift(op, 16), 16)
if p == "E" then disp = band(disp, -4) end
if last == "r0" then last = "0" end
operands[#operands] = format("%d(%s)", disp, last)
elseif p >= "2" and p <= "8" then
local disp = band(rshift(op, rs), 31) * p
if last == "r0" then last = "0" end
operands[#operands] = format("%d(%s)", disp, last)
elseif p == "H" then
x = band(rshift(op, rs), 31) + lshift(band(op, 2), 4)
rs = rs - 5
elseif p == "M" then
x = band(rshift(op, rs), 31) + band(op, 0x20)
elseif p == "C" then
x = condfmt(band(rshift(op, rs), 31))
rs = rs - 5
elseif p == "B" then
local bo = rshift(op, 21)
local cond = band(rshift(op, 16), 31)
local cn = ""
rs = rs - 10
if band(bo, 4) == 0 then
cn = band(bo, 2) == 0 and "dnz" or "dz"
if band(bo, 0x10) == 0 then
cn = cn..(band(bo, 8) == 0 and "f" or "t")
end
if band(bo, 0x10) == 0 then x = condfmt(cond) end
name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+")
elseif band(bo, 0x10) == 0 then
cn = map_cond[band(cond, 3) + (band(bo, 8) == 0 and 4 or 0)]
if cond > 3 then x = "cr"..rshift(cond, 2) end
name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+")
end
name = gsub(name, "_", cn)
elseif p == "J" then
x = arshift(lshift(op, 27-rs), 29-rs)*4
if band(op, 2) == 0 then x = ctx.addr + pos + x end
ctx.rel = x
x = "0x"..tohex(x)
elseif p == "K" then
if band(op, 1) ~= 0 then name = name.."l" end
if band(op, 2) ~= 0 then name = name.."a" end
elseif p == "X" or p == "Y" then
x = band(rshift(op, rs+2), 7)
if x == 0 and p == "Y" then x = nil else x = "cr"..x end
rs = rs - 5
elseif p == "W" then
x = "cr"..band(op, 7)
elseif p == "Z" then
x = band(rshift(op, rs-4), 255)
rs = rs - 10
elseif p == ">" then
operands[#operands] = rshift(operands[#operands], 1)
elseif p == "0" then
if last == "r0" then
operands[#operands] = nil
if altname then name = altname end
end
elseif p == "L" then
name = gsub(name, "_", band(op, 0x00200000) ~= 0 and "d" or "w")
elseif p == "." then
if band(op, 1) == 1 then name = name.."." end
elseif p == "N" then
if op == 0x60000000 then name = "nop"; break end
elseif p == "~" then
local n = #operands
operands[n-1], operands[n] = operands[n], operands[n-1]
elseif p == "=" then
local n = #operands
if last == operands[n-1] then
operands[n] = nil
name = altname
end
elseif p == "%" then
local n = #operands
if last == operands[n-1] and last == operands[n-2] then
operands[n] = nil
operands[n-1] = nil
name = altname
end
elseif p == "-" then
rs = rs - 5
else
assert(false)
end
if x then operands[#operands+1] = x; last = x end
end
return putop(ctx, name, operands)
end
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
stop = stop - stop % 4
ctx.pos = ofs - ofs % 4
ctx.rel = nil
while ctx.pos < stop do disass_ins(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = addr or 0
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 8
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass(code, addr, out)
create(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 32 then return map_gpr[r] end
return "f"..(r-32)
end
-- Public module functions.
return {
create = create,
disass = disass,
regname = regname
}
| mit |
TeamTop/Uor | plugins/en-banhammer.lua | 7 | 16299 | --[[
#
#ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#:((
# For More Information ....!
# Developer : Aziz < @TH3_GHOST >
# our channel: @DevPointTeam
# Version: 1.1
#:))
#ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#
]]
local function pre_process(msg)
local data = load_data(_config.moderation.data)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned and not is_momod2(msg.from.id, msg.to.id) or is_gbanned(user_id) and not is_admin2(msg.from.id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) >= 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) >= 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function banall_by_reply(extra, success, result)
if result.to.peer_type == 'chat' or result.to.peer_type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(result.from.peer_id) then -- Ignore admins
return
end
banall_user(result.from.peer_id)
send_large_msg(chat, "User "..result.from.peer_id.." Golobally Banned")
send_large_msg(channel, "User "..result.from.peer_id.." Golobally Banned")
else
return
end
end
local function unbanall_by_reply(extra, success, result)
if result.to.peer_type == 'chat' or result.to.peer_type == 'channel' then
local user_id = result.from.peer_id
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(result.from.peer_id) then -- Ignore admins
return
end
if is_gbanned(result.from.peer_id) then
return result.from.peer_id..' is already un-Gbanned.'
end
if not is_gbanned(result.from.peer_id) then
unbanall_user(result.from.peer_id)
send_large_msg(chat, "User "..result.from.peer_id.." Golobally un-Banned")
send_large_msg(channel, "User "..result.from.peer_id.." Golobally un-Banned")
end
end
end
local function unban_by_reply(extra, success, result)
if result.to.peer_type == 'chat' or result.to.peer_type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(result.from.peer_id) then -- Ignore admins
return
end
send_large_msg(chat, "User "..result.from.peer_id.." un-Banned")
send_large_msg(channel, "User "..result.from.peer_id.." un-Banned")
local hash = 'banned:'..result.to.peer_id
redis:srem(hash, result.from.peer_id)
else
return
end
end
local function kick_ban_res(extra, success, result)
local chat_id = extra.chat_id
local chat_type = extra.chat_type
if chat_type == "chat" then
receiver = 'chat#id'..chat_id
else
receiver = 'channel#id'..chat_id
end
if success == 0 then
return send_large_msg(receiver, "Cannot find user by that username!")
end
local member_id = result.peer_id
local user_id = member_id
local member = result.username
local from_id = extra.from_id
local get_cmd = extra.get_cmd
if get_cmd == "kick" then
if member_id == from_id then
send_large_msg(receiver, "You can't kick yourself")
return
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "You can't kick mods/owner/admins")
return
end
kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "You can't ban mods/owner/admins")
return
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
banall_user(member_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally unbanned')
unbanall_user(member_id)
end
end
local function run(msg, matches)
local support_id = msg.from.id
if matches[1]:lower() == 'id' and msg.to.type == "chat" or msg.to.type == "user" then
if msg.to.type == "user" then
return "Your id : "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
local text = "_🇮🇷 Group ID : _*"..msg.to.id.."*\n_🇮🇷 Group Name : _*"..msg.to.title.."*"
send_api_msg(msg, get_receiver_api(msg), text, true, 'md')
end
end
if matches[1]:lower() == 'kickme' and msg.to.type == "chat" then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin1(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
local receiver = get_receiver(msg)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(matches[2], msg.to.id)
send_large_msg(receiver, 'User ['..matches[2]..'] banned')
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if not is_admin1(msg) and not is_support(support_id) then
return
end
if matches[1]:lower() == 'banall' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
local receiver = get_receiver(msg)
savelog(msg.to.id, name.." ["..msg.from.id.."] banedall user ".. matches[2])
banall_user(matches[2])
send_large_msg(receiver, 'User ['..matches[2]..'] bannedalled')
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,unbanall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
local receiver = get_receiver(msg)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbanedall user ".. matches[2])
unbanall_user(matches[2])
send_large_msg(receiver, 'User ['..matches[2]..'] unbannedalled')
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
local receiver = get_receiver(msg)
savelog(msg.to.id, name.." ["..msg.from.id.."] unban user ".. matches[2])
unbanall_user(matches[2])
send_large_msg(receiver, 'User ['..matches[2]..'] unbanned')
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[#!/]([Bb]anall) (.*)$",
"^[#!/]([Bb]anall)$",
"^[#!/]([Uu]ubanall)$",
"^[#!/]([Bb]anlist) (.*)$",
"^[#!/]([Bb]anlist)$",
"^[#!/]([Gg]banlist)$",
"^[#!/]([Kk]ickme)",
"^[#!/]([Kk]ick)$",
"^[#!/]([Bb]an)$",
"^[#!/]([Bb]an) (.*)$",
"^[#!/]([Uu]nban) (.*)$",
"^[#!/]([Uu]nbanall) (.*)$",
"^[#!/]([Uu]nbanall)$",
"^[#!/]([Kk]ick) (.*)$",
"^[#!/]([Uu]nban)$",
"^[#!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
rogerpueyo/luci | applications/luci-app-vnstat/luasrc/model/cbi/vnstat.lua | 78 | 1816 | -- Copyright 2010-2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local utl = require "luci.util"
local sys = require "luci.sys"
local fs = require "nixio.fs"
local nw = require "luci.model.network"
local dbdir, line
for line in io.lines("/etc/vnstat.conf") do
dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']")
if dbdir then break end
end
dbdir = dbdir or "/var/lib/vnstat"
m = Map("vnstat", translate("VnStat"),
translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s)."))
m.submit = translate("Restart VnStat")
m.reset = false
nw.init(luci.model.uci.cursor_state())
local ifaces = { }
local enabled = { }
local iface
if fs.access(dbdir) then
for iface in fs.dir(dbdir) do
if iface:sub(1,1) ~= '.' then
ifaces[iface] = iface
enabled[iface] = iface
end
end
end
for _, iface in ipairs(sys.net.devices()) do
ifaces[iface] = iface
end
local s = m:section(TypedSection, "vnstat")
s.anonymous = true
s.addremove = false
mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces"))
mon_ifaces.template = "cbi/network_ifacelist"
mon_ifaces.widget = "checkbox"
mon_ifaces.cast = "table"
mon_ifaces.noinactive = true
mon_ifaces.nocreate = true
function mon_ifaces.write(self, section, val)
local i
local s = { }
if val then
for _, i in ipairs(type(val) == "table" and val or { val }) do
s[i] = true
end
end
for i, _ in pairs(ifaces) do
if not s[i] then
fs.unlink(dbdir .. "/" .. i)
fs.unlink(dbdir .. "/." .. i)
end
end
if next(s) then
m.uci:set_list("vnstat", section, "interface", utl.keys(s))
else
m.uci:delete("vnstat", section, "interface")
end
end
mon_ifaces.remove = mon_ifaces.write
return m
| apache-2.0 |
xponen/Zero-K | units/spherecloaker.lua | 1 | 3911 | unitDef = {
unitname = [[spherecloaker]],
name = [[Eraser]],
description = [[Cloaker/Jammer Walker]],
acceleration = 0.25,
activateWhenBuilt = true,
brakeRate = 0.25,
buildCostEnergy = 600,
buildCostMetal = 600,
buildPic = [[spherecloaker.png]],
buildTime = 600,
canAttack = false,
canGuard = true,
canMove = true,
canPatrol = true,
canstop = [[1]],
category = [[LAND UNARMED]],
corpse = [[DEAD]],
customParams = {
description_de = [[Tarn-/Störsenderroboter]],
description_bp = [[Robô camuflador e gerador de interfer?ncia.]],
description_fi = [[N?kym?tt?myyskent?n luova tutkanh?iritsij?robotti]],
description_fr = [[Marcheur Brouille/Camoufleur]],
description_pl = [[Bot maskujaco-zaklocajacy]],
helptext = [[The Eraser has a jamming device to conceal your units' radar returns. It also has a small cloak shield to hide friendly nearby units from enemy sight.]],
helptext_bp = [[Geradores de interfer?ncia como estes interferem com as ondas de radar inimigas, impedindo a localizaç?o das unidades protegidas. Alguns s?o capazes de gerar falsos sinais de radar.]],
helptext_fi = [[Eraser kykenee piilottamaan muut yksikk?si vastustajaltasi h?iritsem?ll? t?m?n tutkasignaalia ja luomalla pienen n?kym?tt?myyskent?n ymp?rilleen.]],
helptext_fr = [[L'Eraser est munis d'un brouilleur d'onde qui permet de cacher vos unités des radars enemis. Il est aussi munis d'un petit bouclier de camouflage qui permet de cacher vos unités du champ de vision enemis]],
helptext_pl = [[Eraser wyposazony jest w zaklocacz radaru, ktory ukrywa jednostki przed radarem. Posiada takze pole maskujace, która ukrywa pobliskie przyjazne jednostki przed wzrokiem wroga.]],
helptext_de = [[Der Eraser besitzt ein Gerät zum Stören feindlicher Radarwellen. Des Weiteren ist er mit einem kleinen Tarnschild ausgestattet, um nahe, freundliche Einheiten zu tarnen.]],
},
energyUse = 1.5,
explodeAs = [[BIG_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[kbotjammer]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 600,
maxSlope = 36,
maxVelocity = 1.9,
maxWaterDepth = 5000,
minCloakDistance = 180,
movementClass = [[AKBOT2]],
objectName = [[spherecloaker.s3o]],
onoffable = true,
pushResistant = 0,
radarDistanceJam = 440,
seismicSignature = 16,
selfDestructAs = [[BIG_UNITEX]],
sightDistance = 400,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 18,
turnRate = 2100,
featureDefs = {
DEAD = {
description = [[Wreckage - Eraser]],
blocking = true,
damage = 600,
energy = 0,
featureDead = [[HEAP]],
footprintX = 1,
footprintZ = 1,
metal = 240,
object = [[eraser_d.3ds]],
reclaimable = true,
reclaimTime = 240,
},
HEAP = {
description = [[Debris - Eraser]],
blocking = false,
damage = 600,
energy = 0,
footprintX = 1,
footprintZ = 1,
metal = 120,
object = [[debris2x2a.s3o]],
reclaimable = true,
reclaimTime = 120,
},
},
}
return lowerkeys({ spherecloaker = unitDef })
| gpl-2.0 |
sullome/km-freeminer-mods | mods/clothes/init.lua | 2 | 6569 | clothes = {}
clothes.privilege = "clothes"
clothes.chatcommand = "clothes"
clothes.privilege_desc = "Разрешает изменять текстуру одежды у предмета " ..
"(команда /" .. clothes.chatcommand .. ")"
clothes.command_desc = [[Добавляет текстуру одежды в соответствующее поле метадаты у предмета в руке.
<action> — "set" или "remove",
<texture> - название текстуры (без расширения), учитывается только при "set",
[force] - не обязательный параметр, включает игнорирование ошибок, учитывается только при "set".]]
local function download(texture)
--print(minetest.setting_get("http_get_host"))
return "httpload:" .. texture .. ".png"
end
--{{{ Functions
clothes.get = function (itemstack, quiet)
if itemstack:is_empty() then
return nil
end
local quiet = quiet or false
local meta = minetest.deserialize(itemstack:get_metadata())
local default = itemstack:get_definition().clothes
-- If there is serialized metadata, then we check,
-- have it clothes path or not.
-- If not¸ then we try to use default texture.
-- If there is no serialized metadata, then we still try to use default
-- texture.
if meta then
if meta.clothes == nil then
if default ~= nil then
return default
else
if not quiet then
minetest.log("verbose",
"Item (" .. itemstack:to_string() .. ") "..
"doesn't have a clothes texture"
)
end
return nil
end
else
return download(meta.clothes)
end
else
if default ~= nil then
return default
else
if not quiet then
minetest.log("verbose",
"Item (" .. itemstack:to_string() .. ") " ..
"doesn't have a serialized metadata"
)
end
return nil
end
end
end
clothes.update_skin = function (player, clothes_list)
-- Get base player skin
local name = player:get_player_name()
local skin = download(name)
-- Add clothes
for _,itemstack in ipairs(clothes_list) do
local texture = clothes.get(itemstack)
if texture then
skin = skin .. "^" .. texture
end
end
-- Update skin only if it really changes
if player:get_properties().textures[1] ~= skin then
default.player_set_textures(player, {skin})
minetest.log("action",
name .. " updated his skin. Now his skin is: " ..
player:get_properties().textures[1]
)
end
end
--}}}
--{{{ minetest.register...
minetest.register_privilege(clothes.privilege, clothes.privilege_desc)
minetest.register_chatcommand(clothes.chatcommand, {
params = "<action> <texture> [force]",
description = clothes.command_desc,
privs = {[clothes.privilege] = true},
func = function(playername, param)
-- Parse parameters
local params = {}
for p in string.gmatch(param, "%g+") do table.insert(params, p) end
local action, texture, force = params[1], params[2], params[3]
-- Locals
local player = minetest.get_player_by_name(playername)
local item = player:get_wielded_item()
local prev = item
local metadata = item:get_metadata()
local metatable = minetest.deserialize(metadata)
-- Item metadata check
if metatable == nil then
if metadata == "" then
metatable = {}
else
if action == "set" and force == "force" then
metatable = {}
else
return false, "This item has unempty not serialized metadata"
end
end
end
-- Applying needed changes
if action == "set" then
metatable.clothes = texture .. ".png"
metadata = minetest.serialize(metatable)
item:set_metadata(metadata)
player:set_wielded_item(item)
local new = player:get_wielded_item()
minetest.log("action",
playername ..
" added a clothes texture to the metadata of item " ..
"(" .. prev:to_string() .. ").\n" ..
"Now the item is: " ..
"(" .. new:to_string() .. ")"
)
return true, "Texture added: " ..
dump(minetest.deserialize(new:get_metadata()))
elseif action == "remove" then
metatable.clothes = nil
metadata = minetest.serialize(metatable)
item:set_metadata(metadata)
player:set_wielded_item(item)
local new = player:get_wielded_item()
minetest.log("action",
playername ..
" removed a clothes texture from the metadata of item " ..
"(" .. prev:to_string() .. ").\n" ..
"Now the item is: " ..
"(" .. new:to_string() .. ")"
)
return true, "Texture removed: " ..
dump(minetest.deserialize(new:get_metadata()))
elseif action == nil then
return true, "/clothes <action> <texture> [force]\n" ..
clothes.command_desc
else
return false, "Unrecognized action. Command description:\n" ..
clothes.command_desc
end
end
})
--}}}
--{{{ Clothes registration
clothes.list = {
hat = "Шляпа",
shirt = "Рубашка",
pants = "Штаны",
shoes = "Обувь",
coat = "Пальто",
cape = "Плащ",
dress = "Платье",
scarf = "Шарф",
gloves = "Перчатки",
-- If player can't define his clothes as anything from above
dummy = "Одежда",
}
for name, desc in pairs(clothes.list) do
minetest.register_craftitem("clothes:" .. name, {
description = desc,
groups = {clothes = 1},
inventory_image = "clothes_" ..name.. "_inv.png",
wield_image = "clothes_" ..name.. "_inv.png",
stack_max = 1,
-- Default value
clothes = "clothes_" ..name.. ".png"
})
end
--}}}
--{{{ Clothes crafting
--TODO
--}}}
| gpl-3.0 |
vavrusa/ljdns | dns/dnssec.lua | 1 | 12853 | local ffi = require('ffi')
local utils = require('dns.utils')
local dns = require('dns')
local lib = utils.clib('dnssec', {2, 3, 4, 5})
assert(lib, 'libdnssec not found, install libknot >= 2.3.0')
ffi.cdef [[
/* crypto.h */
void dnssec_crypto_init(void);
void dnssec_crypto_cleanup(void);
/* error.h */
const char *dnssec_strerror(int error);
/* binary.h */
typedef struct { size_t size; uint8_t *data; } dnssec_binary_t;
int dnssec_binary_alloc(dnssec_binary_t *data, size_t size);
void dnssec_binary_free(dnssec_binary_t *binary);
/* list.h */
typedef void dnssec_list_t;
typedef void dnssec_item_t;
dnssec_item_t *dnssec_list_head(dnssec_list_t *list);
dnssec_item_t *dnssec_list_next(dnssec_list_t *list, dnssec_item_t *item);
void *dnssec_item_get(const dnssec_item_t *item);
void dnssec_list_free_full(dnssec_list_t *list, void *free_cb, void *free_ctx);
int dnssec_list_append(dnssec_list_t *list, void *data);
/* key.h */
typedef struct {} dnssec_key_t;
int dnssec_key_new(dnssec_key_t **key);
void dnssec_key_clear(dnssec_key_t *key);
void dnssec_key_free(dnssec_key_t *key);
uint16_t dnssec_key_get_keytag(dnssec_key_t *key);
const uint8_t *dnssec_key_get_dname(const dnssec_key_t *key);
int dnssec_key_set_dname(dnssec_key_t *key, const uint8_t *dname);
uint16_t dnssec_key_get_flags(const dnssec_key_t *key);
int dnssec_key_set_flags(dnssec_key_t *key, uint16_t flags);
uint8_t dnssec_key_get_protocol(const dnssec_key_t *key);
int dnssec_key_set_protocol(dnssec_key_t *key, uint8_t protocol);
uint8_t dnssec_key_get_algorithm(const dnssec_key_t *key);
int dnssec_key_set_algorithm(dnssec_key_t *key, uint8_t algorithm);
int dnssec_key_get_rdata(const dnssec_key_t *key, dnssec_binary_t *rdata);
int dnssec_key_set_rdata(dnssec_key_t *key, const dnssec_binary_t *rdata);
int dnssec_key_get_pubkey(const dnssec_key_t *key, dnssec_binary_t *pubkey);
int dnssec_key_set_pubkey(dnssec_key_t *key, const dnssec_binary_t *pubkey);
int dnssec_key_load_pkcs8(dnssec_key_t *key, const dnssec_binary_t *pem);
bool dnssec_key_can_sign(const dnssec_key_t *key);
bool dnssec_key_can_verify(const dnssec_key_t *key);
/* sign.h */
typedef void dnssec_sign_ctx_t;
typedef struct dnssec_signer { dnssec_sign_ctx_t *d[1]; uint8_t algo; uint16_t tag; };
int dnssec_sign_new(dnssec_sign_ctx_t **ctx_ptr, const dnssec_key_t *key);
void dnssec_sign_free(dnssec_sign_ctx_t *ctx);
int dnssec_sign_init(dnssec_sign_ctx_t *ctx);
int dnssec_sign_add(dnssec_sign_ctx_t *ctx, const dnssec_binary_t *data);
int dnssec_sign_write(dnssec_sign_ctx_t *ctx, dnssec_binary_t *signature);
int dnssec_sign_verify(dnssec_sign_ctx_t *ctx, const dnssec_binary_t *signature);
/* bitmap.h */
typedef void dnssec_nsec_bitmap_t;
dnssec_nsec_bitmap_t *dnssec_nsec_bitmap_new(void);
void dnssec_nsec_bitmap_clear(dnssec_nsec_bitmap_t *bitmap);
void dnssec_nsec_bitmap_free(dnssec_nsec_bitmap_t *bitmap);
void dnssec_nsec_bitmap_add(dnssec_nsec_bitmap_t *bitmap, uint16_t type);
size_t dnssec_nsec_bitmap_size(const dnssec_nsec_bitmap_t *bitmap);
void dnssec_nsec_bitmap_write(const dnssec_nsec_bitmap_t *bitmap, uint8_t *output);
]]
-- Crypto library initialiser/deinitialiser
lib.dnssec_crypto_init()
local crypto_init = ffi.gc(ffi.new('dnssec_binary_t'), function () -- luacheck: ignore
lib.dnssec_crypto_cleanup()
end)
-- Helper for error string
local function strerr(e)
return ffi.string(lib.dnssec_strerror(e))
end
-- Helper to allow safe retrieval of wrapped key
local function getdata(v)
assert(v and v.d[0] ~= nil)
return v.d[0]
end
-- Helper to box string or byte array to datum struct
local tmp_binary = ffi.new('dnssec_binary_t')
local function boxdatum(data, len)
if type(data) == 'string' or type(data) == 'cdata' then
tmp_binary.data = ffi.cast('uint8_t *', data)
tmp_binary.size = len or #data
data = tmp_binary
end
return data
end
-- Get/set value from datum-like property
local function getsetdatum(key, get, set, data, len)
if not data then
if not get then return nil end
local ret = get(key, tmp_binary)
if ret ~= 0 then return nil, strerr(ret) end
return ffi.string(tmp_binary.data, tmp_binary.size)
end
local ret = set(key, boxdatum(data, len))
if ret ~= 0 then return nil, strerr(ret) end
return true
end
local function getsetattr(key, get, set, val)
if val then
local ret = set(key, val)
if ret ~= 0 then return nil, strerr(ret) end
end
return get(key)
end
-- RDATA digest size for given algorithm
local algorithms = {
invalid = 0,
dh = 1,
dsa = 2,
dsa_sha1 = 3,
rsa_sha1 = 5,
dsa_sha1_nsec3 = 6,
rsa_sha1_nsec3 = 7,
rsa_sha256 = 8,
rsa_sha512 = 10,
ecc_gost = 12,
ecdsa_p256_sha256 = 13,
ecdsa_p384_sha384 = 14,
ed25519 = 15,
ed448 = 16,
}
-- KASP key state
local keystate = {
INVALID = 0,
PUBLISHED = 1,
ACTIVE = 2,
RETIRED = 3,
REMOVED = 4,
}
-- KASP keyset action
local keyaction = {
ZSK_INIT = 1,
ZSK_PUBLISH = 2,
ZSK_RESIGN = 3,
ZSK_RETIRE = 4,
}
-- Declare module
local M = {
algo = algorithms,
action = keyaction,
state = keystate,
tostring = {
algo = utils.itable(algorithms),
action = utils.itable(keyaction),
state = utils.itable(keystate),
}
}
-- Metatype for DNSSEC key
local key_t = ffi.typeof('dnssec_key_t')
ffi.metatype(key_t, {
__new = function ()
local key = ffi.new('dnssec_key_t *[1]')
local ret = lib.dnssec_key_new(key)
if ret ~= 0 then return nil end
return ffi.gc(key[0][0], lib.dnssec_key_free)
end,
__tostring = function(self)
return tostring(self:tag())
end,
__index = {
tag = function (self)
return tonumber(lib.dnssec_key_get_keytag(self))
end,
name = function (self, name)
local v, err = getsetattr(self, lib.dnssec_key_get_dname, lib.dnssec_key_set_dname, name)
return v and v[0], err
end,
flags = function (self, flags)
local v, err = getsetattr(self, lib.dnssec_key_get_flags, lib.dnssec_key_set_flags, flags)
return v and tonumber(v), err
end,
ksk = function (self) return self:flags() == 257 end,
zsk = function (self) return self:flags() == 256 end,
protocol = function (self, proto)
local v, err = getsetattr(self, lib.dnssec_key_get_protocol, lib.dnssec_key_set_protocol, proto)
return v and tonumber(v), err
end,
algo = function (self, algo)
local v, err = getsetattr(self, lib.dnssec_key_get_algorithm, lib.dnssec_key_set_algorithm, algo)
return v and tonumber(v), err
end,
rdata = function (self, data, len)
return getsetdatum(self, lib.dnssec_key_get_rdata, lib.dnssec_key_set_rdata, data, len)
end,
pubkey = function (self, data, len)
return getsetdatum(self, lib.dnssec_key_get_pubkey, lib.dnssec_key_set_pubkey, data, len)
end,
privkey = function (self, pem, len)
return getsetdatum(self, nil, lib.dnssec_key_load_pkcs8, pem, len)
end,
can_verify = function(self)
return lib.dnssec_key_can_verify(self)
end,
can_sign = function(self)
return lib.dnssec_key_can_sign(self)
end,
}
})
M.key = key_t
-- Metatype for DNSSEC signer
local function add_data(signer, data, len)
local ret = lib.dnssec_sign_add(signer, boxdatum(data, len))
if ret ~= 0 then return nil, strerr(ret) end
return true
end
local tmp_hdr = ffi.new('struct { uint16_t t; uint16_t c; uint32_t l; }')
local tmp_signbuf = ffi.new('uint8_t [512]')
local signer_t = ffi.typeof('struct dnssec_signer')
ffi.metatype(signer_t, {
__new = function (ct, key)
-- Key is required for signer
if not key then return end
assert(ffi.istype(key_t, key), 'invalid key type')
assert(key:can_sign(), 'key cannot be used for signing')
local signer = ffi.new(ct)
local ret = lib.dnssec_sign_new(signer.d, key)
if ret ~= 0 then return nil, strerr(ret) end
-- Cache frequently used key properties
signer.algo = key:algo()
signer.tag = key:tag()
return signer
end,
__gc = function (self)
lib.dnssec_sign_free(getdata(self))
end,
__index = {
reset = function (self)
local ret = lib.dnssec_sign_init(getdata(self))
if ret ~= 0 then return nil, strerr(ret) end
return true
end,
add = function (self, data, len)
local signer = getdata(self)
-- Serialise RRSet if passed as data
if type(data) == 'cdata' and ffi.istype(data, dns.rrset) then
local owner = data:owner()
add_data(signer, owner.bytes, owner:len())
tmp_hdr.t = utils.n16(data:type())
tmp_hdr.c = utils.n16(data:class())
tmp_hdr.l = utils.n32(data:ttl())
assert(ffi.sizeof(tmp_hdr) == 8) -- Assert sane alignment
-- Serialise records RDATA
for _, rdata in ipairs(data) do
add_data(signer, tmp_hdr, ffi.sizeof(tmp_hdr))
add_data(signer, dns.rdata.data(rdata), dns.rdata.len(rdata))
end
else
return add_data(signer, data, len)
end
end,
get = function (self)
local ret = lib.dnssec_sign_write(getdata(self), tmp_binary)
if ret ~= 0 then return nil, strerr(ret) end
-- Must make a copy of binary and recycle
ret = ffi.string(tmp_binary.data, tmp_binary.size)
lib.dnssec_binary_free(tmp_binary)
return ret
end,
verify = function (self, data, len)
local signer = getdata(self)
-- Verify (RR, RRSIG) if passed as data
if type(data) == 'cdata' and ffi.istype(data, dns.rrset) then
local rrsig = len
assert(ffi.typeof(rrsig) == dns.rrset)
assert(rrsig:type() == dns.type.RRSIG, 'second rr is not rrsig')
self:reset()
-- Add RRSIG header and signer
local rrsig_data = rrsig:rdata(0)
local w = utils.wire_reader(rrsig_data, #rrsig_data)
self:add(w:bytes(18), 18) -- Add header
local signer_len = utils.dnamelen(w:tell())
self:add(w:bytes(signer_len), signer_len) -- Add signer
local signature = w:bytes(w.maxlen - w.len)
-- Add RRSet wire and verify against signature
self:add(data)
data, len = signature, #signature
end
-- Generic byte array verification
local ret = lib.dnssec_sign_verify(signer, boxdatum(data, len))
if ret ~= 0 then return nil, strerr(ret) end
return true
end,
sign = function (self, rr, expire, incept, signer)
self:reset()
local owner = rr:owner()
local rrsig = dns.rrset(owner, dns.type.RRSIG)
local labels = owner:labels()
incept = incept or os.time()
if owner:wildcard() then labels = labels - 1 end
-- Need to manually fill the RRSIG header
-- RFC4034 3.1. RRSIG RDATA Wire Format
local w = utils.wire_writer(tmp_signbuf, ffi.sizeof(tmp_signbuf))
w:u16(rr:type())
w:u8(self.algo)
w:u8(labels)
w:u32(rr:ttl())
w:u32(incept + (expire or rr:ttl()))
w:u32(incept)
w:u16(self.tag)
assert(w.len == 18)
-- Either self-signed use given signer
signer = signer or owner
w:bytes(signer, signer:len())
self:add(tmp_signbuf, w.len)
-- Serialise RDATAs
self:add(rr)
-- Write down the RRSIG RDATA
local digest = self:get()
w:bytes(digest, #digest)
rrsig:add(tmp_signbuf, rr:ttl(), w.len)
return rrsig
end,
}
})
M.signer = signer_t
-- Whitelist supported DNS types
local known_types = {}
for _, t in pairs(dns.type) do
if t < 127 then table.insert(known_types, t) end
end
-- NSEC "black lies" denialer
local tmp_bitmap = ffi.gc(lib.dnssec_nsec_bitmap_new(), lib.dnssec_nsec_bitmap_free)
M.denial = function (name, rrtype, ttl, nxdomain)
local nsec = dns.rrset(name, dns.type.NSEC)
local next_name = dns.dname('\1\0' .. name:towire())
local next_len = next_name:len()
-- Construct NSEC bitmap with all basic types byt requested
lib.dnssec_nsec_bitmap_clear(tmp_bitmap)
-- NXDOMAIN can contain only NSEC and its RRSIG
if nxdomain then
lib.dnssec_nsec_bitmap_add(tmp_bitmap, dns.type.NSEC)
lib.dnssec_nsec_bitmap_add(tmp_bitmap, dns.type.RRSIG)
else -- All supported types up to meta types
for _, i in ipairs(known_types) do
if i ~= rrtype and i <= 127 then
lib.dnssec_nsec_bitmap_add(tmp_bitmap, i)
end
end
end
-- Create NSEC RDATA
local bit_size = lib.dnssec_nsec_bitmap_size(tmp_bitmap)
local rdata = utils.wire_writer(tmp_signbuf, next_len + bit_size)
assert(next_len + bit_size < ffi.sizeof(tmp_signbuf))
rdata:bytes(next_name.bytes, next_len)
lib.dnssec_nsec_bitmap_write(tmp_bitmap, rdata:tell())
rdata:seek(bit_size)
-- Finalize RRSET
nsec:add(rdata.p, ttl or 0, rdata.len)
return nsec
end
-- Extend DNS record dissectors
dns.rdata.rrsig_signature = function(rdata)
local w = utils.wire_reader(rdata, utils.rdlen(rdata))
w:seek(18) -- Skip header
local signer_len = utils.dnamelen(w:tell())
w:seek(signer_len) -- Skip signer name
return w:bytes(w.maxlen - w.len)
end
-- Extened DNS RDATA constructors
dns.rdata.dnskey = function(flags, proto, algo, pubkey, pubkey_len)
pubkey_len = pubkey_len or #pubkey
local rdata = ffi.new('char [?]', ffi.sizeof('uint32_t') + pubkey_len)
local w = utils.wire_writer(rdata, ffi.sizeof(rdata))
w:u16(flags)
w:u8(proto)
w:u8(algo)
w:bytes(pubkey, pubkey_len)
assert(w.len == ffi.sizeof(rdata))
return rdata
end
return M | bsd-2-clause |
xponen/Zero-K | effects/babette.lua | 25 | 4072 | -- babette
-- smoke_babette
-- burst_babette
return {
["babette"] = {
boom = {
air = true,
class = [[CExpGenSpawner]],
count = 20,
ground = true,
water = true,
properties = {
delay = [[5 i1]],
explosiongenerator = [[custom:burst_babette]],
pos = [[-25 r50, 0 r50, -25 r50]],
},
},
pikes = {
air = true,
class = [[explspike]],
count = 15,
ground = true,
water = true,
properties = {
alpha = 0.8,
alphadecay = 0.2,
color = [[1.0,0.7,0.4]],
dir = [[-15 r30,-15 r30,-15 r30]],
length = 15,
width = 5,
},
},
smoke = {
air = true,
class = [[CExpGenSpawner]],
count = 20,
ground = true,
water = true,
properties = {
delay = [[5 i1]],
explosiongenerator = [[custom:smoke_babette]],
pos = [[-25 r50, 0 r50, -25 r50]],
},
},
sparks = {
air = true,
class = [[CSimpleParticleSystem]],
count = 0,
ground = true,
water = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[1 1 0 0.01 1 0.7 0.5 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 30,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 20,
particlelife = 15,
particlelifespread = 0,
particlesize = 10,
particlesizespread = 2.5,
particlespeed = 15,
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[plasma]],
},
},
},
["smoke_babette"] = {
pop = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 1,
colormap = [[0.5 0.5 0.7 1 0 0 0 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 10,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 24,
particlelifespread = 0,
particlesize = 2,
particlesizespread = 0,
particlespeed = 0.1,
particlespeedspread = 0,
pos = [[0, 0, 0]],
sizegrowth = 2,
sizemod = 1.0,
texture = [[smoke]],
},
},
},
["burst_babette"] = {
pop = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 1,
colormap = [[1 1 1 1 1 1 1 1]],
directional = false,
emitrot = 0,
emitrotspread = 10,
emitvector = [[0, 1, 0]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 6,
particlelifespread = 0,
particlesize = 2,
particlesizespread = 0,
particlespeed = 0.1,
particlespeedspread = 0,
pos = [[0, 0, 0]],
sizegrowth = 2,
sizemod = 1.0,
texture = [[kburst]],
},
},
},
}
| gpl-2.0 |
LuaDist2/lrexlib-gnu | test/common_sets.lua | 9 | 14050 | -- See Copyright Notice in the file LICENSE
-- This file should contain only test sets that behave identically
-- when being run with pcre or posix regex libraries.
local luatest = require "luatest"
local N = luatest.NT
local unpack = unpack or table.unpack
local function norm(a) return a==nil and N or a end
local function get_gsub (lib)
return lib.gsub or
function (subj, pattern, repl, n)
return lib.new (pattern) : gsub (subj, repl, n)
end
end
local function set_f_gmatch (lib, flg)
-- gmatch (s, p, [cf], [ef])
local function test_gmatch (subj, patt)
local out, guard = {}, 10
for a, b in lib.gmatch (subj, patt) do
table.insert (out, { norm(a), norm(b) })
guard = guard - 1
if guard == 0 then break end
end
return unpack (out)
end
return {
Name = "Function gmatch",
Func = test_gmatch,
--{ subj patt results }
{ {"ab", lib.new"."}, {{"a",N}, {"b",N} } },
{ {("abcd"):rep(3), "(.)b.(d)"}, {{"a","d"},{"a","d"},{"a","d"}} },
{ {"abcd", ".*" }, {{"abcd",N} } },--zero-length match
{ {"abc", "^." }, {{"a",N}} },--anchored pattern
}
end
local function set_f_count (lib, flg)
return {
Name = "Function count",
Func = lib.count,
--{ subj patt results }
{ {"ab", lib.new"."}, { 2 } },
{ {("abcd"):rep(3), "(.)b.(d)"}, { 3 } },
{ {"abcd", ".*" }, { 1 } },
{ {"abc", "^." }, { 1 } },
}
end
local function set_f_split (lib, flg)
-- split (s, p, [cf], [ef])
local function test_split (subj, patt)
local out, guard = {}, 10
for a, b, c in lib.split (subj, patt) do
table.insert (out, { norm(a), norm(b), norm(c) })
guard = guard - 1
if guard == 0 then break end
end
return unpack (out)
end
return {
Name = "Function split",
Func = test_split,
--{ subj patt results }
{ {"ab", lib.new","}, {{"ab",N,N}, } },
{ {"ab", ","}, {{"ab",N,N}, } },
{ {",", ","}, {{"",",",N}, {"", N, N}, } },
{ {",,", ","}, {{"",",",N}, {"",",",N}, {"",N,N} } },
{ {"a,b", ","}, {{"a",",",N}, {"b",N,N}, } },
{ {",a,b", ","}, {{"",",",N}, {"a",",",N}, {"b",N,N}} },
{ {"a,b,", ","}, {{"a",",",N}, {"b",",",N}, {"",N,N} } },
{ {"a,,b", ","}, {{"a",",",N}, {"",",",N}, {"b",N,N}} },
{ {"ab<78>c", "<(.)(.)>"}, {{"ab","7","8"}, {"c",N,N}, } },
{ {"abc", "^."}, {{"", "a",N}, {"bc",N,N}, } },--anchored pattern
{ {"abc", "^"}, {{"", "", N}, {"abc",N,N}, } },
-- { {"abc", "$"}, {{"abc","",N}, {"",N,N}, } },
-- { {"abc", "^|$"}, {{"", "", N}, {"abc","",N},{"",N,N},} },
}
end
local function set_f_find (lib, flg)
return {
Name = "Function find",
Func = lib.find,
-- {subj, patt, st}, { results }
{ {"abcd", lib.new".+"}, { 1,4 } }, -- [none]
{ {"abcd", ".+"}, { 1,4 } }, -- [none]
{ {"abcd", ".+", 2}, { 2,4 } }, -- positive st
{ {"abcd", ".+", -2}, { 3,4 } }, -- negative st
{ {"abcd", ".*"}, { 1,4 } }, -- [none]
{ {"abc", "bc"}, { 2,3 } }, -- [none]
{ {"abcd", "(.)b.(d)"}, { 1,4,"a","d" }}, -- [captures]
}
end
local function set_f_match (lib, flg)
return {
Name = "Function match",
Func = lib.match,
-- {subj, patt, st}, { results }
{ {"abcd", lib.new".+"}, {"abcd"} }, -- [none]
{ {"abcd", ".+"}, {"abcd"} }, -- [none]
{ {"abcd", ".+", 2}, {"bcd"} }, -- positive st
{ {"abcd", ".+", -2}, {"cd"} }, -- negative st
{ {"abcd", ".*"}, {"abcd"} }, -- [none]
{ {"abc", "bc"}, {"bc"} }, -- [none]
{ {"abcd", "(.)b.(d)"}, {"a","d"} }, -- [captures]
}
end
local function set_m_exec (lib, flg)
return {
Name = "Method exec",
Method = "exec",
--{patt}, {subj, st} { results }
{ {".+"}, {"abcd"}, {1,4,{}} }, -- [none]
{ {".+"}, {"abcd",2}, {2,4,{}} }, -- positive st
{ {".+"}, {"abcd",-2}, {3,4,{}} }, -- negative st
{ {".*"}, {"abcd"}, {1,4,{}} }, -- [none]
{ {"bc"}, {"abc"}, {2,3,{}} }, -- [none]
{ { "(.)b.(d)"}, {"abcd"}, {1,4,{1,1,4,4}}},--[captures]
{ {"(a+)6+(b+)"}, {"Taa66bbT",2}, {2,7,{2,3,6,7}}},--[st+captures]
}
end
local function set_m_tfind (lib, flg)
return {
Name = "Method tfind",
Method = "tfind",
--{patt}, {subj, st} { results }
{ {".+"}, {"abcd"}, {1,4,{}} }, -- [none]
{ {".+"}, {"abcd",2}, {2,4,{}} }, -- positive st
{ {".+"}, {"abcd",-2}, {3,4,{}} }, -- negative st
{ {".*"}, {"abcd"}, {1,4,{}} }, -- [none]
{ {"bc"}, {"abc"}, {2,3,{}} }, -- [none]
{ {"(.)b.(d)"}, {"abcd"}, {1,4,{"a","d"}}},--[captures]
}
end
local function set_m_find (lib, flg)
return {
Name = "Method find",
Method = "find",
--{patt}, {subj, st} { results }
{ {".+"}, {"abcd"}, {1,4} }, -- [none]
{ {".+"}, {"abcd",2}, {2,4} }, -- positive st
{ {".+"}, {"abcd",-2}, {3,4} }, -- negative st
{ {".*"}, {"abcd"}, {1,4} }, -- [none]
{ {"bc"}, {"abc"}, {2,3} }, -- [none]
{ {"(.)b.(d)"}, {"abcd"}, {1,4,"a","d"}},--[captures]
}
end
local function set_m_match (lib, flg)
return {
Name = "Method match",
Method = "match",
--{patt}, {subj, st} { results }
{ {".+"}, {"abcd"}, {"abcd"} }, -- [none]
{ {".+"}, {"abcd",2}, {"bcd" } }, -- positive st
{ {".+"}, {"abcd",-2}, {"cd" } }, -- negative st
{ {".*"}, {"abcd"}, {"abcd"} }, -- [none]
{ {"bc"}, {"abc"}, {"bc" } }, -- [none]
{{ "(.)b.(d)"}, {"abcd"}, {"a","d"} }, --[captures]
}
end
local function set_f_gsub1 (lib, flg)
local subj, pat = "abcdef", "[abef]+"
local cpat = lib.new(pat)
return {
Name = "Function gsub, set1",
Func = get_gsub (lib),
--{ s, p, f, n, res1, res2, res3 },
{ {subj, cpat, "", 0}, {subj, 0, 0} }, -- test "n" + empty_replace
{ {subj, pat, "", 0}, {subj, 0, 0} }, -- test "n" + empty_replace
{ {subj, pat, "", -1}, {subj, 0, 0} }, -- test "n" + empty_replace
{ {subj, pat, "", 1}, {"cdef", 1, 1} },
{ {subj, pat, "", 2}, {"cd", 2, 2} },
{ {subj, pat, "", 3}, {"cd", 2, 2} },
{ {subj, pat, "" }, {"cd", 2, 2} },
{ {subj, pat, "#", 0}, {subj, 0, 0} }, -- test "n" + non-empty_replace
{ {subj, pat, "#", 1}, {"#cdef", 1, 1} },
{ {subj, pat, "#", 2}, {"#cd#", 2, 2} },
{ {subj, pat, "#", 3}, {"#cd#", 2, 2} },
{ {subj, pat, "#" }, {"#cd#", 2, 2} },
{ {"abc", "^.", "#" }, {"#bc", 1, 1} }, -- anchored pattern
}
end
local function set_f_gsub2 (lib, flg)
local subj, pat = "abc", "([ac])"
return {
Name = "Function gsub, set2",
Func = get_gsub (lib),
--{ s, p, f, n, res1, res2, res3 },
{ {subj, pat, "<%1>" }, {"<a>b<c>", 2, 2} }, -- test non-escaped chars in f
{ {subj, pat, "%<%1%>" }, {"<a>b<c>", 2, 2} }, -- test escaped chars in f
{ {subj, pat, "" }, {"b", 2, 2} }, -- test empty replace
{ {subj, pat, "1" }, {"1b1", 2, 2} }, -- test odd and even %'s in f
{ {subj, pat, "%1" }, {"abc", 2, 2} },
{ {subj, pat, "%%1" }, {"%1b%1", 2, 2} },
{ {subj, pat, "%%%1" }, {"%ab%c", 2, 2} },
{ {subj, pat, "%%%%1" }, {"%%1b%%1", 2, 2} },
{ {subj, pat, "%%%%%1" }, {"%%ab%%c", 2, 2} },
}
end
local function set_f_gsub3 (lib, flg)
return {
Name = "Function gsub, set3",
Func = get_gsub (lib),
--{ s, p, f, n, res1,res2,res3 },
{ {"abc", "a", "%0" }, {"abc", 1, 1} }, -- test (in)valid capture index
{ {"abc", "a", "%1" }, {"abc", 1, 1} },
{ {"abc", "[ac]", "%1" }, {"abc", 2, 2} },
{ {"abc", "(a)", "%1" }, {"abc", 1, 1} },
{ {"abc", "(a)", "%2" }, "invalid capture index" },
}
end
local function set_f_gsub4 (lib, flg)
return {
Name = "Function gsub, set4",
Func = get_gsub (lib),
--{ s, p, f, n, res1, res2, res3 },
{ {"a2c3", ".", "#" }, {"####", 4, 4} }, -- test .
{ {"a2c3", ".+", "#" }, {"#", 1, 1} }, -- test .+
{ {"a2c3", ".*", "#" }, {"#", 1, 1} }, -- test .*
{ {"/* */ */", "\\/\\*(.*)\\*\\/", "#" }, {"#", 1, 1} },
{ {"a2c3", "[0-9]", "#" }, {"a#c#", 2, 2} }, -- test %d
{ {"a2c3", "[^0-9]", "#" }, {"#2#3", 2, 2} }, -- test %D
{ {"a \t\nb", "[ \t\n]", "#" }, {"a###b", 3, 3} }, -- test %s
{ {"a \t\nb", "[^ \t\n]", "#" }, {"# \t\n#", 2, 2} }, -- test %S
}
end
local function set_f_gsub5 (lib, flg)
local function frep1 () end -- returns nothing
local function frep2 () return "#" end -- ignores arguments
local function frep3 (...) return table.concat({...}, ",") end -- "normal"
local function frep4 () return {} end -- invalid return type
local function frep5 () return "7", "a" end -- 2-nd return is "a"
local function frep6 () return "7", "break" end -- 2-nd return is "break"
local subj = "a2c3"
return {
Name = "Function gsub, set5",
Func = get_gsub (lib),
--{ s, p, f, n, res1, res2, res3 },
{ {subj, "a(.)c(.)", frep1 }, {subj, 1, 0} },
{ {subj, "a(.)c(.)", frep2 }, {"#", 1, 1} },
{ {subj, "a(.)c(.)", frep3 }, {"2,3", 1, 1} },
{ {subj, "a.c.", frep3 }, {subj, 1, 1} },
{ {subj, "z*", frep1 }, {subj, 5, 0} },
{ {subj, "z*", frep2 }, {"#a#2#c#3#", 5, 5} },
{ {subj, "z*", frep3 }, {subj, 5, 5} },
{ {subj, subj, frep4 }, "invalid return type" },
{ {"abc",".", frep5 }, {"777", 3, 3} },
{ {"abc",".", frep6 }, {"777", 3, 3} },
}
end
local function set_f_gsub6 (lib, flg)
local tab1, tab2, tab3 = {}, { ["2"] = 56 }, { ["2"] = {} }
local subj = "a2c3"
return {
Name = "Function gsub, set6",
Func = get_gsub (lib),
--{ s, p, f, n, res1,res2,res3 },
{ {subj, "a(.)c(.)", tab1 }, {subj, 1, 0} },
{ {subj, "a(.)c(.)", tab2 }, {"56", 1, 1} },
{ {subj, "a(.)c(.)", tab3 }, "invalid replacement type" },
{ {subj, "a.c.", tab1 }, {subj, 1, 0} },
{ {subj, "a.c.", tab2 }, {subj, 1, 0} },
{ {subj, "a.c.", tab3 }, {subj, 1, 0} },
}
end
local function set_f_gsub8 (lib, flg)
local subj, patt, repl = "abcdef", "..", "*"
return {
Name = "Function gsub, set8",
Func = get_gsub (lib),
--{ s, p, f, n, res1, res2, res3 },
{ {subj, patt, repl, function() end }, {"abcdef", 3, 0} },
{ {subj, patt, repl, function() return nil end }, {"abcdef", 3, 0} },
{ {subj, patt, repl, function() return false end }, {"abcdef", 3, 0} },
{ {subj, patt, repl, function() return true end }, {"***", 3, 3} },
{ {subj, patt, repl, function() return {} end }, {"***", 3, 3} },
{ {subj, patt, repl, function() return "#" end }, {"###", 3, 3} },
{ {subj, patt, repl, function() return 57 end }, {"575757", 3, 3} },
{ {subj, patt, repl, function (from) return from end }, {"135", 3, 3} },
{ {subj, patt, repl, function (from, to) return to end }, {"246", 3, 3} },
{ {subj, patt, repl, function (from,to,rep) return rep end },
{"***", 3, 3} },
{ {subj, patt, repl, function (from, to, rep) return rep..to..from end },
{"*21*43*65", 3, 3} },
{ {subj, patt, repl, function() return nil end }, {"abcdef", 3, 0} },
{ {subj, patt, repl, function() return nil, nil end }, {"abcdef", 3, 0} },
{ {subj, patt, repl, function() return nil, false end }, {"abcdef", 3, 0} },
{ {subj, patt, repl, function() return nil, true end }, {"ab**", 3, 2} },
{ {subj, patt, repl, function() return true, true end }, {"***", 3, 3} },
{ {subj, patt, repl, function() return nil, 0 end }, {"abcdef", 1, 0} },
{ {subj, patt, repl, function() return true, 0 end }, {"*cdef", 1, 1} },
{ {subj, patt, repl, function() return nil, 1 end }, {"ab*ef", 2, 1} },
{ {subj, patt, repl, function() return true, 1 end }, {"**ef", 2, 2} },
}
end
return function (libname)
local lib = require (libname)
return {
set_f_gmatch (lib),
set_f_split (lib),
set_f_find (lib),
set_f_match (lib),
set_m_exec (lib),
set_m_tfind (lib),
set_m_find (lib),
set_m_match (lib),
set_f_count (lib),
set_f_gsub1 (lib),
set_f_gsub2 (lib),
set_f_gsub3 (lib),
set_f_gsub4 (lib),
set_f_gsub5 (lib),
set_f_gsub6 (lib),
set_f_gsub8 (lib),
}
end
| mit |
xponen/Zero-K | gamedata/modularcomms/weapons/multistunner.lua | 5 | 1340 | local name = "commweapon_multistunner"
local weaponDef = {
name = [[Multi-Stunner]],
areaOfEffect = 144,
avoidFeature = false,
burst = 16,
burstRate = 0.1875,
commandFire = true,
customParams = {
muzzleEffectFire = [[custom:YELLOW_LIGHTNING_MUZZLE]],
slot = [[3]],
},
craterBoost = 0,
craterMult = 0,
cylinderTargeting = 0,
damage = {
default = 542.534722222222,
},
duration = 8,
edgeEffectiveness = 0,
explosionGenerator = [[custom:YELLOW_LIGHTNINGPLOSION]],
fireStarter = 0,
impulseBoost = 0,
impulseFactor = 0,
intensity = 10,
interceptedByShieldType = 1,
noSelfDamage = true,
paralyzer = true,
paralyzeTime = 6,
range = 360,
reloadtime = 12,
rgbColor = [[1 1 0.25]],
soundStart = [[weapon/lightning_fire]],
soundTrigger = false,
sprayAngle = 1920,
texture1 = [[lightning]],
thickness = 10,
turret = true,
weaponType = [[LightningCannon]],
weaponVelocity = 450,
}
return name, weaponDef
| gpl-2.0 |
merlinblack/Game-Engine-Testbed | media/src/dejavu_sans_book_14.lua | 1 | 10867 | font={
size=14,
lineheight=22,
spacelength=6,
monowidth=18,
baseline=18,
letterspacing=0,
range={ start=32, finish=126},
glyphs={},
kerning={},
verticalOffset={}
}
-- Code, X, Y, W, H, Advance
font.glyphs[32]={ 1, 16, 1, 1, 6}
font.glyphs[33]={ 2, 2, 3, 15, 8}
font.glyphs[34]={ 5, 2, 6, 6, 9}
font.glyphs[35]={ 11, 2, 14, 15, 15}
font.glyphs[36]={ 25, 1, 10, 19, 12}
font.glyphs[37]={ 35, 2, 17, 15, 18}
font.glyphs[38]={ 52, 2, 14, 15, 14}
font.glyphs[39]={ 66, 2, 3, 6, 6}
font.glyphs[40]={ 69, 1, 6, 19, 8}
font.glyphs[41]={ 75, 1, 6, 19, 7}
font.glyphs[42]={ 81, 2, 10, 10, 9}
font.glyphs[43]={ 91, 4, 13, 13, 16}
font.glyphs[44]={ 104, 13, 4, 6, 6}
font.glyphs[45]={ 108, 9, 6, 3, 7}
font.glyphs[46]={ 114, 13, 3, 4, 6}
font.glyphs[47]={ 117, 2, 8, 17, 6}
font.glyphs[48]={ 125, 2, 10, 15, 11}
font.glyphs[49]={ 1, 20, 10, 15, 13}
font.glyphs[50]={ 11, 20, 10, 15, 12}
font.glyphs[51]={ 21, 20, 10, 15, 11}
font.glyphs[52]={ 31, 20, 11, 15, 12}
font.glyphs[53]={ 42, 20, 10, 15, 12}
font.glyphs[54]={ 52, 20, 10, 15, 11}
font.glyphs[55]={ 62, 20, 10, 15, 13}
font.glyphs[56]={ 72, 20, 10, 15, 11}
font.glyphs[57]={ 82, 20, 10, 15, 11}
font.glyphs[58]={ 92, 24, 3, 11, 6}
font.glyphs[59]={ 95, 23, 4, 14, 6}
font.glyphs[60]={ 99, 22, 13, 13, 15}
font.glyphs[61]={ 112, 25, 13, 7, 16}
font.glyphs[62]={ 125, 22, 13, 13, 15}
font.glyphs[63]={ 1, 38, 8, 15, 9}
font.glyphs[64]={ 9, 37, 17, 19, 18}
font.glyphs[65]={ 26, 38, 14, 15, 13}
font.glyphs[66]={ 40, 38, 11, 15, 13}
font.glyphs[67]={ 51, 38, 12, 15, 13}
font.glyphs[68]={ 63, 38, 12, 15, 14}
font.glyphs[69]={ 75, 38, 10, 15, 12}
font.glyphs[70]={ 85, 38, 9, 15, 11}
font.glyphs[71]={ 94, 38, 13, 15, 14}
font.glyphs[72]={ 107, 38, 11, 15, 14}
font.glyphs[73]={ 118, 38, 3, 15, 6}
font.glyphs[74]={ 121, 38, 6, 19, 6}
font.glyphs[75]={ 127, 38, 12, 15, 12}
font.glyphs[76]={ 1, 57, 10, 15, 11}
font.glyphs[77]={ 11, 57, 14, 15, 17}
font.glyphs[78]={ 25, 57, 11, 15, 14}
font.glyphs[79]={ 36, 57, 14, 15, 15}
font.glyphs[80]={ 50, 57, 10, 15, 11}
font.glyphs[81]={ 60, 57, 14, 18, 15}
font.glyphs[82]={ 74, 57, 12, 15, 13}
font.glyphs[83]={ 86, 57, 11, 15, 12}
font.glyphs[84]={ 97, 57, 13, 15, 12}
font.glyphs[85]={ 110, 57, 11, 15, 14}
font.glyphs[86]={ 121, 57, 14, 15, 13}
font.glyphs[87]={ 1, 77, 19, 15, 18}
font.glyphs[88]={ 20, 77, 14, 15, 13}
font.glyphs[89]={ 34, 77, 13, 15, 12}
font.glyphs[90]={ 47, 77, 12, 15, 13}
font.glyphs[91]={ 59, 76, 5, 19, 8}
font.glyphs[92]={ 64, 77, 8, 17, 6}
font.glyphs[93]={ 72, 76, 6, 19, 7}
font.glyphs[94]={ 78, 77, 14, 7, 16}
font.glyphs[95]={ 92, 94, 11, 3, 10}
font.glyphs[96]={ 103, 75, 6, 5, 9}
font.glyphs[97]={ 109, 80, 10, 12, 11}
font.glyphs[98]={ 119, 76, 10, 16, 12}
font.glyphs[99]={ 129, 80, 9, 12, 10}
font.glyphs[100]={ 1, 97, 10, 16, 12}
font.glyphs[101]={ 11, 101, 11, 12, 12}
font.glyphs[102]={ 22, 97, 8, 16, 7}
font.glyphs[103]={ 30, 101, 10, 16, 12}
font.glyphs[104]={ 40, 97, 10, 16, 12}
font.glyphs[105]={ 50, 97, 3, 16, 6}
font.glyphs[106]={ 53, 97, 5, 20, 6}
font.glyphs[107]={ 58, 97, 11, 16, 11}
font.glyphs[108]={ 69, 97, 3, 16, 6}
font.glyphs[109]={ 72, 101, 16, 12, 18}
font.glyphs[110]={ 88, 101, 10, 12, 12}
font.glyphs[111]={ 98, 101, 10, 12, 11}
font.glyphs[112]={ 108, 101, 10, 16, 12}
font.glyphs[113]={ 118, 101, 10, 16, 12}
font.glyphs[114]={ 128, 101, 7, 12, 8}
font.glyphs[115]={ 1, 121, 9, 12, 10}
font.glyphs[116]={ 10, 118, 7, 15, 8}
font.glyphs[117]={ 17, 120, 10, 13, 12}
font.glyphs[118]={ 27, 121, 12, 12, 11}
font.glyphs[119]={ 39, 121, 16, 12, 15}
font.glyphs[120]={ 55, 121, 12, 12, 11}
font.glyphs[121]={ 67, 121, 12, 16, 11}
font.glyphs[122]={ 79, 121, 9, 12, 10}
font.glyphs[123]={ 88, 117, 9, 20, 12}
font.glyphs[124]={ 97, 117, 3, 21, 6}
font.glyphs[125]={ 100, 117, 9, 20, 12}
font.glyphs[126]={ 109, 123, 13, 6, 15}
font.kerning[45]={ left=66, k=-1 }
font.kerning[45]={ left=71, k=1 }
font.kerning[45]={ left=74, k=1 }
font.kerning[45]={ left=81, k=1 }
font.kerning[45]={ left=84, k=-1 }
font.kerning[45]={ left=86, k=-1 }
font.kerning[45]={ left=87, k=-1 }
font.kerning[45]={ left=88, k=-1 }
font.kerning[45]={ left=89, k=-2 }
font.kerning[65]={ left=84, k=-1 }
font.kerning[65]={ left=86, k=-1 }
font.kerning[65]={ left=87, k=-1 }
font.kerning[65]={ left=89, k=-1 }
font.kerning[65]={ left=102, k=-1 }
font.kerning[65]={ left=118, k=-1 }
font.kerning[65]={ left=119, k=-1 }
font.kerning[65]={ left=121, k=-1 }
font.kerning[66]={ left=87, k=-1 }
font.kerning[66]={ left=89, k=-1 }
font.kerning[68]={ left=89, k=-1 }
font.kerning[70]={ left=46, k=-2 }
font.kerning[70]={ left=58, k=-1 }
font.kerning[70]={ left=65, k=-1 }
font.kerning[70]={ left=97, k=-1 }
font.kerning[70]={ left=101, k=-1 }
font.kerning[70]={ left=105, k=-1 }
font.kerning[70]={ left=111, k=-1 }
font.kerning[70]={ left=114, k=-1 }
font.kerning[70]={ left=117, k=-1 }
font.kerning[70]={ left=121, k=-1 }
font.kerning[71]={ left=84, k=-1 }
font.kerning[71]={ left=89, k=-1 }
font.kerning[74]={ left=45, k=-1 }
font.kerning[75]={ left=45, k=-1 }
font.kerning[75]={ left=67, k=-1 }
font.kerning[75]={ left=79, k=-1 }
font.kerning[75]={ left=84, k=-1 }
font.kerning[75]={ left=87, k=-1 }
font.kerning[75]={ left=89, k=-1 }
font.kerning[75]={ left=101, k=-1 }
font.kerning[75]={ left=111, k=-1 }
font.kerning[75]={ left=117, k=-1 }
font.kerning[75]={ left=121, k=-1 }
font.kerning[76]={ left=79, k=-1 }
font.kerning[76]={ left=84, k=-2 }
font.kerning[76]={ left=85, k=-1 }
font.kerning[76]={ left=86, k=-2 }
font.kerning[76]={ left=87, k=-1 }
font.kerning[76]={ left=89, k=-2 }
font.kerning[76]={ left=121, k=-1 }
font.kerning[79]={ left=46, k=-1 }
font.kerning[79]={ left=88, k=-1 }
font.kerning[79]={ left=89, k=-1 }
font.kerning[80]={ left=46, k=-2 }
font.kerning[80]={ left=65, k=-1 }
font.kerning[80]={ left=97, k=-1 }
font.kerning[80]={ left=101, k=-1 }
font.kerning[80]={ left=111, k=-1 }
font.kerning[82]={ left=45, k=-1 }
font.kerning[82]={ left=46, k=-1 }
font.kerning[82]={ left=65, k=-1 }
font.kerning[82]={ left=67, k=-1 }
font.kerning[82]={ left=84, k=-1 }
font.kerning[82]={ left=86, k=-1 }
font.kerning[82]={ left=87, k=-1 }
font.kerning[82]={ left=89, k=-1 }
font.kerning[82]={ left=101, k=-1 }
font.kerning[82]={ left=111, k=-1 }
font.kerning[82]={ left=117, k=-1 }
font.kerning[82]={ left=121, k=-1 }
font.kerning[84]={ left=45, k=-1 }
font.kerning[84]={ left=46, k=-2 }
font.kerning[84]={ left=58, k=-2 }
font.kerning[84]={ left=65, k=-1 }
font.kerning[84]={ left=67, k=-1 }
font.kerning[84]={ left=97, k=-2 }
font.kerning[84]={ left=99, k=-2 }
font.kerning[84]={ left=101, k=-2 }
font.kerning[84]={ left=111, k=-2 }
font.kerning[84]={ left=114, k=-2 }
font.kerning[84]={ left=115, k=-2 }
font.kerning[84]={ left=117, k=-2 }
font.kerning[84]={ left=119, k=-2 }
font.kerning[84]={ left=121, k=-2 }
font.kerning[86]={ left=45, k=-1 }
font.kerning[86]={ left=46, k=-2 }
font.kerning[86]={ left=58, k=-1 }
font.kerning[86]={ left=65, k=-1 }
font.kerning[86]={ left=97, k=-1 }
font.kerning[86]={ left=101, k=-1 }
font.kerning[86]={ left=111, k=-1 }
font.kerning[86]={ left=117, k=-1 }
font.kerning[87]={ left=45, k=-1 }
font.kerning[87]={ left=46, k=-2 }
font.kerning[87]={ left=58, k=-1 }
font.kerning[87]={ left=65, k=-1 }
font.kerning[87]={ left=97, k=-1 }
font.kerning[87]={ left=101, k=-1 }
font.kerning[87]={ left=111, k=-1 }
font.kerning[87]={ left=114, k=-1 }
font.kerning[87]={ left=117, k=-1 }
font.kerning[88]={ left=45, k=-1 }
font.kerning[88]={ left=67, k=-1 }
font.kerning[88]={ left=79, k=-1 }
font.kerning[88]={ left=101, k=-1 }
font.kerning[89]={ left=45, k=-2 }
font.kerning[89]={ left=46, k=-3 }
font.kerning[89]={ left=58, k=-2 }
font.kerning[89]={ left=65, k=-1 }
font.kerning[89]={ left=67, k=-1 }
font.kerning[89]={ left=79, k=-1 }
font.kerning[89]={ left=97, k=-2 }
font.kerning[89]={ left=101, k=-2 }
font.kerning[89]={ left=105, k=-1 }
font.kerning[89]={ left=111, k=-2 }
font.kerning[89]={ left=117, k=-2 }
font.kerning[102]={ left=45, k=-1 }
font.kerning[102]={ left=46, k=-1 }
font.kerning[102]={ left=58, k=-1 }
font.kerning[107]={ left=101, k=-1 }
font.kerning[107]={ left=111, k=-1 }
font.kerning[107]={ left=121, k=-1 }
font.kerning[114]={ left=45, k=-1 }
font.kerning[114]={ left=46, k=-1 }
font.kerning[118]={ left=46, k=-1 }
font.kerning[118]={ left=58, k=-1 }
font.kerning[119]={ left=46, k=-1 }
font.kerning[119]={ left=58, k=-1 }
font.kerning[121]={ left=46, k=-2 }
font.kerning[121]={ left=58, k=-1 }
font.verticalOffset[33]=4
font.verticalOffset[34]=4
font.verticalOffset[35]=4
font.verticalOffset[36]=3
font.verticalOffset[37]=4
font.verticalOffset[38]=4
font.verticalOffset[39]=4
font.verticalOffset[40]=3
font.verticalOffset[41]=3
font.verticalOffset[42]=4
font.verticalOffset[43]=6
font.verticalOffset[44]=15
font.verticalOffset[45]=11
font.verticalOffset[46]=15
font.verticalOffset[47]=4
font.verticalOffset[48]=4
font.verticalOffset[49]=4
font.verticalOffset[50]=4
font.verticalOffset[51]=4
font.verticalOffset[52]=4
font.verticalOffset[53]=4
font.verticalOffset[54]=4
font.verticalOffset[55]=4
font.verticalOffset[56]=4
font.verticalOffset[57]=4
font.verticalOffset[58]=8
font.verticalOffset[59]=7
font.verticalOffset[60]=6
font.verticalOffset[61]=9
font.verticalOffset[62]=6
font.verticalOffset[63]=4
font.verticalOffset[64]=3
font.verticalOffset[65]=4
font.verticalOffset[66]=4
font.verticalOffset[67]=4
font.verticalOffset[68]=4
font.verticalOffset[69]=4
font.verticalOffset[70]=4
font.verticalOffset[71]=4
font.verticalOffset[72]=4
font.verticalOffset[73]=4
font.verticalOffset[74]=4
font.verticalOffset[75]=4
font.verticalOffset[76]=4
font.verticalOffset[77]=4
font.verticalOffset[78]=4
font.verticalOffset[79]=4
font.verticalOffset[80]=4
font.verticalOffset[81]=4
font.verticalOffset[82]=4
font.verticalOffset[83]=4
font.verticalOffset[84]=4
font.verticalOffset[85]=4
font.verticalOffset[86]=4
font.verticalOffset[87]=4
font.verticalOffset[88]=4
font.verticalOffset[89]=4
font.verticalOffset[90]=4
font.verticalOffset[91]=3
font.verticalOffset[92]=4
font.verticalOffset[93]=3
font.verticalOffset[94]=4
font.verticalOffset[95]=21
font.verticalOffset[96]=2
font.verticalOffset[97]=7
font.verticalOffset[98]=3
font.verticalOffset[99]=7
font.verticalOffset[100]=3
font.verticalOffset[101]=7
font.verticalOffset[102]=3
font.verticalOffset[103]=7
font.verticalOffset[104]=3
font.verticalOffset[105]=3
font.verticalOffset[106]=3
font.verticalOffset[107]=3
font.verticalOffset[108]=3
font.verticalOffset[109]=7
font.verticalOffset[110]=7
font.verticalOffset[111]=7
font.verticalOffset[112]=7
font.verticalOffset[113]=7
font.verticalOffset[114]=7
font.verticalOffset[115]=7
font.verticalOffset[116]=4
font.verticalOffset[117]=6
font.verticalOffset[118]=7
font.verticalOffset[119]=7
font.verticalOffset[120]=7
font.verticalOffset[121]=7
font.verticalOffset[122]=7
font.verticalOffset[123]=3
font.verticalOffset[124]=3
font.verticalOffset[125]=3
font.verticalOffset[126]=9
| mit |
Zephruz/citadelshock | entities/entities/cis_basestructure/init.lua | 1 | 2058 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self:Activate()
self:SetModel(self.StructureMdl)
self:SetUseType(SIMPLE_USE)
self:SetCollisionGroup( COLLISION_GROUP_NONE )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
local phys = self:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
phys:EnableMotion(false)
end
end
function ENT:OnTakeDamage(dmg)
local atter = dmg:GetAttacker()
local dmgAmt = dmg:GetDamage()
if (atter:IsPlayer() && atter:GetSide() == self:GetIDSide()) then return false end
if (self:Health() - dmgAmt > 0) then
self:SetHealth(self:Health() - dmgAmt)
else
self:SetHealth(0)
local phys = self:GetPhysicsObject()
phys:EnableMotion(true)
phys:AddVelocity(Vector(0,0,2))
timer.Simple(math.random(2,3),
function()
if not (IsValid(self)) then return false end
self:Remove()
end)
end
end
ENT.NextRepair = os.time()+1
function ENT:Use(act, cal, t, val)
if (self.NextRepair > os.time()) then return false end
self.NextRepair = os.time()+1
if !(self.costs) then return false end
local lobby = CitadelShock.Lobby:FindByID(self:GetIDLobby())
if (!lobby or !self:GetIDSide()) then return false end
if (cal:GetIDLobby() != self:GetIDLobby() or cal:GetSide() != self:GetIDSide()) then cal:SendMessage("You can't repair this!") return false end
if (self:Health() >= self.BaseHealth) then cal:SendMessage("This structure is already at full health!") return false end
local lobbySides = lobby:GetGameSides()
local res = lobbySides[self:GetIDSide()].resources
for k,v in pairs(self.costs) do
if (res[k] && res[k] >= 10) then
lobby:GiveResource(k,-10,self:GetIDLobby())
self:SetHealth(self:Health() + 10)
cal:SendMessage("Repaired structure (10 HP)!")
else
cal:SendMessage("You need 10 " .. k .. " to repair this!")
end
end
end | mit |
alastair-robertson/awesome | lib/awful/util.lua | 3 | 17974 | ---------------------------------------------------------------------------
--- Utility module for awful
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008 Julien Danjou
-- @release @AWESOME_VERSION@
-- @module awful.util
---------------------------------------------------------------------------
-- Grab environment we need
local os = os
local io = io
local assert = assert
local load = loadstring or load -- luacheck: globals loadstring (compatibility with Lua 5.1)
local loadfile = loadfile
local debug = debug
local pairs = pairs
local ipairs = ipairs
local type = type
local rtable = table
local string = string
local lgi = require("lgi")
local grect = require("gears.geometry").rectangle
local Gio = require("lgi").Gio
local Pango = lgi.Pango
local capi =
{
awesome = awesome,
mouse = mouse
}
local gears_debug = require("gears.debug")
local floor = math.floor
local util = {}
util.table = {}
util.shell = os.getenv("SHELL") or "/bin/sh"
local displayed_deprecations = {}
--- Display a deprecation notice, but only once per traceback.
-- @param[opt] see The message to a new method / function to use.
function util.deprecate(see)
local tb = debug.traceback()
if displayed_deprecations[tb] then
return
end
displayed_deprecations[tb] = true
-- Get function name/desc from caller.
local info = debug.getinfo(2, "n")
local funcname = info.name or "?"
local msg = "awful: function " .. funcname .. " is deprecated"
if see then
if string.sub(see, 1, 3) == 'Use' then
msg = msg .. ". " .. see
else
msg = msg .. ", see " .. see
end
end
gears_debug.print_warning(msg .. ".\n" .. tb)
end
--- Create a class proxy with deprecation messages.
-- This is useful when a class has moved somewhere else.
-- @tparam table fallback The new class
-- @tparam string old_name The old class name
-- @tparam string new_name The new class name
-- @treturn table A proxy class.
function util.deprecate_class(fallback, old_name, new_name)
local message = old_name.." has been renamed to "..new_name
local function call(_,...)
util.deprecate(message)
return fallback(...)
end
local function index(_, k)
util.deprecate(message)
return fallback[k]
end
local function newindex(_, k, v)
util.deprecate(message)
fallback[k] = v
end
return setmetatable({}, {__call = call, __index = index, __newindex = newindex})
end
--- Get a valid color for Pango markup
-- @param color The color.
-- @tparam string fallback The color to return if the first is invalid. (default: black)
-- @treturn string color if it is valid, else fallback.
function util.ensure_pango_color(color, fallback)
color = tostring(color)
return Pango.Color.parse(Pango.Color(), color) and color or fallback or "black"
end
--- Make i cycle.
-- @param t A length. Must be greater than zero.
-- @param i An absolute index to fit into #t.
-- @return An integer in (1, t) or nil if t is less than or equal to zero.
function util.cycle(t, i)
if t < 1 then return end
i = i % t
if i == 0 then
i = t
end
return i
end
--- Create a directory
-- @param dir The directory.
-- @return mkdir return code
function util.mkdir(dir)
return os.execute("mkdir -p " .. dir)
end
--- Eval Lua code.
-- @return The return value of Lua code.
function util.eval(s)
return assert(load(s))()
end
local xml_entity_names = { ["'"] = "'", ["\""] = """, ["<"] = "<", [">"] = ">", ["&"] = "&" };
--- Escape a string from XML char.
-- Useful to set raw text in textbox.
-- @param text Text to escape.
-- @return Escape text.
function util.escape(text)
return text and text:gsub("['&<>\"]", xml_entity_names) or nil
end
local xml_entity_chars = { lt = "<", gt = ">", nbsp = " ", quot = "\"", apos = "'", ndash = "-", mdash = "-", amp = "&" };
--- Unescape a string from entities.
-- @param text Text to unescape.
-- @return Unescaped text.
function util.unescape(text)
return text and text:gsub("&(%a+);", xml_entity_chars) or nil
end
--- Check if a file is a Lua valid file.
-- This is done by loading the content and compiling it with loadfile().
-- @param path The file path.
-- @return A function if everything is alright, a string with the error
-- otherwise.
function util.checkfile(path)
local f, e = loadfile(path)
-- Return function if function, otherwise return error.
if f then return f end
return e
end
--- Try to restart awesome.
-- It checks if the configuration file is valid, and then restart if it's ok.
-- If it's not ok, the error will be returned.
-- @return Never return if awesome restart, or return a string error.
function util.restart()
local c = util.checkfile(capi.awesome.conffile)
if type(c) ~= "function" then
return c
end
capi.awesome.restart()
end
--- Get the config home according to the XDG basedir specification.
-- @return the config home (XDG_CONFIG_HOME) with a slash at the end.
function util.get_xdg_config_home()
return (os.getenv("XDG_CONFIG_HOME") or os.getenv("HOME") .. "/.config") .. "/"
end
--- Get the cache home according to the XDG basedir specification.
-- @return the cache home (XDG_CACHE_HOME) with a slash at the end.
function util.get_xdg_cache_home()
return (os.getenv("XDG_CACHE_HOME") or os.getenv("HOME") .. "/.cache") .. "/"
end
--- Get the path to the user's config dir.
-- This is the directory containing the configuration file ("rc.lua").
-- @return A string with the requested path with a slash at the end.
function util.get_configuration_dir()
return capi.awesome.conffile:match(".*/") or "./"
end
--- Get the path to a directory that should be used for caching data.
-- @return A string with the requested path with a slash at the end.
function util.get_cache_dir()
return util.get_xdg_cache_home() .. "awesome/"
end
--- Get the path to the directory where themes are installed.
-- @return A string with the requested path with a slash at the end.
function util.get_themes_dir()
return "@AWESOME_THEMES_PATH@" .. "/"
end
--- Get the path to the directory where our icons are installed.
-- @return A string with the requested path with a slash at the end.
function util.get_awesome_icon_dir()
return "@AWESOME_ICON_PATH@" .. "/"
end
--- Get the user's config or cache dir.
-- It first checks XDG_CONFIG_HOME / XDG_CACHE_HOME, but then goes with the
-- default paths.
-- @param d The directory to get (either "config" or "cache").
-- @return A string containing the requested path.
function util.getdir(d)
if d == "config" then
-- No idea why this is what is returned, I recommend everyone to use
-- get_configuration_dir() instead
return util.get_xdg_config_home() .. "awesome/"
elseif d == "cache" then
return util.get_cache_dir()
end
end
--- Search for an icon and return the full path.
-- It searches for the icon path under the given directories with respect to the
-- given extensions for the icon filename.
-- @param iconname The name of the icon to search for.
-- @param exts Table of image extensions allowed, otherwise { 'png', gif' }
-- @param dirs Table of dirs to search, otherwise { '/usr/share/pixmaps/' }
-- @tparam[opt] string size The size. If this is specified, subdirectories `x`
-- of the dirs are searched first.
function util.geticonpath(iconname, exts, dirs, size)
exts = exts or { 'png', 'gif' }
dirs = dirs or { '/usr/share/pixmaps/', '/usr/share/icons/hicolor/' }
local icontypes = { 'apps', 'actions', 'categories', 'emblems',
'mimetypes', 'status', 'devices', 'extras', 'places', 'stock' }
for _, d in pairs(dirs) do
local icon
for _, e in pairs(exts) do
icon = d .. iconname .. '.' .. e
if util.file_readable(icon) then
return icon
end
if size then
for _, t in pairs(icontypes) do
icon = string.format("%s%ux%u/%s/%s.%s", d, size, size, t, iconname, e)
if util.file_readable(icon) then
return icon
end
end
end
end
end
end
--- Check if a file exists, is not readable and not a directory.
-- @param filename The file path.
-- @return True if file exists and is readable.
function util.file_readable(filename)
local file = io.open(filename)
if file then
local _, _, code = file:read(1)
io.close(file)
if code == 21 then
-- "Is a directory".
return false
end
return true
end
return false
end
--- Check if a path exists, is readable and is a directory.
-- @tparam string path The directory path.
-- @treturn boolean True if dir exists and is readable.
function util.dir_readable(path)
local gfile = Gio.File.new_for_path(path)
local gfileinfo = gfile:query_info("standard::type,access::can-read",
Gio.FileQueryInfoFlags.NONE)
return gfileinfo and gfileinfo:get_file_type() == "DIRECTORY" and
gfileinfo:get_attribute_boolean("access::can-read")
end
--- Check if a path is a directory.
-- @tparam string path
-- @treturn bool True if path exists and is a directory.
function util.is_dir(path)
return Gio.File.new_for_path(path):query_file_type({}) == "DIRECTORY"
end
local function subset_mask_apply(mask, set)
local ret = {}
for i = 1, #set do
if mask[i] then
rtable.insert(ret, set[i])
end
end
return ret
end
local function subset_next(mask)
local i = 1
while i <= #mask and mask[i] do
mask[i] = false
i = i + 1
end
if i <= #mask then
mask[i] = 1
return true
end
return false
end
--- Return all subsets of a specific set.
-- This function, giving a set, will return all subset it.
-- For example, if we consider a set with value { 10, 15, 34 },
-- it will return a table containing 2^n set:
-- { }, { 10 }, { 15 }, { 34 }, { 10, 15 }, { 10, 34 }, etc.
-- @param set A set.
-- @return A table with all subset.
function util.subsets(set)
local mask = {}
local ret = {}
for i = 1, #set do mask[i] = false end
-- Insert the empty one
rtable.insert(ret, {})
while subset_next(mask) do
rtable.insert(ret, subset_mask_apply(mask, set))
end
return ret
end
--- Get the nearest rectangle in the given direction. Every rectangle is specified as a table
-- with 'x', 'y', 'width', 'height' keys, the same as client or screen geometries.
-- @deprecated awful.util.get_rectangle_in_direction
-- @param dir The direction, can be either "up", "down", "left" or "right".
-- @param recttbl A table of rectangle specifications.
-- @param cur The current rectangle.
-- @return The index for the rectangle in recttbl closer to cur in the given direction. nil if none found.
-- @see gears.geometry
function util.get_rectangle_in_direction(dir, recttbl, cur)
util.deprecate("gears.geometry.rectangle.get_in_direction")
return grect.get_in_direction(dir, recttbl, cur)
end
--- Join all tables given as parameters.
-- This will iterate all tables and insert all their keys into a new table.
-- @param args A list of tables to join
-- @return A new table containing all keys from the arguments.
function util.table.join(...)
local ret = {}
for _, t in pairs({...}) do
if t then
for k, v in pairs(t) do
if type(k) == "number" then
rtable.insert(ret, v)
else
ret[k] = v
end
end
end
end
return ret
end
--- Override elements in the first table by the one in the second.
--
-- Note that this method doesn't copy entries found in `__index`.
-- @tparam table t the table to be overriden
-- @tparam table set the table used to override members of `t`
-- @tparam[opt=false] boolean raw Use rawset (avoid the metatable)
-- @treturn table t (for convenience)
function util.table.crush(t, set, raw)
if raw then
for k, v in pairs(set) do
rawset(t, k, v)
end
else
for k, v in pairs(set) do
t[k] = v
end
end
return t
end
--- Pack all elements with an integer key into a new table
-- While both lua and luajit implement __len over sparse
-- table, the standard define it as an implementation
-- detail.
--
-- This function remove any non numeric keys from the value set
--
-- @tparam table t A potentially sparse table
-- @treturn table A packed table with all numeric keys
function util.table.from_sparse(t)
local keys= {}
for k in pairs(t) do
if type(k) == "number" then
keys[#keys+1] = k
end
end
table.sort(keys)
local ret = {}
for _,v in ipairs(keys) do
ret[#ret+1] = t[v]
end
return ret
end
--- Check if a table has an item and return its key.
-- @param t The table.
-- @param item The item to look for in values of the table.
-- @return The key were the item is found, or nil if not found.
function util.table.hasitem(t, item)
for k, v in pairs(t) do
if v == item then
return k
end
end
end
--- Split a string into multiple lines
-- @param text String to wrap.
-- @param width Maximum length of each line. Default: 72.
-- @param indent Number of spaces added before each wrapped line. Default: 0.
-- @return The string with lines wrapped to width.
function util.linewrap(text, width, indent)
text = text or ""
width = width or 72
indent = indent or 0
local pos = 1
return text:gsub("(%s+)()(%S+)()",
function(_, st, word, fi)
if fi - pos > width then
pos = st
return "\n" .. string.rep(" ", indent) .. word
end
end)
end
--- Count number of lines in a string
-- @tparam string text Input string.
-- @treturn int Number of lines.
function util.linecount(text)
return select(2, text:gsub('\n', '\n')) + 1
end
--- Get a sorted table with all integer keys from a table
-- @param t the table for which the keys to get
-- @return A table with keys
function util.table.keys(t)
local keys = { }
for k, _ in pairs(t) do
rtable.insert(keys, k)
end
rtable.sort(keys, function (a, b)
return type(a) == type(b) and a < b or false
end)
return keys
end
--- Filter a tables keys for certain content types
-- @param t The table to retrieve the keys for
-- @param ... the types to look for
-- @return A filtered table with keys
function util.table.keys_filter(t, ...)
local keys = util.table.keys(t)
local keys_filtered = { }
for _, k in pairs(keys) do
for _, et in pairs({...}) do
if type(t[k]) == et then
rtable.insert(keys_filtered, k)
break
end
end
end
return keys_filtered
end
--- Reverse a table
-- @param t the table to reverse
-- @return the reversed table
function util.table.reverse(t)
local tr = { }
-- reverse all elements with integer keys
for _, v in ipairs(t) do
rtable.insert(tr, 1, v)
end
-- add the remaining elements
for k, v in pairs(t) do
if type(k) ~= "number" then
tr[k] = v
end
end
return tr
end
--- Clone a table
-- @param t the table to clone
-- @param deep Create a deep clone? (default: true)
-- @return a clone of t
function util.table.clone(t, deep)
deep = deep == nil and true or deep
local c = { }
for k, v in pairs(t) do
if deep and type(v) == "table" then
c[k] = util.table.clone(v)
else
c[k] = v
end
end
return c
end
---
-- Returns an iterator to cycle through, starting from the first element or the
-- given index, all elements of a table that match a given criteria.
--
-- @param t the table to iterate
-- @param filter a function that returns true to indicate a positive match
-- @param start what index to start iterating from. Default is 1 (=> start of
-- the table)
function util.table.iterate(t, filter, start)
local count = 0
local index = start or 1
local length = #t
return function ()
while count < length do
local item = t[index]
index = util.cycle(#t, index + 1)
count = count + 1
if filter(item) then return item end
end
end
end
--- Merge items from the one table to another one
-- @tparam table t the container table
-- @tparam table set the mixin table
-- @treturn table Return `t` for convenience
function util.table.merge(t, set)
for _, v in ipairs(set) do
table.insert(t, v)
end
return t
end
-- Escape all special pattern-matching characters so that lua interprets them
-- literally instead of as a character class.
-- Source: http://stackoverflow.com/a/20778724/15690
function util.quote_pattern(s)
-- All special characters escaped in a string: %%, %^, %$, ...
local patternchars = '['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..']'
return string.gsub(s, patternchars, "%%%1")
end
-- Generate a pattern matching expression that ignores case.
-- @param s Original pattern matching expression.
function util.query_to_pattern(q)
local s = util.quote_pattern(q)
-- Poor man's case-insensitive character matching.
s = string.gsub(s, "%a",
function (c)
return string.format("[%s%s]", string.lower(c),
string.upper(c))
end)
return s
end
--- Round a number to an integer.
-- @tparam number x
-- @treturn integer
function util.round(x)
return floor(x + 0.5)
end
return util
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
youprofit/h2o | deps/klib/lua/klib.lua | 42 | 20155 | --[[
The MIT License
Copyright (c) 2011, Attractive Chaos <attractor@live.co.uk>
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.
]]--
--[[
This is a Lua library, more exactly a collection of Lua snippets, covering
utilities (e.g. getopt), string operations (e.g. split), statistics (e.g.
Fisher's exact test), special functions (e.g. logarithm gamma) and matrix
operations (e.g. Gauss-Jordan elimination). The routines are designed to be
as independent as possible, such that one can copy-paste relevant pieces of
code without worrying about additional library dependencies.
If you use routines from this library, please include the licensing
information above where appropriate.
]]--
--[[
Library functions and dependencies. "a>b" means "a is required by b"; "b<a"
means "b depends on a".
os.getopt()
string:split()
io.xopen()
table.ksmall()
table.shuffle()
math.lgamma() >math.lbinom() >math.igamma()
math.igamma() <math.lgamma() >matrix.chi2()
math.erfc()
math.lbinom() <math.lgamma() >math.fisher_exact()
math.bernstein_poly() <math.lbinom()
math.fisher_exact() <math.lbinom()
math.jackknife()
math.pearson()
math.spearman()
math.fmin()
matrix
matrix.add()
matrix.T() >matrix.mul()
matrix.mul() <matrix.T()
matrix.tostring()
matrix.chi2() <math.igamma()
matrix.solve()
]]--
-- Description: getopt() translated from the BSD getopt(); compatible with the default Unix getopt()
--[[ Example:
for o, a in os.getopt(arg, 'a:b') do
print(o, a)
end
]]--
function os.getopt(args, ostr)
local arg, place = nil, 0;
return function ()
if place == 0 then -- update scanning pointer
place = 1
if #args == 0 or args[1]:sub(1, 1) ~= '-' then place = 0; return nil end
if #args[1] >= 2 then
place = place + 1
if args[1]:sub(2, 2) == '-' then -- found "--"
place = 0
table.remove(args, 1);
return nil;
end
end
end
local optopt = args[1]:sub(place, place);
place = place + 1;
local oli = ostr:find(optopt);
if optopt == ':' or oli == nil then -- unknown option
if optopt == '-' then return nil end
if place > #args[1] then
table.remove(args, 1);
place = 0;
end
return '?';
end
oli = oli + 1;
if ostr:sub(oli, oli) ~= ':' then -- do not need argument
arg = nil;
if place > #args[1] then
table.remove(args, 1);
place = 0;
end
else -- need an argument
if place <= #args[1] then -- no white space
arg = args[1]:sub(place);
else
table.remove(args, 1);
if #args == 0 then -- an option requiring argument is the last one
place = 0;
if ostr:sub(1, 1) == ':' then return ':' end
return '?';
else arg = args[1] end
end
table.remove(args, 1);
place = 0;
end
return optopt, arg;
end
end
-- Description: string split
function string:split(sep, n)
local a, start = {}, 1;
sep = sep or "%s+";
repeat
local b, e = self:find(sep, start);
if b == nil then
table.insert(a, self:sub(start));
break
end
a[#a+1] = self:sub(start, b - 1);
start = e + 1;
if n and #a == n then
table.insert(a, self:sub(start));
break
end
until start > #self;
return a;
end
-- Description: smart file open
function io.xopen(fn, mode)
mode = mode or 'r';
if fn == nil then return io.stdin;
elseif fn == '-' then return (mode == 'r' and io.stdin) or io.stdout;
elseif fn:sub(-3) == '.gz' then return (mode == 'r' and io.popen('gzip -dc ' .. fn, 'r')) or io.popen('gzip > ' .. fn, 'w');
elseif fn:sub(-4) == '.bz2' then return (mode == 'r' and io.popen('bzip2 -dc ' .. fn, 'r')) or io.popen('bgzip2 > ' .. fn, 'w');
else return io.open(fn, mode) end
end
-- Description: find the k-th smallest element in an array (Ref. http://ndevilla.free.fr/median/)
function table.ksmall(arr, k)
local low, high = 1, #arr;
while true do
if high <= low then return arr[k] end
if high == low + 1 then
if arr[high] < arr[low] then arr[high], arr[low] = arr[low], arr[high] end;
return arr[k];
end
local mid = math.floor((high + low) / 2);
if arr[high] < arr[mid] then arr[mid], arr[high] = arr[high], arr[mid] end
if arr[high] < arr[low] then arr[low], arr[high] = arr[high], arr[low] end
if arr[low] < arr[mid] then arr[low], arr[mid] = arr[mid], arr[low] end
arr[mid], arr[low+1] = arr[low+1], arr[mid];
local ll, hh = low + 1, high;
while true do
repeat ll = ll + 1 until arr[ll] >= arr[low]
repeat hh = hh - 1 until arr[low] >= arr[hh]
if hh < ll then break end
arr[ll], arr[hh] = arr[hh], arr[ll];
end
arr[low], arr[hh] = arr[hh], arr[low];
if hh <= k then low = ll end
if hh >= k then high = hh - 1 end
end
end
-- Description: shuffle/permutate an array
function table.shuffle(a)
for i = #a, 1, -1 do
local j = math.random(i)
a[j], a[i] = a[i], a[j]
end
end
--
-- Mathematics
--
-- Description: log gamma function
-- Required by: math.lbinom()
-- Reference: AS245, 2nd algorithm, http://lib.stat.cmu.edu/apstat/245
function math.lgamma(z)
local x;
x = 0.1659470187408462e-06 / (z+7);
x = x + 0.9934937113930748e-05 / (z+6);
x = x - 0.1385710331296526 / (z+5);
x = x + 12.50734324009056 / (z+4);
x = x - 176.6150291498386 / (z+3);
x = x + 771.3234287757674 / (z+2);
x = x - 1259.139216722289 / (z+1);
x = x + 676.5203681218835 / z;
x = x + 0.9999999999995183;
return math.log(x) - 5.58106146679532777 - z + (z-0.5) * math.log(z+6.5);
end
-- Description: regularized incomplete gamma function
-- Dependent on: math.lgamma()
--[[
Formulas are taken from Wiki, with additional input from Numerical
Recipes in C (for modified Lentz's algorithm) and AS245
(http://lib.stat.cmu.edu/apstat/245).
A good online calculator is available at:
http://www.danielsoper.com/statcalc/calc23.aspx
It calculates upper incomplete gamma function, which equals
math.igamma(s,z,true)*math.exp(math.lgamma(s))
]]--
function math.igamma(s, z, complement)
local function _kf_gammap(s, z)
local sum, x = 1, 1;
for k = 1, 100 do
x = x * z / (s + k);
sum = sum + x;
if x / sum < 1e-14 then break end
end
return math.exp(s * math.log(z) - z - math.lgamma(s + 1.) + math.log(sum));
end
local function _kf_gammaq(s, z)
local C, D, f, TINY;
f = 1. + z - s; C = f; D = 0.; TINY = 1e-290;
-- Modified Lentz's algorithm for computing continued fraction. See Numerical Recipes in C, 2nd edition, section 5.2
for j = 1, 100 do
local d;
local a, b = j * (s - j), j*2 + 1 + z - s;
D = b + a * D;
if D < TINY then D = TINY end
C = b + a / C;
if C < TINY then C = TINY end
D = 1. / D;
d = C * D;
f = f * d;
if math.abs(d - 1) < 1e-14 then break end
end
return math.exp(s * math.log(z) - z - math.lgamma(s) - math.log(f));
end
if complement then
return ((z <= 1 or z < s) and 1 - _kf_gammap(s, z)) or _kf_gammaq(s, z);
else
return ((z <= 1 or z < s) and _kf_gammap(s, z)) or (1 - _kf_gammaq(s, z));
end
end
math.M_SQRT2 = 1.41421356237309504880 -- sqrt(2)
math.M_SQRT1_2 = 0.70710678118654752440 -- 1/sqrt(2)
-- Description: complement error function erfc(x): \Phi(x) = 0.5 * erfc(-x/M_SQRT2)
function math.erfc(x)
local z = math.abs(x) * math.M_SQRT2
if z > 37 then return (x > 0 and 0) or 2 end
local expntl = math.exp(-0.5 * z * z)
local p
if z < 10. / math.M_SQRT2 then -- for small z
p = expntl * ((((((.03526249659989109 * z + .7003830644436881) * z + 6.37396220353165) * z + 33.912866078383)
* z + 112.0792914978709) * z + 221.2135961699311) * z + 220.2068679123761)
/ (((((((.08838834764831844 * z + 1.755667163182642) * z + 16.06417757920695) * z + 86.78073220294608)
* z + 296.5642487796737) * z + 637.3336333788311) * z + 793.8265125199484) * z + 440.4137358247522);
else p = expntl / 2.506628274631001 / (z + 1. / (z + 2. / (z + 3. / (z + 4. / (z + .65))))) end
return (x > 0 and 2 * p) or 2 * (1 - p)
end
-- Description: log binomial coefficient
-- Dependent on: math.lgamma()
-- Required by: math.fisher_exact()
function math.lbinom(n, m)
if m == nil then
local a = {};
a[0], a[n] = 0, 0;
local t = math.lgamma(n+1);
for m = 1, n-1 do a[m] = t - math.lgamma(m+1) - math.lgamma(n-m+1) end
return a;
else return math.lgamma(n+1) - math.lgamma(m+1) - math.lgamma(n-m+1) end
end
-- Description: Berstein polynomials (mainly for Bezier curves)
-- Dependent on: math.lbinom()
-- Note: to compute derivative: let beta_new[i]=beta[i+1]-beta[i]
function math.bernstein_poly(beta)
local n = #beta - 1;
local lbc = math.lbinom(n); -- log binomial coefficients
return function (t)
assert(t >= 0 and t <= 1);
if t == 0 then return beta[1] end
if t == 1 then return beta[n+1] end
local sum, logt, logt1 = 0, math.log(t), math.log(1-t);
for i = 0, n do sum = sum + beta[i+1] * math.exp(lbc[i] + i * logt + (n-i) * logt1) end
return sum;
end
end
-- Description: Fisher's exact test
-- Dependent on: math.lbinom()
-- Return: left-, right- and two-tail P-values
--[[
Fisher's exact test for 2x2 congintency tables:
n11 n12 | n1_
n21 n22 | n2_
-----------+----
n_1 n_2 | n
Reference: http://www.langsrud.com/fisher.htm
]]--
function math.fisher_exact(n11, n12, n21, n22)
local aux; -- keep the states of n* for acceleration
-- Description: hypergeometric function
local function hypergeo(n11, n1_, n_1, n)
return math.exp(math.lbinom(n1_, n11) + math.lbinom(n-n1_, n_1-n11) - math.lbinom(n, n_1));
end
-- Description: incremental hypergeometric function
-- Note: aux = {n11, n1_, n_1, n, p}
local function hypergeo_inc(n11, n1_, n_1, n)
if n1_ ~= 0 or n_1 ~= 0 or n ~= 0 then
aux = {n11, n1_, n_1, n, 1};
else -- then only n11 is changed
local mod;
_, mod = math.modf(n11 / 11);
if mod ~= 0 and n11 + aux[4] - aux[2] - aux[3] ~= 0 then
if n11 == aux[1] + 1 then -- increase by 1
aux[5] = aux[5] * (aux[2] - aux[1]) / n11 * (aux[3] - aux[1]) / (n11 + aux[4] - aux[2] - aux[3]);
aux[1] = n11;
return aux[5];
end
if n11 == aux[1] - 1 then -- descrease by 1
aux[5] = aux[5] * aux[1] / (aux[2] - n11) * (aux[1] + aux[4] - aux[2] - aux[3]) / (aux[3] - n11);
aux[1] = n11;
return aux[5];
end
end
aux[1] = n11;
end
aux[5] = hypergeo(aux[1], aux[2], aux[3], aux[4]);
return aux[5];
end
-- Description: computing the P-value by Fisher's exact test
local max, min, left, right, n1_, n_1, n, two, p, q, i, j;
n1_, n_1, n = n11 + n12, n11 + n21, n11 + n12 + n21 + n22;
max = (n_1 < n1_ and n_1) or n1_; -- max n11, for the right tail
min = n1_ + n_1 - n;
if min < 0 then min = 0 end -- min n11, for the left tail
two, left, right = 1, 1, 1;
if min == max then return 1 end -- no need to do test
q = hypergeo_inc(n11, n1_, n_1, n); -- the probability of the current table
-- left tail
i, left, p = min + 1, 0, hypergeo_inc(min, 0, 0, 0);
while p < 0.99999999 * q do
left, p, i = left + p, hypergeo_inc(i, 0, 0, 0), i + 1;
end
i = i - 1;
if p < 1.00000001 * q then left = left + p;
else i = i - 1 end
-- right tail
j, right, p = max - 1, 0, hypergeo_inc(max, 0, 0, 0);
while p < 0.99999999 * q do
right, p, j = right + p, hypergeo_inc(j, 0, 0, 0), j - 1;
end
j = j + 1;
if p < 1.00000001 * q then right = right + p;
else j = j + 1 end
-- two-tail
two = left + right;
if two > 1 then two = 1 end
-- adjust left and right
if math.abs(i - n11) < math.abs(j - n11) then right = 1 - left + q;
else left = 1 - right + q end
return left, right, two;
end
-- Description: Delete-m Jackknife
--[[
Given g groups of values with a statistics estimated from m[i] samples in
i-th group being t[i], compute the mean and the variance. t0 below is the
estimate from all samples. Reference:
Busing et al. (1999) Delete-m Jackknife for unequal m. Statistics and Computing, 9:3-8.
]]--
function math.jackknife(g, m, t, t0)
local h, n, sum = {}, 0, 0;
for j = 1, g do n = n + m[j] end
if t0 == nil then -- When t0 is absent, estimate it in a naive way
t0 = 0;
for j = 1, g do t0 = t0 + m[j] * t[j] end
t0 = t0 / n;
end
local mean, var = 0, 0;
for j = 1, g do
h[j] = n / m[j];
mean = mean + (1 - m[j] / n) * t[j];
end
mean = g * t0 - mean; -- Eq. (8)
for j = 1, g do
local x = h[j] * t0 - (h[j] - 1) * t[j] - mean;
var = var + 1 / (h[j] - 1) * x * x;
end
var = var / g;
return mean, var;
end
-- Description: Pearson correlation coefficient
-- Input: a is an n*2 table
function math.pearson(a)
-- compute the mean
local x1, y1 = 0, 0
for _, v in pairs(a) do
x1, y1 = x1 + v[1], y1 + v[2]
end
-- compute the coefficient
x1, y1 = x1 / #a, y1 / #a
local x2, y2, xy = 0, 0, 0
for _, v in pairs(a) do
local tx, ty = v[1] - x1, v[2] - y1
xy, x2, y2 = xy + tx * ty, x2 + tx * tx, y2 + ty * ty
end
return xy / math.sqrt(x2) / math.sqrt(y2)
end
-- Description: Spearman correlation coefficient
function math.spearman(a)
local function aux_func(t) -- auxiliary function
return (t == 1 and 0) or (t*t - 1) * t / 12
end
for _, v in pairs(a) do v.r = {} end
local T, S = {}, {}
-- compute the rank
for k = 1, 2 do
table.sort(a, function(u,v) return u[k]<v[k] end)
local same = 1
T[k] = 0
for i = 2, #a + 1 do
if i <= #a and a[i-1][k] == a[i][k] then same = same + 1
else
local rank = (i-1) * 2 - same + 1
for j = i - same, i - 1 do a[j].r[k] = rank end
if same > 1 then T[k], same = T[k] + aux_func(same), 1 end
end
end
S[k] = aux_func(#a) - T[k]
end
-- compute the coefficient
local sum = 0
for _, v in pairs(a) do -- TODO: use nested loops to reduce loss of precision
local t = (v.r[1] - v.r[2]) / 2
sum = sum + t * t
end
return (S[1] + S[2] - sum) / 2 / math.sqrt(S[1] * S[2])
end
-- Description: Hooke-Jeeves derivative-free optimization
function math.fmin(func, x, data, r, eps, max_calls)
local n, n_calls = #x, 0;
r = r or 0.5;
eps = eps or 1e-7;
max_calls = max_calls or 50000
function fmin_aux(x1, data, fx1, dx) -- auxiliary function
local ftmp;
for k = 1, n do
x1[k] = x1[k] + dx[k];
local ftmp = func(x1, data); n_calls = n_calls + 1;
if ftmp < fx1 then fx1 = ftmp;
else -- search the opposite direction
dx[k] = -dx[k];
x1[k] = x1[k] + dx[k] + dx[k];
ftmp = func(x1, data); n_calls = n_calls + 1;
if ftmp < fx1 then fx1 = ftmp
else x1[k] = x1[k] - dx[k] end -- back to the original x[k]
end
end
return fx1; -- here: fx1=f(n,x1)
end
local dx, x1 = {}, {};
for k = 1, n do -- initial directions, based on MGJ
dx[k] = math.abs(x[k]) * r;
if dx[k] == 0 then dx[k] = r end;
end
local radius = r;
local fx1, fx;
fx = func(x, data); fx1 = fx; n_calls = n_calls + 1;
while true do
for i = 1, n do x1[i] = x[i] end; -- x1 = x
fx1 = fmin_aux(x1, data, fx, dx);
while fx1 < fx do
for k = 1, n do
local t = x[k];
dx[k] = (x1[k] > x[k] and math.abs(dx[k])) or -math.abs(dx[k]);
x[k] = x1[k];
x1[k] = x1[k] + x1[k] - t;
end
fx = fx1;
if n_calls >= max_calls then break end
fx1 = func(x1, data); n_calls = n_calls + 1;
fx1 = fmin_aux(x1, data, fx1, dx);
if fx1 >= fx then break end
local kk = n;
for k = 1, n do
if math.abs(x1[k] - x[k]) > .5 * math.abs(dx[k]) then
kk = k;
break;
end
end
if kk == n then break end
end
if radius >= eps then
if n_calls >= max_calls then break end
radius = radius * r;
for k = 1, n do dx[k] = dx[k] * r end
else break end
end
return fx1, n_calls;
end
--
-- Matrix
--
matrix = {}
-- Description: matrix transpose
-- Required by: matrix.mul()
function matrix.T(a)
local m, n, x = #a, #a[1], {};
for i = 1, n do
x[i] = {};
for j = 1, m do x[i][j] = a[j][i] end
end
return x;
end
-- Description: matrix add
function matrix.add(a, b)
assert(#a == #b and #a[1] == #b[1]);
local m, n, x = #a, #a[1], {};
for i = 1, m do
x[i] = {};
local ai, bi, xi = a[i], b[i], x[i];
for j = 1, n do xi[j] = ai[j] + bi[j] end
end
return x;
end
-- Description: matrix mul
-- Dependent on: matrix.T()
-- Note: much slower without transpose
function matrix.mul(a, b)
assert(#a[1] == #b);
local m, n, p, x = #a, #a[1], #b[1], {};
local c = matrix.T(b); -- transpose for efficiency
for i = 1, m do
x[i] = {}
local xi = x[i];
for j = 1, p do
local sum, ai, cj = 0, a[i], c[j];
for k = 1, n do sum = sum + ai[k] * cj[k] end
xi[j] = sum;
end
end
return x;
end
-- Description: matrix print
function matrix.tostring(a)
local z = {};
for i = 1, #a do
z[i] = table.concat(a[i], "\t");
end
return table.concat(z, "\n");
end
-- Description: chi^2 test for contingency tables
-- Dependent on: math.igamma()
function matrix.chi2(a)
if #a == 2 and #a[1] == 2 then -- 2x2 table
local x, z
x = (a[1][1] + a[1][2]) * (a[2][1] + a[2][2]) * (a[1][1] + a[2][1]) * (a[1][2] + a[2][2])
if x == 0 then return 0, 1, false end
z = a[1][1] * a[2][2] - a[1][2] * a[2][1]
z = (a[1][1] + a[1][2] + a[2][1] + a[2][2]) * z * z / x
return z, math.igamma(.5, .5 * z, true), true
else -- generic table
local rs, cs, n, m, N, z = {}, {}, #a, #a[1], 0, 0
for i = 1, n do rs[i] = 0 end
for j = 1, m do cs[j] = 0 end
for i = 1, n do -- compute column sum and row sum
for j = 1, m do cs[j], rs[i] = cs[j] + a[i][j], rs[i] + a[i][j] end
end
for i = 1, n do N = N + rs[i] end
for i = 1, n do -- compute the chi^2 statistics
for j = 1, m do
local E = rs[i] * cs[j] / N;
z = z + (a[i][j] - E) * (a[i][j] - E) / E
end
end
return z, math.igamma(.5 * (n-1) * (m-1), .5 * z, true), true;
end
end
-- Description: Gauss-Jordan elimination (solving equations; computing inverse)
-- Note: on return, a[n][n] is the inverse; b[n][m] is the solution
-- Reference: Section 2.1, Numerical Recipes in C, 2nd edition
function matrix.solve(a, b)
assert(#a == #a[1]);
local n, m = #a, (b and #b[1]) or 0;
local xc, xr, ipiv = {}, {}, {};
local ic, ir;
for j = 1, n do ipiv[j] = 0 end
for i = 1, n do
local big = 0;
for j = 1, n do
local aj = a[j];
if ipiv[j] ~= 1 then
for k = 1, n do
if ipiv[k] == 0 then
if math.abs(aj[k]) >= big then
big = math.abs(aj[k]);
ir, ic = j, k;
end
elseif ipiv[k] > 1 then return -2 end -- singular matrix
end
end
end
ipiv[ic] = ipiv[ic] + 1;
if ir ~= ic then
for l = 1, n do a[ir][l], a[ic][l] = a[ic][l], a[ir][l] end
if b then
for l = 1, m do b[ir][l], b[ic][l] = b[ic][l], b[ir][l] end
end
end
xr[i], xc[i] = ir, ic;
if a[ic][ic] == 0 then return -3 end -- singular matrix
local pivinv = 1 / a[ic][ic];
a[ic][ic] = 1;
for l = 1, n do a[ic][l] = a[ic][l] * pivinv end
if b then
for l = 1, n do b[ic][l] = b[ic][l] * pivinv end
end
for ll = 1, n do
if ll ~= ic then
local tmp = a[ll][ic];
a[ll][ic] = 0;
local all, aic = a[ll], a[ic];
for l = 1, n do all[l] = all[l] - aic[l] * tmp end
if b then
local bll, bic = b[ll], b[ic];
for l = 1, m do bll[l] = bll[l] - bic[l] * tmp end
end
end
end
end
for l = n, 1, -1 do
if xr[l] ~= xc[l] then
for k = 1, n do a[k][xr[l]], a[k][xc[l]] = a[k][xc[l]], a[k][xr[l]] end
end
end
return 0;
end
| mit |
merlinblack/Game-Engine-Testbed | scripts/main.lua | 1 | 3190 | require 'scheduler'
require 'keys'
require 'gui/gui'
require 'autocomplete'
require 'events'
function version()
message( '%@14%' .. Engine.versionString()..'\n\n' )
end
local old_dofile = dofile
function dofile( f )
if f == nil then
print 'stdin dofile tomfoolery not availible.'
return
end
old_dofile( f )
end
function getCounter()
local count=0
return function()
count=count+1
return count
end
end
timeSinceStart = 0
yield = coroutine.yield
function FrameEnded( timeSinceLastFrame )
timeSinceStart = timeSinceStart + timeSinceLastFrame
currentTaskId = runNextTask( currentTaskId )
end
function exit()
quitProgram()
end
function quitProgram()
Engine.queueEvent( Engine.Event( "MSG_QUIT" ) )
end
function wait( seconds )
local endTime = timeSinceStart + seconds
while timeSinceStart < endTime do
yield()
end
end
function waitForTask( task )
while task.status() ~= 'dead' do
yield()
end
end
function testWait()
print' Createing task.'
local t = createTask( function() wait(10) end )
print' Waiting for task to complete.'
waitForTask( t )
print' Task finished, continuing.'
end
function dump(t)
if type(t) == 'table' then
table.foreach(t,print)
else
--table.foreach( class_info( t ), print )
print( 'Not a table' )
end
end
function quitKeyListener( event )
inputdata = Engine.InputEventData.downcast( event.data )
if inputdata and inputdata.key == KeyCodes.KC_ESCAPE and #gui.modal == 0 then
quit()
return true
end
end
function resizeListener( event )
windowdata = Engine.WindowEventData.downcast( event.data )
if windowdata then
setViewportSize( windowdata.width, windowdata.height )
end
end
function setViewportSize(width, height)
mouse.width = width
mouse.height = height
end
function setup()
oldprint = print
print = console.print
log = console.log
clear = console.clear
local sb = Gorilla.Silverback.getSingleton()
gui.screen = sb:createScreen( Ogre.getViewport( 0 ), 'atlas' )
gui.mainLayer = gui.screen:createLayer(0)
gui.dialogBackground = Ogre.ColourValue( 112/255, 131/255, 152/255, .5 )
setupMouse()
events.subscribe( 'EVT_MOUSEMOVE', mouseMovedEventListener )
events.subscribe( 'EVT_MOUSEDOWN', mouseMovedEventListener )
events.subscribe( 'EVT_MOUSEUP', mouseMovedEventListener )
events.subscribe( 'EVT_KEYUP', quitKeyListener )
events.subscribe( 'EVT_KEYDOWN', keyPressedEventListener )
events.subscribe( 'EVT_KEYUP', keyReleasedEventListener )
events.subscribe( 'EVT_WINDOW_RESIZE', resizeListener )
--Something to look at...
require 'fps'
require 'clock'
require 'lualogo'
require 'cameracontrol'
--require 'walk'
require 'test'
--require 'mydebug'
require 'loadlevel'
player = createGameEntity( root, 'Robot', 'robot.mesh' )
player.node:scale( .5, .5, .5 )
loadLevel 'levels/level2'
print "Setup task completed"
end
createTask( setup )
print " *** main.lua processed. *** "
| mit |
jllacuna/docker-vim | nvim/config/nvim/lua/user/gitsigns.lua | 1 | 3527 | local status_ok, gitsigns = pcall(require, "gitsigns")
if not status_ok then
vim.notify "gitsigns not found"
return
end
gitsigns.setup {
on_attach = function(bufnr)
local gs = package.loaded.gitsigns
local function map(mode, l, r, opts)
opts = opts or {}
opts.buffer = bufnr
vim.keymap.set(mode, l, r, opts)
end
-- Navigation
map('n', ']c', function()
if vim.wo.diff then return ']c' end
vim.schedule(function() gs.next_hunk() end)
return '<Ignore>'
end, { expr = true, desc = '[git] Next hunk' })
map('n', '[c', function()
if vim.wo.diff then return '[c' end
vim.schedule(function() gs.prev_hunk() end)
return '<Ignore>'
end, { expr = true, desc = '[git] Previous hunk' })
-- Actions
map({'n', 'v'}, '<leader>hs', ':Gitsigns stage_hunk<CR>', { desc = '[git] Stage hunk' })
map({'n', 'v'}, '<leader>hr', ':Gitsigns reset_hunk<CR>', { desc = '[git] Reset hunk' })
map('n', '<leader>hu', gs.undo_stage_hunk, { desc = '[git] Undo stage hunk' })
map('n', '<leader>hS', gs.stage_buffer, { desc = '[git] Stage buffer' })
map('n', '<leader>hR', gs.reset_buffer, { desc = '[git] Reset buffer' })
map('n', '<leader>hp', gs.preview_hunk, { desc = '[git] Preview hunk' })
map('n', '<leader>hb', function() gs.blame_line{full=true} end, { desc = '[git] Blame line' })
map('n', '<leader>hB', gs.toggle_current_line_blame, { desc = '[git] Toggle blame current line' })
map('n', '<leader>hd', gs.diffthis, { desc = '[git] Diff unstaged' })
map('n', '<leader>hD', function() gs.diffthis('~') end, { desc = '[git] Diff last commit'})
map('n', '<leader>ht', function() gs.toggle_word_diff(); gs.toggle_deleted() end, { desc = '[git] Toggle inline diff' })
-- Text object
map({'o', 'x'}, 'ih', ':<C-U>Gitsigns select_hunk<CR>', { desc = '[git] inner hunk' })
end,
signs = {
add = { hl = "GitSignsAdd", text = "▎", numhl = "GitSignsAddNr", linehl = "GitSignsAddLn" },
change = { hl = "GitSignsChange", text = "▎", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn" },
delete = { hl = "GitSignsDelete", text = "契", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn" },
topdelete = { hl = "GitSignsDelete", text = "契", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn" },
changedelete = { hl = "GitSignsChange", text = "▎", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn" },
},
signcolumn = true, -- Toggle with `:Gitsigns toggle_signs`
numhl = true, -- Toggle with `:Gitsigns toggle_numhl`
linehl = false, -- Toggle with `:Gitsigns toggle_linehl`
word_diff = false, -- Toggle with `:Gitsigns toggle_word_diff`
watch_gitdir = {
interval = 1000,
follow_files = true,
},
attach_to_untracked = true,
current_line_blame = false, -- Toggle with `:Gitsigns toggle_current_line_blame` (See <leader>hB above)
current_line_blame_opts = {
virt_text = true,
virt_text_pos = "eol", -- 'eol' | 'overlay' | 'right_align'
delay = 0,
ignore_whitespace = false,
},
current_line_blame_formatter = " [<abbrev_sha>] <author_time> <author>: <summary>",
sign_priority = 6,
update_debounce = 100,
status_formatter = nil, -- Use default
max_file_length = 40000,
preview_config = {
-- Options passed to nvim_open_win
border = "rounded",
style = "minimal",
relative = "cursor",
row = 0,
col = 1,
},
yadm = {
enable = false,
},
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.