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 |
|---|---|---|---|---|---|
TrossSoftwareAndTech/webvt | lib/node-v7.2.0/deps/v8/tools/gcmole/gccause.lua | 157 | 2313 | -- Copyright 2011 the V8 project authors. All rights reserved.
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are
-- met:
--
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above
-- copyright notice, this list of conditions and the following
-- disclaimer in the documentation and/or other materials provided
-- with the distribution.
-- * Neither the name of Google Inc. nor the names of its
-- contributors may be used to endorse or promote products derived
-- from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-- This is an auxiliary tool that reads gccauses file generated by
-- gcmole.lua and prints tree of the calls that can potentially cause a GC
-- inside a given function.
--
-- Usage: lua tools/gcmole/gccause.lua <function-name-pattern>
--
assert(loadfile "gccauses")()
local P = ...
local T = {}
local function TrackCause(name, lvl)
io.write((" "):rep(lvl or 0), name, "\n")
if GC[name] then
local causes = GC[name]
for i = 1, #causes do
local f = causes[i]
if not T[f] then
T[f] = true
TrackCause(f, (lvl or 0) + 1)
end
if f == '<GC>' then break end
end
end
end
for name, _ in pairs(GC) do
if name:match(P) then
T = {}
TrackCause(name)
end
end
| gpl-3.0 |
nstockton/mushclient-mume | lua/getch.lua | 1 | 1417 | -- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
-- Copyright (C) 2019 Nick Stockton <https://github.com/nstockton>
-- For compatibility with Lua >= 5.2.
local unpack = rawget(table, "unpack") or unpack
local ffi = require "ffi"
local msvcrt = ffi.load("msvcrt.dll")
ffi.cdef[[
typedef wchar_t wint_t;
int __stdcall _getch(void);
int __stdcall _getche(void);
wint_t __stdcall _getwch(void);
wint_t __stdcall _getwche(void);
]]
local function _getch(func)
local result = {}
table.insert(result, func())
if result[1] < 0 or result[1] >= 256 then
return nil
elseif result[1] == 0 or result[1] == 224 then
-- It is likely that one of the function keys or arrows was pressed.
-- If this is the case, _getch needs to be called again to get the second character in the 2-character sequence.
local char = func()
table.insert(result, char >= 0 and char < 256 and char or nil)
end
return string.char(unpack(result))
end
local __all__ = {
["getch"] = function () return _getch(msvcrt._getch) end,
["getche"] = function () return _getch(msvcrt._getche) end,
["getwch"] = function () return _getch(msvcrt._getwch) end,
["getwche"] = function () return _getch(msvcrt._getwche) end
}
return __all__
| mpl-2.0 |
SiENcE/APE | ui_scripts/ui_collection.lua | 2 | 2143 | -- undrawable container element
-- you can hold stuff in it, strings, numbers, tables, userdata etc
-- has simple adding, deleting and getting interface
-- UIManager's version of an array
Collection = {}
Collection.__index = Collection
Collection.ident = "ui_collection"
Collection.name = "Collection"
Collection.updateable = false
Collection.input = false
Collection.drawable = false
function Collection:new(name)
local self = {}
setmetatable(self,Collection)
self.items = {}
if name ~= nil then self.name = name end
return self
end
setmetatable(Collection,{__index = Element})
-- adds element into collection and fires onadd event
function Collection:addItem(item)
table.insert(self.items,item)
self:onadd()
end
-- if element is a table or userdata, you will receive a reference to it, in other cases you will create duplicate of that element in your variable
function Collection:getItem(index)
return self.items[index]
end
function Collection:deleteItem(index)
table.remove(self.items,index)
self:ondelete()
end
-- clears collection of anything
function Collection:purge()
for k,v in pairs(self.items) do self.items[k] = nil end
end
function Collection:getCount()
return #self.items
end
function Collection:onadd() end
function Collection:ondelete() end
-- UIManager will try to update this collection, you should declare what should it do on every tick,
--[[
local collection = Collection:new("UColl")
function collection:update(dt)
.. do stuff
end
]]
-- otherwise it will do nothing
UpdateableCollection = {}
UpdateableCollection.__index = UpdateableCollection
UpdateableCollection.ident = "ui_updateablecollection"
UpdateableCollection.name = "UpdateableCollection"
UpdateableCollection.updateable = true
UpdateableCollection.input = false
UpdateableCollection.drawable = false
function UpdateableCollection:new(name)
local self = {}
setmetatable(self,UpdateableCollection)
self.items = {}
return self
end
setmetatable(UpdateableCollection,{__index = Collection})
function UpdateableCollection:update(dt)
local c = self:getCount()
if c>0 then
for i=1,c do
self.items[i]:update(dt)
end
end
end | mit |
mrmhxx82/JokerBot | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
uonline/debut | src/day2/act3/bazaar_stories.dlg.lua | 1 | 11993 | -- Диалог с продавцом пряностей
bazaar_stories = dlg {
nam = 'Продавец пряностей';
hideinv = true;
entered = [[
-- И чего мы так шумим? -- обращаешься ты к торговцу, на столе которого
расставлено множество баночек самых разных размеров и форм.
^
Тот в ответ с досадой разводит руками.
^
-- Да ведь не покупают ничего, -- объясняет продавец, -- эти
купцы из Вольных городов всю торговлю портят. Распугали своим говором
всех покупателей, а тех немногих, что проходят мимо, сразу хватают и тащат к себе.
^
Ты присматриваешься к торговцу. Его туника выглядит так же необычно, как и светлые
наряды вольных купцов.
]];
phr = {
-- Просишь рассказать откуда продавец
{
true;
tag='first_question';
'Ты сам-то откуда?';
[[
-- Из Салфир, -- отвечает продавец, поглаживая живот.
^
Не увидев понимания на твоём лице, он добавляет:
^
-- Из полиса Салфиры.
^
-- А, Имперские колонии, -- киваешь ты.
^
-- Да, в вашей стране, кажется, ходит именно это название, --
сухо соглашается продавец.
^
-- Всегда удивлялся, что заставляет людей из ваших краёв оторваться от
своих песочных пляжей, солнца и тёплого моря и удариться в странствия.
^
-- Ты описываешь жизнь на восточном побережье, но в остальной части страны
всё совсем не так.
]];
function()
bazaar_stories:pon('free_kingdome_question');
bazaar_stories:pon('trade_way');
end;
};
-- Просишь рассказать про Имперские колонии
{
false;
tag='free_kingdome_question';
'Выходит, проповедники Благих нас обманывают, не так уж и хороша жизнь в ваших благословенных землях?';
[[
-- Я бы сказал, как и везде. Банды орков-головорезов и пираты терроризируют
нас, как и любую другую страну. Но не каждая страна граничит с
проклятыми эльфийскими лесами или пустыней мерзких жуков и мутантов.
Хотя в том же Режиме проблем не меньше: все эти еретические секты,
жуткие истории про призраков Скалистого полуострова и гоблинские полчища в тундрах,
-- торговец втянул голову в плечи, словно от озноба.
^
Ты скептически поднял бровь, но тот не обратил внимания.
^
-- Короче, если ты священнослужитель с большой паствой в крупном полисе
и можешь позволить себе особняк у лазурных волн на
восточном побережье, то у тебя просто райская жизнь.
А если ты обычный крестьянин в центральной части страны, то изволь гнуть
спину в полях под палящим солнцем и надеяться, что охотники вычистили
все гнёзда хищных ящеров в окрестных лесах, -- тирада окончилась вздохом
досады, -- что уж и говорить о простых торговцах, что странствуют по миру,
наблюдая все его напасти.
]];
function()
bazaar_stories:pon('termites');
end;
};
-- Просишь рассказать про Термитники
{
false;
tag='termites';
'Ты кажется упоминал каких-то пустынных жуков-мутантов?';
[[
-- Вернее, жуков и мутантов. Вы, южане, поди и не слышали про наши
беды. Главная из них всё-таки Термитники с их жуками.
^
Ты неуверенно покачал головой.
^
-- О, полисы на западе страны только и заняты патрулированием
границы с пустыней. Её пески просто кишат этими тварями. Самое отвратительное
-- они роют тоннели под землёй. Никакие рвы и стены их не остановят, они
вылезут прямо у тебя перед носом! Ходят слухи, что западным полисам приходится
обращаться за помощью к богомерзким чернокнижникам с Мистического архипелага,
чтобы те остужали землю. Иначе эту напасть просто не удержать: твёрдая и
холодная почва жукам, кажется, не по нраву. Хотя никто не может сказать этого
наверняка, Термитники никогда не пытались расширять владения за пределы пустыни.
Такое ощущение, что что-то удерживает их там.
^
-- Возможно, они питаются там чем-то, -- решаешься на догадку ты.
^
-- Да, некоторые тоже так считают, -- соглашается торговец, -- говорят, в сердце
пустыни -- Пепельных горах -- обитают чудища пострашнее. С ними-то жуки и
воюют, а заодно и поедают.
^
-- Это и есть те мутанты? Жуки поедают их?
^
-- Никто не знает. Мутантов можно встретить начиная с северных областей Режима
Ремана. И чем ближе к Стене и крепости Диовен у границы с эльфийскими лесами,
тем больше этих монстров. Так что нельзя сказать, что они водятся только в пустыне.
Хотя по правде, раз в десятилетие какому-нибудь западному
полису приходится отбивать нападения множества этих выродков. И, кажется, они
действительно наступают со стороны песков.
^
-- Во всё это сложно поверить, -- отвечаешь ты.
^
-- Самое страшное -- жуки всё глубже вгрызаются в земные недра. Кто знает
какие силы они потревожат в тёмных глубинах? Но ты продолжай бояться орков,
-- торговец хлопает тебя по плечу, -- они ближе.
]];
};
-- Просишь рассказать про Торговый путь
{
false;
tag='trade_way';
'Почему ты отправился торговать именно в Приграничье?';
[[
-- Лучше спроси, почему я отправился торговать в этот
захудалый городок, -- с усмешкой заметил продавец.
-- Через Приграничье проходит Торговый путь. Караваны выходят из Полисов
и направляются в Тантикул, затем отправляются в земли Приграничья. Отсюда
два пути: либо по суше обратно на северо-восток в Полисы, либо на кораблях
на Мистический архипелаг в Вольные города. Особо рисковые, впрочем, могут
выбрать и третий путь -- в земли орков. Правда, там привыкли платить не
золотом, а железом и кровью.
^
-- Так значит, вы идёте через Тантикул? Это вроде бы как большой крюк,
чтобы попасть из Колоний в Приграничье?
^
-- Зато это безопасный крюк. В отличие от здешних правителей, Режим ревностно стережёт
торговые тракты, -- торговец внезапно запинается и подозрительно косится
в твою сторону, -- весьма странно, что его солдат задаёт мне подобный вопрос.
^
-- Я рекрут из местных, -- спокойно отвечаешь ты.
^
-- А, тогда понятно. Доказательство кровью, слышал об этом.
Режим пробовал провернуть подобный трюк в Полисах. Но, насколько мне известно,
желающих не нашлось. Их новая еретическая религия никого не привлекает среди
истинных почитателей Благих, -- с некоторой гордостью в голосе вещает торговец,
-- а половина моих соотечественников вообще уверена,
что богоизбранные -- те же колдуны и богохульники, которых надо сжигать
на кострах.
^
-- Кажется, ваши инквизиторы пытались это проделать, но богоизбранные их истребили,
-- с усмешкой отвечаешь ты.
^
-- Только у себя в стране, хотя я и в этом не был бы уверен. Настоящие инквизиторы
не выдают себя просто так, -- продавец внезапно стал серьёзным,
-- к тому же к моей стране они имеют мало отношения.
Инквизиторы прибывают из-за моря, из Империи Карающей.
^
-- И вы удивляетесь, почему ваши полисы называют колонией.
^
-- В древности это действительно было так, но теперь все мы слишком погрязли в грехе,
чтобы наша судьба интересовала Святых с островов.
]];
};
-- Уходишь
{
always = true;
'Я пойду.';
'Приходи ещё.';
function()
bazaar_stories:pon('first_question');
back()
end;
};
};
}
| gpl-3.0 |
cyanskies/OpenRA | mods/ra/maps/survival02/survival02.lua | 10 | 13010 | FrenchSquad = { "2tnk", "2tnk", "mcv" }
TimerTicks = DateTime.Minutes(10)
AttackTicks = DateTime.Seconds(52)
AttackAtFrame = DateTime.Seconds(18)
AttackAtFrameIncrement = DateTime.Seconds(18)
Producing = true
SpawningInfantry = true
ProduceAtFrame = DateTime.Seconds(12)
ProduceAtFrameIncrement = DateTime.Seconds(12)
SovietGroupSize = 4
SovietAttackGroupSize = 7
InfantryGuards = { }
HarvGuards = { HarvGuard1, HarvGuard2, HarvGuard3 }
SovietPlatoonUnits = { "e1", "e1", "e2", "e4", "e4", "e1", "e1", "e2", "e4", "e4" }
SovietTanks = { "3tnk", "3tnk", "3tnk" }
SovietVehicles = { "3tnk", "3tnk", "v2rl" }
SovietInfantry = { "e1", "e4", "e2" }
SovietEntryPoints = { SovietEntry1, SovietEntry2, SovietEntry3 }
SovietRallyPoints = { SovietRally2, SovietRally4, SovietRally5, SovietRally6 }
NewSovietEntryPoints = { SovietParaDropEntry, SovietEntry3 }
NewSovietRallyPoints = { SovietRally3, SovietRally4, SovietRally8 }
ParaWaves =
{
{ delay = AttackTicks, type = "SovietSquad", target = SovietRally5 },
{ delay = 0, type = "SovietSquad", target = SovietRally6 },
{ delay = AttackTicks * 2, type = "SovietSquad", target = SovietParaDrop3 },
{ delay = 0, type = "SovietPlatoonUnits", target = SovietRally5 },
{ delay = 0, type = "SovietPlatoonUnits", target = SovietRally6 },
{ delay = 0, type = "SovietSquad", target = SovietRally2 },
{ delay = AttackTicks * 2, type = "SovietSquad", target = SovietParaDrop2 },
{ delay = AttackTicks * 2, type = "SovietSquad", target = SovietParaDrop1 },
{ delay = AttackTicks * 3, type = "SovietSquad", target = SovietParaDrop1 }
}
IdleHunt = function(unit)
Trigger.OnIdle(unit, function(a)
if a.IsInWorld then
a.Hunt()
end
end)
end
GuardHarvester = function(unit, harvester)
if not unit.IsDead then
unit.Stop()
local start = unit.Location
if not harvester.IsDead then
unit.AttackMove(harvester.Location)
else
unit.Hunt()
end
Trigger.OnIdle(unit, function()
if unit.Location == start then
Trigger.ClearAll(unit)
else
unit.AttackMove(start)
end
end)
Trigger.OnCapture(unit, function()
Trigger.ClearAll(unit)
end)
end
end
ticked = TimerTicks
Tick = function()
if soviets.HasNoRequiredUnits() then
if DestroyObj then
allies.MarkCompletedObjective(DestroyObj)
else
DestroyObj = allies.AddPrimaryObjective("Destroy all Soviet forces in the area.")
allies.MarkCompletedObjective(DestroyObj)
end
end
if allies.HasNoRequiredUnits() then
soviets.MarkCompletedObjective(SovietObj)
end
if soviets.Resources > soviets.ResourceCapacity / 2 then
soviets.Resources = soviets.ResourceCapacity / 2
end
if DateTime.GameTime == ProduceAtFrame then
if SpawningInfantry then
ProduceAtFrame = ProduceAtFrame + ProduceAtFrameIncrement
ProduceAtFrameIncrement = ProduceAtFrameIncrement * 2 - 5
SpawnSovietInfantry()
end
end
if DateTime.GameTime == AttackAtFrame then
AttackAtFrame = AttackAtFrame + AttackAtFrameIncrement
AttackAtFrameIncrement = AttackAtFrameIncrement * 2 - 5
if Producing then
SpawnSovietVehicle(SovietEntryPoints, SovietRallyPoints)
else
SpawnSovietVehicle(NewSovietEntryPoints, NewSovietRallyPoints)
end
end
if DateTime.Minutes(5) == ticked then
Media.PlaySpeechNotification(allies, "WarningFiveMinutesRemaining")
InitCountDown()
end
if ticked > 0 then
UserInterface.SetMissionText("Soviet reinforcements arrive in " .. Utils.FormatTime(ticked), TimerColor)
ticked = ticked - 1
elseif ticked == 0 then
FinishTimer()
ticked = ticked - 1
end
end
SendSovietParadrops = function(table)
local paraproxy = Actor.Create(table.type, false, { Owner = soviets })
units = paraproxy.SendParatroopers(table.target.CenterPosition)
Utils.Do(units, function(unit) IdleHunt(unit) end)
paraproxy.Destroy()
end
SpawnSovietInfantry = function()
soviets.Build({ Utils.Random(SovietInfantry) }, function(units)
IdleHunt(units[1])
end)
end
SpawnSovietVehicle = function(spawnpoints, rallypoints)
local route = Utils.RandomInteger(1, #spawnpoints + 1)
local rally = Utils.RandomInteger(1, #rallypoints + 1)
local unit = Reinforcements.Reinforce(soviets, { Utils.Random(SovietVehicles) }, { spawnpoints[route].Location })[1]
unit.AttackMove(rallypoints[rally].Location)
IdleHunt(unit)
Trigger.OnCapture(unit, function()
Trigger.ClearAll(unit)
end)
end
SpawnAndAttack = function(types, entry)
local units = Reinforcements.Reinforce(soviets, types, { entry })
Utils.Do(units, function(unit)
IdleHunt(unit)
Trigger.OnCapture(unit, function()
Trigger.ClearAll(unit)
end)
end)
return units
end
SendFrenchReinforcements = function()
local camera = Actor.Create("camera", true, { Owner = allies, Location = SovietRally1.Location })
Beacon.New(allies, FranceEntry.CenterPosition - WVec.New(0, 3 * 1024, 0))
Media.PlaySpeechNotification(allies, "AlliedReinforcementsArrived")
Reinforcements.Reinforce(allies, FrenchSquad, { FranceEntry.Location, FranceRally.Location })
Trigger.AfterDelay(DateTime.Seconds(3), function() camera.Destroy() end)
end
FrenchReinforcements = function()
Camera.Position = SovietRally1.CenterPosition
if drum1.IsDead or drum2.IsDead or drum3.IsDead then
SendFrenchReinforcements()
return
end
powerproxy = Actor.Create("powerproxy.parabombs", false, { Owner = allies })
powerproxy.SendAirstrike(drum1.CenterPosition, false, Facing.NorthEast + 4)
powerproxy.SendAirstrike(drum2.CenterPosition, false, Facing.NorthEast)
powerproxy.SendAirstrike(drum3.CenterPosition, false, Facing.NorthEast - 4)
powerproxy.Destroy()
Trigger.AfterDelay(DateTime.Seconds(3), function()
SendFrenchReinforcements()
end)
end
FinalAttack = function()
local units1 = SpawnAndAttack(SovietTanks, SovietEntry1.Location)
local units2 = SpawnAndAttack(SovietTanks, SovietEntry1.Location)
local units3 = SpawnAndAttack(SovietTanks, SovietEntry2.Location)
local units4 = SpawnAndAttack(SovietPlatoonUnits, SovietEntry1.Location)
local units5 = SpawnAndAttack(SovietPlatoonUnits, SovietEntry2.Location)
local units = { }
local insert = function(table)
local count = #units
Utils.Do(table, function(unit)
units[count] = unit
count = count + 1
end)
end
insert(units1)
insert(units2)
insert(units3)
insert(units4)
insert(units5)
Trigger.OnAllKilledOrCaptured(units, function()
if not DestroyObj then
Media.DisplayMessage("Excellent work Commander! We have reinforced our position enough to initiate a counter-attack.", "Incoming Report")
DestroyObj = allies.AddPrimaryObjective("Destroy the remaining Soviet forces in the area.")
end
allies.MarkCompletedObjective(SurviveObj)
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("Soviet reinforcements have arrived!", c) end)
end
Trigger.AfterDelay(DateTime.Seconds(10), function() UserInterface.SetMissionText("") end)
end
wave = 1
SendParadrops = function()
SendSovietParadrops(ParaWaves[wave])
wave = wave + 1
if wave > #ParaWaves then
Trigger.AfterDelay(AttackTicks, FrenchReinforcements)
else
Trigger.AfterDelay(ParaWaves[wave].delay, SendParadrops)
end
end
SetupBridges = function()
local count = 0
local counter = function()
count = count + 1
if count == 2 then
allies.MarkCompletedObjective(RepairBridges)
end
end
Media.DisplayMessage("Commander! The Soviets destroyed the bridges to disable our reinforcements. Repair them for additional reinforcements.", "Incoming Report")
RepairBridges = allies.AddSecondaryObjective("Repair the two southern bridges.")
local bridgeA = Map.ActorsInCircle(BrokenBridge1.CenterPosition, WDist.FromCells(1), function(self) return self.Type == "bridge1" end)
local bridgeB = Map.ActorsInCircle(BrokenBridge2.CenterPosition, WDist.FromCells(1), function(self) return self.Type == "bridge1" end)
Utils.Do(bridgeA, function(bridge)
Trigger.OnDamaged(bridge, function()
Utils.Do(bridgeA, function(self) Trigger.ClearAll(self) end)
Media.PlaySpeechNotification(allies, "AlliedReinforcementsArrived")
Reinforcements.Reinforce(allies, { "1tnk", "2tnk", "2tnk" }, { ReinforcementsEntry1.Location, ReinforcementsRally1.Location })
counter()
end)
end)
Utils.Do(bridgeB, function(bridge)
Trigger.OnDamaged(bridge, function()
Utils.Do(bridgeB, function(self) Trigger.ClearAll(self) end)
Media.PlaySpeechNotification(allies, "AlliedReinforcementsArrived")
Reinforcements.Reinforce(allies, { "jeep", "1tnk", "1tnk" }, { ReinforcementsEntry2.Location, ReinforcementsRally2.Location })
counter()
end)
end)
end
InitCountDown = function()
Trigger.AfterDelay(DateTime.Minutes(1), function() Media.PlaySpeechNotification(allies, "WarningFourMinutesRemaining") end)
Trigger.AfterDelay(DateTime.Minutes(2), function() Media.PlaySpeechNotification(allies, "WarningThreeMinutesRemaining") end)
Trigger.AfterDelay(DateTime.Minutes(3), function() Media.PlaySpeechNotification(allies, "WarningTwoMinutesRemaining") end)
Trigger.AfterDelay(DateTime.Minutes(4), function() Media.PlaySpeechNotification(allies, "WarningOneMinuteRemaining") end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(allies, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
SurviveObj = allies.AddPrimaryObjective("Enforce your position and hold-out the onslaught.")
SovietObj = soviets.AddPrimaryObjective("Eliminate all Allied forces.")
Trigger.AfterDelay(DateTime.Seconds(15), function()
SetupBridges()
end)
Trigger.OnObjectiveCompleted(allies, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(allies, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(allies, function()
Media.PlaySpeechNotification(allies, "Lose")
end)
Trigger.OnPlayerWon(allies, function()
Media.PlaySpeechNotification(allies, "Win")
Media.DisplayMessage("We have destroyed the remaining Soviet presence!", "Incoming Report")
end)
end
InitMission = function()
Camera.Position = AlliesBase.CenterPosition
TimerColor = HSLColor.Red
Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(allies, "MissionTimerInitialised") end)
Trigger.AfterDelay(TimerTicks, function()
Media.DisplayMessage("The Soviet reinforcements are approaching!", "Incoming Report")
Media.PlaySpeechNotification(allies, "SovietReinforcementsArrived")
SpawnSovietVehicle(NewSovietEntryPoints, NewSovietRallyPoints)
FinalAttack()
Producing = false
end)
Trigger.AfterDelay(AttackTicks, SendParadrops)
Trigger.OnKilled(drum1, function() --Kill the remaining stuff from FrenchReinforcements
if not boom2.IsDead then boom2.Kill() end
if not boom4.IsDead then boom4.Kill() end
if not drum2.IsDead then drum2.Kill() end
if not drum3.IsDead then drum3.Kill() end
end)
Trigger.OnKilled(drum2, function()
if not boom1.IsDead then boom1.Kill() end
if not boom5.IsDead then boom5.Kill() end
Trigger.AfterDelay(DateTime.Seconds(1), function() if not drum1.IsDead then drum1.Kill() end end)
end)
Trigger.OnKilled(drum3, function()
if not boom1.IsDead then boom1.Kill() end
if not boom3.IsDead then boom3.Kill() end
Trigger.AfterDelay(DateTime.Seconds(1), function() if not drum1.IsDead then drum1.Kill() end end)
end)
end
SetupSoviets = function()
Barrack1.IsPrimaryBuilding = true
Barrack1.RallyPoint = SovietRally.Location
Trigger.OnKilledOrCaptured(Barrack1, function()
SpawningInfantry = false
end)
Harvester1.FindResources()
Trigger.OnDamaged(Harvester1, function()
Utils.Do(HarvGuards, function(unit)
GuardHarvester(unit, Harvester1)
end)
end)
Trigger.OnCapture(Harvester1, function()
Trigger.ClearAll(Harvester1)
end)
Harvester2.FindResources()
Trigger.OnDamaged(Harvester2, function()
Utils.Do(InfantryGuards, function(unit) GuardHarvester(unit, Harvester2) end)
local toBuild = { }
for i = 1, 6, 1 do
toBuild[i] = Utils.Random(SovietInfantry)
end
soviets.Build(toBuild, function(units)
Utils.Do(units, function(unit)
InfantryGuards[#InfantryGuards + 1] = unit
GuardHarvester(unit, Harvester2)
end)
end)
end)
Trigger.OnCapture(Harvester2, function()
Trigger.ClearAll(Harvester2)
end)
Trigger.AfterDelay(0, function()
local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == soviets and self.HasProperty("StartBuildingRepairs") end)
Utils.Do(buildings, function(actor)
Trigger.OnDamaged(actor, function(building)
if building.Owner == soviets and building.Health < building.MaxHealth * 3/4 then
building.StartBuildingRepairs()
end
end)
end)
end)
end
WorldLoaded = function()
allies = Player.GetPlayer("Allies")
soviets = Player.GetPlayer("Soviets")
InitObjectives()
InitMission()
SetupSoviets()
end
| gpl-3.0 |
opentechinstitute/luci | applications/luci-hd-idle/luasrc/model/cbi/hd_idle.lua | 36 | 1043 | --[[
LuCI hd-idle
(c) 2008 Yanira <forum-2008@email.de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("nixio.fs")
m = Map("hd-idle", "hd-idle",
translate("hd-idle is a utility program for spinning-down external " ..
"disks after a period of idle time."))
s = m:section(TypedSection, "hd-idle", translate("Settings"))
s.anonymous = true
s:option(Flag, "enabled", translate("Enable"))
disk = s:option(Value, "disk", translate("Disk"))
disk.rmempty = true
for dev in nixio.fs.glob("/dev/[sh]d[a-z]") do
disk:value(nixio.fs.basename(dev))
end
s:option(Value, "idle_time_interval", translate("Idle-time")).default = 10
s.rmempty = true
unit = s:option(ListValue, "idle_time_unit", translate("Idle-time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
unit.rmempty = true
return m
| apache-2.0 |
tinydanbo/Impoverished-Starfighter | lib/loveframes/objects/progressbar.lua | 7 | 8120 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- progressbar object
local newobject = loveframes.NewObject("progressbar", "loveframes_object_progressbar", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize()
self.type = "progressbar"
self.text = ""
self.width = 100
self.height = 25
self.min = 0
self.max = 10
self.value = 0
self.barwidth = 0
self.lerprate = 1000
self.lerpvalue = 0
self.lerpto = 0
self.lerpfrom = 0
self.completed = false
self.lerp = false
self.internal = false
self.OnComplete = nil
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local lerp = self.lerp
local lerprate = self.lerprate
local lerpvalue = self.lerpvalue
local lerpto = self.lerpto
local lerpfrom = self.lerpfrom
local value = self.value
local completed = self.completed
local parent = self.parent
local base = loveframes.base
local update = self.Update
local oncomplete = self.OnComplete
self:CheckHover()
-- caclulate barwidth
if lerp then
if lerpfrom < lerpto then
if lerpvalue < lerpto then
self.lerpvalue = lerpvalue + lerprate*dt
elseif lerpvalue > lerpto then
self.lerpvalue = lerpto
end
elseif lerpfrom > lerpto then
if lerpvalue > lerpto then
self.lerpvalue = lerpvalue - lerprate*dt
elseif lerpvalue < lerpto then
self.lerpvalue = lerpto
end
elseif lerpfrom == lerpto then
self.lerpvalue = lerpto
end
self.barwidth = self.lerpvalue/self.max * self.width
-- min check
if self.lerpvalue < self.min then
self.lerpvalue = self.min
end
-- max check
if self.lerpvalue > self.max then
self.lerpvalue = self.max
end
else
self.barwidth = value/self.max * self.width
-- min max check
if value < self.min then
self.value = self.min
elseif value > self.max then
self.value = self.max
end
end
-- move to parent if there is a parent
if parent ~= base then
self.x = self.parent.x + self.staticx
self.y = self.parent.y + self.staticy
end
-- completion check
if not completed then
if self.value >= self.max then
self.completed = true
if oncomplete then
oncomplete(self)
end
end
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawProgressBar or skins[defaultskin].DrawProgressBar
local draw = self.Draw
local drawcount = loveframes.drawcount
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
end
--[[---------------------------------------------------------
- func: SetMax(max)
- desc: sets the object's maximum value
--]]---------------------------------------------------------
function newobject:SetMax(max)
self.max = max
return self
end
--[[---------------------------------------------------------
- func: GetMax()
- desc: gets the object's maximum value
--]]---------------------------------------------------------
function newobject:GetMax()
return self.max
end
--[[---------------------------------------------------------
- func: SetMin(min)
- desc: sets the object's minimum value
--]]---------------------------------------------------------
function newobject:SetMin(min)
self.min = min
return self
end
--[[---------------------------------------------------------
- func: GetMin()
- desc: gets the object's minimum value
--]]---------------------------------------------------------
function newobject:GetMin()
return self.min
end
--[[---------------------------------------------------------
- func: SetMinMax()
- desc: sets the object's minimum and maximum values
--]]---------------------------------------------------------
function newobject:SetMinMax(min, max)
self.min = min
self.max = max
return self
end
--[[---------------------------------------------------------
- func: GetMinMax()
- desc: gets the object's minimum and maximum values
--]]---------------------------------------------------------
function newobject:GetMinMax()
return self.min, self.max
end
--[[---------------------------------------------------------
- func: SetValue(value)
- desc: sets the object's value
--]]---------------------------------------------------------
function newobject:SetValue(value)
local lerp = self.lerp
if lerp then
self.lerpvalue = self.lerpvalue
self.lerpto = value
self.lerpfrom = self.lerpvalue
self.value = value
else
self.value = value
end
return self
end
--[[---------------------------------------------------------
- func: GetValue()
- desc: gets the object's value
--]]---------------------------------------------------------
function newobject:GetValue()
return self.value
end
--[[---------------------------------------------------------
- func: SetLerp(bool)
- desc: sets whether or not the object should lerp
when changing between values
--]]---------------------------------------------------------
function newobject:SetLerp(bool)
self.lerp = bool
self.lerpto = self:GetValue()
self.lerpvalue = self:GetValue()
return self
end
--[[---------------------------------------------------------
- func: GetLerp()
- desc: gets whether or not the object should lerp
when changing between values
--]]---------------------------------------------------------
function newobject:GetLerp()
return self.lerp
end
--[[---------------------------------------------------------
- func: SetLerpRate(rate)
- desc: sets the object's lerp rate
--]]---------------------------------------------------------
function newobject:SetLerpRate(rate)
self.lerprate = rate
return self
end
--[[---------------------------------------------------------
- func: GetLerpRate()
- desc: gets the object's lerp rate
--]]---------------------------------------------------------
function newobject:GetLerpRate()
return self.lerprate
end
--[[---------------------------------------------------------
- func: GetCompleted()
- desc: gets whether or not the object has reached its
maximum value
--]]---------------------------------------------------------
function newobject:GetCompleted()
return self.completed
end
--[[---------------------------------------------------------
- func: GetBarWidth()
- desc: gets the object's bar width
--]]---------------------------------------------------------
function newobject:GetBarWidth()
return self.barwidth
end
--[[---------------------------------------------------------
- func: SetText(text)
- desc: sets the object's text
--]]---------------------------------------------------------
function newobject:SetText(text)
self.text = text
return self
end
--[[---------------------------------------------------------
- func: GetText()
- desc: gets the object's text
--]]---------------------------------------------------------
function newobject:GetText()
return self.text
end | mit |
adamflott/wargus | scripts/ai/passive.lua | 3 | 1938 | -- _________ __ __
-- / _____// |_____________ _/ |______ ____ __ __ ______
-- \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
-- / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ \
-- /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
-- \/ \/ \//_____/ \/
-- ______________________ ______________________
-- T H E W A R B E G I N S
-- Stratagus - A free fantasy real time strategy game engine
--
-- passive.lua - Define the passive AI.
--
-- (c) Copyright 2000-2004 by Lutz Sammer and Jimmy Salmon
--
-- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
function AiPassive()
end
--=============================================================================
--
-- Define an AI engine.
--
-- DefineAi(name race class script)
--
-- name name of the AI for selection.
-- race race of the AI for selection.
-- class class of the AI for map editor.
-- script Main AI script.
--
DefineAi("wc2-passive", "*", "wc2-passive", AiPassive)
DefineAi("ai-passive", "*", "ai-passive", AiPassive)
| gpl-2.0 |
hfjgjfg/seed355 | plugins/admin.lua | 230 | 6382 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function user_info_callback(cb_extra, success, result)
result.access_hash = nil
result.flags = nil
result.phone = nil
if result.username then
result.username = '@'..result.username
end
result.print_name = result.print_name:gsub("_","")
local text = serpent.block(result, {comment=false})
text = text:gsub("[{}]", "")
text = text:gsub('"', "")
text = text:gsub(",","")
if cb_extra.msg.to.type == "chat" then
send_large_msg("chat#id"..cb_extra.msg.to.id, text)
else
send_large_msg("user#id"..cb_extra.msg.to.id, text)
end
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairs(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
local function run(msg,matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local group = msg.to.id
if not is_admin(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'Please send me bot photo now'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
send_large_msg("user#id"..matches[2],matches[3])
return "Msg sent"
end
if matches[1] == "block" then
if is_admin2(matches[2]) then
return "You can't block admins"
end
block_user("user#id"..matches[2],ok_cb,false)
return "User blocked"
end
if matches[1] == "unblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "User unblocked"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent dialog list with both json and text format to your private"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
return
end
return {
patterns = {
"^[!/](pm) (%d+) (.*)$",
"^[!/](import) (.*)$",
"^[!/](unblock) (%d+)$",
"^[!/](block) (%d+)$",
"^[!/](markread) (on)$",
"^[!/](markread) (off)$",
"^[!/](setbotphoto)$",
"%[(photo)%]",
"^[!/](contactlist)$",
"^[!/](dialoglist)$",
"^[!/](delcontact) (%d+)$",
"^[!/](whois) (%d+)$"
},
run = run,
}
--By @imandaneshi :)
--https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
| gpl-2.0 |
lizh06/premake-core | modules/codelite/tests/test_codelite_workspace.lua | 6 | 3637 | ---
-- codelite/tests/test_codelite_workspace.lua
-- Validate generation for CodeLite workspaces.
-- Author Manu Evans
-- Copyright (c) 2015 Manu Evans and the Premake project
---
local suite = test.declare("codelite_workspace")
local codelite = premake.modules.codelite
--
-- Setup
--
local wks, prj
function suite.setup()
premake.action.set("codelite")
premake.indent(" ")
wks = test.createWorkspace()
end
local function prepare()
wks = test.getWorkspace(wks)
codelite.workspace.generate(wks)
end
--
-- Check the basic structure of a workspace.
--
function suite.onEmptyWorkspace()
wks.projects = {}
prepare()
test.capture [[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
<BuildMatrix>
<WorkspaceConfiguration Name="Debug" Selected="yes">
</WorkspaceConfiguration>
<WorkspaceConfiguration Name="Release" Selected="yes">
</WorkspaceConfiguration>
</BuildMatrix>
</CodeLite_Workspace>
]]
end
function suite.onDefaultWorkspace()
prepare()
test.capture [[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
<Project Name="MyProject" Path="MyProject.project"/>
<BuildMatrix>
<WorkspaceConfiguration Name="Debug" Selected="yes">
<Project Name="MyProject" ConfigName="Debug"/>
</WorkspaceConfiguration>
<WorkspaceConfiguration Name="Release" Selected="yes">
<Project Name="MyProject" ConfigName="Release"/>
</WorkspaceConfiguration>
</BuildMatrix>
</CodeLite_Workspace>
]]
end
function suite.onMultipleProjects()
test.createproject(wks)
prepare()
test.capture [[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
<Project Name="MyProject" Path="MyProject.project"/>
<Project Name="MyProject2" Path="MyProject2.project"/>
<BuildMatrix>
<WorkspaceConfiguration Name="Debug" Selected="yes">
<Project Name="MyProject" ConfigName="Debug"/>
<Project Name="MyProject2" ConfigName="Debug"/>
</WorkspaceConfiguration>
<WorkspaceConfiguration Name="Release" Selected="yes">
<Project Name="MyProject" ConfigName="Release"/>
<Project Name="MyProject2" ConfigName="Release"/>
</WorkspaceConfiguration>
</BuildMatrix>
</CodeLite_Workspace>
]]
end
--
-- Projects should include relative path from workspace.
--
function suite.onNestedProjectPath()
location "MyProject"
prepare()
test.capture([[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
<Project Name="MyProject" Path="MyProject/MyProject.project"/>
<BuildMatrix>
<WorkspaceConfiguration Name="Debug" Selected="yes">
<Project Name="MyProject" ConfigName="Debug"/>
</WorkspaceConfiguration>
<WorkspaceConfiguration Name="Release" Selected="yes">
<Project Name="MyProject" ConfigName="Release"/>
</WorkspaceConfiguration>
</BuildMatrix>
</CodeLite_Workspace>
]])
end
function suite.onExternalProjectPath()
location "../MyProject"
prepare()
test.capture([[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
<Project Name="MyProject" Path="../MyProject/MyProject.project"/>
<BuildMatrix>
<WorkspaceConfiguration Name="Debug" Selected="yes">
<Project Name="MyProject" ConfigName="Debug"/>
</WorkspaceConfiguration>
<WorkspaceConfiguration Name="Release" Selected="yes">
<Project Name="MyProject" ConfigName="Release"/>
</WorkspaceConfiguration>
</BuildMatrix>
</CodeLite_Workspace>
]])
end
| bsd-3-clause |
RickvanMiltenburg/vktut | project/android/app/include/vulkan/spirv.lua | 6 | 23353 | -- Copyright (c) 2014-2016 The Khronos Group Inc.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and/or associated documentation files (the "Materials"),
-- to deal in the Materials without restriction, including without limitation
-- the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Materials, and to permit persons to whom the
-- Materials are 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 Materials.
--
-- MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
-- STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
-- HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
--
-- THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS
-- IN THE MATERIALS.
-- This header is automatically generated by the same tool that creates
-- the Binary Section of the SPIR-V specification.
-- Enumeration tokens for SPIR-V, in various styles:
-- C, C++, C++11, JSON, Lua, Python
--
-- - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL
-- - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL
-- - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL
-- - Lua will use tables, e.g.: spv.SourceLanguage.GLSL
-- - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL']
--
-- Some tokens act like mask values, which can be OR'd together,
-- while others are mutually exclusive. The mask-like ones have
-- "Mask" in their name, and a parallel enum that has the shift
-- amount (1 << x) for each corresponding enumerant.
spv = {
MagicNumber = 0x07230203,
Version = 0x00010100,
Revision = 3,
OpCodeMask = 0xffff,
WordCountShift = 16,
SourceLanguage = {
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCL_CPP = 4,
},
ExecutionModel = {
Vertex = 0,
TessellationControl = 1,
TessellationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6,
},
AddressingModel = {
Logical = 0,
Physical32 = 1,
Physical64 = 2,
},
MemoryModel = {
Simple = 0,
GLSL450 = 1,
OpenCL = 2,
},
ExecutionMode = {
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
Isolines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31,
Initializer = 33,
Finalizer = 34,
SubgroupSize = 35,
SubgroupsPerWorkgroup = 36,
},
StorageClass = {
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11,
},
Dim = {
Dim1D = 0,
Dim2D = 1,
Dim3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6,
},
SamplerAddressingMode = {
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4,
},
SamplerFilterMode = {
Nearest = 0,
Linear = 1,
},
ImageFormat = {
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39,
},
ImageChannelOrder = {
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18,
ABGR = 19,
},
ImageChannelDataType = {
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16,
},
ImageOperandsShift = {
Bias = 0,
Lod = 1,
Grad = 2,
ConstOffset = 3,
Offset = 4,
ConstOffsets = 5,
Sample = 6,
MinLod = 7,
},
ImageOperandsMask = {
MaskNone = 0,
Bias = 0x00000001,
Lod = 0x00000002,
Grad = 0x00000004,
ConstOffset = 0x00000008,
Offset = 0x00000010,
ConstOffsets = 0x00000020,
Sample = 0x00000040,
MinLod = 0x00000080,
},
FPFastMathModeShift = {
NotNaN = 0,
NotInf = 1,
NSZ = 2,
AllowRecip = 3,
Fast = 4,
},
FPFastMathModeMask = {
MaskNone = 0,
NotNaN = 0x00000001,
NotInf = 0x00000002,
NSZ = 0x00000004,
AllowRecip = 0x00000008,
Fast = 0x00000010,
},
FPRoundingMode = {
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3,
},
LinkageType = {
Export = 0,
Import = 1,
},
AccessQualifier = {
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2,
},
FunctionParameterAttribute = {
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7,
},
Decoration = {
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44,
MaxByteOffset = 45,
},
BuiltIn = {
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43,
},
SelectionControlShift = {
Flatten = 0,
DontFlatten = 1,
},
SelectionControlMask = {
MaskNone = 0,
Flatten = 0x00000001,
DontFlatten = 0x00000002,
},
LoopControlShift = {
Unroll = 0,
DontUnroll = 1,
DependencyInfinite = 2,
DependencyLength = 3,
},
LoopControlMask = {
MaskNone = 0,
Unroll = 0x00000001,
DontUnroll = 0x00000002,
DependencyInfinite = 0x00000004,
DependencyLength = 0x00000008,
},
FunctionControlShift = {
Inline = 0,
DontInline = 1,
Pure = 2,
Const = 3,
},
FunctionControlMask = {
MaskNone = 0,
Inline = 0x00000001,
DontInline = 0x00000002,
Pure = 0x00000004,
Const = 0x00000008,
},
MemorySemanticsShift = {
Acquire = 1,
Release = 2,
AcquireRelease = 3,
SequentiallyConsistent = 4,
UniformMemory = 6,
SubgroupMemory = 7,
WorkgroupMemory = 8,
CrossWorkgroupMemory = 9,
AtomicCounterMemory = 10,
ImageMemory = 11,
},
MemorySemanticsMask = {
MaskNone = 0,
Acquire = 0x00000002,
Release = 0x00000004,
AcquireRelease = 0x00000008,
SequentiallyConsistent = 0x00000010,
UniformMemory = 0x00000040,
SubgroupMemory = 0x00000080,
WorkgroupMemory = 0x00000100,
CrossWorkgroupMemory = 0x00000200,
AtomicCounterMemory = 0x00000400,
ImageMemory = 0x00000800,
},
MemoryAccessShift = {
Volatile = 0,
Aligned = 1,
Nontemporal = 2,
},
MemoryAccessMask = {
MaskNone = 0,
Volatile = 0x00000001,
Aligned = 0x00000002,
Nontemporal = 0x00000004,
},
Scope = {
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4,
},
GroupOperation = {
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2,
},
KernelEnqueueFlags = {
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2,
},
KernelProfilingInfoShift = {
CmdExecTime = 0,
},
KernelProfilingInfoMask = {
MaskNone = 0,
CmdExecTime = 0x00000001,
},
Capability = {
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57,
SubgroupDispatch = 58,
NamedBarrier = 59,
PipeStorage = 60,
},
Op = {
OpNop = 0,
OpUndef = 1,
OpSourceContinued = 2,
OpSource = 3,
OpSourceExtension = 4,
OpName = 5,
OpMemberName = 6,
OpString = 7,
OpLine = 8,
OpExtension = 10,
OpExtInstImport = 11,
OpExtInst = 12,
OpMemoryModel = 14,
OpEntryPoint = 15,
OpExecutionMode = 16,
OpCapability = 17,
OpTypeVoid = 19,
OpTypeBool = 20,
OpTypeInt = 21,
OpTypeFloat = 22,
OpTypeVector = 23,
OpTypeMatrix = 24,
OpTypeImage = 25,
OpTypeSampler = 26,
OpTypeSampledImage = 27,
OpTypeArray = 28,
OpTypeRuntimeArray = 29,
OpTypeStruct = 30,
OpTypeOpaque = 31,
OpTypePointer = 32,
OpTypeFunction = 33,
OpTypeEvent = 34,
OpTypeDeviceEvent = 35,
OpTypeReserveId = 36,
OpTypeQueue = 37,
OpTypePipe = 38,
OpTypeForwardPointer = 39,
OpConstantTrue = 41,
OpConstantFalse = 42,
OpConstant = 43,
OpConstantComposite = 44,
OpConstantSampler = 45,
OpConstantNull = 46,
OpSpecConstantTrue = 48,
OpSpecConstantFalse = 49,
OpSpecConstant = 50,
OpSpecConstantComposite = 51,
OpSpecConstantOp = 52,
OpFunction = 54,
OpFunctionParameter = 55,
OpFunctionEnd = 56,
OpFunctionCall = 57,
OpVariable = 59,
OpImageTexelPointer = 60,
OpLoad = 61,
OpStore = 62,
OpCopyMemory = 63,
OpCopyMemorySized = 64,
OpAccessChain = 65,
OpInBoundsAccessChain = 66,
OpPtrAccessChain = 67,
OpArrayLength = 68,
OpGenericPtrMemSemantics = 69,
OpInBoundsPtrAccessChain = 70,
OpDecorate = 71,
OpMemberDecorate = 72,
OpDecorationGroup = 73,
OpGroupDecorate = 74,
OpGroupMemberDecorate = 75,
OpVectorExtractDynamic = 77,
OpVectorInsertDynamic = 78,
OpVectorShuffle = 79,
OpCompositeConstruct = 80,
OpCompositeExtract = 81,
OpCompositeInsert = 82,
OpCopyObject = 83,
OpTranspose = 84,
OpSampledImage = 86,
OpImageSampleImplicitLod = 87,
OpImageSampleExplicitLod = 88,
OpImageSampleDrefImplicitLod = 89,
OpImageSampleDrefExplicitLod = 90,
OpImageSampleProjImplicitLod = 91,
OpImageSampleProjExplicitLod = 92,
OpImageSampleProjDrefImplicitLod = 93,
OpImageSampleProjDrefExplicitLod = 94,
OpImageFetch = 95,
OpImageGather = 96,
OpImageDrefGather = 97,
OpImageRead = 98,
OpImageWrite = 99,
OpImage = 100,
OpImageQueryFormat = 101,
OpImageQueryOrder = 102,
OpImageQuerySizeLod = 103,
OpImageQuerySize = 104,
OpImageQueryLod = 105,
OpImageQueryLevels = 106,
OpImageQuerySamples = 107,
OpConvertFToU = 109,
OpConvertFToS = 110,
OpConvertSToF = 111,
OpConvertUToF = 112,
OpUConvert = 113,
OpSConvert = 114,
OpFConvert = 115,
OpQuantizeToF16 = 116,
OpConvertPtrToU = 117,
OpSatConvertSToU = 118,
OpSatConvertUToS = 119,
OpConvertUToPtr = 120,
OpPtrCastToGeneric = 121,
OpGenericCastToPtr = 122,
OpGenericCastToPtrExplicit = 123,
OpBitcast = 124,
OpSNegate = 126,
OpFNegate = 127,
OpIAdd = 128,
OpFAdd = 129,
OpISub = 130,
OpFSub = 131,
OpIMul = 132,
OpFMul = 133,
OpUDiv = 134,
OpSDiv = 135,
OpFDiv = 136,
OpUMod = 137,
OpSRem = 138,
OpSMod = 139,
OpFRem = 140,
OpFMod = 141,
OpVectorTimesScalar = 142,
OpMatrixTimesScalar = 143,
OpVectorTimesMatrix = 144,
OpMatrixTimesVector = 145,
OpMatrixTimesMatrix = 146,
OpOuterProduct = 147,
OpDot = 148,
OpIAddCarry = 149,
OpISubBorrow = 150,
OpUMulExtended = 151,
OpSMulExtended = 152,
OpAny = 154,
OpAll = 155,
OpIsNan = 156,
OpIsInf = 157,
OpIsFinite = 158,
OpIsNormal = 159,
OpSignBitSet = 160,
OpLessOrGreater = 161,
OpOrdered = 162,
OpUnordered = 163,
OpLogicalEqual = 164,
OpLogicalNotEqual = 165,
OpLogicalOr = 166,
OpLogicalAnd = 167,
OpLogicalNot = 168,
OpSelect = 169,
OpIEqual = 170,
OpINotEqual = 171,
OpUGreaterThan = 172,
OpSGreaterThan = 173,
OpUGreaterThanEqual = 174,
OpSGreaterThanEqual = 175,
OpULessThan = 176,
OpSLessThan = 177,
OpULessThanEqual = 178,
OpSLessThanEqual = 179,
OpFOrdEqual = 180,
OpFUnordEqual = 181,
OpFOrdNotEqual = 182,
OpFUnordNotEqual = 183,
OpFOrdLessThan = 184,
OpFUnordLessThan = 185,
OpFOrdGreaterThan = 186,
OpFUnordGreaterThan = 187,
OpFOrdLessThanEqual = 188,
OpFUnordLessThanEqual = 189,
OpFOrdGreaterThanEqual = 190,
OpFUnordGreaterThanEqual = 191,
OpShiftRightLogical = 194,
OpShiftRightArithmetic = 195,
OpShiftLeftLogical = 196,
OpBitwiseOr = 197,
OpBitwiseXor = 198,
OpBitwiseAnd = 199,
OpNot = 200,
OpBitFieldInsert = 201,
OpBitFieldSExtract = 202,
OpBitFieldUExtract = 203,
OpBitReverse = 204,
OpBitCount = 205,
OpDPdx = 207,
OpDPdy = 208,
OpFwidth = 209,
OpDPdxFine = 210,
OpDPdyFine = 211,
OpFwidthFine = 212,
OpDPdxCoarse = 213,
OpDPdyCoarse = 214,
OpFwidthCoarse = 215,
OpEmitVertex = 218,
OpEndPrimitive = 219,
OpEmitStreamVertex = 220,
OpEndStreamPrimitive = 221,
OpControlBarrier = 224,
OpMemoryBarrier = 225,
OpAtomicLoad = 227,
OpAtomicStore = 228,
OpAtomicExchange = 229,
OpAtomicCompareExchange = 230,
OpAtomicCompareExchangeWeak = 231,
OpAtomicIIncrement = 232,
OpAtomicIDecrement = 233,
OpAtomicIAdd = 234,
OpAtomicISub = 235,
OpAtomicSMin = 236,
OpAtomicUMin = 237,
OpAtomicSMax = 238,
OpAtomicUMax = 239,
OpAtomicAnd = 240,
OpAtomicOr = 241,
OpAtomicXor = 242,
OpPhi = 245,
OpLoopMerge = 246,
OpSelectionMerge = 247,
OpLabel = 248,
OpBranch = 249,
OpBranchConditional = 250,
OpSwitch = 251,
OpKill = 252,
OpReturn = 253,
OpReturnValue = 254,
OpUnreachable = 255,
OpLifetimeStart = 256,
OpLifetimeStop = 257,
OpGroupAsyncCopy = 259,
OpGroupWaitEvents = 260,
OpGroupAll = 261,
OpGroupAny = 262,
OpGroupBroadcast = 263,
OpGroupIAdd = 264,
OpGroupFAdd = 265,
OpGroupFMin = 266,
OpGroupUMin = 267,
OpGroupSMin = 268,
OpGroupFMax = 269,
OpGroupUMax = 270,
OpGroupSMax = 271,
OpReadPipe = 274,
OpWritePipe = 275,
OpReservedReadPipe = 276,
OpReservedWritePipe = 277,
OpReserveReadPipePackets = 278,
OpReserveWritePipePackets = 279,
OpCommitReadPipe = 280,
OpCommitWritePipe = 281,
OpIsValidReserveId = 282,
OpGetNumPipePackets = 283,
OpGetMaxPipePackets = 284,
OpGroupReserveReadPipePackets = 285,
OpGroupReserveWritePipePackets = 286,
OpGroupCommitReadPipe = 287,
OpGroupCommitWritePipe = 288,
OpEnqueueMarker = 291,
OpEnqueueKernel = 292,
OpGetKernelNDrangeSubGroupCount = 293,
OpGetKernelNDrangeMaxSubGroupSize = 294,
OpGetKernelWorkGroupSize = 295,
OpGetKernelPreferredWorkGroupSizeMultiple = 296,
OpRetainEvent = 297,
OpReleaseEvent = 298,
OpCreateUserEvent = 299,
OpIsValidEvent = 300,
OpSetUserEventStatus = 301,
OpCaptureEventProfilingInfo = 302,
OpGetDefaultQueue = 303,
OpBuildNDRange = 304,
OpImageSparseSampleImplicitLod = 305,
OpImageSparseSampleExplicitLod = 306,
OpImageSparseSampleDrefImplicitLod = 307,
OpImageSparseSampleDrefExplicitLod = 308,
OpImageSparseSampleProjImplicitLod = 309,
OpImageSparseSampleProjExplicitLod = 310,
OpImageSparseSampleProjDrefImplicitLod = 311,
OpImageSparseSampleProjDrefExplicitLod = 312,
OpImageSparseFetch = 313,
OpImageSparseGather = 314,
OpImageSparseDrefGather = 315,
OpImageSparseTexelsResident = 316,
OpNoLine = 317,
OpAtomicFlagTestAndSet = 318,
OpAtomicFlagClear = 319,
OpImageSparseRead = 320,
OpSizeOf = 321,
OpTypePipeStorage = 322,
OpConstantPipeStorage = 323,
OpCreatePipeFromPipeStorage = 324,
OpGetKernelLocalSizeForSubgroupCount = 325,
OpGetKernelMaxNumSubgroups = 326,
OpTypeNamedBarrier = 327,
OpNamedBarrierInitialize = 328,
OpMemoryNamedBarrier = 329,
OpModuleProcessed = 330,
},
}
| mit |
Frenzie/koreader-base | spec/unit/common_spec.lua | 3 | 2111 | package.path = "common/?.lua;" .. package.path
package.cpath = "common/?.so;" .. package.cpath
require("ffi_wrapper")
local url = require("socket.url")
local http = require("socket.http")
local https = require("ssl.https")
local buffer = require("string.buffer")
local Blitbuffer = require("ffi/blitbuffer")
describe("Common modules", function()
it("should get response from HTTP request", function()
local urls = {
"http://www.example.com",
"https://www.example.com",
}
for i=1, #urls do
local http_scheme = url.parse(urls[i]).scheme == "http"
local request = http_scheme and http.request or https.request
local body, code, headers, status = request(urls[i])
assert.truthy(body)
assert.are.same(code, 200)
assert.truthy(headers)
assert.truthy(status)
end
end)
it("should serialize blitbuffer", function()
local w, h = 600, 800
local bb = Blitbuffer.new(w, h)
local random = math.random
for i = 0, h -1 do
for j = 0, w - 1 do
local color = Blitbuffer.Color4(random(16))
bb:setPixel(j, i, color)
end
end
local t = {
w = bb.w,
h = bb.h,
stride = tonumber(bb.stride),
fmt = bb:getType(),
data = Blitbuffer.tostring(bb),
}
local ser = buffer.encode(t)
local deser = buffer.decode(ser)
assert.are.same(t, deser)
local ss = Blitbuffer.fromstring(deser.w, deser.h, deser.fmt, deser.data, deser.stride)
assert.are.same(bb.w, ss.w)
assert.are.same(bb.h, ss.h)
assert.are.same(bb.stride, ss.stride)
assert.are.same(bb:getType(), ss:getType())
for i = 0, h - 1 do
for j = 0, w - 1 do
local bb_color = bb:getPixel(j, i):getColor4L().a
local ss_color = ss:getPixel(j, i):getColor4L().a
assert.are.same(bb_color, ss_color)
end
end
end)
end)
| agpl-3.0 |
opentechinstitute/luci | protocols/ppp/luasrc/model/cbi/admin_network/proto_pppoe.lua | 59 | 3798 | --[[
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
]]--
local map, section, net = ...
local username, password, ac, service
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
ac = section:taboption("general", Value, "ac",
translate("Access Concentrator"),
translate("Leave empty to autodetect"))
ac.placeholder = translate("auto")
service = section:taboption("general", Value, "service",
translate("Service Name"),
translate("Leave empty to autodetect"))
service.placeholder = translate("auto")
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
function keepalive_failure.write() end
function keepalive_failure.remove() end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
mahdib9/89 | plugins/search_youtube.lua | 674 | 1270 | do
local google_config = load_from_file('data/google.lua')
local function httpsRequest(url)
print(url)
local res,code = https.request(url)
if code ~= 200 then return nil end
return json:decode(res)
end
local function searchYoutubeVideos(text)
local url = 'https://www.googleapis.com/youtube/v3/search?'
url = url..'part=snippet'..'&maxResults=4'..'&type=video'
url = url..'&q='..URL.escape(text)
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local data = httpsRequest(url)
if not data then
print("HTTP Error")
return nil
elseif not data.items then
return nil
end
return data.items
end
local function run(msg, matches)
local text = ''
local items = searchYoutubeVideos(matches[1])
if not items then
return "Error!"
end
for k,item in pairs(items) do
text = text..'http://youtu.be/'..item.id.videoId..' '..
item.snippet.title..'\n\n'
end
return text
end
return {
description = "Search video on youtube and send it.",
usage = "!youtube [term]: Search for a youtube video and send it.",
patterns = {
"^!youtube (.*)"
},
run = run
}
end
| gpl-2.0 |
ioiasff/khp | plugins/search_youtube.lua | 674 | 1270 | do
local google_config = load_from_file('data/google.lua')
local function httpsRequest(url)
print(url)
local res,code = https.request(url)
if code ~= 200 then return nil end
return json:decode(res)
end
local function searchYoutubeVideos(text)
local url = 'https://www.googleapis.com/youtube/v3/search?'
url = url..'part=snippet'..'&maxResults=4'..'&type=video'
url = url..'&q='..URL.escape(text)
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local data = httpsRequest(url)
if not data then
print("HTTP Error")
return nil
elseif not data.items then
return nil
end
return data.items
end
local function run(msg, matches)
local text = ''
local items = searchYoutubeVideos(matches[1])
if not items then
return "Error!"
end
for k,item in pairs(items) do
text = text..'http://youtu.be/'..item.id.videoId..' '..
item.snippet.title..'\n\n'
end
return text
end
return {
description = "Search video on youtube and send it.",
usage = "!youtube [term]: Search for a youtube video and send it.",
patterns = {
"^!youtube (.*)"
},
run = run
}
end
| gpl-2.0 |
leanlyne/ShootColorX | cocos2d/external/lua/luajit/src/src/jit/dis_x86.lua | 99 | 29330 | ----------------------------------------------------------------------------
-- LuaJIT x86/x64 disassembler module.
--
-- Copyright (C) 2005-2013 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- Sending small code snippets to an external disassembler and mixing the
-- output with our own stuff was too fragile. So I had to bite the bullet
-- and write yet another x86 disassembler. Oh well ...
--
-- The output format is very similar to what ndisasm generates. But it has
-- been developed independently by looking at the opcode tables from the
-- Intel and AMD manuals. The supported instruction set is quite extensive
-- and reflects what a current generation Intel or AMD CPU implements in
-- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3,
-- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM)
-- instructions.
--
-- Notes:
-- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported.
-- * No attempt at optimization has been made -- it's fast enough for my needs.
-- * The public API may change when more architectures are added.
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local lower, rep = string.lower, string.rep
-- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on.
local map_opc1_32 = {
--0x
[0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es",
"orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*",
--1x
"adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss",
"sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds",
--2x
"andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa",
"subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das",
--3x
"xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa",
"cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas",
--4x
"incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR",
"decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR",
--5x
"pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR",
"popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR",
--6x
"sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr",
"fs:seg","gs:seg","o16:","a16",
"pushUi","imulVrmi","pushBs","imulVrms",
"insb","insVS","outsb","outsVS",
--7x
"joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj",
"jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj",
--8x
"arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms",
"testBmr","testVmr","xchgBrm","xchgVrm",
"movBmr","movVmr","movBrm","movVrm",
"movVmg","leaVrm","movWgm","popUm",
--9x
"nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR",
"xchgVaR","xchgVaR","xchgVaR","xchgVaR",
"sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait",
"sz*pushfw,pushf","sz*popfw,popf","sahf","lahf",
--Ax
"movBao","movVao","movBoa","movVoa",
"movsb","movsVS","cmpsb","cmpsVS",
"testBai","testVai","stosb","stosVS",
"lodsb","lodsVS","scasb","scasVS",
--Bx
"movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi",
"movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI",
--Cx
"shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi",
"enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS",
--Dx
"shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb",
"fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7",
--Ex
"loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj",
"inBau","inVau","outBua","outVua",
"callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda",
--Fx
"lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm",
"clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm",
}
assert(#map_opc1_32 == 255)
-- Map for 1st opcode byte in 64 bit mode (overrides only).
local map_opc1_64 = setmetatable({
[0x06]=false, [0x07]=false, [0x0e]=false,
[0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false,
[0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false,
[0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:",
[0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb",
[0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb",
[0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb",
[0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb",
[0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false,
[0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false,
}, { __index = map_opc1_32 })
-- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you.
-- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2
local map_opc2 = {
--0x
[0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret",
"invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu",
--1x
"movupsXrm|movssXrm|movupdXrm|movsdXrm",
"movupsXmr|movssXmr|movupdXmr|movsdXmr",
"movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm",
"movlpsXmr||movlpdXmr",
"unpcklpsXrm||unpcklpdXrm",
"unpckhpsXrm||unpckhpdXrm",
"movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm",
"movhpsXmr||movhpdXmr",
"$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm",
"hintnopVm","hintnopVm","hintnopVm","hintnopVm",
--2x
"movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil,
"movapsXrm||movapdXrm",
"movapsXmr||movapdXmr",
"cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt",
"movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr",
"cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm",
"cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm",
"ucomissXrm||ucomisdXrm",
"comissXrm||comisdXrm",
--3x
"wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec",
"opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil,
--4x
"cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm",
"cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm",
"cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm",
"cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm",
--5x
"movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm",
"rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm",
"andpsXrm||andpdXrm","andnpsXrm||andnpdXrm",
"orpsXrm||orpdXrm","xorpsXrm||xorpdXrm",
"addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm",
"cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm",
"cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm",
"subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm",
"divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm",
--6x
"punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm",
"pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm",
"punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm",
"||punpcklqdqXrm","||punpckhqdqXrm",
"movPrVSm","movqMrm|movdquXrm|movdqaXrm",
--7x
"pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu",
"pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu",
"pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|",
"vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$",
nil,nil,
"||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm",
"movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr",
--8x
"joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj",
"jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj",
--9x
"setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm",
"setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm",
--Ax
"push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil,
"push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm",
--Bx
"cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr",
"$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt",
"|popcntVrm","ud2Dp","bt!Vmu","btcVmr",
"bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt",
--Cx
"xaddBmr","xaddVmr",
"cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|",
"pinsrwPrWmu","pextrwDrPmu",
"shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp",
"bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR",
--Dx
"||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm",
"paddqPrm","pmullwPrm",
"|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm",
"psubusbPrm","psubuswPrm","pminubPrm","pandPrm",
"paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm",
--Ex
"pavgbPrm","psrawPrm","psradPrm","pavgwPrm",
"pmulhuwPrm","pmulhwPrm",
"|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr",
"psubsbPrm","psubswPrm","pminswPrm","porPrm",
"paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm",
--Fx
"|||lddquXrm","psllwPrm","pslldPrm","psllqPrm",
"pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$",
"psubbPrm","psubwPrm","psubdPrm","psubqPrm",
"paddbPrm","paddwPrm","padddPrm","ud",
}
assert(map_opc2[255] == "ud")
-- Map for three-byte opcodes. Can't wait for their next invention.
local map_opc3 = {
["38"] = { -- [66] 0f 38 xx
--0x
[0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm",
"pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm",
"psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm",
nil,nil,nil,nil,
--1x
"||pblendvbXrma",nil,nil,nil,
"||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm",
nil,nil,nil,nil,
"pabsbPrm","pabswPrm","pabsdPrm",nil,
--2x
"||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm",
"||pmovsxwqXrm","||pmovsxdqXrm",nil,nil,
"||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm",
nil,nil,nil,nil,
--3x
"||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm",
"||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm",
"||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm",
"||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm",
--4x
"||pmulddXrm","||phminposuwXrm",
--Fx
[0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt",
},
["3a"] = { -- [66] 0f 3a xx
--0x
[0x00]=nil,nil,nil,nil,nil,nil,nil,nil,
"||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu",
"||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu",
--1x
nil,nil,nil,nil,
"||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru",
nil,nil,nil,nil,nil,nil,nil,nil,
--2x
"||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil,
--4x
[0x40] = "||dppsXrmu",
[0x41] = "||dppdXrmu",
[0x42] = "||mpsadbwXrmu",
--6x
[0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu",
[0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu",
},
}
-- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands).
local map_opcvm = {
[0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff",
[0xc8]="monitor",[0xc9]="mwait",
[0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave",
[0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga",
[0xf8]="swapgs",[0xf9]="rdtscp",
}
-- Map for FP opcodes. And you thought stack machines are simple?
local map_opcfp = {
-- D8-DF 00-BF: opcodes with a memory operand.
-- D8
[0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm",
"fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm",
-- DA
"fiaddDm","fimulDm","ficomDm","ficompDm",
"fisubDm","fisubrDm","fidivDm","fidivrDm",
-- DB
"fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp",
-- DC
"faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm",
-- DD
"fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm",
-- DE
"fiaddWm","fimulWm","ficomWm","ficompWm",
"fisubWm","fisubrWm","fidivWm","fidivrWm",
-- DF
"fildWm","fisttpWm","fistWm","fistpWm",
"fbld twordFmp","fildQm","fbstp twordFmp","fistpQm",
-- xx C0-FF: opcodes with a pseudo-register operand.
-- D8
"faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf",
-- D9
"fldFf","fxchFf",{"fnop"},nil,
{"fchs","fabs",nil,nil,"ftst","fxam"},
{"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"},
{"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"},
{"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"},
-- DA
"fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil,
-- DB
"fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf",
{nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil,
-- DC
"fadd toFf","fmul toFf",nil,nil,
"fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf",
-- DD
"ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil,
-- DE
"faddpFf","fmulpFf",nil,{nil,"fcompp"},
"fsubrpFf","fsubpFf","fdivrpFf","fdivpFf",
-- DF
nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil,
}
assert(map_opcfp[126] == "fcomipFf")
-- Map for opcode groups. The subkey is sp from the ModRM byte.
local map_opcgroup = {
arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" },
shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" },
testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" },
testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" },
incb = { "inc", "dec" },
incd = { "inc", "dec", "callUmp", "$call farDmp",
"jmpUmp", "$jmp farDmp", "pushUm" },
sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" },
sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt",
"smsw", nil, "lmsw", "vm*$invlpg" },
bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" },
cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil,
nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" },
pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" },
pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" },
pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" },
pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" },
fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr",
nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" },
prefetch = { "prefetch", "prefetchw" },
prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" },
}
------------------------------------------------------------------------------
-- Maps for register names.
local map_regs = {
B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di",
"r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" },
D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
"r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" },
Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" },
M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
"mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext!
X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" },
}
local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" }
-- Maps for size names.
local map_sz2n = {
B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16,
}
local map_sz2prefix = {
B = "byte", W = "word", D = "dword",
Q = "qword",
M = "qword", X = "xword",
F = "dword", G = "qword", -- No need for sizes/register names for these two.
}
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local code, pos, hex = ctx.code, ctx.pos, ""
local hmax = ctx.hexdump
if hmax > 0 then
for i=ctx.start,pos-1 do
hex = hex..format("%02X", byte(code, i, i))
end
if #hex > hmax then hex = sub(hex, 1, hmax)..". "
else hex = hex..rep(" ", hmax-#hex+2) end
end
if operands then text = text.." "..operands end
if ctx.o16 then text = "o16 "..text; ctx.o16 = false end
if ctx.a32 then text = "a32 "..text; ctx.a32 = false end
if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end
if ctx.rex then
local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "")..
(ctx.rexx and "x" or "")..(ctx.rexb and "b" or "")
if t ~= "" then text = "rex."..t.." "..text end
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false
end
if ctx.seg then
local text2, n = gsub(text, "%[", "["..ctx.seg..":")
if n == 0 then text = ctx.seg.." "..text else text = text2 end
ctx.seg = false
end
if ctx.lock then text = "lock "..text; ctx.lock = false end
local imm = ctx.imm
if imm then
local sym = ctx.symtab[imm]
if sym then text = text.."\t->"..sym end
end
ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text))
ctx.mrm = false
ctx.start = pos
ctx.imm = nil
end
-- Clear all prefix flags.
local function clearprefixes(ctx)
ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false; ctx.a32 = false
end
-- Fallback for incomplete opcodes at the end.
local function incomplete(ctx)
ctx.pos = ctx.stop+1
clearprefixes(ctx)
return putop(ctx, "(incomplete)")
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
clearprefixes(ctx)
return putop(ctx, "(unknown)")
end
-- Return an immediate of the specified size.
local function getimm(ctx, pos, n)
if pos+n-1 > ctx.stop then return incomplete(ctx) end
local code = ctx.code
if n == 1 then
local b1 = byte(code, pos, pos)
return b1
elseif n == 2 then
local b1, b2 = byte(code, pos, pos+1)
return b1+b2*256
else
local b1, b2, b3, b4 = byte(code, pos, pos+3)
local imm = b1+b2*256+b3*65536+b4*16777216
ctx.imm = imm
return imm
end
end
-- Process pattern string and generate the operands.
local function putpat(ctx, name, pat)
local operands, regs, sz, mode, sp, rm, sc, rx, sdisp
local code, pos, stop = ctx.code, ctx.pos, ctx.stop
-- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz
for p in gmatch(pat, ".") do
local x = nil
if p == "V" or p == "U" then
if ctx.rexw then sz = "Q"; ctx.rexw = false
elseif ctx.o16 then sz = "W"; ctx.o16 = false
elseif p == "U" and ctx.x64 then sz = "Q"
else sz = "D" end
regs = map_regs[sz]
elseif p == "T" then
if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end
regs = map_regs[sz]
elseif p == "B" then
sz = "B"
regs = ctx.rex and map_regs.B64 or map_regs.B
elseif match(p, "[WDQMXFG]") then
sz = p
regs = map_regs[sz]
elseif p == "P" then
sz = ctx.o16 and "X" or "M"; ctx.o16 = false
regs = map_regs[sz]
elseif p == "S" then
name = name..lower(sz)
elseif p == "s" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = imm <= 127 and format("+0x%02x", imm)
or format("-0x%02x", 256-imm)
pos = pos+1
elseif p == "u" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = format("0x%02x", imm)
pos = pos+1
elseif p == "w" then
local imm = getimm(ctx, pos, 2); if not imm then return end
x = format("0x%x", imm)
pos = pos+2
elseif p == "o" then -- [offset]
if ctx.x64 then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("[0x%08x%08x]", imm2, imm1)
pos = pos+8
else
local imm = getimm(ctx, pos, 4); if not imm then return end
x = format("[0x%08x]", imm)
pos = pos+4
end
elseif p == "i" or p == "I" then
local n = map_sz2n[sz]
if n == 8 and ctx.x64 and p == "I" then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("0x%08x%08x", imm2, imm1)
else
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then
imm = (0xffffffff+1)-imm
x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm)
else
x = format(imm > 65535 and "0x%08x" or "0x%x", imm)
end
end
pos = pos+n
elseif p == "j" then
local n = map_sz2n[sz]
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "B" and imm > 127 then imm = imm-256
elseif imm > 2147483647 then imm = imm-4294967296 end
pos = pos+n
imm = imm + pos + ctx.addr
if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end
ctx.imm = imm
if sz == "W" then
x = format("word 0x%04x", imm%65536)
elseif ctx.x64 then
local lo = imm % 0x1000000
x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo)
else
x = format("0x%08x", imm)
end
elseif p == "R" then
local r = byte(code, pos-1, pos-1)%8
if ctx.rexb then r = r + 8; ctx.rexb = false end
x = regs[r+1]
elseif p == "a" then x = regs[1]
elseif p == "c" then x = "cl"
elseif p == "d" then x = "dx"
elseif p == "1" then x = "1"
else
if not mode then
mode = ctx.mrm
if not mode then
if pos > stop then return incomplete(ctx) end
mode = byte(code, pos, pos)
pos = pos+1
end
rm = mode%8; mode = (mode-rm)/8
sp = mode%8; mode = (mode-sp)/8
sdisp = ""
if mode < 3 then
if rm == 4 then
if pos > stop then return incomplete(ctx) end
sc = byte(code, pos, pos)
pos = pos+1
rm = sc%8; sc = (sc-rm)/8
rx = sc%8; sc = (sc-rx)/8
if ctx.rexx then rx = rx + 8; ctx.rexx = false end
if rx == 4 then rx = nil end
end
if mode > 0 or rm == 5 then
local dsz = mode
if dsz ~= 1 then dsz = 4 end
local disp = getimm(ctx, pos, dsz); if not disp then return end
if mode == 0 then rm = nil end
if rm or rx or (not sc and ctx.x64 and not ctx.a32) then
if dsz == 1 and disp > 127 then
sdisp = format("-0x%x", 256-disp)
elseif disp >= 0 and disp <= 0x7fffffff then
sdisp = format("+0x%x", disp)
else
sdisp = format("-0x%x", (0xffffffff+1)-disp)
end
else
sdisp = format(ctx.x64 and not ctx.a32 and
not (disp >= 0 and disp <= 0x7fffffff)
and "0xffffffff%08x" or "0x%08x", disp)
end
pos = pos+dsz
end
end
if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end
if ctx.rexr then sp = sp + 8; ctx.rexr = false end
end
if p == "m" then
if mode == 3 then x = regs[rm+1]
else
local aregs = ctx.a32 and map_regs.D or ctx.aregs
local srm, srx = "", ""
if rm then srm = aregs[rm+1]
elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end
ctx.a32 = false
if rx then
if rm then srm = srm.."+" end
srx = aregs[rx+1]
if sc > 0 then srx = srx.."*"..(2^sc) end
end
x = format("[%s%s%s]", srm, srx, sdisp)
end
if mode < 3 and
(not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck.
x = map_sz2prefix[sz].." "..x
end
elseif p == "r" then x = regs[sp+1]
elseif p == "g" then x = map_segregs[sp+1]
elseif p == "p" then -- Suppress prefix.
elseif p == "f" then x = "st"..rm
elseif p == "x" then
if sp == 0 and ctx.lock and not ctx.x64 then
x = "CR8"; ctx.lock = false
else
x = "CR"..sp
end
elseif p == "y" then x = "DR"..sp
elseif p == "z" then x = "TR"..sp
elseif p == "t" then
else
error("bad pattern `"..pat.."'")
end
end
if x then operands = operands and operands..", "..x or x end
end
ctx.pos = pos
return putop(ctx, name, operands)
end
-- Forward declaration.
local map_act
-- Fetch and cache MRM byte.
local function getmrm(ctx)
local mrm = ctx.mrm
if not mrm then
local pos = ctx.pos
if pos > ctx.stop then return nil end
mrm = byte(ctx.code, pos, pos)
ctx.pos = pos+1
ctx.mrm = mrm
end
return mrm
end
-- Dispatch to handler depending on pattern.
local function dispatch(ctx, opat, patgrp)
if not opat then return unknown(ctx) end
if match(opat, "%|") then -- MMX/SSE variants depending on prefix.
local p
if ctx.rep then
p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)"
ctx.rep = false
elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false
else p = "^[^%|]*" end
opat = match(opat, p)
if not opat then return unknown(ctx) end
-- ctx.rep = false; ctx.o16 = false
--XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi]
--XXX remove in branches?
end
if match(opat, "%$") then -- reg$mem variants.
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)")
if opat == "" then return unknown(ctx) end
end
if opat == "" then return unknown(ctx) end
local name, pat = match(opat, "^([a-z0-9 ]*)(.*)")
if pat == "" and patgrp then pat = patgrp end
return map_act[sub(pat, 1, 1)](ctx, name, pat)
end
-- Get a pattern from an opcode map and dispatch to handler.
local function dispatchmap(ctx, opcmap)
local pos = ctx.pos
local opat = opcmap[byte(ctx.code, pos, pos)]
pos = pos + 1
ctx.pos = pos
return dispatch(ctx, opat)
end
-- Map for action codes. The key is the first char after the name.
map_act = {
-- Simple opcodes without operands.
[""] = function(ctx, name, pat)
return putop(ctx, name)
end,
-- Operand size chars fall right through.
B = putpat, W = putpat, D = putpat, Q = putpat,
V = putpat, U = putpat, T = putpat,
M = putpat, X = putpat, P = putpat,
F = putpat, G = putpat,
-- Collect prefixes.
[":"] = function(ctx, name, pat)
ctx[pat == ":" and name or sub(pat, 2)] = name
if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes.
end,
-- Chain to special handler specified by name.
["*"] = function(ctx, name, pat)
return map_act[name](ctx, name, sub(pat, 2))
end,
-- Use named subtable for opcode group.
["!"] = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2))
end,
-- o16,o32[,o64] variants.
sz = function(ctx, name, pat)
if ctx.o16 then ctx.o16 = false
else
pat = match(pat, ",(.*)")
if ctx.rexw then
local p = match(pat, ",(.*)")
if p then pat = p; ctx.rexw = false end
end
end
pat = match(pat, "^[^,]*")
return dispatch(ctx, pat)
end,
-- Two-byte opcode dispatch.
opc2 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc2)
end,
-- Three-byte opcode dispatch.
opc3 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc3[pat])
end,
-- VMX/SVM dispatch.
vm = function(ctx, name, pat)
return dispatch(ctx, map_opcvm[ctx.mrm])
end,
-- Floating point opcode dispatch.
fp = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
local rm = mrm%8
local idx = pat*8 + ((mrm-rm)/8)%8
if mrm >= 192 then idx = idx + 64 end
local opat = map_opcfp[idx]
if type(opat) == "table" then opat = opat[rm+1] end
return dispatch(ctx, opat)
end,
-- REX prefix.
rex = function(ctx, name, pat)
if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed.
for p in gmatch(pat, ".") do ctx["rex"..p] = true end
ctx.rex = true
end,
-- Special case for nop with REX prefix.
nop = function(ctx, name, pat)
return dispatch(ctx, ctx.rex and pat or "nop")
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
ofs = ofs + 1
ctx.start = ofs
ctx.pos = ofs
ctx.stop = stop
ctx.imm = nil
ctx.mrm = false
clearprefixes(ctx)
while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end
if ctx.pos ~= ctx.start then incomplete(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) - 1
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 16
ctx.x64 = false
ctx.map1 = map_opc1_32
ctx.aregs = map_regs.D
return ctx
end
local function create64_(code, addr, out)
local ctx = create_(code, addr, out)
ctx.x64 = true
ctx.map1 = map_opc1_64
ctx.aregs = map_regs.Q
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
local function disass64_(code, addr, out)
create64_(code, addr, out):disass()
end
-- Return register name for RID.
local function regname_(r)
if r < 8 then return map_regs.D[r+1] end
return map_regs.X[r-7]
end
local function regname64_(r)
if r < 16 then return map_regs.Q[r+1] end
return map_regs.X[r-15]
end
-- Public module functions.
module(...)
create = create_
create64 = create64_
disass = disass_
disass64 = disass64_
regname = regname_
regname64 = regname64_
| mit |
HEYAHONG/nodemcu-firmware | lua_modules/ds3231/ds3231-web.lua | 7 | 1339 | local ds3231 = require('ds3231')
-- ESP-01 GPIO Mapping
local gpio0, gpio2 = 3, 4
local port = 80
local days = {
[1] = "Sunday",
[2] = "Monday",
[3] = "Tuesday",
[4] = "Wednesday",
[5] = "Thursday",
[6] = "Friday",
[7] = "Saturday"
}
local months = {
[1] = "January",
[2] = "Febuary",
[3] = "March",
[4] = "April",
[5] = "May",
[6] = "June",
[7] = "July",
[8] = "August",
[9] = "September",
[10] = "October",
[11] = "November",
[12] = "December"
}
do
i2c.setup(0, gpio0, gpio2, i2c.SLOW) -- call i2c.setup() only once
local srv = net.createServer(net.TCP)
srv:listen(port, function(conn)
local second, minute, hour, day, date, month, year = ds3231.getTime()
local prettyTime = string.format("%s, %s %s %s %s:%s:%s",
days[day], date, months[month], year, hour, minute, second)
conn:send("HTTP/1.1 200 OK\nContent-Type: text/html\nRefresh: 5\n\n" ..
"<!DOCTYPE HTML>" ..
"<html><body>" ..
"<b>ESP8266</b></br>" ..
"Time and Date: " .. prettyTime .. "<br>" ..
"Node ChipID : " .. node.chipid() .. "<br>" ..
"Node MAC : " .. wifi.sta.getmac() .. "<br>" ..
"Node Heap : " .. node.heap() .. "<br>" ..
"Timer Ticks : " .. tmr.now() .. "<br>" ..
"</html></body>")
conn:on("sent",function(sck) sck:close() end)
end)
end
| mit |
JarnoVgr/Mr.Green-MTA-Resources | resources/[gameplay]/-shaders-palette/c_rtpool.lua | 4 | 2366 | --
-- c_rtpool.lua
--
scx, scy = guiGetScreenSize ()
-----------------------------------------------------------------------------------
-- Pool of render targets
-----------------------------------------------------------------------------------
RTPool = {}
RTPool.list = {}
function RTPool.frameStart()
for rt,info in pairs(RTPool.list) do
info.bInUse = false
end
end
function RTPool.GetUnused( sx, sy )
-- Find unused existing
for rt,info in pairs(RTPool.list) do
if not info.bInUse and info.sx == sx and info.sy == sy then
info.bInUse = true
return rt
end
end
-- Add new
-- outputDebugString( "creating new RT " .. tostring(sx) .. " x " .. tostring(sy) )
local rt = dxCreateRenderTarget( sx, sy )
if rt then
RTPool.list[rt] = { bInUse = true, sx = sx, sy = sy }
end
return rt
end
function RTPool.clear()
for rt,info in pairs(RTPool.list) do
destroyElement(rt)
end
RTPool.list = {}
end
-----------------------------------------------------------------------------------
-- DebugResults
-- Store all the rendertarget results for debugging
-----------------------------------------------------------------------------------
DebugResults = {}
DebugResults.items = {}
function DebugResults.frameStart()
DebugResults.items = {}
end
function DebugResults.addItem( rt, label )
table.insert( DebugResults.items, { rt=rt, label=label } )
end
function DebugResults.drawItems( sizeX, sliderX, sliderY )
local posX = 5
local gapX = 4
local sizeY = sizeX * 90 / 140
local textSizeY = 15 + 10
local posY = 5
local textColor = tocolor(0,255,0,255)
local textShad = tocolor(0,0,0,255)
local numImages = #DebugResults.items
local totalWidth = numImages * sizeX + (numImages-1) * gapX
local totalHeight = sizeY + textSizeY
posX = posX - (totalWidth - (scx-10)) * sliderX / 100
posY = posY - (totalHeight - scy) * sliderY / 100
local textY = posY+sizeY+1
for index,item in ipairs(DebugResults.items) do
dxDrawImage( posX, posY, sizeX, sizeY, item.rt )
local sizeLabel = string.format( "%d) %s %dx%d", index, item.label, dxGetMaterialSize( item.rt ) )
dxDrawText( sizeLabel, posX+1.0, textY+1, posX+sizeX+1.0, textY+16, textShad, 1, "arial", "center", "top", true )
dxDrawText( sizeLabel, posX, textY, posX+sizeX, textY+15, textColor, 1, "arial", "center", "top", true )
posX = posX + sizeX + gapX
end
end | mit |
mrvigeo/NewTelegram | plugins/owners.lua | 284 | 12473 |
local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function show_group_settingsmod(msg, data, target)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
opentechinstitute/luci | applications/luci-diag-devinfo/luasrc/controller/luci_diag/luci_diag_devinfo.lua | 76 | 2144 | --[[
Luci diag - Diagnostics controller module
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.controller.luci_diag.luci_diag_devinfo", package.seeall)
function index()
local e
e = entry({"admin", "voice", "diag", "phones"}, arcombine(cbi("luci_diag/smap_devinfo"), cbi("luci_diag/smap_devinfo_config")), _("Phones"), 10)
e.leaf = true
e.subindex = true
e.dependent = true
e = entry({"admin", "voice", "diag", "phones", "config"}, cbi("luci_diag/smap_devinfo_config"), _("Configure"), 10)
e = entry({"admin", "status", "smap_devinfo"}, cbi("luci_diag/smap_devinfo"), _("SIP Devices on Network"), 120)
e.leaf = true
e.dependent = true
e = entry({"admin", "network", "diag_config", "netdiscover_devinfo_config"}, cbi("luci_diag/netdiscover_devinfo_config"), _("Network Device Scan"), 100)
e.leaf = true
e.dependent = true
e = entry({"admin", "network", "diag_config", "smap_devinfo_config"}, cbi("luci_diag/smap_devinfo_config"), _("SIP Device Scan"))
e.leaf = true
e.dependent = true
e = entry({"admin", "status", "netdiscover_devinfo"}, cbi("luci_diag/netdiscover_devinfo"), _("Devices on Network"), 90)
e.dependent = true
e = entry({"admin", "network", "mactodevinfo"}, cbi("luci_diag/mactodevinfo"), _("MAC Device Info Overrides"), 190)
e.dependent = true
e = entry({"mini", "diag", "phone_scan"}, cbi("luci_diag/smap_devinfo_mini"), _("Phone Scan"), 100)
e.dependent = true
e = entry({"mini", "voice", "phones", "phone_scan_config"}, cbi("luci_diag/smap_devinfo_config_mini"), _("Config Phone Scan"), 90)
e.dependent = true
e = entry({"mini", "diag", "netdiscover_devinfo"}, cbi("luci_diag/netdiscover_devinfo_mini"), _("Network Device Scan"), 10)
e.dependent = true
e = entry({"mini", "network", "netdiscover_devinfo_config"}, cbi("luci_diag/netdiscover_devinfo_config_mini"), _("Device Scan Config"))
e.dependent = true
end
| apache-2.0 |
opentechinstitute/luci | modules/rpc/luasrc/jsonrpcbind/uci.lua | 81 | 1914 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci".cursor()
local ucis = require "luci.model.uci".cursor_state()
local table = require "table"
module "luci.jsonrpcbind.uci"
_M, _PACKAGE, _NAME = nil, nil, nil
function add(config, ...)
uci:load(config)
local stat = uci:add(config, ...)
return uci:save(config) and stat
end
function apply(config)
return uci:apply(config)
end
function changes(...)
return uci:changes(...)
end
function commit(config)
return uci:load(config) and uci:commit(config)
end
function delete(config, ...)
uci:load(config)
return uci:delete(config, ...) and uci:save(config)
end
function delete_all(config, ...)
uci:load(config)
return uci:delete_all(config, ...) and uci:save(config)
end
function foreach(config, stype)
uci:load(config)
local sections = {}
return uci:foreach(config, stype, function(section)
table.insert(sections, section)
end) and sections
end
function get(config, ...)
uci:load(config)
return uci:get(config, ...)
end
function get_all(config, ...)
uci:load(config)
return uci:get_all(config, ...)
end
function get_state(config, ...)
ucis:load(config)
return ucis:get(config, ...)
end
function revert(config)
return uci:load(config) and uci:revert(config)
end
function section(config, ...)
uci:load(config)
return uci:section(config, ...) and uci:save(config)
end
function set(config, ...)
uci:load(config)
return uci:set(config, ...) and uci:save(config)
end
function tset(config, ...)
uci:load(config)
return uci:tset(config, ...) and uci:save(config)
end
| apache-2.0 |
lsaint/act | script/room.lua | 1 | 13673 |
require "utility"
require "round"
require "gift"
require "db"
GameRoom = {}
GameRoom.__index = GameRoom
function GameRoom.new(tsid, sid)
local self = setmetatable({}, GameRoom)
self.tsid = tsid
self.sid = sid
self.uid2player = {}
self.presenters = {}
self.status = "Ready"
self.mode = "MODE_ACT"
self:init()
return self
end
function GameRoom.init(self)
print("init")
self.over = {}
self.scores = {0, 0}
self.timer = Timer:new(self.sid)
self.guess = nil
self.giftmgr = GiftMgr:new(self.tsid, self.sid, self.presenters)
self.roundmgr = RoundMgr:new(self)
self.billboard = {topn = GetBillBoard(self.tsid)}
self.timer:settimer(SAMPLER_INTERVAL, nil, self.postSamele, self)
end
--self:SendMsg("S2CLoginRep", rep, {player.uid}) -- multi
function GameRoom.SendMsg(self, pname, msg, uids)
SendMsg(pname, msg, uids, self.tsid, self.sid)
end
--self:Broadcast("S2CLoginRep", rep) -- all
function GameRoom.Broadcast(self, pname, msg)
SendMsg(pname, msg, {}, self.tsid, self.sid)
end
function GameRoom.settimer(self, interval, count, func, ...)
return self.timer:settimer(interval, count, func, ...)
end
function GameRoom.notifyStatus(self, st)
self.status = st
self:Broadcast("S2CNotifyStatus", {status = st})
end
function GameRoom.A(self)
return self.presenters[1]
end
function GameRoom.B(self)
return self.presenters[2]
end
function GameRoom.updateBillboard(self)
self.billboard = {topn = GetBillBoard(self.tsid)}
end
function GameRoom.addPlayer(self, player)
local n = self.uid2player.n or 0
self.uid2player[player.uid] = player
self.uid2player.n = n + 1
end
function GameRoom.delPlayer(self, player)
local n = self.uid2player.n or 0
self.uid2player[player.uid] = nil
self.uid2player.n = n - 1
end
function GameRoom.OnLogin(self, player, req)
local rep = { ret = "UNMATCH_VERSION"}
local v = req.version:split(".")
if #v < 2 or tonumber(v[1]) ~= V1 or tonumber(v[2]) ~= V2 then
player:SendMsg("S2CLoginRep", rep)
return
end
self:addPlayer(player)
rep = {
ret = "OK",
mode = self.mode,
status = self.status,
user = { },
}
rep.user.power = self.giftmgr:getPower(player.uid)
player:SendMsg("S2CLoginRep", rep)
player:SendMsg("S2CNotifyPrelude", self:getPrelude())
player:SendMsg("S2CNotifyBillboard", self.billboard)
if self.status == "Poll" then
player:SendMsg("S2CNotfiyPunishOptions",
{options = self.giftmgr.options, loser = self:getLoser().user})
elseif self.status == "Punish" then
player:SendMsg("S2CNotfiyPunishOptions",
{options = self.giftmgr.options, loser = self:getLoser().user})
player:SendMsg("S2CNotifyPunish", {punish = self.giftmgr:getPollResult()})
player:SendMsg("S2CNotifyScores", {scores = self.scores})
elseif self.status == "Round" and self.roundmgr then
local remain_time = self.roundmgr:GetRemainTime()
if remain_time < 0 then return end
player:SendMsg("S2CNotifyRoundStart", {
presenter = {uid = self.roundmgr:GetCurPresenter().uid},
round = self.roundmgr.roundNum,
mot = self.roundmgr:GetCurMotion(),
time = remain_time,
})
end
SaveName(player.uid, player.name)
end
function GameRoom.OnChangeMode(self, player, req)
print("changemode", dump(req))
local rep = {ret = "FL"}
if player.role ~= "Attendee" and req.mode ~= self.mode and self.status == "Ready" then
self.mode = req.mode
rep.ret = "OK"
self:Broadcast("S2CNotifyChangeMode",
{mode = self.mode, user = {uid = player.uid, name = player.name}})
self:init()
end
player:SendMsg("S2CChangeModeRep", rep)
end
function GameRoom.OnPrelude(self, player, req)
local a, b = self:A(), self:B()
local r1 = self:updateRole(player, a, req.user.role, "CandidateA", "PresenterA", 1, b)
local r2 = self:updateRole(player, b, req.user.role, "CandidateB", "PresenterB", 2, a)
if r1 or r2 then
self:Broadcast("S2CNotifyPrelude", self:getPrelude())
else
print("update role FL")
return
end
if a and b then
if a.role == "PresenterA" and b.role == "PresenterB" then
tprint("START", self.tsid, self.sid)
self:notifyStatus("Round")
self:settimer(5, 1, self.roundmgr.RoundStart, self.roundmgr)
self:settimer(BC_TOPN_INTERVAL, nil, self.notifyTopn, self)
self:settimer(BC_BILLBOARD_INTERVAL, nil, self.notifyBillboard, self)
self.scoreTimerId = self:settimer(BC_SCORE_INTERVAL, nil, self.notifyScore, self)
self.giftmgr.presenters = self.presenters
end
end
end
function GameRoom.updateRole(self, player, cur, role, ca, pr, idx, oth)
local r, uid = nil, player.uid
if cur then
if cur.role == ca and role == pr and uid == cur.uid then
r = "OK"; cur.role = role
end
if cur.role == ca and role == "Attendee" and uid == cur.uid then
r = "OK"; cur.role = role
self.presenters[idx] = nil
end
if cur.role == pr and role == "Attendee" and uid == cur.uid
and self.status == "Ready" then
r = "OK"; cur.role = role
self.presenters[idx] = nil
end
if cur.role == role and role == ca then
r = "OCCUPY"
end
else
if role == ca and oth ~= player then
r = "OK"
player.role = role
self.presenters[idx] = player
end
end
if r then
player:SendMsg("S2CPreludeRep", {ret = r})
end
return r
end
function GameRoom.getPrelude(self)
local a, b = self:A(), self:B()
local rep = {}
if not a and not b then
return rep
elseif a and b then
rep = {a = {uid = a.uid, role = a.role}, b = {uid = b.uid, role = b.role}}
elseif not b then
rep = {a = {uid = a.uid, role = a.role}}
else
rep = {b = {uid = b.uid, role = b.role}}
end
return rep
end
function GameRoom.notifyScore(self)
local bc = {scores = self.scores}
self:Broadcast("S2CNotifyScores", bc)
end
function GameRoom.pollStart(self)
print("pollStart")
self:notifyStatus("Poll")
local bc = {options = RandomPunish({public=3, private=1, sid=self.tsid}),
loser = self:getLoser().user}
self.giftmgr.options = bc.options
self:Broadcast("S2CNotfiyPunishOptions", bc)
self.timer:settimer(POLL_TIME, 1, self.punishStart, self)
self.timer:settimer(BC_POLLS_INTERVAL, POLL_TIME/BC_POLLS_INTERVAL+1, self.notifyPolls, self)
self.timer:rmtimer(self.scoreTimerId)
end
function GameRoom.OnPoll(self, player, req)
local r, p, idx = self.giftmgr:poll(player, req.punish_id)
player:SendMsg("S2CPollRep", {ret = r})
if p > 1 then
self:Broadcast("S2CNotifyPowerPoll", {
user = {
name = player.name,
power = p,
},
id = idx,
})
end
end
function GameRoom.notifyPolls(self)
self:Broadcast("S2CNotifyPolls", {polls = self.giftmgr.polls})
end
function GameRoom.punishStart(self)
print("punishStart")
self:notifyStatus("Punish")
self:Broadcast("S2CNotifyPunish", {punish = self.giftmgr:getPollResult()})
end
function GameRoom.OnPunishOver(self, player, req)
print("PunishOver")
if #self.over >= 2 then return end
table.insert(self.over, player)
local rep = {ret = "WAIT_OTHER"}
if #self.over == 2 then
self:stopGame()
rep.ret = "OK"
else
print("waiting other over")
self:Broadcast("S2CNotifyPunishOver",
{presenter = {uid = self.over[1].uid}})
end
player:SendMsg("S2CPunishOverRep", rep)
end
function GameRoom.OnStopGame(self, player, req)
print("OnStopGame")
if player:isAorB() then
self:stopGame(STOP_LEFT, player.name)
end
end
function GameRoom.OnAdminClear(self, player, req)
if player.privilege >= 200 and #self.presenters > 0 then
self:setPresenter2Attendee(self:A())
self:setPresenter2Attendee(self:B())
self:stopGame(STOP_ADMIN, player.name)
end
end
function GameRoom.stopGame(self, t, n)
print("stopGame", t, n)
self:notifyStatus("Ready")
self:init()
self:setPresenter2Candidate()
self:Broadcast("S2CNotifyPrelude", self:getPrelude())
self:Broadcast("S2CNotifyChat", { msg = "", user = { name = n }, type = t })
end
function GameRoom.OnRegGift(self, player, req)
self.giftmgr:regGiftOrder(player, req)
end
function GameRoom.OnGiftCb(self, op, from_uid, to_uid, gid, gcount, orderid)
tprint("OnGiftCb", op, from_uid, to_uid, gid, gcount, orderid)
if op == 1 then
GiftMgr.finishGift(from_uid, orderid, gid, gcount)
end
local req, giver = GiftMgr.orderid2req[orderid], self.uid2player[from_uid]
if giver then
giver:SendMsg("S2CGiftRep", {op = op, orderid = orderid})
end
if not req or op ~= 1 then
-- not register or pay unsucess, nothing to do with power
SaveGift({orderid=orderid, step=STEP_GIFT_UNSUCESS, op_ret=op})
return
end
if self.status ~= "Ready" then
self.giftmgr:increasePower(from_uid, to_uid, gid, gcount)
end
GiftMgr.orderid2req[orderid] = nil
local receiver = self.uid2player[to_uid]
local gname, rname, guid, ruid = "", "", 0, 0
if receiver then
rname = receiver.name
ruid = receiver.uid
end
if giver then
gname = giver.name
guid = giver.uid
self.giftmgr:sign(guid, gname)
end
local bc = {
giver = {name = gname, uid = guid},
receiver = {name = rname, uid = ruid},
gift = {id = gid, count = gcount},
}
self:Broadcast("S2CNotifyGift", bc)
end
function GameRoom.OnChat(self, player, req)
local bc = {
msg = req.msg,
user = {
uid = player.uid,
name = player.name,
}
}
if self.status == "Round" and self.guess then
local ret, isfirst, answer = self.guess:guess(player, req.msg)
bc.msg = answer
bc.correct = ret
if ret then
if isfirst then
self:addScore()
else
return
end
end
end
self:Broadcast("S2CNotifyChat", bc)
end
function GameRoom.addScore(self)
if self.roundmgr:GetCurPresenter() == self.presenters[1] then
self.scores[1] = self.scores[1] + BINGO_SCORE
elseif self.roundmgr:GetCurPresenter() == self.presenters[2] then
self.scores[2] = self.scores[2] + BINGO_SCORE
end
end
function GameRoom.getLoser(self)
local idx = 1
if self.scores[2] < self.scores[1] then
idx = 2
elseif self.scores[2] == self.scores[1] then
idx = math.random(2)
end
return self.presenters[idx]
end
function GameRoom.notifyVips(self)
local a, b = self.giftmgr:vips()
self:Broadcast("S2CNotifyVips", {a_vip = a, b_vip = b})
end
function GameRoom.notifyTopn(self)
self:Broadcast("S2CNotifyTopnGiver", {topn = self.giftmgr:topn()})
end
function GameRoom.notifyBillboard(self)
self:updateBillboard()
self:Broadcast("S2CNotifyBillboard", self.billboard)
end
function GameRoom.setPresenter2Attendee(self, player)
if not player then return end
if self:A() and player.uid == self:A().uid then
player.role = "Attendee"
self.presenters[1] = nil
end
if self:B() and player.uid == self:B().uid then
player.role = "Attendee"
self.presenters[2] = nil
end
end
function GameRoom.setPresenter2Candidate(self)
if self:A() then self:A().role = "CandidateA" end
if self:B() then self:B().role = "CandidateB" end
end
function GameRoom.OnLogout(self, player, req)
if not player then return end
print("OnLogout", player.uid, player.role)
if player:isAorB() then
self:setPresenter2Attendee(player)
if self.status ~= "Ready" then
self:stopGame(STOP_LOGOUT, player.name)
else
self:Broadcast("S2CNotifyPrelude", self:getPrelude())
end
end
self:delPlayer(player)
end
function GameRoom.OnAbortRound(self, player, req)
if self.roundmgr:AbortRound(player, req.round_num) then
self:Broadcast("S2CNotifyAbortRound", {user = {uid = player.uid}})
end
end
function GameRoom.OnNetCtrl(self, dt)
if dt.op == "restart" then
tprint("[CTRL]RESTART")
local defer = dt.defer or "60"
self:Broadcast("S2CNotifyChat", {msg = defer, type = STOP_RESTART})
end
end
function GameRoom.postSamele(self)
local p = {"report", self.tsid, self.sid, self.uid2player.n, self.mode, self.status, SAMPLER_PWD}
local d = string.format("?action=%s&tsid=%s&ssid=%s&ccu=%s&mode=%s&status=%s&pwd=%s", unpack(p))
--local ret = GoPost(string.format("%s%s", SAMPLER_URL, d), "L")
GoPostAsync(string.format("%s%s", SAMPLER_URL, d), "L")
end
function GameRoom.OnPing(self, player, req)
end
function GameRoom.checkPing(self)
print("checkping")
local now = os.time()
for uid, player in pairs(self.uid2player) do
if now - player.lastping > PING_LOST then
print("ping lost", uid)
self:OnLogout(player)
end
end
end
function GameRoom.OnInvildProto(self, uid, pname)
self:SendMsg("S2CReLogin", {}, {uid})
end
| apache-2.0 |
adib1380/antispam | plugins/get.lua | 613 | 1067 | local function get_variables_hash(msg)
if msg.to.type == 'chat' then
return 'chat:'..msg.to.id..':variables'
end
if msg.to.type == 'user' then
return 'user:'..msg.from.id..':variables'
end
end
local function list_variables(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
text = text..names[i]..'\n'
end
return text
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return'Not found, use "!get" to list variables'
else
return var_name..' => '..value
end
end
end
local function run(msg, matches)
if matches[2] then
return get_value(msg, matches[2])
else
return list_variables(msg)
end
end
return {
description = "Retrieves variables saved with !set",
usage = "!get (value_name): Returns the value_name value.",
patterns = {
"^(!get) (.+)$",
"^!get$"
},
run = run
}
| gpl-2.0 |
opentechinstitute/luci | applications/luci-radvd/luasrc/model/cbi/radvd/prefix.lua | 74 | 3766 | --[[
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 - Prefix"),
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) ~= "prefix" then
luci.http.redirect(m.redirect)
return
end
s = m:section(NamedSection, sid, "interface", translate("Prefix Configuration"))
s.addremove = false
s:tab("general", translate("General"))
s:tab("advanced", translate("Advanced"))
--
-- 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, "prefix", translate("Prefixes"),
translate("Advertised IPv6 prefixes. If empty, the current interface prefix is used"))
o.optional = true
o.datatype = "ip6addr"
o.placeholder = translate("default")
function o.cfgvalue(self, section)
local l = { }
local v = m.uci:get_list("radvd", section, "prefix")
for v in utl.imatch(v) do
l[#l+1] = v
end
return l
end
o = s:taboption("general", Flag, "AdvOnLink", translate("On-link determination"),
translate("Indicates that this prefix can be used for on-link determination (RFC4861)"))
o.rmempty = false
o.default = "1"
o = s:taboption("general", Flag, "AdvAutonomous", translate("Autonomous"),
translate("Indicates that this prefix can be used for autonomous address configuration (RFC4862)"))
o.rmempty = false
o.default = "1"
--
-- Advanced
--
o = s:taboption("advanced", Flag, "AdvRouterAddr", translate("Advertise router address"),
translate("Indicates that the address of interface is sent instead of network prefix, as is required by Mobile IPv6"))
o = s:taboption("advanced", Value, "AdvValidLifetime", translate("Valid lifetime"),
translate("Advertises the length of time in seconds that the prefix is valid for the purpose of on-link determination."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 86400
o = s:taboption("advanced", Value, "AdvPreferredLifetime", translate("Preferred lifetime"),
translate("Advertises the length of time in seconds that addresses generated from the prefix via stateless address autoconfiguration remain preferred."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 14400
o = s:taboption("advanced", Value, "Base6to4Interface", translate("6to4 interface"),
translate("Specifies a logical interface name to derive a 6to4 prefix from. The interfaces public IPv4 address is combined with 2002::/3 and the value of the prefix option"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.unspecified = true
return m
| apache-2.0 |
tinydanbo/Impoverished-Starfighter | game/enemies/mediumFrigate.lua | 1 | 2348 | Class = require "lib.hump.class"
Enemy = require "entities.enemy"
vector = require "lib.hump.vector"
EnemyBullet = require "entities.enemyBullet"
EntityTypes = require "entities.types"
MediumFrigate = Class{__includes = Enemy,
init = function(self, x, y, state)
Enemy.init(self, x, y, state)
self.health = 200
self.image = love.graphics.newImage("data/img/enemy/medium-frigate/frigate.png")
self.rotation = 0
self.phase = 1
self.burstRate = 1
self.burstCounter = 0
self.salvoCount = 0
self.salvoRate = 0.2
self.salvoCounter = 0
self.hitbox = {
x1 = x - 70,
x2 = x + 70,
y1 = y - 70,
y2 = y + 70
}
end,
}
function MediumFrigate:update(dt)
local player = self.state.player
local movement = vector(0, 30)
self:move(movement * dt)
self.burstCounter = self.burstCounter + dt
if self.burstCounter > self.burstRate then
self.burstCounter = self.burstCounter - self.burstRate
if self.phase == 1 then
local difference = self.state.player.position - self.position
local aimAt = difference:normalized()
local x,y = self.position:unpack()
for i=-5,5,1 do
local phi = (20*i) * (math.pi / 180)
local spreadAimAt = aimAt:rotated(phi)
local bulletVel = spreadAimAt * 130
local newBullet = EnemyBullet(x+(spreadAimAt.x * 50), y+(spreadAimAt.y * 50), bulletVel.x, bulletVel.y, self.state)
self.state.manager:addEntity(newBullet, EntityTypes.ENEMY_BULLET)
end
self.phase = 2
elseif self.phase == 2 then
self.salvoCount = 5
end
end
if self.salvoCount > 0 then
self.salvoCounter = self.salvoCounter + dt
if self.salvoCounter > self.salvoRate then
self.salvoCounter = self.salvoCounter - self.salvoRate
self.salvoCount = self.salvoCount - 1
local difference = self.state.player.position - self.position
local aimAt = difference:normalized()
local bulletVel = aimAt * 180
local x,y = self.position:unpack()
local newBullet = EnemyBullet(x, y, bulletVel.x, bulletVel.y, self.state)
self.state.manager:addEntity(newBullet, EntityTypes.ENEMY_BULLET)
if self.salvoCount == 0 then
self.phase = 1
end
end
end
end
function MediumFrigate:draw()
local x,y = self.position:unpack()
love.graphics.setColor(255, 255, 255)
love.graphics.draw(self.image, x, y, self.rotation, 1, 1, 85, 71)
Entity.draw(self)
end
return MediumFrigate | mit |
opentechinstitute/luci | applications/luci-meshwizard/luasrc/model/cbi/freifunk/meshwizard.lua | 92 | 6917 | -- wizard rewrite wip
local uci = require "luci.model.uci".cursor()
local sys = require "luci.sys"
local util = require "luci.util"
local ip = require "luci.ip"
local community = "profile_" .. (uci:get("freifunk", "community", "name") or "Freifunk")
local mesh_network = ip.IPv4(uci:get_first(community, "community", "mesh_network") or "10.0.0.0/8")
local community_ipv6 = uci:get_first(community, "community", "ipv6") or 0
local community_ipv6mode = uci:get_first(community, "community", "ipv6_config") or "static"
local meshkit_ipv6 = uci:get("meshwizard", "ipv6", "enabled") or 0
local community_vap = uci:get_first(community, "community", "vap") or 0
m = Map("meshwizard", translate("Wizard"), translate("This wizard will assist you in setting up your router for Freifunk " ..
"or another similar wireless community network."))
n = m:section(NamedSection, "netconfig", nil, translate("Interfaces"))
n.anonymous = true
-- common functions
function cbi_configure(device)
local configure = n:taboption(device, Flag, device .. "_config", translate("Configure this interface"),
translate("Note: this will set up this interface for mesh operation, i.e. add it to zone 'freifunk' and enable olsr."))
end
function cbi_ip4addr(device)
local ip4addr = n:taboption(device, Value, device .. "_ip4addr", translate("Mesh IP address"),
translate("This is a unique address in the mesh (e.g. 10.1.1.1) and has to be registered at your local community."))
ip4addr:depends(device .. "_config", 1)
ip4addr.datatype = "ip4addr"
function ip4addr.validate(self, value)
local x = ip.IPv4(value)
if mesh_network:contains(x) then
return value
else
return nil, translate("The given IP address is not inside the mesh network range ") ..
"(" .. mesh_network:string() .. ")."
end
end
end
function cbi_ip6addr(device)
local ip6addr = n:taboption(device, Value, device .. "_ip6addr", translate("Mesh IPv6 address"),
translate("This is a unique IPv6 address in CIDR notation (e.g. 2001:1:2:3::1/64) and has to be registered at your local community."))
ip6addr:depends(device .. "_config", 1)
ip6addr.datatype = "ip6addr"
end
function cbi_dhcp(device)
local dhcp = n:taboption(device, Flag, device .. "_dhcp", translate("Enable DHCP"),
translate("DHCP will automatically assign ip addresses to clients"))
dhcp:depends(device .. "_config", 1)
dhcp.rmempty = true
end
function cbi_ra(device)
local ra = n:taboption(device, Flag, device .. "_ipv6ra", translate("Enable RA"),
translate("Send router advertisements on this device."))
ra:depends(device .. "_config", 1)
ra.rmempty = true
end
function cbi_dhcprange(device)
local dhcprange = n:taboption(device, Value, device .. "_dhcprange", translate("DHCP IP range"),
translate("The IP range from which clients are assigned ip addresses (e.g. 10.1.2.1/28). " ..
"If this is a range inside your mesh network range, then it will be announced as HNA. Any other range will use NAT. " ..
"If left empty then the defaults from the community profile will be used."))
dhcprange:depends(device .. "_dhcp", "1")
dhcprange.rmempty = true
dhcprange.datatype = "ip4addr"
end
-- create tabs and config for wireless
local nets={}
uci:foreach("wireless", "wifi-device", function(section)
local device = section[".name"]
table.insert(nets, device)
end)
local wired_nets = {}
uci:foreach("network", "interface", function(section)
local device = section[".name"]
if not util.contains(nets, device) and device ~= "loopback" and not device:find("wireless") then
table.insert(nets, device)
table.insert(wired_nets, device)
end
end)
for _, net in util.spairs(nets, function(a,b) return (nets[a] < nets[b]) end) do
n:tab(net, net)
end
-- create cbi config for wireless
uci:foreach("wireless", "wifi-device", function(section)
local device = section[".name"]
local hwtype = section.type
local syscc = section.country or uci:get(community, "wifi_device", "country") or
uci:get("freifunk", "wifi_device", "country")
cbi_configure(device)
-- Channel selection
if hwtype == "atheros" then
local cc = util.trim(sys.exec("grep -i '" .. syscc .. "' /lib/wifi/cc_translate.txt |cut -d ' ' -f 2")) or 0
sys.exec('"echo " .. cc .. " > /proc/sys/dev/" .. device .. "/countrycode"')
elseif hwtype == "mac80211" then
sys.exec("iw reg set " .. syscc)
elseif hwtype == "broadcom" then
sys.exec ("wlc country " .. syscc)
end
local chan = n:taboption(device, ListValue, device .. "_channel", translate("Channel"),
translate("Your device and neighbouring nodes have to use the same channel."))
chan:depends(device .. "_config", 1)
chan:value('default')
local iwinfo = sys.wifi.getiwinfo(device)
if iwinfo and iwinfo.freqlist then
for _, f in ipairs(iwinfo.freqlist) do
if not f.restricted then
chan:value(f.channel)
end
end
end
-- IPv4 address
cbi_ip4addr(device)
-- DHCP enable
cbi_dhcp(device)
-- DHCP range
cbi_dhcprange(device)
-- IPv6 addr and RA
if community_ipv6 == "1" then
if community_ipv6mode == "static" then
cbi_ip6addr(device)
end
cbi_ra(device)
end
-- Enable VAP
local supports_vap = 0
if sys.call("/usr/bin/meshwizard/helpers/supports_vap.sh " .. device .. " " .. hwtype) == 0 then
supports_vap = 1
end
if supports_vap == 1 then
local vap = n:taboption(device, Flag, device .. "_vap", translate("Virtual Access Point (VAP)"),
translate("This will setup a new virtual wireless interface in Access Point mode."))
vap:depends(device .. "_dhcp", "1")
vap.rmempty = true
if community_vap == "1" then
vap.default = "1"
end
end
end)
for _, device in pairs(wired_nets) do
cbi_configure(device)
cbi_ip4addr(device)
cbi_dhcp(device)
cbi_dhcprange(device)
-- IPv6 addr and RA
if community_ipv6 == "1" then
if community_ipv6mode == "static" then
cbi_ip6addr(device)
end
cbi_ra(device)
end
end
-- General settings
g = m:section(TypedSection, "general", translate("General Settings"))
g.anonymous = true
local cleanup = g:option(Flag, "cleanup", translate("Cleanup config"),
translate("If this is selected then config is cleaned before setting new config options."))
cleanup.default = "1"
local restrict = g:option(Flag, "local_restrict", translate("Protect LAN"),
translate("Check this to protect your LAN from other nodes or clients") .. " (" .. translate("recommended") .. ").")
local share = g:option(Flag, "sharenet", translate("Share your internet connection"),
translate("Select this to allow others to use your connection to access the internet."))
share.rmempty = true
-- IPv6 config
if community_ipv6 == "1" then
v6 = m:section(NamedSection, "ipv6", nil, translate("IPv6 Settings"))
local enabled = v6:option(Flag, "enabled", translate("Enabled"),
translate("Activate or deactivate IPv6 config globally."))
enabled.default = meshkit_ipv6
enabled.rmempty = false
end
return m
| apache-2.0 |
minecraftgame-andrd/minecraftgame | bot/utils.lua | 473 | 24167 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
-- vardump(user_info)
if user_info then
if user_info.username then
user = '@'..user_info.username
elseif user_info.print_name and not user_info.username then
user = string.gsub(user_info.print_name, "_", " ")
else
user = ''
end
text = text..k.." - "..user.." ["..v.."]\n"
end
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
-- vardump(user_info)
if user_info then
if user_info.username then
user = '@'..user_info.username
elseif user_info.print_name and not user_info.username then
user = string.gsub(user_info.print_name, "_", " ")
else
user = ''
end
text = text..k.." - "..user.." ["..v.."]\n"
end
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
tinydanbo/Impoverished-Starfighter | lib/loveframes/objects/internal/columnlist/columnlistrow.lua | 10 | 6336 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- columnlistrow class
local newobject = loveframes.NewObject("columnlistrow", "loveframes_object_columnlistrow", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: intializes the element
--]]---------------------------------------------------------
function newobject:initialize(parent, data)
self.type = "columnlistrow"
self.parent = parent
self.state = parent.state
self.colorindex = self.parent.rowcolorindex
self.font = loveframes.basicfontsmall
self.width = 80
self.height = 25
self.textx = 5
self.texty = 5
self.selected = false
self.internal = true
self.columndata = {}
for k, v in ipairs(data) do
self.columndata[k] = tostring(v)
end
-- apply template properties to the object
loveframes.templates.ApplyToObject(self)
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local parent = self.parent
local base = loveframes.base
local update = self.Update
self:CheckHover()
-- move to parent if there is a parent
if parent ~= base then
self.x = parent.x + self.staticx
self.y = parent.y + self.staticy
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local visible = self.visible
if not visible then
return
end
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawColumnListRow or skins[defaultskin].DrawColumnListRow
local draw = self.Draw
local drawcount = loveframes.drawcount
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
if not self.visible then
return
end
local hover = self.hover
if hover and button == "l" then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
local parent1 = self:GetParent()
local parent2 = parent1:GetParent()
local ctrldown = loveframes.util.IsCtrlDown()
parent2:SelectRow(self, ctrldown)
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
if not self.visible then
return
end
if self.hover then
local parent1 = self:GetParent()
local parent2 = parent1:GetParent()
if button == "l" then
local onrowclicked = parent2.OnRowClicked
if onrowclicked then
onrowclicked(parent2, self, self.columndata)
end
elseif button == "r" then
local onrowrightclicked = parent2.OnRowRightClicked
if onrowrightclicked then
onrowrightclicked(parent2, self, self.columndata)
end
end
end
end
--[[---------------------------------------------------------
- func: SetTextPos(x, y)
- desc: sets the positions of the object's text
--]]---------------------------------------------------------
function newobject:SetTextPos(x, y)
self.textx = x
self.texty = y
end
--[[---------------------------------------------------------
- func: GetTextX()
- desc: gets the object's text x position
--]]---------------------------------------------------------
function newobject:GetTextX()
return self.textx
end
--[[---------------------------------------------------------
- func: GetTextY()
- desc: gets the object's text y position
--]]---------------------------------------------------------
function newobject:GetTextY()
return self.texty
end
--[[---------------------------------------------------------
- func: SetFont(font)
- desc: sets the object's font
--]]---------------------------------------------------------
function newobject:SetFont(font)
self.font = font
end
--[[---------------------------------------------------------
- func: GetFont()
- desc: gets the object's font
--]]---------------------------------------------------------
function newobject:GetFont()
return self.font
end
--[[---------------------------------------------------------
- func: GetColorIndex()
- desc: gets the object's color index
--]]---------------------------------------------------------
function newobject:GetColorIndex()
return self.colorindex
end
--[[---------------------------------------------------------
- func: SetColumnData(data)
- desc: sets the object's column data
--]]---------------------------------------------------------
function newobject:SetColumnData(data)
self.columndata = data
end
--[[---------------------------------------------------------
- func: GetColumnData()
- desc: gets the object's column data
--]]---------------------------------------------------------
function newobject:GetColumnData()
return self.columndata
end
--[[---------------------------------------------------------
- func: SetSelected(selected)
- desc: sets whether or not the object is selected
--]]---------------------------------------------------------
function newobject:SetSelected(selected)
self.selected = true
end
--[[---------------------------------------------------------
- func: GetSelected()
- desc: gets whether or not the object is selected
--]]---------------------------------------------------------
function newobject:GetSelected()
return self.selected
end | mit |
HEYAHONG/nodemcu-firmware | app/lua53/host/tests/all.lua | 7 | 7745 | #!../lua
-- $Id: all.lua,v 1.95 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice at the end of this file
local version = "Lua 5.3"
if _VERSION ~= version then
io.stderr:write("\nThis test suite is for ", version, ", not for ", _VERSION,
"\nExiting tests\n")
return
end
_G._ARG = arg -- save arg for other tests
-- next variables control the execution of some tests
-- true means no test (so an undefined variable does not skip a test)
-- defaults are for Linux; test everything.
-- Make true to avoid long or memory consuming tests
_soft = rawget(_G, "_soft") or false
-- Make true to avoid non-portable tests
_port = rawget(_G, "_port") or false
-- Make true to avoid messages about tests not performed
_nomsg = rawget(_G, "_nomsg") or false
local usertests = rawget(_G, "_U")
if usertests then
-- tests for sissies ;) Avoid problems
_soft = true
_port = true
_nomsg = true
end
-- tests should require debug when needed
debug = nil
if usertests then
T = nil -- no "internal" tests for user tests
else
T = rawget(_G, "T") -- avoid problems with 'strict' module
end
math.randomseed(0)
--[=[
example of a long [comment],
[[spanning several [lines]]]
]=]
print("current path:\n****" .. package.path .. "****\n")
local initclock = os.clock()
local lastclock = initclock
local walltime = os.time()
local collectgarbage = collectgarbage
do -- (
-- track messages for tests not performed
local msgs = {}
function Message (m)
if not _nomsg then
print(m)
msgs[#msgs+1] = string.sub(m, 3, -3)
end
end
assert(os.setlocale"C")
local T,print,format,write,assert,type,unpack,floor =
T,print,string.format,io.write,assert,type,table.unpack,math.floor
-- use K for 1000 and M for 1000000 (not 2^10 -- 2^20)
local function F (m)
local function round (m)
m = m + 0.04999
return format("%.1f", m) -- keep one decimal digit
end
if m < 1000 then return m
else
m = m / 1000
if m < 1000 then return round(m).."K"
else
return round(m/1000).."M"
end
end
end
local showmem
if not T then
local max = 0
showmem = function ()
local m = collectgarbage("count") * 1024
max = (m > max) and m or max
print(format(" ---- total memory: %s, max memory: %s ----\n",
F(m), F(max)))
end
else
showmem = function ()
T.checkmemory()
local total, numblocks, maxmem = T.totalmem()
local count = collectgarbage("count")
print(format(
"\n ---- total memory: %s (%.0fK), max use: %s, blocks: %d\n",
F(total), count, F(maxmem), numblocks))
print(format("\t(strings: %d, tables: %d, functions: %d, "..
"\n\tudata: %d, threads: %d)",
T.totalmem"string", T.totalmem"table", T.totalmem"function",
T.totalmem"userdata", T.totalmem"thread"))
end
end
--
-- redefine dofile to run files through dump/undump
--
local function report (n) print("\n***** FILE '"..n.."'*****") end
local olddofile = dofile
local dofile = function (n, strip)
showmem()
local c = os.clock()
print(string.format("time: %g (+%g)", c - initclock, c - lastclock))
lastclock = c
report(n)
local f = assert(loadfile(n))
local b = string.dump(f, strip)
f = assert(load(b))
return f()
end
dofile('main.lua')
do
local next, setmetatable, stderr = next, setmetatable, io.stderr
-- track collections
local mt = {}
-- each time a table is collected, remark it for finalization
-- on next cycle
mt.__gc = function (o)
stderr:write'.' -- mark progress
local n = setmetatable(o, mt) -- remark it
end
local n = setmetatable({}, mt) -- create object
end
report"gc.lua"
local f = assert(loadfile('gc.lua'))
f=nil -- NodeMCU removed f()
dofile('db.lua')
assert(dofile('calls.lua') == deep and deep)
olddofile('strings.lua')
olddofile('literals.lua')
dofile('tpack.lua')
assert(dofile('attrib.lua') == 27)
assert(dofile('locals.lua') == 5)
dofile('constructs.lua')
dofile('code.lua', true)
if not _G._soft then
report('big.lua')
local f = coroutine.wrap(assert(loadfile('big.lua')))
assert(f() == 'b')
assert(f() == 'a')
end
dofile('nextvar.lua')
dofile('pm.lua')
dofile('utf8.lua')
dofile('api.lua')
assert(dofile('events.lua') == 12)
dofile('vararg.lua')
dofile('closure.lua')
dofile('coroutine.lua')
dofile('goto.lua', true)
dofile('errors.lua')
dofile('math.lua')
dofile('sort.lua', true)
dofile('bitwise.lua')
assert(dofile('verybig.lua', true) == 10); collectgarbage()
dofile('files.lua')
if #msgs > 0 then
print("\ntests not performed:")
for i=1,#msgs do
print(msgs[i])
end
print()
end
-- no test module should define 'debug'
-- assert(debug == nil) -- NodeMCU. debug is always defined in ROM
local debug = require "debug"
print(string.format("%d-bit integers, %d-bit floats",
string.packsize("j") * 8, string.packsize("n") * 8))
debug.sethook(function (a) assert(type(a) == 'string') end, "cr")
-- to survive outside block
_G.showmem = showmem
end --)
local _G, showmem, print, format, clock, time, difftime, assert, open =
_G, showmem, print, string.format, os.clock, os.time, os.difftime,
assert, io.open
-- file with time of last performed test
local fname = T and "time-debug.txt" or "time.txt"
local lasttime
if not usertests then
-- open file with time of last performed test
local f = io.open(fname)
if f then
lasttime = assert(tonumber(f:read'a'))
f:close();
else -- no such file; assume it is recording time for first time
lasttime = nil
end
end
-- erase (almost) all globals
print('cleaning all!!!!')
for n in pairs(_G) do
if not ({___Glob = 1, tostring = 1})[n] then
_G[n] = nil
end
end
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage();showmem()
local clocktime = clock() - initclock
walltime = difftime(time(), walltime)
print(format("\n\ntotal time: %.2fs (wall time: %gs)\n", clocktime, walltime))
if not usertests then
lasttime = lasttime or clocktime -- if no last time, ignore difference
-- check whether current test time differs more than 5% from last time
local diff = (clocktime - lasttime) / lasttime
local tolerance = 0.05 -- 5%
if (diff >= tolerance or diff <= -tolerance) then
print(format("WARNING: time difference from previous test: %+.1f%%",
diff * 100))
end
assert(open(fname, "w")):write(clocktime):close()
end
print("final OK !!!")
--[[
*****************************************************************************
* Copyright (C) 1994-2016 Lua.org, PUC-Rio.
*
* 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.
*****************************************************************************
]]
| mit |
darkdukey/sdkbox-facebook-sample-v2 | samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceSpriteTest.lua | 9 | 16025 | local kMaxNodes = 50000
local kBasicZOrder = 10
local kNodesIncrease = 250
local TEST_COUNT = 7
local s = CCDirector:sharedDirector():getWinSize()
-----------------------------------
-- For test functions
-----------------------------------
local function performanceActions(sprite)
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
local period = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local rot = CCRotateBy:create(period, 360.0 * math.random())
local rot = CCRotateBy:create(period, 360.0 * math.random())
local permanentRotation = CCRepeatForever:create(CCSequence:createWithTwoActions(rot, rot:reverse()))
sprite:runAction(permanentRotation)
local growDuration = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local grow = CCScaleBy:create(growDuration, 0.5, 0.5)
local permanentScaleLoop = CCRepeatForever:create(CCSequence:createWithTwoActions(grow, grow:reverse()))
sprite:runAction(permanentScaleLoop)
end
local function performanceActions20(sprite)
if math.random() < 0.2 then
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
else
sprite:setPosition(CCPointMake(-1000, -1000))
end
local period = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local rot = CCRotateBy:create(period, 360.0 * math.random())
local permanentRotation = CCRepeatForever:create(CCSequence:createWithTwoActions(rot, rot:reverse()))
sprite:runAction(permanentRotation)
local growDuration = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local grow = CCScaleBy:create(growDuration, 0.5, 0.5)
local permanentScaleLoop = CCRepeatForever:create(CCSequence:createWithTwoActions(grow, grow:reverse()))
sprite:runAction(permanentScaleLoop)
end
local function performanceRotationScale(sprite)
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
sprite:setRotation(math.random() * 360)
sprite:setScale(math.random() * 2)
end
local function performancePosition(sprite)
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
end
local function performanceout20(sprite)
if math.random() < 0.2 then
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
else
sprite:setPosition(CCPointMake(-1000, -1000))
end
end
local function performanceOut100(sprite)
sprite:setPosition(CCPointMake( -1000, -1000))
end
local function performanceScale(sprite)
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
sprite:setScale(math.random() * 100 / 50)
end
-----------------------------------
-- Subtest
-----------------------------------
local subtestNumber = 1
local batchNode = nil -- CCSpriteBatchNode
local parent = nil -- CCNode
local function initWithSubTest(nSubTest, p)
subtestNumber = nSubTest
parent = p
batchNode = nil
local mgr = CCTextureCache:sharedTextureCache()
-- remove all texture
mgr:removeTexture(mgr:addImage("Images/grossinis_sister1.png"))
mgr:removeTexture(mgr:addImage("Images/grossini_dance_atlas.png"))
mgr:removeTexture(mgr:addImage("Images/spritesheet1.png"))
if subtestNumber == 2 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888)
batchNode = CCSpriteBatchNode:create("Images/grossinis_sister1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 3 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444)
batchNode = CCSpriteBatchNode:create("Images/grossinis_sister1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 5 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888)
batchNode = CCSpriteBatchNode:create("Images/grossini_dance_atlas.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 6 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444)
batchNode = CCSpriteBatchNode:create("Images/grossini_dance_atlas.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 8 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888)
batchNode = CCSpriteBatchNode:create("Images/spritesheet1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 9 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444)
batchNode = CCSpriteBatchNode:create("Images/spritesheet1.png", 100)
p:addChild(batchNode, 0)
end
-- todo
if batchNode ~= nil then
batchNode:retain()
end
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default)
end
local function createSpriteWithTag(tag)
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888)
local sprite = nil
if subtestNumber == 1 then
sprite = CCSprite:create("Images/grossinis_sister1.png")
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 2 then
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(0, 0, 52, 139))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 3 then
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(0, 0, 52, 139))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 4 then
local idx = math.floor((math.random() * 1400 / 100)) + 1
local num
if idx < 10 then
num = "0" .. idx
else
num = idx
end
local str = "Images/grossini_dance_" .. num .. ".png"
sprite = CCSprite:create(str)
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 5 then
local y, x
local r = math.floor(math.random() * 1400 / 100)
y = math.floor(r / 5)
x = math.mod(r, 5)
x = x * 85
y = y * 121
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(x, y, 85, 121))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 6 then
local y, x
local r = math.floor(math.random() * 1400 / 100)
y = math.floor(r / 5)
x = math.mod(r, 5)
x = x * 85
y = y * 121
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(x, y, 85, 121))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 7 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
local str = "Images/sprites_test/sprite-"..x.."-"..y..".png"
sprite = CCSprite:create(str)
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 8 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
x = x * 32
y = y * 32
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(x, y, 32, 32))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 9 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
x = x * 32
y = y * 32
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(x, y, 32, 32))
batchNode:addChild(sprite, 0, tag + 100)
end
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default)
return sprite
end
local function removeByTag(tag)
if subtestNumber == 1 then
parent:removeChildByTag(tag + 100, true)
elseif subtestNumber == 4 then
parent:removeChildByTag(tag + 100, true)
elseif subtestNumber == 7 then
parent:removeChildByTag(tag + 100, true)
else
batchNode:removeChildAtIndex(tag, true)
end
end
-----------------------------------
-- PerformBasicLayer
-----------------------------------
local curCase = 0
local maxCases = 7
local function showThisTest()
local scene = CreateSpriteTestScene()
CCDirector:sharedDirector():replaceScene(scene)
end
local function backCallback(sender)
subtestNumber = 1
curCase = curCase - 1
if curCase < 0 then
curCase = curCase + maxCases
end
showThisTest()
end
local function restartCallback(sender)
subtestNumber = 1
showThisTest()
end
local function nextCallback(sender)
subtestNumber = 1
curCase = curCase + 1
curCase = math.mod(curCase, maxCases)
showThisTest()
end
local function toPerformanceMainLayer(sender)
CCDirector:sharedDirector():replaceScene(PerformanceTest())
end
local function initWithLayer(layer, controlMenuVisible)
CCMenuItemFont:setFontName("Arial")
CCMenuItemFont:setFontSize(24)
local mainItem = CCMenuItemFont:create("Back")
mainItem:registerScriptTapHandler(toPerformanceMainLayer)
mainItem:setPosition(s.width - 50, 25)
local menu = CCMenu:create()
menu:addChild(mainItem)
menu:setPosition(CCPointMake(0, 0))
if controlMenuVisible == true then
local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2)
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
item1:setPosition(s.width / 2 - 100, 30)
item2:setPosition(s.width / 2, 30)
item3:setPosition(s.width / 2 + 100, 30)
menu:addChild(item1, kItemTagBasic)
menu:addChild(item2, kItemTagBasic)
menu:addChild(item3, kItemTagBasic)
end
layer:addChild(menu)
end
-----------------------------------
-- SpriteMainScene
-----------------------------------
local lastRenderedCount = nil
local quantityNodes = nil
local infoLabel = nil
local titleLabel = nil
local function testNCallback(tag)
subtestNumber = tag - kBasicZOrder
showThisTest()
end
local function updateNodes()
if quantityNodes ~= lastRenderedCount then
local str = quantityNodes .. " nodes"
infoLabel:setString(str)
lastRenderedCount = quantityNodes
end
end
local function onDecrease(sender)
if quantityNodes <= 0 then
return
end
for i = 0, kNodesIncrease - 1 do
quantityNodes = quantityNodes - 1
removeByTag(quantityNodes)
end
updateNodes()
end
local function onIncrease(sender)
if quantityNodes >= kMaxNodes then
return
end
for i = 0, kNodesIncrease - 1 do
local sprite = createSpriteWithTag(quantityNodes)
if curCase == 0 then
doPerformSpriteTest1(sprite)
elseif curCase == 1 then
doPerformSpriteTest2(sprite)
elseif curCase == 2 then
doPerformSpriteTest3(sprite)
elseif curCase == 3 then
doPerformSpriteTest4(sprite)
elseif curCase == 4 then
doPerformSpriteTest5(sprite)
elseif curCase == 5 then
doPerformSpriteTest6(sprite)
elseif curCase == 6 then
doPerformSpriteTest7(sprite)
end
quantityNodes = quantityNodes + 1
end
updateNodes()
end
local function initWithMainTest(scene, asubtest, nNodes)
subtestNumber = asubtest
initWithSubTest(asubtest, scene)
lastRenderedCount = 0
quantityNodes = 0
CCMenuItemFont:setFontSize(65)
local decrease = CCMenuItemFont:create(" - ")
decrease:registerScriptTapHandler(onDecrease)
decrease:setColor(ccc3(0, 200, 20))
local increase = CCMenuItemFont:create(" + ")
increase:registerScriptTapHandler(onIncrease)
increase:setColor(ccc3(0, 200, 20))
local menu = CCMenu:create()
menu:addChild(decrease)
menu:addChild(increase)
menu:alignItemsHorizontally()
menu:setPosition(s.width / 2, s.height - 65)
scene:addChild(menu, 1)
infoLabel = CCLabelTTF:create("0 nodes", "Marker Felt", 30)
infoLabel:setColor(ccc3(0, 200, 20))
infoLabel:setPosition(s.width / 2, s.height - 90)
scene:addChild(infoLabel, 1)
maxCases = TEST_COUNT
-- Sub Tests
CCMenuItemFont:setFontSize(32)
subMenu = CCMenu:create()
for i = 1, 9 do
local str = i .. " "
local itemFont = CCMenuItemFont:create(str)
itemFont:registerScriptTapHandler(testNCallback)
--itemFont:setTag(i)
subMenu:addChild(itemFont, kBasicZOrder + i, kBasicZOrder + i)
if i <= 3 then
itemFont:setColor(ccc3(200, 20, 20))
elseif i <= 6 then
itemFont:setColor(ccc3(0, 200, 20))
else
itemFont:setColor(ccc3(0, 20, 200))
end
end
subMenu:alignItemsHorizontally()
subMenu:setPosition(CCPointMake(s.width / 2, 80))
scene:addChild(subMenu, 1)
-- add title label
titleLabel = CCLabelTTF:create("No title", "Arial", 40)
scene:addChild(titleLabel, 1)
titleLabel:setPosition(s.width / 2, s.height - 32)
titleLabel:setColor(ccc3(255, 255, 40))
while quantityNodes < nNodes do
onIncrease()
end
end
-----------------------------------
-- SpritePerformTest1
-----------------------------------
function doPerformSpriteTest1(sprite)
performancePosition(sprite)
end
local function SpriteTestLayer1()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "A (" .. subtestNumber .. ") position"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest2
-----------------------------------
function doPerformSpriteTest2(sprite)
performanceScale(sprite)
end
local function SpriteTestLayer2()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "B (" .. subtestNumber .. ") scale"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest3
-----------------------------------
function doPerformSpriteTest3(sprite)
performanceRotationScale(sprite)
end
local function SpriteTestLayer3()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "C (" .. subtestNumber .. ") scale + rot"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest4
-----------------------------------
function doPerformSpriteTest4(sprite)
performanceOut100(sprite)
end
local function SpriteTestLayer4()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "D (" .. subtestNumber .. ") 100% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest5
-----------------------------------
function doPerformSpriteTest5(sprite)
performanceout20(sprite)
end
local function SpriteTestLayer5()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "E (" .. subtestNumber .. ") 80% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest6
-----------------------------------
function doPerformSpriteTest6(sprite)
performanceActions(sprite)
end
local function SpriteTestLayer6()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "F (" .. subtestNumber .. ") actions"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest7
-----------------------------------
function doPerformSpriteTest7(sprite)
performanceActions20(sprite)
end
local function SpriteTestLayer7()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "G (" .. subtestNumber .. ") actions 80% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- PerformanceSpriteTest
-----------------------------------
function CreateSpriteTestScene()
local scene = CCScene:create()
initWithMainTest(scene, subtestNumber, kNodesIncrease)
if curCase == 0 then
scene:addChild(SpriteTestLayer1())
elseif curCase == 1 then
scene:addChild(SpriteTestLayer2())
elseif curCase == 2 then
scene:addChild(SpriteTestLayer3())
elseif curCase == 3 then
scene:addChild(SpriteTestLayer4())
elseif curCase == 4 then
scene:addChild(SpriteTestLayer5())
elseif curCase == 5 then
scene:addChild(SpriteTestLayer6())
elseif curCase == 6 then
scene:addChild(SpriteTestLayer7())
end
return scene
end
function PerformanceSpriteTest()
curCase = 0
return CreateSpriteTestScene()
end
| mit |
lipp/tinker | tinker/voltage.lua | 1 | 1843 | return {
methods = {
get_voltage = {
funcid = 1,
outs = 'H'
},
get_analog_value = {
funcid = 2,
outs = 'H'
},
set_voltage_callback_period = {
funcid = 3,
ins = 'I'
},
get_voltage_callback_period = {
funcid = 4,
outs = 'I'
},
set_analog_value_callback_period = {
funcid = 5,
ins = 'I'
},
get_analog_value_callback_period = {
funcid = 6,
outs = 'I'
},
set_voltage_callback_threshold = {
funcid = 7,
ins = 'Ahh',
format_ins =
function(option,min,max)
if #option ~= 1 then
error('invalid option value')
end
return option,min,max
end
},
get_voltage_callback_threshold = {
funcid = 8,
outs = 'A1hh'
},
set_analog_value_callback_threshold = {
funcid = 9,
ins = 'AHH',
format_ins =
function(option,min,max)
if #option ~= 1 then
error('invalid option value')
end
return option,min,max
end
},
get_analog_value_callback_threshold = {
funcid = 10,
outs = 'A1HH'
},
set_debounce_period = {
funcid = 11,
ins = 'I'
},
get_debounce_period = {
funcid = 12,
outs = 'I'
}
},
callbacks = {
voltage = {
funcid = 13,
ins = 'H'
},
analog_value = {
funcid = 14,
ins = 'H'
},
voltage_reached = {
funcid = 15,
ins = 'H'
},
analog_value_reached = {
funcid = 16,
ins = 'H'
}
}
}
| mit |
merlokk/proxmark3 | client/scripts/ndef_dump.lua | 12 | 7084 |
-- Ability to read what card is there
local getopt = require('getopt')
local cmds = require('commands')
local taglib = require('taglib')
local desc =
[[This script will automatically recognize and dump full content of a NFC NDEF Initialized tag; non-initialized tags will be ignored.
It also write the dump to an eml-file <uid>.eml.
(The difference between an .eml-file and a .bin-file is that the eml file contains
ASCII representation of the hex-data, with linebreaks between 'rows'. A .bin-file contains the
raw data, but when saving into that for, we lose the infromation about how the memory is structured.
For example: 24 bytes could be 6 blocks of 4 bytes, or vice versa.
Therefore, the .eml is better to use file when saving dumps.)
Arguments:
-d debug logging on
-h this help
]]
local example = "script run xxx"
local author = "Martin Holst Swende & Asper"
---
-- PrintAndLog
function prlog(...)
-- TODO; replace this with a call to the proper PrintAndLog
print(...)
end
---
-- This is only meant to be used when errors occur
function oops(err)
prlog("ERROR: ",err)
return nil,err
end
-- Perhaps this will be moved to a separate library at one point
local utils = {
--- Writes an eml-file.
-- @param uid - the uid of the tag. Used in filename
-- @param blockData. Assumed to be on the format {'\0\1\2\3,'\b\e\e\f' ...,
-- that is, blockData[row] contains a string with the actual data, not ascii hex representation
-- return filename if all went well,
-- @reurn nil, error message if unsuccessfull
writeDumpFile = function(uid, blockData)
local destination = string.format("%s.eml", uid)
local file = io.open(destination, "w")
if file == nil then
return nil, string.format("Could not write to file %s", destination)
end
local rowlen = string.len(blockData[1])
for i,block in ipairs(blockData) do
if rowlen ~= string.len(block) then
prlog(string.format("WARNING: Dumpdata seems corrupted, line %d was not the same length as line 1",i))
end
local formatString = string.format("H%d", string.len(block))
local _,hex = bin.unpack(formatString,block)
file:write(hex.."\n")
end
file:close()
return destination
end,
}
---
-- Usage help
function help()
prlog(desc)
prlog("Example usage")
prlog(example)
end
function debug(...)
if DEBUG then
prlog("debug:", ...)
end
end
local function show(data)
if DEBUG then
local formatString = ("H%d"):format(string.len(data))
local _,hexdata = bin.unpack(formatString, data)
debug("Hexdata" , hexdata)
end
end
--- Fire up a connection with a tag, return uid
-- @return UID if successfull
-- @return nil, errormessage if unsuccessfull
local function open()
debug("Opening connection")
core.clearCommandBuffer()
local x = string.format("hf 14a raw -r -p -s")
debug(x)
core.console(x)
debug("done")
data, err = waitCmd(true)
if err then return oops(err) end
show(data)
local formatString = ("H%d"):format(string.len(data))
local _,uid = bin.unpack(formatString, data)
return uid
end
--- Shut down tag communication
-- return no return values
local function close()
debug("Closing connection")
core.clearCommandBuffer()
local x = string.format("hf 14a raw -r")
debug(x)
core.console(x)
debug("done")
--data, err = waitCmd(true)
--data, err = waitCmd(false)
end
---_ Gets data from a block
-- @return {block, block+1, block+2, block+3} if successfull
-- @return nil, errormessage if unsuccessfull
local function getBlock(block)
local data, err
core.clearCommandBuffer()
local x = string.format("hf 14a raw -r -c -p 30 %02x", block)
debug(x)
core.console(x)
debug("done")
-- By now, there should be an ACK waiting from the device, since
-- we used the -r flag (don't read response).
data, err = waitCmd(false)
if err then return oops(err) end
show(data)
if string.len(data) < 18 then
return nil, ("Expected at least 18 bytes, got %d - this tag is not NDEF-compliant"):format(string.len(data))
end
-- Now, parse out the block data
-- 0534 00B9 049C AD7F 4A00 0000 E110 1000 2155
-- b0b0 b0b0 b1b1 b1b1 b2b2 b2b2 b3b3 b3b3 CRCC
b0 = string.sub(data,1,4)
b1 = string.sub(data,5,8)
b2 = string.sub(data,9,12)
b3 = string.sub(data,13,16)
return {b0,b1,b2,b3}
end
--- This function is a lua-implementation of
-- cmdhf14a.c:waitCmd(uint8_t iSelect)
function waitCmd(iSelect)
local response = core.WaitForResponseTimeout(cmds.CMD_ACK,1000)
if response then
local count,cmd,arg0,arg1,arg2 = bin.unpack('LLLL',response)
local iLen = arg0
if iSelect then iLen = arg1 end
debug(("Received %i octets (arg0:%d, arg1:%d)"):format(iLen, arg0, arg1))
if iLen == 0 then return nil, "No response from tag" end
local recv = string.sub(response,count, iLen+count-1)
return recv
end
return nil, "No response from device"
end
local function main( args)
debug("script started")
local err, data, data2,k,v,i
-- Read the parameters
for o, a in getopt.getopt(args, 'hd') do
if o == "h" then help() return end
if o == "d" then DEBUG = true end
end
-- Info contained within the tag (block 0 example)
-- 0534 00B9 049C AD7F 4A00 0000 E110 1000 2155
-- b0b0 b0b0 b1b1 b1b1 b2b2 b2b2 b3b3 b3b3 CRCC
-- MM?? ???? ???? ???? ???? ???? NNVV SS?? ----
-- M = Manufacturer info
-- N = NDEF-Structure-Compliant (if value is E1)
-- V = NFC Forum Specification version (if 10 = v1.0)
-- First, 'connect' (fire up the field) and get the uid
local uidHexstr = open()
-- First, get blockt 3 byte 2
local blocks, err = getBlock(0)
if err then return oops(err) end
-- Block 3 contains number of blocks
local b3chars = {string.byte(blocks[4], 1,4)}
local numBlocks = b3chars[3] * 2 + 6
prlog("Number of blocks:", numBlocks)
-- NDEF compliant?
if b3chars[1] ~= 0xE1 then
return oops("This tag is not NDEF-Compliant")
end
local ndefVersion = b3chars[2]
-- Block 1, byte 1 contains manufacturer info
local bl1_b1 = string.byte(blocks[1], 1)
local manufacturer = taglib.lookupManufacturer(bl1_b1)
-- Reuse existing info
local blockData = {blocks[1],blocks[2],blocks[3],blocks[4]}
--[[ Due to the infineon my-d move bug
(if I send 30 0F i receive block0f+block00+block01+block02 insted of block0f+block10+block11+block12)
the only way to avoid this is to send the read command as many times as block numbers
removing bytes from 5 to 18 from each answer.
--]]
prlog("Dumping data...please wait")
for i=4,numBlocks-1,1 do
blocks, err = getBlock(i)
if err then return oops(err) end
table.insert(blockData,blocks[1])
end
-- Deactivate field
close()
-- Print results
prlog(string.format("Tag manufacturer: %s", manufacturer))
prlog(string.format("Tag UID: %s", uidHexstr))
prlog(string.format("Tag NDEF version: 0x%02x", ndefVersion))
for k,v in ipairs(blockData) do
prlog(string.format("Block %02x: %02x %02x %02x %02x",k-1, string.byte(v, 1,4)))
end
local filename, err = utils.writeDumpFile(uidHexstr, blockData)
if err then return oops(err) end
prlog(string.format("Dumped data into %s", filename))
end
main(args) | gpl-2.0 |
cyanskies/OpenRA | mods/cnc/maps/nod06a/nod06a.lua | 25 | 7746 | NodStartUnitsRight = { 'ltnk', 'bike', 'e1', 'e1', 'e3', 'e3' }
NodStartUnitsLeft = { 'ltnk', 'ltnk', 'bggy', 'e1', 'e1', 'e1', 'e1', 'e3', 'e3', 'e3', 'e3' }
Chn1Units = { 'e1', 'e1', 'e1', 'e1', 'e1' }
Chn2Units = { 'e2', 'e2', 'e2', 'e2', 'e2' }
Obj2Units = { 'ltnk', 'bike', 'e1', 'e1', 'e1' }
Chn3CellTriggerActivator = { CPos.New(49,58), CPos.New(48,58), CPos.New(49,57), CPos.New(48,57), CPos.New(49,56), CPos.New(48,56), CPos.New(49,55), CPos.New(48,55) }
DzneCellTriggerActivator = { CPos.New(61,45), CPos.New(60,45), CPos.New(59,45), CPos.New(58,45), CPos.New(57,45), CPos.New(61,44), CPos.New(60,44), CPos.New(59,44), CPos.New(58,44), CPos.New(57,44), CPos.New(61,43), CPos.New(60,43), CPos.New(58,43), CPos.New(57,43), CPos.New(61,42), CPos.New(60,42), CPos.New(59,42), CPos.New(58,42), CPos.New(57,42), CPos.New(61,41), CPos.New(60,41), CPos.New(59,41), CPos.New(58,41), CPos.New(57,41) }
Win1CellTriggerActivator = { CPos.New(59,43) }
Win2CellTriggerActivator = { CPos.New(54,58), CPos.New(53,58), CPos.New(52,58), CPos.New(54,57), CPos.New(53,57), CPos.New(52,57), CPos.New(54,56), CPos.New(53,56), CPos.New(52,56), CPos.New(54,55), CPos.New(53,55), CPos.New(52,55) }
Grd2ActorTriggerActivator = { Guard1, Guard2, Guard3 }
Atk1ActorTriggerActivator = { Atk1Activator1, Atk1Activator2 }
Atk2ActorTriggerActivator = { Atk2Activator1, Atk2Activator2 }
Chn1ActorTriggerActivator = { Chn1Activator1, Chn1Activator2, Chn1Activator3, Chn1Activator4, Chn1Activator5 }
Chn2ActorTriggerActivator = { Chn2Activator1, Chn2Activator2, Chn2Activator3 }
Obj2ActorTriggerActivator = { Chn1Activator1, Chn1Activator2, Chn1Activator3, Chn1Activator4, Chn1Activator5, Chn2Activator1, Chn2Activator2, Chn2Activator3, Atk3Activator }
Chn1Waypoints = { ChnEntry.Location, waypoint5.Location }
Chn2Waypoints = { ChnEntry.Location, waypoint6.Location }
Gdi3Waypoints = { waypoint1, waypoint3, waypoint7, waypoint8, waypoint9 }
Gdi4Waypoints = { waypoint4, waypoint10, waypoint9, waypoint11, waypoint9, waypoint10 }
Gdi5Waypoints = { waypoint1, waypoint4 }
Gdi6Waypoints = { waypoint2, waypoints3 }
Grd1TriggerFunctionTime = DateTime.Seconds(3)
Grd1TriggerFunction = function()
MyActors = Utils.Take(2, enemy.GetActorsByType('mtnk'))
Utils.Do(MyActors, function(actor)
MovementAndHunt(actor, Gdi3Waypoints)
end)
end
Grd2TriggerFunction = function()
if not Grd2Switch then
for type, count in pairs({ ['e1'] = 2, ['e2'] = 1, ['jeep'] = 1 }) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
MovementAndHunt(actor, Gdi4Waypoints)
end)
end
Grd2Swicth = true
end
end
Atk1TriggerFunction = function()
if not Atk1Switch then
for type, count in pairs({ ['e1'] = 3, ['e2'] = 3, ['jeep'] = 1 }) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
MovementAndHunt(actor, Gdi5Waypoints)
end)
end
Atk1Switch = true
end
end
Atk2TriggerFunction = function()
if not Atk2Switch then
for type, count in pairs({ ['mtnk'] = 1, ['jeep'] = 1 }) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
MovementAndHunt(actor, Gdi6Waypoints)
end)
end
Atk2Switch = true
end
end
Atk3TriggerFunction = function()
if not Atk3Switch then
Atk3Switch = true
if not Radar.IsDead then
local targets = player.GetGroundAttackers()
local target = targets[DateTime.GameTime % #targets + 1].CenterPosition
if target then
Radar.SendAirstrike(target, false, Facing.NorthEast + 4)
end
end
end
end
Chn1TriggerFunction = function()
local cargo = Reinforcements.ReinforceWithTransport(enemy, 'tran', Chn1Units, Chn1Waypoints, { waypoint14.Location })[2]
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
end
Chn2TriggerFunction = function()
local cargo = Reinforcements.ReinforceWithTransport(enemy, 'tran', Chn2Units, Chn2Waypoints, { waypoint14.Location })[2]
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
end
Obj2TriggerFunction = function()
player.MarkCompletedObjective(NodObjective2)
Reinforcements.Reinforce(player, Obj2Units, { Obj2UnitsEntry.Location, waypoint13.Location }, 15)
end
MovementAndHunt = function(unit, waypoints)
if unit ~= nil then
Utils.Do(waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
end
InsertNodUnits = function()
Camera.Position = UnitsRallyRight.CenterPosition
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, NodStartUnitsLeft, { UnitsEntryLeft.Location, UnitsRallyLeft.Location }, 15)
Reinforcements.Reinforce(player, NodStartUnitsRight, { UnitsEntryRight.Location, UnitsRallyRight.Location }, 15)
end
WorldLoaded = function()
player = Player.GetPlayer("Nod")
enemy = Player.GetPlayer("GDI")
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)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
NodObjective1 = player.AddPrimaryObjective("Steal the GDI nuclear detonator.")
NodObjective2 = player.AddSecondaryObjective("Destroy the houses of the GDI supporters\nin the village.")
GDIObjective = enemy.AddPrimaryObjective("Stop the Nod taskforce from escaping with the detonator.")
InsertNodUnits()
Trigger.AfterDelay(Grd1TriggerFunctionTime, Grd1TriggerFunction)
Utils.Do(Grd2ActorTriggerActivator, function(actor)
Trigger.OnDiscovered(actor, Grd2TriggerFunction)
end)
OnAnyDamaged(Atk1ActorTriggerActivator, Atk1TriggerFunction)
OnAnyDamaged(Atk2ActorTriggerActivator, Atk2TriggerFunction)
Trigger.OnDamaged(Atk3Activator, Atk3TriggerFunction)
Trigger.OnAllKilled(Chn1ActorTriggerActivator, Chn1TriggerFunction)
Trigger.OnAllKilled(Chn2ActorTriggerActivator, Chn2TriggerFunction)
Trigger.OnEnteredFootprint(Chn3CellTriggerActivator, function(a, id)
if a.Owner == player then
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.ReinforceWithTransport(player, 'tran', nil, { ChnEntry.Location, waypoint17.Location }, nil, nil, nil)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(DzneCellTriggerActivator, function(a, id)
if a.Owner == player then
Actor.Create('flare', true, { Owner = player, Location = waypoint17.Location })
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnAllRemovedFromWorld(Obj2ActorTriggerActivator, Obj2TriggerFunction)
Trigger.OnEnteredFootprint(Win1CellTriggerActivator, function(a, id)
if a.Owner == player then
NodObjective3 = player.AddPrimaryObjective("Move to the evacuation point.")
player.MarkCompletedObjective(NodObjective1)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Win2CellTriggerActivator, function(a, id)
if a.Owner == player and NodObjective3 then
player.MarkCompletedObjective(NodObjective3)
Trigger.RemoveFootprintTrigger(id)
end
end)
end
Tick = function()
if DateTime.GameTime > 2 and player.HasNoRequiredUnits() then
enemy.MarkCompletedObjective(GDIObjective)
end
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
OnAnyDamaged = function(actors, func)
Utils.Do(actors, function(actor)
Trigger.OnDamaged(actor, func)
end)
end
| gpl-3.0 |
Arashbrsh/a1wez- | plugins/domaintools.lua | 359 | 1494 | local ltn12 = require "ltn12"
local https = require "ssl.https"
-- 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 check(name)
local api = "https://domainsearch.p.mashape.com/index.php?"
local param = "name="..name
local url = api..param
local api_key = mashape.api_key
if api_key:isempty() then
return 'Configure your Mashape API Key'
end
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "application/json"
}
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)
local body = json:decode(body)
--vardump(body)
local domains = "List of domains for '"..name.."':\n"
for k,v in pairs(body) do
print(k)
local status = " ❌ "
if v == "Available" then
status = " ✔ "
end
domains = domains..k..status.."\n"
end
return domains
end
local function run(msg, matches)
if matches[1] == "check" then
local name = matches[2]
return check(name)
end
end
return {
description = "Domain tools",
usage = {"!domain check [domain] : Check domain name availability.",
},
patterns = {
"^!domain (check) (.*)$",
},
run = run
}
| gpl-2.0 |
ashkanpj/fire | plugins/domaintools.lua | 359 | 1494 | local ltn12 = require "ltn12"
local https = require "ssl.https"
-- 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 check(name)
local api = "https://domainsearch.p.mashape.com/index.php?"
local param = "name="..name
local url = api..param
local api_key = mashape.api_key
if api_key:isempty() then
return 'Configure your Mashape API Key'
end
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "application/json"
}
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)
local body = json:decode(body)
--vardump(body)
local domains = "List of domains for '"..name.."':\n"
for k,v in pairs(body) do
print(k)
local status = " ❌ "
if v == "Available" then
status = " ✔ "
end
domains = domains..k..status.."\n"
end
return domains
end
local function run(msg, matches)
if matches[1] == "check" then
local name = matches[2]
return check(name)
end
end
return {
description = "Domain tools",
usage = {"!domain check [domain] : Check domain name availability.",
},
patterns = {
"^!domain (check) (.*)$",
},
run = run
}
| gpl-2.0 |
cyberz-eu/octopus | extensions/database/src/controller/DatabaseAddReferenceController.lua | 1 | 2107 | local json = require "json"
local param = require "param"
local exception = require "exception"
local exit = require "exit"
local util = require "util"
local database = require "database"
local from = param.from
local to = param.to
local parentId = param.parentId
local id = param.id
local db = database.connect()
local op = db:operators()
local function add (typeTo, typeFrom)
if util.isNotEmpty(id) and util.isNotEmpty(parentId) then
if typeTo == typeFrom then -- self referencing
if from < to then
db:add({[from .. "-" .. to] = {key = id, value = parentId}})
else
db:add({[to .. "-" .. from] = {key = parentId, value = id}})
end
else
if from < to then
db:add({[from .. "-" .. to] = {key = parentId, value = id}})
else
db:add({[to .. "-" .. from] = {key = id, value = parentId}})
end
end
else
exception("id or parantId is empty")
end
end
local function f ()
-- find if reference(to) object exist
local typeAndPropertyTo = util.split(to, ".")
local typeTo = typeAndPropertyTo[1]
local propertyTo = typeAndPropertyTo[2]
local toObject = db:findOne({[typeTo] = {id = op.equal(id)}})
-- add reference
local typeAndPropertyFrom = util.split(from, ".")
local typeFrom = typeAndPropertyFrom[1]
local propertyFrom = typeAndPropertyFrom[2]
local t = db.types[typeFrom]
local property = t[propertyFrom]
if property then
if property.has then
if property.has == "one" then
local res
if from < to then
res = db:find({[from .. "-" .. to] = {key = op.equal(parentId)}})
else
res = db:find({[to .. "-" .. from] = {value = op.equal(parentId)}})
end
if #res >= 1 then
exception(from .. " must be one not many")
else
add(typeTo, typeFrom)
end
else
add(typeTo, typeFrom)
end
else
exception(from .. " is not reference")
end
else
exception(from .. " does not exists")
end
end
local status, res = pcall(db.transaction, db, f)
db:close()
if status then
ngx.say("Add done!")
else
exit(res)
end | bsd-2-clause |
ioiasff/khp | plugins/webshot.lua | 919 | 1473 | local helpers = require "OAuth.helpers"
local base = 'https://screenshotmachine.com/'
local url = base .. 'processor.php'
local function get_webshot_url(param)
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
headers = {
referer = base,
dnt = "1",
origin = base,
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
},
redirect = false
}
local arguments = {
urlparam = param,
size = "FULL"
}
request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments)
local ok, response_code, response_headers, response_status_line = https.request(request_constructor)
if not ok or response_code ~= 200 then
return nil
end
local response = table.concat(response_body)
return string.match(response, "href='(.-)'")
end
local function run(msg, matches)
local find = get_webshot_url(matches[1])
if find then
local imgurl = base .. find
local receiver = get_receiver(msg)
send_photo_from_url(receiver, imgurl)
end
end
return {
description = "Send an screenshot of a website.",
usage = {
"!webshot [url]: Take an screenshot of the web and send it back to you."
},
patterns = {
"^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$",
},
run = run
}
| gpl-2.0 |
paulfertser/packages | net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/ruleconfig.lua | 14 | 4185 | -- ------ extra functions ------ --
function ruleCheck() -- determine if rule needs a protocol specified
local sourcePort = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".src_port"))
local destPort = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".dest_port"))
if sourcePort ~= "" or destPort ~= "" then -- ports configured
local protocol = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".proto"))
if protocol == "" or protocol == "all" then -- no or improper protocol
error_protocol = 1
end
end
end
function ruleWarn() -- display warning message at the top of the page
if error_protocol == 1 then
return "<font color=\"ff0000\"><strong>WARNING: this rule is incorrectly configured with no or improper protocol specified! Please configure a specific protocol!</strong></font>"
else
return ""
end
end
function cbiAddPolicy(field)
uci.cursor():foreach("mwan3", "policy",
function (section)
field:value(section[".name"])
end
)
end
function cbiAddProtocol(field)
local protocols = ut.trim(sys.exec("cat /etc/protocols | grep ' # ' | awk '{print $1}' | grep -vw -e 'ip' -e 'tcp' -e 'udp' -e 'icmp' -e 'esp' | grep -v 'ipv6' | sort | tr '\n' ' '"))
for p in string.gmatch(protocols, "%S+") do
field:value(p)
end
end
-- ------ rule configuration ------ --
dsp = require "luci.dispatcher"
sys = require "luci.sys"
ut = require "luci.util"
arg[1] = arg[1] or ""
error_protocol = 0
ruleCheck()
m5 = Map("mwan3", translate("MWAN Rule Configuration - ") .. arg[1],
translate(ruleWarn()))
m5.redirect = dsp.build_url("admin", "network", "mwan", "configuration", "rule")
mwan_rule = m5:section(NamedSection, arg[1], "rule", "")
mwan_rule.addremove = false
mwan_rule.dynamic = false
src_ip = mwan_rule:option(Value, "src_ip", translate("Source address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
src_ip.datatype = ipaddr
src_port = mwan_rule:option(Value, "src_port", translate("Source port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
dest_ip = mwan_rule:option(Value, "dest_ip", translate("Destination address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
dest_ip.datatype = ipaddr
dest_port = mwan_rule:option(Value, "dest_port", translate("Destination port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
proto = mwan_rule:option(Value, "proto", translate("Protocol"),
translate("View the contents of /etc/protocols for protocol descriptions"))
proto.default = "all"
proto.rmempty = false
proto:value("all")
proto:value("ip")
proto:value("tcp")
proto:value("udp")
proto:value("icmp")
proto:value("esp")
cbiAddProtocol(proto)
sticky = mwan_rule:option(ListValue, "sticky", translate("Sticky"),
translate("Traffic from the same source IP address that previously matched this rule within the sticky timeout period will use the same WAN interface"))
sticky.default = "0"
sticky:value("1", translate("Yes"))
sticky:value("0", translate("No"))
timeout = mwan_rule:option(Value, "timeout", translate("Sticky timeout"),
translate("Seconds. Acceptable values: 1-1000000. Defaults to 600 if not set"))
timeout.datatype = "range(1, 1000000)"
ipset = mwan_rule:option(Value, "ipset", translate("IPset"),
translate("Name of IPset rule. Requires IPset rule in /etc/dnsmasq.conf (eg \"ipset=/youtube.com/youtube\")"))
use_policy = mwan_rule:option(Value, "use_policy", translate("Policy assigned"))
cbiAddPolicy(use_policy)
use_policy:value("unreachable", translate("unreachable (reject)"))
use_policy:value("blackhole", translate("blackhole (drop)"))
use_policy:value("default", translate("default (use main routing table)"))
-- ------ currently configured policies ------ --
mwan_policy = m5:section(TypedSection, "policy", translate("Currently Configured Policies"))
mwan_policy.addremove = false
mwan_policy.dynamic = false
mwan_policy.sortable = false
mwan_policy.template = "cbi/tblsection"
return m5
| gpl-2.0 |
nstockton/mushclient-mume | lua/sha2.lua | 1 | 2859 | --sha256/384/512 hash and digest
local ffi = require'ffi'
local C = ffi.load'sha2.dll'
ffi.cdef[[
enum {
SHA1_BLOCK_LENGTH = 40,
SHA1_DIGEST_LENGTH = 20,
SHA224_BLOCK_LENGTH = 56,
SHA224_DIGEST_LENGTH = 28,
SHA256_BLOCK_LENGTH = 64,
SHA256_DIGEST_LENGTH = 32,
SHA384_BLOCK_LENGTH = 128,
SHA384_DIGEST_LENGTH = 48,
SHA512_BLOCK_LENGTH = 128,
SHA512_DIGEST_LENGTH = 64,
};
typedef union _SHA_CTX {
struct {
uint32_t state[5];
uint64_t bitcount;
uint8_t buffer[64];
} s1;
struct {
uint32_t state[8];
uint64_t bitcount;
uint8_t buffer[64];
} s256;
struct {
uint64_t state[8];
uint64_t bitcount[2];
uint8_t buffer[128];
} s512;
} SHA_CTX;
void SHA1_Init(SHA_CTX*);
void SHA1_Update(SHA_CTX*, const uint8_t*, size_t);
void SHA1_Final(uint8_t[SHA1_DIGEST_LENGTH], SHA_CTX*);
void SHA224_Init(SHA_CTX*);
void SHA224_Update(SHA_CTX*, const uint8_t*, size_t);
void SHA224_Final(uint8_t[SHA224_DIGEST_LENGTH], SHA_CTX*);
void SHA256_Init(SHA_CTX*);
void SHA256_Update(SHA_CTX*, const uint8_t*, size_t);
void SHA256_Final(uint8_t[SHA256_DIGEST_LENGTH], SHA_CTX*);
void SHA384_Init(SHA_CTX*);
void SHA384_Update(SHA_CTX*, const uint8_t*, size_t);
void SHA384_Final(uint8_t[SHA384_DIGEST_LENGTH], SHA_CTX*);
void SHA512_Init(SHA_CTX*);
void SHA512_Update(SHA_CTX*, const uint8_t*, size_t);
void SHA512_Final(uint8_t[SHA512_DIGEST_LENGTH], SHA_CTX*);
]]
local function digest_function(Context, Init, Update, Final, DIGEST_LENGTH)
return function()
local ctx = ffi.new(Context)
local result = ffi.new('uint8_t[?]', DIGEST_LENGTH)
Init(ctx)
return function(data, size)
if data then
Update(ctx, data, size or #data)
else
Final(result, ctx)
return ffi.string(result, ffi.sizeof(result))
end
end
end
end
local function hash_function(digest_function)
return function(data, size)
local d = digest_function(); d(data, size); return d()
end
end
local M = {C = C}
M.sha1_digest = digest_function(ffi.typeof'SHA_CTX', C.SHA1_Init, C.SHA1_Update, C.SHA1_Final, C.SHA1_DIGEST_LENGTH)
M.sha224_digest = digest_function(ffi.typeof'SHA_CTX', C.SHA224_Init, C.SHA224_Update, C.SHA224_Final, C.SHA224_DIGEST_LENGTH)
M.sha256_digest = digest_function(ffi.typeof'SHA_CTX', C.SHA256_Init, C.SHA256_Update, C.SHA256_Final, C.SHA256_DIGEST_LENGTH)
M.sha384_digest = digest_function(ffi.typeof'SHA_CTX', C.SHA384_Init, C.SHA384_Update, C.SHA384_Final, C.SHA384_DIGEST_LENGTH)
M.sha512_digest = digest_function(ffi.typeof'SHA_CTX', C.SHA512_Init, C.SHA512_Update, C.SHA512_Final, C.SHA512_DIGEST_LENGTH)
M.sha1 = hash_function(M.sha1_digest)
M.sha224 = hash_function(M.sha224_digest)
M.sha256 = hash_function(M.sha256_digest)
M.sha384 = hash_function(M.sha384_digest)
M.sha512 = hash_function(M.sha512_digest)
return M
| mpl-2.0 |
adamflott/wargus | scripts/ui.lua | 1 | 19866 | -- _________ __ __
-- / _____// |_____________ _/ |______ ____ __ __ ______
-- \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
-- / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ \
-- /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
-- \/ \/ \//_____/ \/
-- ______________________ ______________________
-- T H E W A R B E G I N S
-- Stratagus - A free fantasy real time strategy game engine
--
-- ui.lua - Define the user interface
--
-- (c) Copyright 2000-2007 by Lutz Sammer and Jimmy Salmon
--
-- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
Load("scripts/widgets.lua")
--
-- Define Decorations.
--
if (CanAccessFile("ui/health2.png")) then
DefineSprites({Name = "sprite-health", File = "ui/health2.png", Offset = {0, -4}, Size = {31, 4}})
DefineDecorations({Index = "HitPoints", HideNeutral = true, CenterX = true, ShowOpponent=true,
OffsetPercent = {50, 100}, Method = {"sprite", {"sprite-health"}}})
end
if (CanAccessFile("ui/mana2.png")) then
DefineSprites({Name = "sprite-mana", File = "ui/mana2.png", Offset = {0, -1}, Size = {31, 4}})
DefineDecorations({Index = "Mana", HideNeutral = true, CenterX = true,OffsetPercent = {50, 100},Method = {"sprite", {"sprite-mana"}}})
DefineDecorations({Index = "Transport", HideNeutral = true, CenterX = true,OffsetPercent = {50, 100},Method = {"sprite", {"sprite-mana"}}})
DefineDecorations({Index = "Research", HideNeutral = true, CenterX = true,OffsetPercent = {50, 100},Method = {"sprite", {"sprite-mana"}}})
DefineDecorations({Index = "Training", HideNeutral = true, CenterX = true,OffsetPercent = {50, 100},Method = {"sprite", {"sprite-mana"}}})
DefineDecorations({Index = "UpgradeTo", HideNeutral = true, CenterX = true,OffsetPercent = {50, 100},Method = {"sprite", {"sprite-mana"}}})
DefineDecorations({Index = "GiveResource", ShowWhenMax = true, HideNeutral = false, CenterX = true,OffsetPercent = {50, 100},Method = {"sprite", {"sprite-mana"}}})
DefineDecorations({Index = "CarryResource", HideNeutral = false, CenterX = true,OffsetPercent = {50, 100},Method = {"sprite", {"sprite-mana"}}})
end
DefineSprites({Name = "sprite-shadow", File = "missiles/unit_shadow.png", Offset = {3, 42}, Size = {32, 32}})
DefineSprites({Name = "sprite-spell", File = "ui/bloodlust,haste,slow,invisible,shield.png", Offset = {1, 1}, Size = {16, 16}})
DefineDecorations({Index = "Bloodlust", ShowOpponent = true,
Offset = {0, 0}, Method = {"static-sprite", {"sprite-spell", 0}}})
DefineDecorations({Index = "Haste", ShowOpponent = true,
Offset = {16, 0}, Method = {"static-sprite", {"sprite-spell", 1}}})
DefineDecorations({Index = "Slow", ShowOpponent = true,
Offset = {16, 0}, Method = {"static-sprite", {"sprite-spell", 2}}})
DefineDecorations({Index = "Invisible", ShowOpponent = true,
Offset = {32, 0}, Method = {"static-sprite", {"sprite-spell", 3}}})
DefineDecorations({Index = "UnholyArmor", ShowOpponent = true,
Offset = {48, 0}, Method = {"static-sprite", {"sprite-spell", 4}}})
DefineDecorations({Index = "ShadowFly", ShowOpponent = true, ShowWhenMax = true, ShowWhenNull = true,
Offset = {0, 0}, Method = {"sprite", {"sprite-shadow"}}})
--
-- Define Panels
--
local info_panel_x = 0
local info_panel_y
if (wargus.tales == true) then
info_panel_y = Video.Height - 136 - 24 - 16
else
info_panel_y = 160
end
local min_damage = Div(ActiveUnitVar("PiercingDamage"), 2)
local max_damage = Add(ActiveUnitVar("PiercingDamage"), ActiveUnitVar("BasicDamage"))
local damage_bonus = Sub(ActiveUnitVar("PiercingDamage", "Value", "Type"),
ActiveUnitVar("PiercingDamage", "Value", "Initial"));
DefinePanelContents(
-- Default presentation. ------------------------
{
Ident = "panel-general-contents",
Pos = {info_panel_x, info_panel_y}, DefaultFont = "game",
Contents = {
{ Pos = {8, 51}, Condition = {ShowOpponent = true, HideNeutral = false},
More = {"LifeBar", {Variable = "HitPoints", Height = 7, Width = 50}}
},
{ Pos = {35, 61}, Condition = {ShowOpponent = false, HideNeutral = true},
More = {"FormattedText2", {
Font = "small", Variable = "HitPoints", Format = "%d/%d",
Component1 = "Value", Component2 = "Max", Centered = true}}
},
{ Pos = {114, 11}, More = {"Text", {Text = Line(1, UnitName("Active"), 110, "game"), Centered = true}} },
{ Pos = {114, 25}, More = {"Text", {Text = Line(2, UnitName("Active"), 110, "game"), Centered = true}} },
-- Ressource Left
{ Pos = {88, 86}, Condition = {ShowOpponent = false, GiveResource = "only"},
More = {"FormattedText2", {Format = _("%s Left~|:%d"), Variable = "GiveResource",
Component1 = "Name", Component2 = "Value", Centered = true}}
},
-- Construction
{ Pos = {12, 152}, Condition = {ShowOpponent = false, HideNeutral = true, Build = "only"},
More = {"CompleteBar", {Variable = "Build", Width = 152, Height = 14, Border = false}}
},
{ Pos = {50, 155}, Condition = {ShowOpponent = false, HideNeutral = true, Build = "only"},
More = {"Text", _("% Complete")}},
{ Pos = {107, 78}, Condition = {ShowOpponent = false, HideNeutral = true, Build = "only"},
More = {"Icon", {Unit = "Worker"}}}
} },
-- Supply Building constructed.----------------
{
Ident = "panel-building-contents",
Pos = {info_panel_x, info_panel_y}, DefaultFont = "game",
Condition = {ShowOpponent = false, HideNeutral = true, Center = "false", Build = "false", Supply = "only", Training = "false", UpgradeTo = "false"},
Contents = {
-- Food building
{ Pos = {100, 71}, More = {"Text", _("Usage~|")} },
{ Pos = {100, 86}, More = {"Text", {Text = _("Supply~|: "), Variable = "Supply", Component = "Max"}} },
{ Pos = {100, 102}, More = { "Text", {Text = Concat(_("Demand~|: "),
If(GreaterThan(ActiveUnitVar("Demand", "Max"), ActiveUnitVar("Supply", "Max")),
InverseVideo(String(ActiveUnitVar("Demand", "Max"))),
String(ActiveUnitVar("Demand", "Max")) ))}}
}
} },
-- Center
{
Ident = "panel-center-contents",
Pos = {info_panel_x, info_panel_y}, DefaultFont = "game",
Condition = {ShowOpponent = false, HideNeutral = true, Center = "only", Build = "false", Supply = "only", Training = "false", UpgradeTo = "false"},
Contents = {
{ Pos = {16, 71}, More = {"Text", _("Production")} },
{ Pos = {85, 86}, More = { "Text", {Text = Concat(_("Gold~|: 100"),
If(GreaterThan(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "gold"), 100),
InverseVideo(Concat("+", String(Sub(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "gold"), 100)))),
"" ))}}
},
{ Pos = {85, 102}, Condition = {WoodImprove = "only"}, More = { "Text", {Text = Concat(_("Lumber~|: 100"),
If(GreaterThan(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "wood"), 100),
InverseVideo(Concat("+", String(Sub(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "wood"), 100)))),
"" ))}}
},
{ Pos = {85, 118}, Condition = {OilImprove = "only"}, More = { "Text", {Text = Concat(_("Oil~|: 100"),
If(GreaterThan(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "oil"), 100),
InverseVideo(Concat("+", String(Sub(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "oil"), 100)))),
"" ))}}
},
} },
--res inmprovement
{
Ident = "panel-resimrove-contents",
Pos = {info_panel_x, info_panel_y}, DefaultFont = "game",
Condition = {ShowOpponent = false, HideNeutral = true, Center = "false", Build = "false", Training = "false", UpgradeTo = "false", Research = "false"},
Contents = {
{ Pos = {16, 86}, Condition = {WoodImprove = "only"}, More = {"Text", _("Production")} },
{ Pos = {16, 86}, Condition = {OilImprove = "only"}, More = {"Text", _("Production")} },
{ Pos = {85, 102}, Condition = {WoodImprove = "only"}, More = { "Text", {Text = Concat(_("Lumber~|: 100"),
If(GreaterThan(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "wood"), 100),
InverseVideo(Concat("+", String(Sub(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "wood"), 100)))),
"" ))}}
},
{ Pos = {85, 102}, Condition = {OilImprove = "only"}, More = { "Text", {Text = Concat(_("Oil~|: 100"),
If(GreaterThan(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "oil"), 100),
InverseVideo(Concat("+", String(Sub(PlayerData(ActiveUnitVar("Player", "Value"), "Incomes", "oil"), 100)))),
"" ))}}
},
} },
-- All own unit -----------------
{
Ident = "panel-all-unit-contents",
Pos = {info_panel_x, info_panel_y},
DefaultFont = "game",
Condition = {ShowOpponent = false, HideNeutral = true, Build = "false"},
Contents = {
{ Pos = {100, 86}, Condition = {BasicDamage = "only"},
More = {"Text", {Text = Concat(_("Damage~|: "), String(min_damage), "-", String(max_damage),
If(Equal(0, damage_bonus), "",
InverseVideo(Concat("+", String(damage_bonus)))) )}}
},
{ Pos = {100, 86}, Condition = {PiercingDamage = "only"},
More = {"Text", {Text = Concat(_("Damage~|: "), String(min_damage), "-", String(max_damage),
If(Equal(0, damage_bonus), "",
InverseVideo(Concat("+", String(damage_bonus)))) )}}
},
{ Pos = {100, 86}, Condition = {BasicDamage = "only", PiercingDamage = "only"},
More = {"Text", {Text = Concat(_("Damage~|: "), String(min_damage), "-", String(max_damage),
If(Equal(0, damage_bonus), "",
InverseVideo(Concat("+", String(damage_bonus)))) )}}
},
{ Pos = {100, 102}, Condition = {AttackRange = "only"},
More = {"Text", {
Text = _("Range~|: "), Variable = "AttackRange" , Stat = true}}
},
-- Research
{ Pos = {12, 152}, Condition = {Research = "only"},
More = {"CompleteBar", {Variable = "Research", Width = 152, Height = 14, Border = false}}
},
{ Pos = {100, 86}, Condition = {Research = "only"}, More = {"Text", _("Researching~|:")}},
{ Pos = {50, 154}, Condition = {Research = "only"}, More = {"Text", _("% Complete")}},
-- Training
{ Pos = {12, 152}, Condition = {Training = "only"},
More = {"CompleteBar", {Variable = "Training", Width = 152, Height = 14, Border = false}}
},
{ Pos = {50, 154}, Condition = {Training = "only"}, More = {"Text", _("% Complete")}},
-- Upgrading To
{ Pos = {12, 152}, Condition = {UpgradeTo = "only"},
More = {"CompleteBar", {Variable = "UpgradeTo", Width = 152, Height = 14, Border = false}}
},
{ Pos = {100, 86}, More = {"Text", _("Upgrading~|:")}, Condition = {UpgradeTo = "only"} },
{ Pos = {50, 154}, More = {"Text", _("% Complete")}, Condition = {UpgradeTo = "only"} },
-- Resource Carry
{ Pos = {100, 149}, Condition = {CarryResource = "only"},
More = {"FormattedText2", {Format = _("Carry~|: %d %s"), Variable = "CarryResource",
Component1 = "Value", Component2 = "Name"}}
}
} },
-- Attack Unit -----------------------------
{
Ident = "panel-attack-unit-contents",
Pos = {info_panel_x, info_panel_y},
DefaultFont = "game",
Condition = {ShowOpponent = true, HideNeutral = true, Building = "false", Build = "false"},
Contents = {
-- Unit caracteristics
{ Pos = {154, 41},
More = {"FormattedText", {Variable = "Level", Format = _("Level ~|~<%d~>")}}
},
{ Pos = {154, 56}, Condition = {ShowOpponent = false},
More = {"FormattedText2", {Centered = true,
Variable1 = "Xp", Variable2 = "Kill", Format = _("XP:~<%d~> Kills:~|~<%d~>")}}
},
{ Pos = {100, 71}, Condition = {Armor = "only"},
More = {"Text", {
Text = _("Armor~|: "), Variable = "Armor", Stat = true}}
},
{ Pos = {100, 118}, Condition = {SightRange = "only"},
More = {"Text", {Text = _("Sight~|: "), Variable = "SightRange", Stat = true}}
},
{ Pos = {100, 133}, Condition = {Speed = "only"},
More = {"Text", {Text = _("Speed~|: "), Variable = "Speed", Stat = true}}
},
-- Mana
{ Pos = {100, 148}, Condition = {Mana = "only"},
More = {"Text", {Text = _("Mana~|: ")}}
},
{ Pos = {103, 148}, Condition = {Mana = "only"},
More = {"CompleteBar", {Color = "light-blue", Variable = "Mana", Height = 14, Width = 60, Border = true}}
},
{ Pos = {126, 149}, More = {"Text", {Variable = "Mana", Centered = true}}, Condition = {Mana = "only"} }} })
Load("scripts/human/ui.lua")
Load("scripts/orc/ui.lua")
wargus.playlist = { "music/Main Menu" .. wargus.music_extension }
UI.MessageFont = Fonts["game"]
UI.MessageScrollSpeed = 5
DefineCursor({
Name = "cursor-glass",
Race = "any",
File = "ui/cursors/magnifying_glass.png",
HotSpot = {11, 11},
Size = {34, 35}})
DefineCursor({
Name = "cursor-cross",
Race = "any",
File = "ui/cursors/small_green_cross.png",
HotSpot = { 8, 8},
Size = {18, 18}})
if (CanAccessFile("ui/cursors/cross.png")) then
DefineCursor({
Name = "cursor-scroll",
Race = "any",
File = "ui/cursors/cross.png",
HotSpot = {15, 15},
Size = {32, 32}})
end
DefineCursor({
Name = "cursor-arrow-e",
Race = "any",
File = "ui/cursors/arrow_E.png",
HotSpot = {22, 10},
Size = {32, 24}})
DefineCursor({
Name = "cursor-arrow-ne",
Race = "any",
File = "ui/cursors/arrow_NE.png",
HotSpot = {20, 2},
Size = {32, 24}})
DefineCursor({
Name = "cursor-arrow-n",
Race = "any",
File = "ui/cursors/arrow_N.png",
HotSpot = {12, 2},
Size = {32, 24}})
DefineCursor({
Name = "cursor-arrow-nw",
Race = "any",
File = "ui/cursors/arrow_NW.png",
HotSpot = { 2, 2},
Size = {32, 24}})
DefineCursor({
Name = "cursor-arrow-w",
Race = "any",
File = "ui/cursors/arrow_W.png",
HotSpot = { 4, 10},
Size = {32, 24}})
DefineCursor({
Name = "cursor-arrow-s",
Race = "any",
File = "ui/cursors/arrow_S.png",
HotSpot = {12, 22},
Size = {32, 24}})
DefineCursor({
Name = "cursor-arrow-sw",
Race = "any",
File = "ui/cursors/arrow_SW.png",
HotSpot = { 2, 18},
Size = {32, 24}})
DefineCursor({
Name = "cursor-arrow-se",
Race = "any",
File = "ui/cursors/arrow_SE.png",
HotSpot = {20, 18},
Size = {32, 24}})
function GetRGBA(r, g, b, a)
if (wc2.preferences.UseOpenGL == false) then
return b + g*0x100 + r*0x10000 + a*0x1000000
else
return r + g*0x100 + b*0x10000 + a*0x1000000
end
end
PopupFont = nil
if (wargus.tales == true) then
PopupFont = "game"
else
PopupFont = "small"
end
DefinePopup({
Ident = "popup-commands",
BackgroundColor = GetRGBA(128,128,128, 160),
BorderColor = GetRGBA(192,192,255, 160),
Contents = {
{ Margin = {1, 1},
More = {"ButtonInfo", {InfoType = "Hint", Font = PopupFont}}
},
-- Description
{ Margin = {1, 1}, Condition = {HasDescription = true},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {HasDescription = true}, Margin = {1, 1},
More = {"ButtonInfo", {InfoType = "Description", MaxWidth = Video.Width / 5, Font = PopupFont}}
},
}
})
DefinePopup({
Ident = "popup-human-commands",
BackgroundColor = GetRGBA(0,64,160, 160),
BorderColor = GetRGBA(192,192,255, 160),
Contents = {
{ Margin = {1, 1}, HighlightColor = "full-red",
More = {"ButtonInfo", {InfoType = "Hint", Font = PopupFont}}
},
-- Description
{ Margin = {1, 1}, Condition = {HasDescription = true},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {HasDescription = true}, Margin = {1, 1}, HighlightColor = "full-red",
More = {"ButtonInfo", {InfoType = "Description", MaxWidth = Video.Width / 5, Font = PopupFont}}
},
-- Move hint
{ Margin = {1, 1}, Condition = {ButtonAction = "move"},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {ButtonAction = "move"}, Margin = {1, 1}, TextColor = "yellow", HighlightColor = "cyan",
More = {"Text", {Text = _("~<ALT~>-click to defend unit."), MaxWidth = Video.Width / 5, Font = PopupFont}}
},
{ Condition = {ButtonAction = "move"}, Margin = {1, 1}, TextColor = "yellow", HighlightColor = "cyan",
More = {"Text", {Text = _("~<SHIFT~>-click to make waypoints."), MaxWidth = Video.Width / 5, Font = PopupFont}}
},
-- Repair hint
{ Margin = {1, 1}, Condition = {ButtonAction = "repair"},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {ButtonAction = "repair"}, Margin = {1, 1}, TextColor = "yellow", HighlightColor = "cyan",
More = {"Text", {Text = _("~<CTRL~>-click on button enables/disables auto-repair of damaged buildings."), MaxWidth = Video.Width / 5, Font = PopupFont}}
},
-- Heal hint
{ Margin = {1, 1}, Condition = {ButtonValue = "spell-medic-heal"},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {ButtonValue = "spell-healing"}, Margin = {1, 1}, TextColor = "yellow", HighlightColor = "cyan",
More = {"Text", {Text = _("~<CTRL~>-click on button enables/disables autoheal ability."), MaxWidth = Video.Width / 5, Font = PopupFont}}
}
}
})
DefinePopup({
Ident = "popup-orc-commands",
BackgroundColor = GetRGBA(0,64,160, 160),
BorderColor = GetRGBA(192,192,255, 160),
Contents = {
{ Margin = {1, 1}, HighlightColor = "full-red",
More = {"ButtonInfo", {InfoType = "Hint", Font = PopupFont}}
},
-- Description
{ Margin = {1, 1}, Condition = {HasDescription = true},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {HasDescription = true}, Margin = {1, 1}, HighlightColor = "full-red",
More = {"ButtonInfo", {InfoType = "Description", MaxWidth = Video.Width / 5, Font = PopupFont}}
},
-- Move hint
{ Margin = {1, 1}, Condition = {ButtonAction = "move"},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {ButtonAction = "move"}, Margin = {1, 1}, TextColor = "yellow", HighlightColor = "cyan",
More = {"Text", {Text = _("~<ALT~>-click to defend unit."), MaxWidth = Video.Width / 5, Font = PopupFont}}
},
{ Condition = {ButtonAction = "move"}, Margin = {1, 1}, TextColor = "yellow", HighlightColor = "cyan",
More = {"Text", {Text = _("~<SHIFT~>-click to make waypoints."), MaxWidth = Video.Width / 5, Font = PopupFont}}
},
-- Repair hint
{ Margin = {1, 1}, Condition = {ButtonAction = "repair"},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {ButtonAction = "repair"}, Margin = {1, 1}, TextColor = "yellow", HighlightColor = "cyan",
More = {"Text", {Text = _("~<CTRL~>-click on button enables/disables auto-repair of damaged buildings."), MaxWidth = Video.Width / 5, Font = PopupFont}}
},
-- Heal hint
{ Margin = {1, 1}, Condition = {ButtonValue = "spell-medic-heal"},
More = {"Line", {Width = 0, Height = 1, Color = GetRGBA(192,192,255, 160)}}
},
{ Condition = {ButtonValue = "spell-healing"}, Margin = {1, 1}, TextColor = "yellow", HighlightColor = "cyan",
More = {"Text", {Text = _("~<CTRL~>-click on button enables/disables autoheal ability."), MaxWidth = Video.Width / 5, Font = PopupFont}}
}
}
}) | gpl-2.0 |
Frenzie/koreader-base | ffi/harfbuzz.lua | 1 | 3910 | local coverage = require("ffi/harfbuzz_coverage")
local ffi = require("ffi")
local hb = ffi.load("libs/libharfbuzz." .. (ffi.os == "OSX" and "0.dylib" or "so.0"))
local HB = setmetatable({}, {__index = hb})
require("ffi/harfbuzz_h")
local hb_face_t = {}
hb_face_t.__index = hb_face_t
ffi.metatype("hb_face_t", hb_face_t)
-- Dump contents of OT name fields
function hb_face_t:getNames(maxlen)
maxlen = maxlen or 256
local n = ffi.new("unsigned[1]")
local list = hb.hb_ot_name_list_names(self, n)
if list == nil then return end
local buf = ffi.new("char[?]", maxlen)
local res = {}
for i=0, n[0]-1 do
local name_id = list[i].name_id
local hb_lang = list[i].language
local lang = hb.hb_language_to_string(hb_lang)
if lang ~= nil then
lang = ffi.string(lang)
local got = hb.hb_ot_name_get_utf8(self, name_id, hb_lang, ffi.new("unsigned[1]", maxlen), buf)
name_id = tonumber(name_id)
if got > 0 then
res[lang] = res[lang] or {}
res[lang][name_id] = ffi.string(buf)
end
end
end
return res
end
-- Alphabets are subset of a larger script - just enough for a specific language.
-- This is used to mark face as eligibile to speak some tongue in particular.
-- Later on the results are sorted by best ratio still, when multiple choices are available.
-- TODO: These numbers are ballkpark, tweak this to more real-world defaults
local coverage_thresholds = {
-- nglyph coverage %
0, 100, -- Simple alphabets of 0-100 glyphs. Be strict, all glyphs are typically in use.
100, 99, -- 100-250 glyphs. abundant diacritics, allow for 1% missing, typically some archaisms
250, 98, -- 250-1000 glyphs. even more diacritics (eg cyrillic dialects), allow for 2% missing
1000, 85, -- 1000 and more = CJK, allow for 15% missing
}
-- Get script and language coverage
function hb_face_t:getCoverage()
local set, tmp = hb.hb_set_create(), hb.hb_set_create()
local scripts = {}
local langs = {}
hb.hb_face_collect_unicodes(self, set)
local function intersect(tab)
hb.hb_set_set(tmp, set)
hb.hb_set_intersect(tmp, tab)
return hb.hb_set_get_population(tmp), hb.hb_set_get_population(tab)
end
for script_id, tab in ipairs(coverage.scripts) do
local hit, total = intersect(tab)
-- for scripts, we do only rough majority hit
if 2*hit > total then
scripts[script_id] = hit / total
end
end
for lang_id, tab in pairs(coverage.langs) do
local found
local hit, total = intersect(tab)
-- for languages, consider predefined threshold by glyph count
for i=1, #coverage_thresholds, 2 do
if total > coverage_thresholds[i] then
found = i+1
end
end
if hit*100/total >= coverage_thresholds[found] then
langs[lang_id] = hit/total
end
end
hb.hb_set_destroy(set)
hb.hb_set_destroy(tmp)
return scripts, langs
end
function hb_face_t:destroy()
hb.hb_face_destroy(self)
end
-- private
-- preprocess the script/language tables into HB range sets
local function make_set(tab)
local set = hb.hb_set_create()
local first = 0
local seen = 0
for i=1,#tab,2 do
first = first + tab[i]
local count = tab[i+1]
seen = seen + count
local last = first + count - 1
hb.hb_set_add_range(set, first, last)
first = last
end
assert(hb.hb_set_get_population(set) == seen, "invalid coverage table")
return set
end
for ucd_id, ranges in ipairs(coverage.scripts) do
coverage.scripts[ucd_id] = make_set(ranges)
end
for lang_id, ranges in pairs(coverage.langs) do
coverage.langs[lang_id] = make_set(ranges)
end
return HB
| agpl-3.0 |
cyberz-eu/octopus | extensions/editor/config.lua | 1 | 5205 | local config = {} -- extension configuration
local editorHeaderStyleButton = [[style="font-size: 21px; padding-top: 5px;"></i>]]
config.frontend = {
mainColor = "#49bf9d",
selectedColor = "#1e90ff",
editorUrl = "/editor",
editorHomeUrl = "",
editorFileContentUrl = "/fileContent",
editorDirectoryUrl = "/directory",
editorSaveUrl = "/save",
editorSearchUrl = "/search",
editorRenameUrl = "/rename",
editorRemoveUrl = "/remove",
editorCreateFileUrl = "/createFile",
editorCreateDirectoryUrl = "/createDirectory",
editorEditFileUrl = "/editFile",
editorUploadFileUrl = "/uploadFile",
editorDownloadFileUrl = "/downloadFile",
compareUrl = "/compare",
cryptographyUrl = "/cryptography",
cryptographyEncrypt = "encrypt",
cryptographyDecrypt = "decrypt",
cryptographyHashPassword = "hashPassword",
editorSaved = [[<i class="fa fa-lock" ]] .. editorHeaderStyleButton,
editorUnsaved = [[<i class="fa fa-unlock" ]] .. editorHeaderStyleButton,
editorSearchExpand = [[<i class="fa fa-expand" ]] .. editorHeaderStyleButton,
editorSearchCompress = [[<i class="fa fa-compress" ]] .. editorHeaderStyleButton,
}
config.property = {
fileUploadChunkSize = 8196,
}
config.location = {
{name = property.editorUrl .. property.editorHomeUrl, script = "controller/EditorController.lua", access = "EditorRedirectOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorFileContentUrl, script = "controller/operation/FileContentController.lua", access = "EditorThrowErrorOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorDirectoryUrl, script = "controller/operation/DirectoryController.lua", access = "EditorThrowErrorOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorSaveUrl, script = "controller/operation/SaveController.lua", requestBody = "20M", access = "EditorThrowErrorOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorSearchUrl, script = "controller/EditorSearchController.lua", access = "EditorThrowErrorOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorRenameUrl, script = "controller/operation/RenameController.lua", access = "EditorThrowErrorOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorRemoveUrl, script = "controller/operation/RemoveController.lua", access = "EditorThrowErrorOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorCreateFileUrl, script = "controller/operation/CreateFileController.lua", access = "EditorThrowErrorOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorCreateDirectoryUrl, script = "controller/operation/CreateDirectoryController.lua", access = "EditorThrowErrorOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorEditFileUrl, script = "controller/EditorEditFileController.lua", access = "EditorRedirectOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorUploadFileUrl, script = "controller/EditorUploadFileController.lua", uploadBody = "20M", access = "EditorRedirectOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.editorDownloadFileUrl, script = "controller/EditorDownloadFileController.lua", access = "EditorRedirectOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.compareUrl, script = "controller/CompareController.lua", access = "EditorRedirectOnSessionTimeoutFilter"},
{name = property.editorUrl .. property.cryptographyUrl, script = "controller/CryptographyController.lua", requestBody = true, access = "EditorRedirectOnSessionTimeoutFilter"},
}
config.access = {
{name = "EditorRedirectOnSessionTimeoutFilter", script = "filter/EditorRedirectOnSessionTimeoutFilter.lua"},
{name = "EditorThrowErrorOnSessionTimeoutFilter", script = "filter/EditorThrowErrorOnSessionTimeoutFilter.lua"},
}
config.javascript = {
{name = "EditorTemplate", script = "controller/EditorTemplate.js"},
{name = "Editor", script = "widget/Editor.js"},
{name = "EditorNavigation", script = "widget/EditorNavigation.js"},
{name = "EditorHeader", script = "widget/EditorHeader.js"},
{name = "EditorSearchPopup", script = "widget/EditorSearchPopup.js"},
{name = "EditorSearchResult", script = "widget/EditorSearchResult.js"},
{name = "EditorSearchTemplate", script = "controller/EditorSearchTemplate.js"},
{name = "EditorSearchHeader", script = "widget/EditorSearchHeader.js"},
{name = "UploadResult", script = "widget/UploadResult.js"},
{name = "CompareEditor", script = "widget/CompareEditor.js"},
{name = "CompareTabs", script = "widget/CompareTabs.js"},
{name = "CompareHeader", script = "widget/CompareHeader.js"},
{name = "CryptographyTabs", script = "widget/CryptographyTabs.js"},
}
config.stylesheet = {
{name = "EditorTemplate", script = "controller/EditorTemplate.css"},
{name = "EditorNavigation", script = "widget/EditorNavigation.css"},
{name = "EditorHeader", script = "widget/EditorHeader.css"},
}
config.module = {
{name = "Directory", script = "module/Directory.lua"},
{name = "Editor", script = "module/Editor.lua"}
}
config.static = {
"static"
}
return config -- return extension configuration | bsd-2-clause |
Arashbrsh/a1wez- | plugins/moderation.lua | 336 | 9979 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
local username = v.username
data[tostring(msg.to.id)] = {
moderators = {[tostring(member_id)] = username},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as moderator for this group.')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
else
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
if msg.from.username then
username = msg.from.username
else
username = msg.from.print_name
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={[tostring(msg.from.id)] = username},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return 'Group has been added, and @'..username..' has been promoted as moderator for this group.'
end
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return 'Group has been added.'
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return 'Group has been removed'
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function admin_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
elseif mod_cmd == 'adminprom' then
return admin_promote(receiver, member_username, member_id)
elseif mod_cmd == 'admindem' then
return admin_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message .. '- '..v..' [' ..k.. '] \n'
end
return message
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if next(data['admins']) == nil then --fix way
return 'No admin available.'
end
local message = 'List for Bot admins:\n'
for k,v in pairs(data['admins']) do
message = message .. '- ' .. v ..' ['..k..'] \n'
end
return message
end
function run(msg, matches)
if matches[1] == 'debug' then
return debugs(msg)
end
if not is_chat_msg(msg) then
return "Only works on group"
end
local mod_cmd = matches[1]
local receiver = get_receiver(msg)
if matches[1] == 'modadd' then
return modadd(msg)
end
if matches[1] == 'modrem' then
return modrem(msg)
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return "Only moderator can promote"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return "Only moderator can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'modlist' then
return modlist(msg)
end
if matches[1] == 'adminprom' then
if not is_admin(msg) then
return "Only sudo can promote user as admin"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'admindem' then
if not is_admin(msg) then
return "Only sudo can promote user as admin"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'adminlist' then
if not is_admin(msg) then
return 'Admin only!'
end
return admin_list(msg)
end
if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
end
return {
description = "Moderation plugin",
usage = {
moderator = {
"!promote <username> : Promote user as moderator",
"!demote <username> : Demote user from moderator",
"!modlist : List of moderators",
},
admin = {
"!modadd : Add group to moderation list",
"!modrem : Remove group from moderation list",
},
sudo = {
"!adminprom <username> : Promote user as admin (must be done from a group)",
"!admindem <username> : Demote user from admin (must be done from a group)",
},
},
patterns = {
"^!(modadd)$",
"^!(modrem)$",
"^!(promote) (.*)$",
"^!(demote) (.*)$",
"^!(modlist)$",
"^!(adminprom) (.*)$", -- sudoers only
"^!(admindem) (.*)$", -- sudoers only
"^!(adminlist)$",
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_created)$",
},
run = run,
}
end
| gpl-2.0 |
Frenzie/koreader-base | ffi/giflib_h.lua | 3 | 2072 | local ffi = require("ffi")
ffi.cdef[[
static const int GIF_OK = 1;
static const int GIF_ERROR = 0;
typedef int GifWord;
typedef unsigned char GifByteType;
typedef struct GifColorType GifColorType;
struct GifColorType {
GifByteType Red;
GifByteType Green;
GifByteType Blue;
};
typedef struct ColorMapObject ColorMapObject;
struct ColorMapObject {
int ColorCount;
int BitsPerPixel;
bool SortFlag;
GifColorType *Colors;
};
typedef struct GifImageDesc GifImageDesc;
struct GifImageDesc {
GifWord Left;
GifWord Top;
GifWord Width;
GifWord Height;
bool Interlace;
ColorMapObject *ColorMap;
};
typedef struct ExtensionBlock ExtensionBlock;
struct ExtensionBlock {
int ByteCount;
GifByteType *Bytes;
int Function;
};
typedef struct GraphicsControlBlock GraphicsControlBlock;
struct GraphicsControlBlock {
int DisposalMode;
bool UserInputFlag;
int DelayTime;
int TransparentColor;
};
typedef struct SavedImage SavedImage;
struct SavedImage {
GifImageDesc ImageDesc;
GifByteType *RasterBits;
int ExtensionBlockCount;
ExtensionBlock *ExtensionBlocks;
};
typedef struct GifFileType GifFileType;
struct GifFileType {
GifWord SWidth;
GifWord SHeight;
GifWord SColorResolution;
GifWord SBackGroundColor;
GifByteType AspectByte;
ColorMapObject *SColorMap;
int ImageCount;
GifImageDesc Image;
SavedImage *SavedImages;
int ExtensionBlockCount;
ExtensionBlock *ExtensionBlocks;
int Error;
void *UserData;
void *Private;
};
GifFileType *DGifOpenFileName(const char *, int *);
GifFileType *DGifOpenFileHandle(int, int *);
int DGifCloseFile(GifFileType *, int *);
int DGifSlurp(GifFileType *);
const char *GifErrorString(int);
int DGifSavedExtensionToGCB(GifFileType *, int, GraphicsControlBlock *);
static const int DISPOSAL_UNSPECIFIED = 0;
static const int DISPOSE_DO_NOT = 1;
static const int DISPOSE_BACKGROUND = 2;
static const int DISPOSE_PREVIOUS = 3;
static const int NO_TRANSPARENT_COLOR = -1;
typedef int (*InputFunc)(GifFileType *, GifByteType *, int);
GifFileType *DGifOpen(void *, InputFunc, int *);
]]
| agpl-3.0 |
opentechinstitute/luci | applications/luci-qos/luasrc/model/cbi/qos/qos.lua | 41 | 2689 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.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 wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
m = Map("qos", translate("Quality of Service"),
translate("With <abbr title=\"Quality of Service\">QoS</abbr> you " ..
"can prioritize network traffic selected by addresses, " ..
"ports or services."))
s = m:section(TypedSection, "interface", translate("Interfaces"))
s.addremove = true
s.anonymous = false
e = s:option(Flag, "enabled", translate("Enable"))
e.rmempty = false
c = s:option(ListValue, "classgroup", translate("Classification group"))
c:value("Default", translate("default"))
c.default = "Default"
s:option(Flag, "overhead", translate("Calculate overhead"))
s:option(Flag, "halfduplex", translate("Half-duplex"))
dl = s:option(Value, "download", translate("Download speed (kbit/s)"))
dl.datatype = "and(uinteger,min(1))"
ul = s:option(Value, "upload", translate("Upload speed (kbit/s)"))
ul.datatype = "and(uinteger,min(1))"
s = m:section(TypedSection, "classify", translate("Classification Rules"))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
s.sortable = true
t = s:option(ListValue, "target", translate("Target"))
t:value("Priority", translate("priority"))
t:value("Express", translate("express"))
t:value("Normal", translate("normal"))
t:value("Bulk", translate("low"))
t.default = "Normal"
srch = s:option(Value, "srchost", translate("Source host"))
srch.rmempty = true
srch:value("", translate("all"))
wa.cbi_add_knownips(srch)
dsth = s:option(Value, "dsthost", translate("Destination host"))
dsth.rmempty = true
dsth:value("", translate("all"))
wa.cbi_add_knownips(dsth)
l7 = s:option(ListValue, "layer7", translate("Service"))
l7.rmempty = true
l7:value("", translate("all"))
local pats = io.popen("find /etc/l7-protocols/ -type f -name '*.pat'")
if pats then
local l
while true do
l = pats:read("*l")
if not l then break end
l = l:match("([^/]+)%.pat$")
if l then
l7:value(l)
end
end
pats:close()
end
p = s:option(Value, "proto", translate("Protocol"))
p:value("", translate("all"))
p:value("tcp", "TCP")
p:value("udp", "UDP")
p:value("icmp", "ICMP")
p.rmempty = true
ports = s:option(Value, "ports", translate("Ports"))
ports.rmempty = true
ports:value("", translate("all"))
bytes = s:option(Value, "connbytes", translate("Number of bytes"))
comment = s:option(Value, "comment", translate("Comment"))
return m
| apache-2.0 |
daurnimator/lua-http | http/stream_common.lua | 1 | 4479 | --[[
This module provides common functions for HTTP streams
no matter the underlying protocol version.
This is usually an internal module, and should be used by adding the
`methods` exposed to your own HTTP stream objects.
]]
local cqueues = require "cqueues"
local monotime = cqueues.monotime
local new_headers = require "http.headers".new
local CHUNK_SIZE = 2^20 -- write in 1MB chunks
local stream_methods = {}
function stream_methods:checktls()
return self.connection:checktls()
end
function stream_methods:localname()
return self.connection:localname()
end
function stream_methods:peername()
return self.connection:peername()
end
-- 100-Continue response
local continue_headers = new_headers()
continue_headers:append(":status", "100")
function stream_methods:write_continue(timeout)
return self:write_headers(continue_headers, false, timeout)
end
-- need helper to discard 'last' argument
-- (which would otherwise end up going in 'timeout')
local function each_chunk_helper(self)
return self:get_next_chunk()
end
function stream_methods:each_chunk()
return each_chunk_helper, self
end
function stream_methods:get_body_as_string(timeout)
local deadline = timeout and (monotime()+timeout)
local body, i = {}, 0
while true do
local chunk, err, errno = self:get_next_chunk(timeout)
if chunk == nil then
if err == nil then
break
else
return nil, err, errno
end
end
i = i + 1
body[i] = chunk
timeout = deadline and (deadline-monotime())
end
return table.concat(body, "", 1, i)
end
function stream_methods:get_body_chars(n, timeout)
local deadline = timeout and (monotime()+timeout)
local body, i, len = {}, 0, 0
while len < n do
local chunk, err, errno = self:get_next_chunk(timeout)
if chunk == nil then
if err == nil then
break
else
return nil, err, errno
end
end
i = i + 1
body[i] = chunk
len = len + #chunk
timeout = deadline and (deadline-monotime())
end
if i == 0 then
return nil
end
local r = table.concat(body, "", 1, i)
if n < len then
self:unget(r:sub(n+1, -1))
r = r:sub(1, n)
end
return r
end
function stream_methods:get_body_until(pattern, plain, include_pattern, timeout)
local deadline = timeout and (monotime()+timeout)
local body
while true do
local chunk, err, errno = self:get_next_chunk(timeout)
if chunk == nil then
if err == nil then
return body, err
else
return nil, err, errno
end
end
if body then
body = body .. chunk
else
body = chunk
end
local s, e = body:find(pattern, 1, plain)
if s then
if e < #body then
self:unget(body:sub(e+1, -1))
end
if include_pattern then
return body:sub(1, e)
else
return body:sub(1, s-1)
end
end
timeout = deadline and (deadline-monotime())
end
end
function stream_methods:save_body_to_file(file, timeout)
local deadline = timeout and (monotime()+timeout)
while true do
local chunk, err, errno = self:get_next_chunk(timeout)
if chunk == nil then
if err == nil then
break
else
return nil, err, errno
end
end
assert(file:write(chunk))
timeout = deadline and (deadline-monotime())
end
return true
end
function stream_methods:get_body_as_file(timeout)
local file = assert(io.tmpfile())
local ok, err, errno = self:save_body_to_file(file, timeout)
if not ok then
return nil, err, errno
end
assert(file:seek("set"))
return file
end
function stream_methods:write_body_from_string(str, timeout)
return self:write_chunk(str, true, timeout)
end
function stream_methods:write_body_from_file(options, timeout)
local deadline = timeout and (monotime()+timeout)
local file, count
if io.type(options) then -- lua-http <= 0.2 took a file handle
file = options
else
file = options.file
count = options.count
end
if count == nil then
count = math.huge
elseif type(count) ~= "number" or count < 0 or count % 1 ~= 0 then
error("invalid .count parameter (expected positive integer)")
end
while count > 0 do
local chunk, err = file:read(math.min(CHUNK_SIZE, count))
if chunk == nil then
if err then
error(err)
elseif count ~= math.huge and count > 0 then
error("unexpected EOF")
end
break
end
local ok, err2, errno2 = self:write_chunk(chunk, false, deadline and (deadline-monotime()))
if not ok then
return nil, err2, errno2
end
count = count - #chunk
end
return self:write_chunk("", true, deadline and (deadline-monotime()))
end
return {
methods = stream_methods;
}
| mit |
Arashbrsh/a1wez- | plugins/id.lua | 355 | 2795 | local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
--local chat_id = "chat#id"..result.id
local chat_id = result.id
local chatname = result.print_name
local text = 'IDs for chat '..chatname
..' ('..chat_id..')\n'
..'There are '..result.members_num..' members'
..'\n---------\n'
i = 0
for k,v in pairs(result.members) do
i = i+1
text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n"
end
send_large_msg(receiver, text)
end
local function username_id(cb_extra, success, result)
local receiver = cb_extra.receiver
local qusername = cb_extra.qusername
local text = 'User '..qusername..' not found in this group!'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == qusername then
text = 'ID for username\n'..vusername..' : '..v.id
end
end
send_large_msg(receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "!id" then
local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id
if is_chat_msg(msg) then
text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")"
end
return text
elseif matches[1] == "chat" then
-- !ids? (chat) (%d+)
if matches[2] and is_sudo(msg) then
local chat = 'chat#id'..matches[2]
chat_info(chat, returnids, {receiver=receiver})
else
if not is_chat_msg(msg) then
return "You are not in a group."
end
local chat = get_receiver(msg)
chat_info(chat, returnids, {receiver=receiver})
end
else
if not is_chat_msg(msg) then
return "Only works in group"
end
local qusername = string.gsub(matches[1], "@", "")
local chat = get_receiver(msg)
chat_info(chat, username_id, {receiver=receiver, qusername=qusername})
end
end
return {
description = "Know your id or the id of a chat members.",
usage = {
"!id: Return your ID and the chat id if you are in one.",
"!ids chat: Return the IDs of the current chat members.",
"!ids chat <chat_id>: Return the IDs of the <chat_id> members.",
"!id <username> : Return the id from username given."
},
patterns = {
"^!id$",
"^!ids? (chat) (%d+)$",
"^!ids? (chat)$",
"^!id (.*)$"
},
run = run
}
| gpl-2.0 |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/tests/lua-tests/src/Sprite3DTest/Sprite3DTest.lua | 2 | 44338 | require "cocos.3d.3dConstants"
local size = cc.Director:getInstance():getWinSize()
local scheduler = cc.Director:getInstance():getScheduler()
local attributeNames =
{
"a_position",
"a_color",
"a_texCoord",
"a_texCoord1",
"a_texCoord2",
"a_texCoord3",
"a_texCoord4",
"a_texCoord5",
"a_texCoord6",
"a_texCoord7",
"a_normal",
"a_blendWeight",
"a_blendIndex",
}
----------------------------------------
----Sprite3DBasicTest
----------------------------------------
local Sprite3DBasicTest = {}
Sprite3DBasicTest.__index = Sprite3DBasicTest
function Sprite3DBasicTest.onTouchesEnd(touches, event)
for i = 1,table.getn(touches) do
local location = touches[i]:getLocation()
Sprite3DBasicTest.addNewSpriteWithCoords(Helper.currentLayer, location.x, location.y )
end
end
function Sprite3DBasicTest.addNewSpriteWithCoords(parent,x,y)
local sprite = cc.Sprite3D:create("Sprite3DTest/boss1.obj")
sprite:setScale(3.0)
sprite:setTexture("Sprite3DTest/boss.png")
parent:addChild(sprite)
sprite:setPosition(cc.p(x,y))
local random = math.random()
local action = nil
if random < 0.2 then
action = cc.ScaleBy:create(3,2)
elseif random < 0.4 then
action = cc.RotateBy:create(3, 360)
elseif random < 0.6 then
action = cc.Blink:create(1, 3)
elseif random < 0.8 then
action = cc.TintBy:create(2, 0, -255, -255)
else
action = cc.FadeOut:create(2)
end
local action_back = action:reverse()
local seq = cc.Sequence:create(action, action_back)
sprite:runAction(cc.RepeatForever:create(seq))
end
function Sprite3DBasicTest.create()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Testing Sprite3D")
Helper.subtitleLabel:setString("Tap screen to add more sprites")
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(Sprite3DBasicTest.onTouchesEnd,cc.Handler.EVENT_TOUCHES_ENDED )
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer)
Sprite3DBasicTest.addNewSpriteWithCoords(layer, size.width / 2, size.height / 2)
return layer
end
----------------------------------------
----Sprite3DHitTest
----------------------------------------
local Sprite3DHitTest = {}
Sprite3DHitTest.__index = Sprite3DHitTest
function Sprite3DHitTest.create()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Testing Sprite3D Touch in 2D")
Helper.subtitleLabel:setString("Tap Sprite3D and Drag")
local sprite1 = cc.Sprite3D:create("Sprite3DTest/boss1.obj")
sprite1:setScale(4.0)
sprite1:setTexture("Sprite3DTest/boss.png")
sprite1:setPosition( cc.p(size.width/2, size.height/2) )
sprite1:runAction(cc.RepeatForever:create(cc.RotateBy:create(3, 360)))
layer:addChild(sprite1)
local sprite2 = cc.Sprite3D:create("Sprite3DTest/boss1.obj")
sprite2:setScale(4.0)
sprite2:setTexture("Sprite3DTest/boss.png")
sprite2:setPosition( cc.p(size.width/2, size.height/2) )
sprite2:setAnchorPoint(cc.p(0.5, 0.5))
sprite2:runAction(cc.RepeatForever:create(cc.RotateBy:create(3, -360)))
layer:addChild(sprite2)
local listener = cc.EventListenerTouchOneByOne:create()
listener:setSwallowTouches(true)
listener:registerScriptHandler(function (touch, event)
local target = event:getCurrentTarget()
local rect = target:getBoundingBox()
if cc.rectContainsPoint(rect, touch:getLocation()) then
print(string.format("sprite3d began... x = %f, y = %f", touch:getLocation().x, touch:getLocation().y))
target:setOpacity(100)
return true
end
return false
end,cc.Handler.EVENT_TOUCH_BEGAN )
listener:registerScriptHandler(function (touch, event)
local target = event:getCurrentTarget()
local x,y = target:getPosition()
target:setPosition(cc.p(x + touch:getDelta().x, y + touch:getDelta().y))
end, cc.Handler.EVENT_TOUCH_MOVED)
listener:registerScriptHandler(function (touch, event)
local target = event:getCurrentTarget()
print("sprite3d onTouchEnd")
target:setOpacity(255)
end, cc.Handler.EVENT_TOUCH_ENDED)
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, sprite1)
eventDispatcher:addEventListenerWithSceneGraphPriority(listener:clone(), sprite2)
return layer
end
----------------------------------------
----Sprite3DWithSkinTest
----------------------------------------
local Sprite3DWithSkinTest = {}
Sprite3DWithSkinTest.__index = Sprite3DWithSkinTest
Sprite3DWithSkinTest._animateQuality = cc.Animate3DQuality.QUALITY_HIGH
Sprite3DWithSkinTest._sprites = {}
function Sprite3DWithSkinTest.onTouchesEnd(touches, event)
for i = 1,table.getn(touches) do
local location = touches[i]:getLocation()
Sprite3DWithSkinTest.addNewSpriteWithCoords(Helper.currentLayer, location.x, location.y )
end
end
function Sprite3DWithSkinTest.addNewSpriteWithCoords(parent,x,y)
local sprite = cc.Sprite3D:create("Sprite3DTest/orc.c3b")
sprite:setScale(3)
sprite:setRotation3D({x = 0, y = 180, z = 0})
sprite:setPosition(cc.p(x, y))
parent:addChild(sprite)
table.insert(Sprite3DWithSkinTest._sprites, sprite)
local animation = cc.Animation3D:create("Sprite3DTest/orc.c3b")
if nil ~= animation then
local animate = cc.Animate3D:create(animation)
local inverse = false
if math.random() == 0 then
inverse = true
end
local rand2 = math.random()
local speed = 1.0
if rand2 < 1/3 then
speed = animate:getSpeed() + math.random()
elseif rand2 < 2/3 then
speed = animate:getSpeed() - 0.5 * math.random()
end
if inverse then
animate:setSpeed(-speed)
else
animate:setSpeed(speed)
end
animate:setTag(110)
animate:setQuality(Sprite3DWithSkinTest._animateQuality)
local repeate = cc.RepeatForever:create(animate)
repeate:setTag(110)
sprite:runAction(repeate)
end
end
function Sprite3DWithSkinTest.create()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Testing Sprite3D for animation from c3t")
Helper.subtitleLabel:setString("Tap screen to add more sprite3D")
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(Sprite3DWithSkinTest.onTouchesEnd,cc.Handler.EVENT_TOUCHES_ENDED )
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer)
Sprite3DWithSkinTest._sprites = {}
Sprite3DWithSkinTest.addNewSpriteWithCoords(layer, size.width / 2, size.height / 2)
cc.MenuItemFont:setFontName("fonts/arial.ttf")
cc.MenuItemFont:setFontSize(15)
local menuItem = cc.MenuItemFont:create("High Quality")
Sprite3DWithSkinTest._animateQuality = cc.Animate3DQuality.QUALITY_HIGH
menuItem:registerScriptTapHandler(function(tag, sender)
Sprite3DWithSkinTest._animateQuality = Sprite3DWithSkinTest._animateQuality + 1
if Sprite3DWithSkinTest._animateQuality > cc.Animate3DQuality.QUALITY_HIGH then
Sprite3DWithSkinTest._animateQuality = cc.Animate3DQuality.QUALITY_NONE
end
if Sprite3DWithSkinTest._animateQuality == cc.Animate3DQuality.QUALITY_NONE then
menuItem:setString("None Quality")
elseif Sprite3DWithSkinTest._animateQuality == cc.Animate3DQuality.QUALITY_LOW then
menuItem:setString("Low Quality")
elseif Sprite3DWithSkinTest._animateQuality == cc.Animate3DQuality.QUALITY_HIGH then
menuItem:setString("High Quality")
end
for i,spriteIter in ipairs(Sprite3DWithSkinTest._sprites) do
local repAction = spriteIter:getActionByTag(110)
local animate3D = repAction:getInnerAction()
animate3D:setQuality(Sprite3DWithSkinTest._animateQuality)
end
end)
local menu = cc.Menu:create(menuItem)
menu:setPosition(cc.p(0.0, 0.0))
menuItem:setPosition(VisibleRect:left().x + 50, VisibleRect:top().y -70)
layer:addChild(menu, 1)
return layer
end
----------------------------------------
----Animate3DTest
----------------------------------------
local State =
{
SWIMMING = 0,
SWIMMING_TO_HURT = 1,
HURT = 2,
HURT_TO_SWIMMING = 3,
}
local Animate3DTest = {}
Animate3DTest.__index = Animate3DTest
function Animate3DTest.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, Animate3DTest)
return target
end
function Animate3DTest:onEnter()
self._hurt = nil
self._swim = nil
self._sprite = nil
self._moveAction = nil
self._transTime = 0.1
self._elapseTransTime = 0.0
local function renewCallBack()
self._sprite:stopActionByTag(101)
self._state = State.HURT_TO_SWIMMING
end
local function onTouchesEnd(touches, event )
for i = 1,table.getn(touches) do
local location = touches[i]:getLocation()
if self._sprite ~= nil then
local len = cc.pGetLength(cc.pSub(cc.p(self._sprite:getPosition()), location))
if len < 40 then
if self._state == State.SWIMMING then
self._sprite:runAction(self._hurt)
local delay = cc.DelayTime:create(self._hurt:getDuration() - 0.1)
local seq = cc.Sequence:create(delay, cc.CallFunc:create(renewCallBack))
seq:setTag(101)
self._sprite:runAction(seq)
self._state = State.SWIMMING_TO_HURT
end
return
end
end
end
end
self:addSprite3D()
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(onTouchesEnd,cc.Handler.EVENT_TOUCHES_ENDED )
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
local function update(dt)
if self._state == State.HURT_TO_SWIMMING then
self._elapseTransTime = self._elapseTransTime + dt
local t = self._elapseTransTime / self._transTime
if t >= 1.0 then
t = 1.0
self._sprite:stopAction(self._hurt)
self._state = State.SWIMMING
end
self._swim:setWeight(t)
self._hurt:setWeight(1.0 - t)
elseif self._state == State.SWIMMING_TO_HURT then
self._elapseTransTime = self._elapseTransTime + dt
local t = self._elapseTransTime / self._transTime
if t >= 1.0 then
t = 1.0
self._state = State.HURT
end
self._swim:setWeight(1.0 - t)
self._hurt:setWeight(t)
end
end
self:scheduleUpdateWithPriorityLua(update,0)
end
function Animate3DTest:onExit()
self._moveAction:release()
self._hurt:release()
self._swim:release()
self:unscheduleUpdate()
end
function Animate3DTest:addSprite3D()
-- body
local fileName = "Sprite3DTest/tortoise.c3b"
local sprite = cc.Sprite3D:create(fileName)
sprite:setScale(0.1)
local winSize = cc.Director:getInstance():getWinSize()
sprite:setPosition(cc.p(winSize.width * 4.0 / 5.0, winSize.height / 2.0))
self:addChild(sprite)
self._sprite = sprite
local animation = cc.Animation3D:create(fileName)
if nil ~= animation then
local animate = cc.Animate3D:create(animation, 0.0, 1.933)
sprite:runAction(cc.RepeatForever:create(animate))
self._swim = animate
self._swim:retain()
self._hurt = cc.Animate3D:create(animation, 1.933, 2.8)
self._hurt:retain()
self._state = State.SWIMMING
end
self._moveAction = cc.MoveTo:create(4.0, cc.p(winSize.width / 5.0, winSize.height / 2.0))
self._moveAction:retain()
local function reachEndCallBack()
local winSize = cc.Director:getInstance():getWinSize()
self._sprite:stopActionByTag(100)
local inverse = cc.MoveTo:create(4.0, cc.p(winSize.width - self._sprite:getPositionX(), winSize.height / 2.0))
inverse:retain()
self._moveAction:release()
self._moveAction = inverse
local rot = cc.RotateBy:create(1.0, { x = 0.0, y = 180.0, z = 0.0})
local seq = cc.Sequence:create(rot, self._moveAction, cc.CallFunc:create(reachEndCallBack))
seq:setTag(100)
self._sprite:runAction(seq)
end
local seq = cc.Sequence:create(self._moveAction, cc.CallFunc:create(reachEndCallBack))
seq:setTag(100)
sprite:runAction(seq)
end
function Animate3DTest.create()
local layer = Animate3DTest.extend(cc.Layer:create())
if nil ~= layer then
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Testing Animate3D")
Helper.subtitleLabel:setString("Touch to beat the tortoise")
local function onNodeEvent(event)
if "enter" == event then
layer:onEnter()
elseif "exit" == event then
layer:onExit()
end
end
layer:registerScriptHandler(onNodeEvent)
end
return layer
end
----------------------------------------
----AttachmentTest
----------------------------------------
local AttachmentTest = {}
AttachmentTest.__index = AttachmentTest
function AttachmentTest.create()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Testing Sprite3D Attachment")
Helper.subtitleLabel:setString("touch to switch weapon")
local _sprite = nil
local _hasWeapon = nil
local function addNewSpriteWithCoords(pos)
local fileName = "Sprite3DTest/orc.c3b"
local sprite = cc.Sprite3D:create(fileName)
sprite:setScale(5)
sprite:setRotation3D({x = 0, y =180, z = 0})
layer:addChild(sprite)
sprite:setPosition( cc.p( pos.x, pos.y) )
--test attach
local sp = cc.Sprite3D:create("Sprite3DTest/axe.c3b")
sprite:getAttachNode("Bip001 R Hand"):addChild(sp)
local animation = cc.Animation3D:create(fileName)
if nil ~=animation then
local animate = cc.Animate3D:create(animation)
sprite:runAction(cc.RepeatForever:create(animate))
end
_sprite = sprite
_hasWeapon = true
end
addNewSpriteWithCoords(cc.p(size.width / 2, size.height / 2))
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(function (touches, event)
if _hasWeapon then
_sprite:removeAllAttachNode()
else
local sp = cc.Sprite3D:create("Sprite3DTest/axe.c3b")
_sprite:getAttachNode("Bip001 R Hand"):addChild(sp)
end
_hasWeapon = not _hasWeapon
end,cc.Handler.EVENT_TOUCHES_ENDED)
local eventDispatcher = layer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer)
return layer
end
----------------------------------------
----Sprite3DReskinTest
----------------------------------------
local Sprite3DReskinTest = {}
Sprite3DReskinTest.__index = Sprite3DReskinTest
function Sprite3DReskinTest.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, Sprite3DReskinTest)
return target
end
function Sprite3DReskinTest:init()
self._girlPants = {}
self._usePantsId = 0
self._girlUpperBody = {}
self._useUpBodyId = 0
self._girlShoes = {}
self._useShoesId = 0
self._girlHair = {}
self._useHairId = 0
self._sprite = nil
self:addNewSpriteWithCoords(cc.p(size.width / 2, size.height / 2))
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(function (touches, event)
end,cc.Handler.EVENT_TOUCHES_ENDED)
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
local ttfConfig = {}
ttfConfig.fontFilePath = "fonts/arial.ttf"
ttfConfig.fontSize = 20
local label1 = cc.Label:createWithTTF(ttfConfig,"Hair")
local item1 = cc.MenuItemLabel:create(label1)
item1:registerScriptTapHandler(function (tag, sender ) -- swithHair
self._useHairId = self._useHairId + 1
if self._useHairId > 1 then
self._useHairId = 0
end
if self._useHairId >= 0 and self._sprite ~= nil then
for i=1,2 do
local subMesh = self._sprite:getMeshByName(self._girlHair[i])
if nil ~= subMesh then
if (i - 1) == self._useHairId then
subMesh:setVisible(true)
else
subMesh:setVisible(false)
end
end
end
end
end)
local label2 = cc.Label:createWithTTF(ttfConfig,"Glasses")
local item2 = cc.MenuItemLabel:create(label2)
item2:registerScriptTapHandler(function (tag, sender ) -- switchGlasses
local subMesh = self._sprite:getMeshByName("Girl_Glasses01")
if nil ~= subMesh then
if subMesh:isVisible() then
subMesh:setVisible(false)
else
subMesh:setVisible(true)
end
end
end)
local label3 = cc.Label:createWithTTF(ttfConfig,"Coat")
local item3 = cc.MenuItemLabel:create(label3)
item3:registerScriptTapHandler(function (tag, sender ) -- switchCoat
self._useUpBodyId = self._useUpBodyId + 1
if self._useUpBodyId > 1 then
self._useUpBodyId = 0
end
if self._useUpBodyId >= 0 and nil ~= self._sprite then
for i=1,2 do
local subMesh = self._sprite:getMeshByName(self._girlUpperBody[i])
if nil ~=subMesh then
if (i - 1) == self._useUpBodyId then
subMesh:setVisible(true)
else
subMesh:setVisible(false)
end
end
end
end
end)
local label4 = cc.Label:createWithTTF(ttfConfig,"Pants")
local item4 = cc.MenuItemLabel:create(label4)
item4:registerScriptTapHandler(function (tag, sender ) -- switchPants
self._usePantsId = self._usePantsId + 1
if self._usePantsId > 1 then
self._usePantsId = 0
end
if self._usePantsId >= 0 and nil ~= self._sprite then
for i=1,2 do
local subMesh = self._sprite:getMeshByName(self._girlPants[i])
if nil ~= subMesh then
if (i - 1) == self._usePantsId then
subMesh:setVisible(true)
else
subMesh:setVisible(false)
end
end
end
end
end)
local label5 = cc.Label:createWithTTF(ttfConfig,"Shoes")
local item5 = cc.MenuItemLabel:create(label5)
item5:registerScriptTapHandler(function (tag, sender ) -- switchShoes
self._useShoesId = self._useShoesId + 1
if self._useShoesId > 1 then
self._useShoesId = 0
end
if self._useShoesId >= 0 and nil ~= self._sprite then
for i=1,2 do
local subMesh = self._sprite:getMeshByName(self._girlShoes[i])
if nil ~= subMesh then
if (i - 1) == self._useShoesId then
subMesh:setVisible(true)
else
subMesh:setVisible(false)
end
end
end
end
end)
item1:setPosition( cc.p(VisibleRect:left().x+50, VisibleRect:bottom().y+item1:getContentSize().height*4 ) )
item2:setPosition( cc.p(VisibleRect:left().x+50, VisibleRect:bottom().y+item1:getContentSize().height *5 ) )
item3:setPosition( cc.p(VisibleRect:left().x+50, VisibleRect:bottom().y+item1:getContentSize().height*6 ) )
item4:setPosition( cc.p(VisibleRect:left().x+50, VisibleRect:bottom().y+item1:getContentSize().height *7 ) )
item5:setPosition( cc.p(VisibleRect:left().x+50, VisibleRect:bottom().y+item1:getContentSize().height *8 ) )
local menu = cc.Menu:create(item1,item2,item3,item4,item5)
menu:setPosition(cc.p(0,0))
self:addChild(menu, 10)
end
function Sprite3DReskinTest:addNewSpriteWithCoords(pos)
self._girlPants = {"Girl_LowerBody01", "Girl_LowerBody02"}
self._girlUpperBody = {"Girl_UpperBody01", "Girl_UpperBody02"}
self._girlShoes = {"Girl_Shoes01", "Girl_Shoes02"}
self._girlHair = {"Girl_Hair01", "Girl_Hair02"}
self._usePantsId = 0
self._useUpBodyId = 0
self._useShoesId =0
self._useHairId = 0
local fileName = "Sprite3DTest/ReskinGirl.c3b"
local sprite = cc.Sprite3D:create(fileName)
sprite:setScale(4)
sprite:setRotation3D({x = 0, y =0 ,z = 0})
local girlPants = sprite:getMeshByName(self._girlPants[2])
if nil ~= girlPants then
girlPants:setVisible(false)
end
local girlShoes = sprite:getMeshByName(self._girlShoes[2])
if nil ~= girlShoes then
girlShoes:setVisible(false)
end
local girlHair = sprite:getMeshByName(self._girlHair[2])
if nil ~= girlHair then
girlHair:setVisible(false)
end
local girlUpBody = sprite:getMeshByName( self._girlUpperBody[2])
if nil ~=girlUpBody then
girlUpBody:setVisible(false)
end
self:addChild(sprite)
sprite:setPosition( cc.p( pos.x, pos.y-60) )
local animation = cc.Animation3D:create(fileName)
if nil ~= animation then
local animate = cc.Animate3D:create(animation)
sprite:runAction(cc.RepeatForever:create(animate))
end
self._sprite = sprite
end
function Sprite3DReskinTest.create()
local layer = Sprite3DReskinTest.extend(cc.Layer:create())
if nil ~= layer then
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Testing Sprite3D Reskin")
layer:init()
end
return layer
end
----------------------------------------
----Sprite3DWithOBBPerfromanceTest
----------------------------------------
local Sprite3DWithOBBPerfromanceTest = class("Sprite3DWithOBBPerfromanceTest",function()
return cc.Layer:create()
end)
function Sprite3DWithOBBPerfromanceTest:ctor()
self._obb = {}
local listener = cc.EventListenerTouchAllAtOnce:create()
listener:registerScriptHandler(function (touches, event)
for i,touch in ipairs(touches) do
local location = touch:getLocationInView()
if nil ~= self._obb and #self._obb > 0 then
self._intersetList = {}
local ray = cc.Ray:new()
self:calculateRayByLocationInView(ray, location)
for idx,value in ipairs(self._obb) do
if ray:intersects(value) then
table.insert(self._intersetList, idx)
return
end
end
end
end
end,cc.Handler.EVENT_TOUCHES_BEGAN)
listener:registerScriptHandler(function (touches, event)
end,cc.Handler.EVENT_TOUCHES_ENDED)
listener:registerScriptHandler(function (touches, event)
for i,touch in ipairs(touches) do
local location = touch:getLocation()
for idx,value in ipairs(self._obb) do
for lstIdx,lstValue in ipairs(self._intersetList) do
if idx == lstValue then
self._obb[idx]._center = cc.vec3(location.x,location.y,0)
end
end
end
end
end,cc.Handler.EVENT_TOUCHES_MOVED)
local eventDispatcher = self:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
local s = cc.Director:getInstance():getWinSize()
self:initDrawBox()
self:addNewSpriteWithCoords(cc.p(s.width/2, s.height/2))
cc.MenuItemFont:setFontName("fonts/arial.ttf")
cc.MenuItemFont:setFontSize(65)
local decrease = cc.MenuItemFont:create(" - ")
decrease:registerScriptTapHandler(function(tag, sender)
self:delOBBWithCount(10)
end)
decrease:setColor(cc.c3b(0, 200, 20))
local increase = cc.MenuItemFont:create(" + ")
increase:registerScriptTapHandler(function(tag, sender)
self:addOBBWithCount(10)
end)
increase:setColor(cc.c3b(0, 200, 20))
local menu = cc.Menu:create(decrease, increase)
menu:alignItemsHorizontally()
menu:setPosition(cc.p(s.width/2, s.height - 90))
self:addChild(menu, 1)
local ttfConfig = {}
ttfConfig.fontFilePath = "fonts/Marker Felt.ttf"
ttfConfig.fontSize = 30
self._labelCubeCount = cc.Label:createWithTTF(ttfConfig,"0 cubes")
self._labelCubeCount:setColor(cc.c3b(0,200,20))
self._labelCubeCount:setPosition(cc.p(s.width/2, s.height-90))
self:addChild(self._labelCubeCount)
self:addOBBWithCount(10)
self:scheduleUpdateWithPriorityLua(function(dt)
self._labelCubeCount:setString(string.format("%u cubes", #self._obb))
if nil ~= self._drawDebug then
self._drawDebug:clear()
local mat = self._sprite:getNodeToWorldTransform()
self._obbt._xAxis = cc.vec3(mat[1], mat[2], mat[3])
self._obbt._xAxis = cc.vec3normalize(self._obbt._xAxis)
self._obbt._yAxis = cc.vec3(mat[5], mat[6], mat[7])
self._obbt._yAxis = cc.vec3normalize(self._obbt._yAxis)
self._obbt._zAxis = cc.vec3(-mat[9], -mat[10], -mat[11])
self._obbt._zAxis = cc.vec3normalize(self._obbt._zAxis)
self._obbt._center = self._sprite:getPosition3D()
local corners = {}
for i=1,8 do
corners[i] = {}
end
corners = self._obbt:getCorners(corners)
self._drawDebug:drawCube(corners, cc.c4f(0, 0, 1, 1))
end
if #self._obb > 0 then
self._drawOBB:clear()
for i= 1, #self._obb do
local corners = {}
for i=1,8 do
corners[i] = {}
end
corners = self._obb[i]:getCorners(corners)
if self._obbt:intersects(self._obb[i]) then
self._drawOBB:drawCube(corners, cc.c4f(1, 0, 0, 1))
else
self._drawOBB:drawCube(corners, cc.c4f(0, 1, 0, 1))
end
end
end
end, 0)
end
function Sprite3DWithOBBPerfromanceTest:addOBBWithCount( value )
for i=1,value do
local randompos = cc.p(math.random() * cc.Director:getInstance():getWinSize().width, math.random() * cc.Director:getInstance():getWinSize().height)
local extents = cc.vec3(10, 10, 10)
local aabb = cc.AABB:new({x = -10, y = -10, z = -10}, extents)
local obb = cc.OBB:new(aabb)
obb._center = cc.vec3(randompos.x,randompos.y,0)
table.insert(self._obb, obb)
end
end
function Sprite3DWithOBBPerfromanceTest:delOBBWithCount( value )
if #self._obb >= 10 then
for i= 1, 10 do
table.remove(self._obb)
end
self._drawOBB:clear()
end
end
function Sprite3DWithOBBPerfromanceTest:initDrawBox()
self._drawOBB = cc.DrawNode3D:create()
self:addChild(self._drawOBB )
end
function Sprite3DWithOBBPerfromanceTest:unproject( viewProjection, viewport, src, dst)
assert(viewport.width ~= 0.0 and viewport.height ~= 0)
local screen = cc.vec4(src.x / viewport.width, (viewport.height - src.y) / viewport.height, src.z, 1.0)
screen.x = screen.x * 2.0 - 1.0
screen.y = screen.y * 2.0 - 1.0
screen.z = screen.z * 2.0 - 1.0
local inversed = cc.mat4.new(viewProjection:getInversed())
screen = inversed:transformVector(screen, screen)
if screen.w ~= 0.0 then
screen.x = screen.x / screen.w
screen.y = screen.y / screen.w
screen.z = screen.z / screen.w
end
dst.x = screen.x
dst.y = screen.y
dst.z = screen.z
return viewport, src, dst
end
function Sprite3DWithOBBPerfromanceTest:calculateRayByLocationInView(ray, location)
local dir = cc.Director:getInstance()
local view = dir:getWinSize()
local mat = cc.mat4.new(dir:getMatrix(cc.MATRIX_STACK_TYPE.PROJECTION))
local src = cc.vec3(location.x, location.y, -1)
local nearPoint = {}
view, src, nearPoint = self:unproject(mat, view, src, nearPoint)
src = cc.vec3(location.x, location.y, 1)
local farPoint = {}
view, src, farPoint = self:unproject(mat, view, src, farPoint)
local direction = {}
direction.x = farPoint.x - nearPoint.x
direction.y = farPoint.y - nearPoint.y
direction.z = farPoint.z - nearPoint.z
direction = cc.vec3normalize(direction)
ray._origin = nearPoint
ray._direction = direction
end
function Sprite3DWithOBBPerfromanceTest:addNewSpriteWithCoords(vec2)
local fileName = "Sprite3DTest/tortoise.c3b"
local sprite = cc.Sprite3D:create(fileName)
sprite:setScale(0.1)
local s = cc.Director:getInstance():getWinSize()
sprite:setPosition(cc.p(s.width * 4.0 / 5.0, s.height / 2.0))
self:addChild(sprite)
self._sprite = sprite
local animation = cc.Animation3D:create(fileName)
if nil ~= animation then
local animate = cc.Animate3D:create(animation, 0.0, 1.933)
sprite:runAction(cc.RepeatForever:create(animate))
end
self._moveAction = cc.MoveTo:create(4.0, cc.p(s.width / 5.0, s.height / 2.0))
self._moveAction:retain()
local function reachEndCallBack()
local s = cc.Director:getInstance():getWinSize()
self._sprite:stopActionByTag(100)
local inverse = cc.MoveTo:create(4.0, cc.p(s.width - self._sprite:getPositionX(), s.height / 2.0))
inverse:retain()
self._moveAction:release()
self._moveAction = inverse
local rot = cc.RotateBy:create(1.0, { x = 0.0, y = 180.0, z = 0.0})
local seq = cc.Sequence:create(rot, self._moveAction, cc.CallFunc:create(reachEndCallBack))
seq:setTag(100)
self._sprite:runAction(seq)
end
local seq = cc.Sequence:create(self._moveAction, cc.CallFunc:create(reachEndCallBack))
seq:setTag(100)
sprite:runAction(seq)
local aabb = self._sprite:getAABB()
self._obbt = cc.OBB:new(aabb)
self._drawDebug = cc.DrawNode3D:create()
self:addChild(self._drawDebug)
end
function Sprite3DWithOBBPerfromanceTest.create()
local layer = Sprite3DWithOBBPerfromanceTest.new()
Helper.initWithLayer(layer)
Helper.titleLabel:setString("OBB Collison Perfromance Test")
return layer
end
----------------------------------------
----Sprite3DMirrorTest
----------------------------------------
local Sprite3DMirrorTest = {}
Sprite3DMirrorTest.__index = Sprite3DMirrorTest
function Sprite3DMirrorTest.create()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
Helper.titleLabel:setString("Sprite3D Mirror Test")
local fileName = "Sprite3DTest/orc.c3b"
local sprite = cc.Sprite3D:create(fileName)
sprite:setScale(5.0)
sprite:setRotation3D({x = 0, y = 180, z = 0})
sprite:setPosition( cc.p(size.width/2 - 80, size.height/2) )
layer:addChild(sprite)
local sp = cc.Sprite3D:create("Sprite3DTest/axe.c3b")
sprite:getAttachNode("Bip001 R Hand"):addChild(sp)
local animation = cc.Animation3D:create(fileName)
if nil ~= animation then
local animate = cc.Animate3D:create(animation)
sprite:runAction(cc.RepeatForever:create(animate))
end
--create mirror Sprite3D
sprite = cc.Sprite3D:create(fileName)
sprite:setScale(5)
sprite:setScaleX(-5)
sprite:setCullFace(gl.FRONT)
sprite:setRotation3D({x = 0, y = 180,z = 0})
layer:addChild(sprite)
sprite:setPosition( cc.p( size.width/2 + 80, size.height/2))
--test attach
sp = cc.Sprite3D:create("Sprite3DTest/axe.c3b")
sprite:getAttachNode("Bip001 R Hand"):addChild(sp)
animation = cc.Animation3D:create(fileName)
if nil ~= animation then
local animate = cc.Animate3D:create(animation)
sprite:runAction(cc.RepeatForever:create(animate))
end
return layer
end
----------------------------------------
----AsyncLoadSprite3DTest
----------------------------------------
local AsyncLoadSprite3DTest = class("AsyncLoadSprite3DTest", function ()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
return layer
end)
function AsyncLoadSprite3DTest:ctor()
-- body
self:init()
end
function AsyncLoadSprite3DTest:init()
Helper.titleLabel:setString(self:title())
Helper.subtitleLabel:setString(self:subtitle())
self:registerScriptHandler(function (event)
if event == "enter" then
self:onEnter()
elseif event == "exit" then
self:onExit()
end
end)
end
function AsyncLoadSprite3DTest:title()
return "Testing Sprite3D:createAsync"
end
function AsyncLoadSprite3DTest:subtitle()
return ""
end
function AsyncLoadSprite3DTest:onEnter()
local ttfConfig = {}
ttfConfig.fontFilePath = "fonts/arial.ttf"
ttfConfig.fontSize = 15
local paths = {"Sprite3DTest/boss.obj", "Sprite3DTest/girl.c3b", "Sprite3DTest/orc.c3b", "Sprite3DTest/ReskinGirl.c3b", "Sprite3DTest/axe.c3b"}
local label1 = cc.Label:createWithTTF(ttfConfig,"AsyncLoad Sprite3D")
local item1 = cc.MenuItemLabel:create(label1)
function menuCallback_asyncLoadSprite(tag, sender)
--Note that you must stop the tasks before leaving the scene.
cc.AsyncTaskPool:getInstance():stopTasks(cc.AsyncTaskPool.TaskType.TASK_IO)
local node = self:getChildByTag(101)
--remove all loaded sprite
node:removeAllChildren()
--remove cache data
cc.Sprite3DCache:getInstance():removeAllSprite3DData()
local function callback(sprite, index)
local node = self:getChildByTag(101)
local s = cc.Director:getInstance():getWinSize()
local width = s.width / (#paths)
local point = cc.p(width * (0.5 + index), s.height / 2.0)
sprite:setPosition(point)
node:addChild(sprite)
end
cc.Sprite3D:createAsync(paths[1], function(sprite)
callback(sprite, 0)
end)
cc.Sprite3D:createAsync(paths[2], function(sprite)
callback(sprite, 1)
end)
cc.Sprite3D:createAsync(paths[3], function(sprite)
callback(sprite, 2)
end)
cc.Sprite3D:createAsync(paths[4], function(sprite)
callback(sprite, 3)
end)
cc.Sprite3D:createAsync(paths[5], function(sprite)
callback(sprite, 4)
end)
end
item1:registerScriptTapHandler(menuCallback_asyncLoadSprite)
local s = cc.Director:getInstance():getWinSize()
item1:setPosition( s.width * 0.5, s.height * 0.8)
local menu = cc.Menu:create(item1)
menu:setPosition(cc.p(0,0))
self:addChild(menu, 10)
local node = cc.Node:create()
node:setTag(101)
self:addChild(node)
menuCallback_asyncLoadSprite()
end
function AsyncLoadSprite3DTest:onExit()
end
----------------------------------------
----Sprite3DCubeTexture
----------------------------------------
local Sprite3DCubeMapTest = class("Sprite3DCubeMapTest", function ()
local layer = cc.Layer:create()
return layer
end)
function Sprite3DCubeMapTest:ctor()
-- body
self:init()
self._textureCube = nil
self._skyBox = nil
self._teapot = nil
end
function Sprite3DCubeMapTest:init()
self:registerScriptHandler(function (event)
if event == "enter" then
self:onEnter()
elseif event == "exit" then
self:onExit()
end
end)
end
function Sprite3DCubeMapTest:title()
return "CubeMap & Skybox Test"
end
function Sprite3DCubeMapTest:subtitle()
return ""
end
function Sprite3DCubeMapTest:onEnter()
local s = cc.Director:getInstance():getWinSize()
self:addNewSpriteWithCoords(cc.p(s.width / 2, s.height / 2))
Helper.initWithLayer(self)
Helper.titleLabel:setString(self:title())
Helper.subtitleLabel:setString(self:subtitle())
end
function Sprite3DCubeMapTest:onExit()
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if targetPlatform == cc.PLATFORM_OS_ANDROID or targetPlatform == cc.PLATFORM_OS_WINRT or targetPlatform == cc.PLATFORM_OS_WP8 then
cc.Director:getInstance():getEventDispatcher():removeEventListener(self._backToForegroundListener)
end
end
function Sprite3DCubeMapTest:addNewSpriteWithCoords(pos)
local visibleSize = cc.Director:getInstance():getVisibleSize()
local camera = cc.Camera:createPerspective(60, visibleSize.width / visibleSize.height, 10, 1000)
camera:setPosition3D(cc.vec3(0.0, 0.0, 50.0))
camera:setCameraFlag(cc.CameraFlag.USER1)
--create a teapot
self._teapot = cc.Sprite3D:create("Sprite3DTest/teapot.c3b")
local shader = cc.GLProgram:createWithFilenames("Sprite3DTest/cube_map.vert", "Sprite3DTest/cube_map.frag")
local state = cc.GLProgramState:create(shader)
self._textureCube = cc.TextureCube:create("Sprite3DTest/skybox/left.jpg", "Sprite3DTest/skybox/right.jpg",
"Sprite3DTest/skybox/top.jpg", "Sprite3DTest/skybox/bottom.jpg",
"Sprite3DTest/skybox/front.jpg", "Sprite3DTest/skybox/back.jpg")
--set texture parameters
local tRepeatParams = { magFilter=gl.LINEAR , minFilter=gl.LINEAR , wrapS=gl.MIRRORED_REPEAT , wrapT=gl.MIRRORED_REPEAT }
self._textureCube:setTexParameters(tRepeatParams)
--pass the texture sampler to our custom shader
state:setUniformTexture("u_cubeTex", self._textureCube)
self._teapot:setGLProgramState(state)
self._teapot:setPosition3D(cc.vec3(0, -5, 0))
self._teapot:setRotation3D(cc.vec3(-90, 180, 0))
local rotate_action = cc.RotateBy:create(1.5, cc.vec3(0, 30, 0))
self._teapot:runAction(cc.RepeatForever:create(rotate_action))
--pass mesh's attribute to shader
local attributeNames =
{
"a_position",
"a_color",
"a_texCoord",
"a_texCoord1",
"a_texCoord2",
"a_texCoord3",
"a_normal",
"a_blendWeight",
"a_blendIndex",
}
local offset = 0
local attributeCount = self._teapot:getMesh():getMeshVertexAttribCount()
for i = 1, attributeCount do
local meshattribute = self._teapot:getMesh():getMeshVertexAttribute(i - 1)
state:setVertexAttribPointer(attributeNames[meshattribute.vertexAttrib+1],
meshattribute.size,
meshattribute.type,
false,
self._teapot:getMesh():getVertexSizeInBytes(),
offset)
offset = offset + meshattribute.attribSizeBytes
end
self:addChild(self._teapot)
--config skybox
self._skyBox = cc.Skybox:create()
self._skyBox:setTexture(self._textureCube)
self:addChild(self._skyBox)
self._skyBox:setScale(700)
self:addChild(camera)
self:setCameraMask(2)
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if targetPlatform == cc.PLATFORM_OS_ANDROID or targetPlatform == cc.PLATFORM_OS_WINRT or targetPlatform == cc.PLATFORM_OS_WP8 then
self._backToForegroundListener = cc.EventListenerCustom:create("event_renderer_recreated", function (eventCustom)
local state = self._teapot:getGLProgramState()
local glProgram = state:getGLProgram()
glProgramreset()
glProgram:initWithFilenames("Sprite3DTest/cube_map.vert", "Sprite3DTest/cube_map.frag")
glProgram:link()
glProgram:updateUniforms()
self._textureCube:reloadTexture()
local tRepeatParams = { magFilter=gl.NEAREST , minFilter=gl.NEAREST , wrapS=gl.MIRRORED_REPEAT , wrapT=gl.MIRRORED_REPEAT }
self._textureCube:setTexParameters(tRepeatParams)
state:setUniformTexture("u_cubeTex", self._textureCube)
self._skyBox:reload()
self._skyBox:setTexture(self._textureCube)
end)
cc.Director:getInstance():getEventDispatcher():addEventListenerWithFixedPriority(self._backToForegroundListener, -1)
end
end
----------------------------------------
----Sprite3DNormalMappingTest
----------------------------------------
local Sprite3DNormalMappingTest = class("Sprite3DNormalMappingTest", function ()
local layer = cc.Layer:create()
Helper.initWithLayer(layer)
return layer
end)
function Sprite3DNormalMappingTest:ctor()
-- body
self:init()
end
function Sprite3DNormalMappingTest:init()
Helper.titleLabel:setString(self:title())
Helper.subtitleLabel:setString(self:subtitle())
self:registerScriptHandler(function (event)
if event == "enter" then
self:onEnter()
elseif event == "exit" then
self:onExit()
end
end)
end
function Sprite3DNormalMappingTest:title()
return "Testing Normal Mapping"
end
function Sprite3DNormalMappingTest:subtitle()
return ""
end
function Sprite3DNormalMappingTest:onEnter()
local sprite3d = cc.Sprite3D:create("Sprite3DTest/sphere.c3b")
sprite3d:setScale(2.0)
sprite3d:setPosition(cc.p(-30,0))
sprite3d:setRotation3D(cc.vec3(90.0, 0.0, 0.0))
sprite3d:setTexture("Sprite3DTest/brickwork-texture.jpg")
sprite3d:setCameraMask(2)
self:addChild(sprite3d)
local sprite3dBumped = cc.Sprite3D:create("Sprite3DTest/sphere_bumped.c3b")
sprite3dBumped:setScale(20.0)
sprite3dBumped:setPosition(cc.p(30,0))
sprite3dBumped:setRotation3D(cc.vec3(90.0, 0.0, 0.0))
sprite3dBumped:setCameraMask(2)
self:addChild(sprite3dBumped)
local radius = 100.0
local angle = 0.0
local reverseDir = false
local light = cc.PointLight:create(cc.vec3(0.0, 0.0, 0.0), cc.c3b(255, 255, 255), 1000.0)
local function lightUpdate()
light:setPosition3D(cc.vec3(radius * math.cos(angle), 0.0, radius * math.sin(angle)))
if reverseDir == true then
angle = angle - 0.01
if angle < 0.0 then
reverseDir = false
end
else
angle = angle + 0.01
if 3.14159 < angle then
reverseDir = true
end
end
end
local seq = cc.Sequence:create(cc.CallFunc:create(lightUpdate))
light:runAction(cc.RepeatForever:create(seq))
self:addChild(light)
local visibleSize = cc.Director:getInstance():getVisibleSize()
local camera = cc.Camera:createPerspective(60, visibleSize.width / visibleSize.height, 10, 1000)
camera:setPosition3D(cc.vec3(0.0, 0.0, 100.0))
camera:lookAt(cc.vec3(0.0, 0.0, 0.0))
camera:setCameraFlag(cc.CameraFlag.USER1)
self:addChild(camera)
end
function Sprite3DNormalMappingTest:onExit()
end
function Sprite3DTest()
local scene = cc.Scene:create()
Helper.createFunctionTable =
{
Sprite3DBasicTest.create,
Sprite3DHitTest.create,
Sprite3DWithSkinTest.create,
Animate3DTest.create,
AttachmentTest.create,
Sprite3DReskinTest.create,
Sprite3DWithOBBPerfromanceTest.create,
Sprite3DMirrorTest.create,
AsyncLoadSprite3DTest.create,
Sprite3DCubeMapTest.create,
Sprite3DNormalMappingTest.create,
}
scene:addChild(Sprite3DBasicTest.create())
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
LuaDist2/oil | lua/loop/component/base.lua | 12 | 6632 | --------------------------------------------------------------------------------
---------------------- ## ##### ##### ###### -----------------------
---------------------- ## ## ## ## ## ## ## -----------------------
---------------------- ## ## ## ## ## ###### -----------------------
---------------------- ## ## ## ## ## ## -----------------------
---------------------- ###### ##### ##### ## -----------------------
---------------------- -----------------------
----------------------- Lua Object-Oriented Programming ------------------------
--------------------------------------------------------------------------------
-- Project: LOOP - Lua Object-Oriented Programming --
-- Release: 2.3 beta --
-- Title : Base Component Model --
-- Author : Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
-- Exported API: --
-- Template --
-- Facet --
-- Receptacle --
-- ListReceptacle --
-- HashReceptacle --
-- SetReceptacle --
-- factoryof(component) --
-- templateof(factory|component) --
-- ports(template) --
-- segmentof(portname, component) --
--------------------------------------------------------------------------------
local next = next
local pairs = pairs
local pcall = pcall
local rawget = rawget
local rawset = rawset
local select = select
local type = type
local oo = require "loop.cached"
module "loop.component.base"
--------------------------------------------------------------------------------
BaseTemplate = oo.class()
function BaseTemplate:__call(...)
return self:__build(self:__new(...))
end
function BaseTemplate:__new(...)
local comp = self.__component or self[1]
if comp then
comp = comp(...)
comp.__component = comp
else
comp = ... or {}
end
comp.__factory = self
for port, class in pairs(self) do
if type(port) == "string" and port:match("^%a[%w_]*$") then
comp[port] = class(comp[port], comp)
end
end
return comp
end
local function tryindex(segment) return segment.context end
function BaseTemplate:__setcontext(segment, context)
local success, setcontext = pcall(tryindex, segment)
if success and setcontext ~= nil then
if type(setcontext) == "function"
then setcontext(segment, context)
else segment.context = context
end
end
end
function BaseTemplate:__build(segments)
for port, class in oo.allmembers(oo.classof(self)) do
if port:match("^%a[%w_]*$") then
class(segments, port, segments)
end
end
segments.__reference = segments
for port in pairs(self) do
if port == 1
then self:__setcontext(segments.__component, segments)
else self:__setcontext(segments[port], segments)
end
end
return segments
end
function Template(template, ...)
if select("#", ...) > 0
then return oo.class(template, ...)
else return oo.class(template, BaseTemplate)
end
end
--------------------------------------------------------------------------------
function factoryof(component)
return component.__factory
end
function templateof(object)
return oo.classof(factoryof(object) or object)
end
local nextmember
local function portiterator(state, name)
local port
repeat
name, port = nextmember(state, name)
if name == nil then return end
until name:find("^%a")
return name, port
end
function ports(template)
if not oo.subclassof(template, BaseTemplate) then
template = templateof(template)
end
local state, var
nextmember, state, var = oo.allmembers(template)
return portiterator, state, var
end
function segmentof(comp, port)
return comp[port]
end
--------------------------------------------------------------------------------
function addport(comp, name, port, class)
if class then
comp[name] = class(comp[name], comp)
end
port(comp, name, comp)
comp.__factory:__setcontext(comp[name], context)
end
function removeport(comp, name)
comp[name] = nil
end
--------------------------------------------------------------------------------
function Facet(segments, name)
segments[name] = segments[name] or
segments.__component[name] or
segments.__component
return false
end
--------------------------------------------------------------------------------
function Receptacle()
return false
end
--------------------------------------------------------------------------------
MultipleReceptacle = oo.class{
__all = pairs,
__hasany = next,
__get = rawget,
}
function MultipleReceptacle:__init(segments, name)
local receptacle = oo.rawnew(self, segments[name])
segments[name] = receptacle
return receptacle
end
function MultipleReceptacle:__newindex(key, value)
if value == nil
then self:__unbind(key)
else self:__bind(value, key)
end
end
function MultipleReceptacle:__unbind(key)
local port = rawget(self, key)
rawset(self, key, nil)
return port
end
--------------------------------------------------------------------------------
ListReceptacle = oo.class({}, MultipleReceptacle)
function ListReceptacle:__bind(port)
local index = #self + 1
rawset(self, index, port)
return index
end
--------------------------------------------------------------------------------
HashReceptacle = oo.class({}, MultipleReceptacle)
function HashReceptacle:__bind(port, key)
rawset(self, key, port)
return key
end
--------------------------------------------------------------------------------
SetReceptacle = oo.class({}, MultipleReceptacle)
function SetReceptacle:__bind(port)
rawset(self, port, port)
return port
end
--------------------------------------------------------------------------------
_M[Facet ] = "Facet"
_M[Receptacle ] = "Receptacle"
_M[ListReceptacle] = "ListReceptacle"
_M[HashReceptacle] = "HashReceptacle"
_M[SetReceptacle ] = "SetReceptacle"
| mit |
stubbfel/blob2wireshark | src/b2ws-plugin/b2ws_import.lua | 1 | 2554 | require "b2ws_const"
local loaded_b2ws_util= assert(loadfile(b2ws_const.B2WS_PLUGIN_PATH .. b2ws_const.B2WS_UTIL_FILE))
loaded_b2ws_util()
function b2ws_import_blob(config_string)
-- create config object
local b2ws_config = create_b2ws_config_object(config_string)
-- read blob file
local bytes = read_b2ws_file(b2ws_config.blob_src)
-- convert to hex string
local data = {}
bytes:gsub(".", function(c) table.insert(data,string.format("%02X ", string.byte(c))) end)
local data_string = table.concat(data)
-- create fake ethernet frame
local header = PseudoHeader.eth()
local eth_fake_header = b2ws_config.eth_fake_header_src .. b2ws_config.eth_fake_header_dst .. b2ws_config.eth_fake_header_type
local eth_fake_frame = eth_fake_header .. data_string
local pcapPath = b2ws_config.blob_src .. ".pcap"
-- write fake frame to pcap file
local dmp = Dumper.new(pcapPath)
dmp:dump(os.time(),header, ByteArray.new(eth_fake_frame))
dmp:flush()
dmp:close()
return pcapPath
end
function b2ws_change_settings(config_string, blob_src, eth_src, eth_dst, eth_type)
local b2ws_config = create_b2ws_config_object(config_string)
if not (blob_src == "") then
b2ws_config.blob_src = blob_src
end
if not (eth_src == "") then
b2ws_config.eth_fake_header_src = eth_src
end
if not (eth_dst == "") then
b2ws_config.eth_fake_header_dst = eth_dst
end
if not (eth_type == "") then
b2ws_config.eth_fake_header_type = eth_type
end
local new_config_string = "{\n\t[\"blob_src\"] = \"" .. b2ws_config.blob_src .. "\",\n"
new_config_string = new_config_string .. "\t[\"eth_fake_header_src\"] = \"" .. b2ws_config.eth_fake_header_src .. "\",\n"
new_config_string = new_config_string .. "\t[\"eth_fake_header_dst\"] = \"" .. b2ws_config.eth_fake_header_dst .. "\",\n"
new_config_string = new_config_string .. "\t[\"eth_fake_header_type\"] = \"" .. b2ws_config.eth_fake_header_type .. "\"\n}"
return new_config_string
end
function b2ws_create_dissector(config_string, disector_name)
local b2ws_config = create_b2ws_config_object(config_string)
local template_string = read_b2ws_folder_file(b2ws_const.B2WS_PLUGIN_PATH, b2ws_const.B2WS_DISSECTOR_TEMPLATE_FILE)
template_string = template_string:gsub("0xffff", "0x" .. b2ws_config.eth_fake_header_type)
template_string = template_string:gsub("example", disector_name)
local dissector_path = create_b2ws_folder_file_path(b2ws_const.B2WS_PLUGIN_PATH, disector_name .. b2ws_const.B2WS_DISSECTOR_EXTENSION)
write_b2ws_file(dissector_path, template_string)
return dissector_path
end
| mit |
satanevil/copy-creed | plugins/cpu.lua | 244 | 1893 | function run_sh(msg)
name = get_name(msg)
text = ''
-- if config.sh_enabled == false then
-- text = '!sh command is disabled'
-- else
-- if is_sudo(msg) then
-- bash = msg.text:sub(4,-1)
-- text = run_bash(bash)
-- else
-- text = name .. ' you have no power here!'
-- end
-- end
if is_sudo(msg) then
bash = msg.text:sub(4,-1)
text = run_bash(bash)
else
text = name .. ' you have no power here!'
end
return text
end
function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
function on_getting_dialogs(cb_extra,success,result)
if success then
local dialogs={}
for key,value in pairs(result) do
for chatkey, chat in pairs(value.peer) do
print(chatkey,chat)
if chatkey=="id" then
table.insert(dialogs,chat.."\n")
end
if chatkey=="print_name" then
table.insert(dialogs,chat..": ")
end
end
end
send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false)
end
end
function run(msg, matches)
if not is_sudo(msg) then
return "You aren't allowed!"
end
local receiver = get_receiver(msg)
if string.match(msg.text, '!sh') then
text = run_sh(msg)
send_msg(receiver, text, ok_cb, false)
return
end
if string.match(msg.text, '!$ uptime') then
text = run_bash('uname -snr') .. ' ' .. run_bash('whoami')
text = text .. '\n' .. run_bash('top -b |head -2')
send_msg(receiver, text, ok_cb, false)
return
end
if matches[1]=="Get dialogs" then
get_dialog_list(on_getting_dialogs,{get_receiver(msg)})
return
end
end
return {
description = "shows cpuinfo",
usage = "!$ uptime",
patterns = {"^!$ uptime", "^!sh","^Get dialogs$"},
run = run
}
| gpl-2.0 |
sumefsp/zile | lib/zile/redisplay.lua | 1 | 2400 | -- Terminal independent redisplay routines
--
-- Copyright (c) 2010-2014 Free Software Foundation, Inc.
--
-- This file is part of GNU Zile.
--
-- 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 3, 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, see <http://www.gnu.org/licenses/>.
function recenter (wp)
local n = offset_to_line (wp.bp, window_o (wp))
if n > wp.eheight / 2 then
wp.topdelta = math.floor (wp.eheight / 2)
else
wp.topdelta = n
end
end
function interactive_recenter ()
recenter (cur_wp)
term_clear ()
term_redisplay ()
term_refresh ()
return true
end
function resize_windows ()
local wp
-- Resize windows horizontally.
for _, wp in ipairs (windows) do
wp.fwidth = term_width ()
wp.ewidth = wp.fwidth
end
-- Work out difference in window height; windows may be taller than
-- terminal if the terminal was very short.
local hdelta = term_height () - 1
for _, wp in ipairs (windows) do
hdelta = hdelta - wp.fheight
end
-- Resize windows vertically.
if hdelta > 0 then
-- Increase windows height.
local w = #windows
while hdelta > 0 do
windows[w].fheight = windows[w].fheight + 1
windows[w].eheight = windows[w].eheight + 1
hdelta = hdelta - 1
w = w - 1
if w == 0 then
w = #windows
end
end
else
-- Decrease windows' height, and close windows if necessary.
local decreased
repeat
local w = #windows
decreased = false
while w > 0 and hdelta < 0 do
local wp = windows[w]
if wp.fheight > 2 then
wp.fheight = wp.fheight - 1
wp.eheight = wp.eheight - 1
hdelta = hdelta + 1
decreased = true
elseif #windows > 1 then
delete_window (wp)
w = w - 1
decreased = true
end
end
until decreased == false
end
interactive_recenter ()
end
| gpl-3.0 |
FarGroup/FarManager | plugins/luamacro/api.lua | 1 | 26154 | -- coding: utf-8
local Shared = ...
local checkarg, utils, yieldcall = Shared.checkarg, Shared.utils, Shared.yieldcall
local MCODE_F_USERMENU = 0x80C66
local MCODE_F_FAR_GETCONFIG = 0x80C69
local F=far.Flags
local band,bor = bit64.band,bit64.bor
local MacroCallFar = Shared.MacroCallFar
local function SetProperties (namespace, proptable)
local meta = {}
meta.__index = function(tb,nm)
local f = proptable[nm]
if f then return f() end
if nm == "properties" then return proptable end -- to allow introspection
error("property not supported: "..tostring(nm), 2)
end
setmetatable(namespace, meta)
return namespace
end
--------------------------------------------------------------------------------
-- "mf" ("macrofunctions") namespace
mf = {
abs = function(...) return MacroCallFar(0x80C01, ...) end,
--akey = function(...) return MacroCallFar(0x80C02, ...) end,
asc = function(...) return MacroCallFar(0x80C03, ...) end,
atoi = function(...) return MacroCallFar(0x80C04, ...) end,
beep = function(...) return MacroCallFar(0x80C48, ...) end,
chr = function(...) return MacroCallFar(0x80C06, ...) end,
clip = function(...) return MacroCallFar(0x80C05, ...) end,
date = function(...) return MacroCallFar(0x80C07, ...) end,
env = function(...) return MacroCallFar(0x80C0D, ...) end,
fattr = function(...) return MacroCallFar(0x80C0E, ...) end,
fexist = function(...) return MacroCallFar(0x80C0F, ...) end,
float = function(...) return MacroCallFar(0x80C41, ...) end,
flock = function(...) return MacroCallFar(0x80C31, ...) end,
fmatch = function(...) return MacroCallFar(0x80C4D, ...) end,
fsplit = function(...) return MacroCallFar(0x80C10, ...) end,
index = function(...) return MacroCallFar(0x80C12, ...) end,
int = function(...) return MacroCallFar(0x80C13, ...) end,
itoa = function(...) return MacroCallFar(0x80C14, ...) end,
key = function(...) return MacroCallFar(0x80C15, ...) end,
lcase = function(...) return MacroCallFar(0x80C16, ...) end,
len = function(...) return MacroCallFar(0x80C17, ...) end,
max = function(...) return MacroCallFar(0x80C18, ...) end,
min = function(...) return MacroCallFar(0x80C1D, ...) end,
mod = function(...) return MacroCallFar(0x80C1E, ...) end,
msgbox = function(...) return MacroCallFar(0x80C21, ...) end,
prompt = function(...) return MacroCallFar(0x80C34, ...) end,
replace = function(...) return MacroCallFar(0x80C33, ...) end,
rindex = function(...) return MacroCallFar(0x80C2A, ...) end,
size2str = function(...) return MacroCallFar(0x80C59, ...) end,
sleep = function(...) return MacroCallFar(0x80C2B, ...) end,
string = function(...) return MacroCallFar(0x80C2C, ...) end,
strpad = function(...) return MacroCallFar(0x80C5F, ...) end,
strwrap = function(...) return MacroCallFar(0x80C5A, ...) end,
substr = function(...) return MacroCallFar(0x80C2D, ...) end,
testfolder = function(...) return MacroCallFar(0x80C42, ...) end,
trim = function(...) return MacroCallFar(0x80C40, ...) end,
ucase = function(...) return MacroCallFar(0x80C2E, ...) end,
waitkey = function(...) return MacroCallFar(0x80C2F, ...) end,
xlat = function(...) return MacroCallFar(0x80C30, ...) end,
}
mf.iif = function(Expr, res1, res2)
if Expr and Expr~=0 and Expr~="" then return res1 else return res2 end
end
mf.usermenu = function(mode, filename)
if Shared.OnlyEditorViewerUsed then return end -- mantis #2986 (crash)
if mode and type(mode)~="number" then return end
mode = mode or 0
local sync_call = band(mode,0x100) ~= 0
mode = band(mode,0xFF)
if mode==0 or mode==1 then
if sync_call then MacroCallFar(MCODE_F_USERMENU, mode==1)
else yieldcall(F.MPRT_USERMENU, mode==1)
end
elseif (mode==2 or mode==3) and type(filename)=="string" then
if mode==3 then
if not (filename:find("^%a:") or filename:find("^[\\/]")) then
filename = win.GetEnv("farprofile").."\\Menus\\"..filename
end
end
if sync_call then MacroCallFar(MCODE_F_USERMENU, filename)
else yieldcall(F.MPRT_USERMENU, filename)
end
end
end
mf.GetMacroCopy = utils.GetMacroCopy
mf.EnumScripts = utils.EnumScripts
--------------------------------------------------------------------------------
Object = {
CheckHotkey = function(...) return MacroCallFar(0x80C19, ...) end,
GetHotkey = function(...) return MacroCallFar(0x80C1A, ...) end,
}
SetProperties(Object, {
Bof = function() return MacroCallFar(0x80413) end,
CurPos = function() return MacroCallFar(0x80827) end,
Empty = function() return MacroCallFar(0x80415) end,
Eof = function() return MacroCallFar(0x80414) end,
Height = function() return MacroCallFar(0x80829) end,
ItemCount = function() return MacroCallFar(0x80826) end,
Selected = function() return MacroCallFar(0x80416) end,
Title = function() return MacroCallFar(0x80828) end,
Width = function() return MacroCallFar(0x8082A) end,
})
--------------------------------------------------------------------------------
local prop_Area = {
Current = function() return utils.GetTrueAreaName(MacroCallFar(0x80805)) end,
Other = function() return MacroCallFar(0)==0 end,
Shell = function() return MacroCallFar(0)==1 end,
Viewer = function() return MacroCallFar(0)==2 end,
Editor = function() return MacroCallFar(0)==3 end,
Dialog = function() return MacroCallFar(0)==4 end,
Search = function() return MacroCallFar(0)==5 end,
Disks = function() return MacroCallFar(0)==6 end,
MainMenu = function() return MacroCallFar(0)==7 end,
Menu = function() return MacroCallFar(0)==8 end,
Help = function() return MacroCallFar(0)==9 end,
Info = function() return MacroCallFar(0)==10 end,
QView = function() return MacroCallFar(0)==11 end,
Tree = function() return MacroCallFar(0)==12 end,
FindFolder = function() return MacroCallFar(0)==13 end,
UserMenu = function() return MacroCallFar(0)==14 end,
ShellAutoCompletion = function() return MacroCallFar(0)==15 end,
DialogAutoCompletion = function() return MacroCallFar(0)==16 end,
Grabber = function() return MacroCallFar(0)==17 end,
Desktop = function() return MacroCallFar(0)==18 end,
}
local prop_APanel = {
Bof = function() return MacroCallFar(0x80418) end,
ColumnCount = function() return MacroCallFar(0x8081E) end,
CurPos = function() return MacroCallFar(0x80816) end,
Current = function() return MacroCallFar(0x80806) end,
DriveType = function() return MacroCallFar(0x8081A) end,
Empty = function() return MacroCallFar(0x8041C) end,
Eof = function() return MacroCallFar(0x8041A) end,
FilePanel = function() return MacroCallFar(0x80426) end,
Filter = function() return MacroCallFar(0x8042E) end,
Folder = function() return MacroCallFar(0x80428) end,
Format = function() return MacroCallFar(0x80824) end,
Height = function() return MacroCallFar(0x8081C) end,
HostFile = function() return MacroCallFar(0x80820) end,
ItemCount = function() return MacroCallFar(0x80814) end,
Left = function() return MacroCallFar(0x8042A) end,
LFN = function() return MacroCallFar(0x8042C) end,
OPIFlags = function() return MacroCallFar(0x80818) end,
Path = function() return MacroCallFar(0x8080A) end,
Path0 = function() return MacroCallFar(0x8080C) end,
Plugin = function() return MacroCallFar(0x80424) end,
Prefix = function() return MacroCallFar(0x80822) end,
Root = function() return MacroCallFar(0x80420) end,
SelCount = function() return MacroCallFar(0x80808) end,
Selected = function() return MacroCallFar(0x8041E) end,
Type = function() return MacroCallFar(0x80812) end,
UNCPath = function() return MacroCallFar(0x8080E) end,
Visible = function() return MacroCallFar(0x80422) end,
Width = function() return MacroCallFar(0x80810) end,
}
local prop_PPanel = {
Bof = function() return MacroCallFar(0x80419) end,
ColumnCount = function() return MacroCallFar(0x8081F) end,
CurPos = function() return MacroCallFar(0x80817) end,
Current = function() return MacroCallFar(0x80807) end,
DriveType = function() return MacroCallFar(0x8081B) end,
Empty = function() return MacroCallFar(0x8041D) end,
Eof = function() return MacroCallFar(0x8041B) end,
FilePanel = function() return MacroCallFar(0x80427) end,
Filter = function() return MacroCallFar(0x8042F) end,
Folder = function() return MacroCallFar(0x80429) end,
Format = function() return MacroCallFar(0x80825) end,
Height = function() return MacroCallFar(0x8081D) end,
HostFile = function() return MacroCallFar(0x80821) end,
ItemCount = function() return MacroCallFar(0x80815) end,
Left = function() return MacroCallFar(0x8042B) end,
LFN = function() return MacroCallFar(0x8042D) end,
OPIFlags = function() return MacroCallFar(0x80819) end,
Path = function() return MacroCallFar(0x8080B) end,
Path0 = function() return MacroCallFar(0x8080D) end,
Plugin = function() return MacroCallFar(0x80425) end,
Prefix = function() return MacroCallFar(0x80823) end,
Root = function() return MacroCallFar(0x80421) end,
SelCount = function() return MacroCallFar(0x80809) end,
Selected = function() return MacroCallFar(0x8041F) end,
Type = function() return MacroCallFar(0x80813) end,
UNCPath = function() return MacroCallFar(0x8080F) end,
Visible = function() return MacroCallFar(0x80423) end,
Width = function() return MacroCallFar(0x80811) end,
}
local prop_CmdLine = {
Bof = function() return MacroCallFar(0x80430) end,
Empty = function() return MacroCallFar(0x80432) end,
Eof = function() return MacroCallFar(0x80431) end,
Selected = function() return MacroCallFar(0x80433) end,
CurPos = function() return MacroCallFar(0x8083C) end,
ItemCount = function() return MacroCallFar(0x8083B) end,
Value = function() return MacroCallFar(0x8083D) end,
Result = function() return Shared.CmdLineResult end,
}
local prop_Drv = {
ShowMode = function() return MacroCallFar(0x8083F) end,
ShowPos = function() return MacroCallFar(0x8083E) end,
}
local prop_Help = {
FileName = function() return MacroCallFar(0x80840) end,
SelTopic = function() return MacroCallFar(0x80842) end,
Topic = function() return MacroCallFar(0x80841) end,
}
local prop_Mouse = {
X = function() return MacroCallFar(0x80434) end,
Y = function() return MacroCallFar(0x80435) end,
Button = function() return MacroCallFar(0x80436) end,
CtrlState = function() return MacroCallFar(0x80437) end,
EventFlags = function() return MacroCallFar(0x80438) end,
LastCtrlState = function() return MacroCallFar(0x80439) end,
}
local prop_Viewer = {
FileName = function() return MacroCallFar(0x80839) end,
State = function() return MacroCallFar(0x8083A) end,
}
--------------------------------------------------------------------------------
Dlg = {
GetValue = function(...) return MacroCallFar(0x80C08, ...) end,
SetFocus = function(...) return MacroCallFar(0x80C57, ...) end,
}
SetProperties(Dlg, {
CurPos = function() return MacroCallFar(0x80835) end,
Id = function() return MacroCallFar(0x80837) end,
Owner = function() return MacroCallFar(0x80838) end,
ItemCount = function() return MacroCallFar(0x80834) end,
ItemType = function() return MacroCallFar(0x80833) end,
PrevPos = function() return MacroCallFar(0x80836) end,
})
--------------------------------------------------------------------------------
Editor = {
DelLine = function(...) return MacroCallFar(0x80C60, ...) end,
GetStr = function(n) return editor.GetString(nil,n,3) or "" end,
InsStr = function(...) return MacroCallFar(0x80C62, ...) end,
Pos = function(...) return MacroCallFar(0x80C0C, ...) end,
Sel = function(...) return MacroCallFar(0x80C09, ...) end,
Set = function(...) return MacroCallFar(0x80C0A, ...) end,
SetStr = function(...) return MacroCallFar(0x80C63, ...) end,
SetTitle = function(...) return MacroCallFar(0x80C45, ...) end,
Undo = function(...) return MacroCallFar(0x80C0B, ...) end,
}
SetProperties(Editor, {
CurLine = function() return MacroCallFar(0x8082D) end,
CurPos = function() return MacroCallFar(0x8082E) end,
FileName = function() return MacroCallFar(0x8082B) end,
Lines = function() return MacroCallFar(0x8082C) end,
RealPos = function() return MacroCallFar(0x8082F) end,
SelValue = function() return MacroCallFar(0x80832) end,
State = function() return MacroCallFar(0x80830) end,
Value = function() return editor.GetString(nil,nil,3) or "" end,
})
--------------------------------------------------------------------------------
Menu = {
Filter = function(...) return MacroCallFar(0x80C55, ...) end,
FilterStr = function(...) return MacroCallFar(0x80C56, ...) end,
GetValue = function(...) return MacroCallFar(0x80C46, ...) end,
ItemStatus = function(...) return MacroCallFar(0x80C47, ...) end,
Select = function(...) return MacroCallFar(0x80C1B, ...) end,
Show = function(...) return MacroCallFar(0x80C1C, ...) end,
}
SetProperties(Menu, {
Id = function() return MacroCallFar(0x80844) end,
Value = function() return MacroCallFar(0x80843) end,
})
--------------------------------------------------------------------------------
Far = {
Cfg_Get = function(...) return MacroCallFar(0x80C58, ...) end,
DisableHistory = function(...) return Shared.keymacro.DisableHistory(...) end,
KbdLayout = function(...) return MacroCallFar(0x80C49, ...) end,
KeyBar_Show = function(...) return MacroCallFar(0x80C4B, ...) end,
Window_Scroll = function(...) return MacroCallFar(0x80C4A, ...) end,
}
function Far.GetConfig (keyname)
checkarg(keyname, 1, "string")
local key, name = keyname:match("^(.+)%.([^.]+)$")
if not key then
error("invalid format of arg. #1", 2)
end
local tp,val = MacroCallFar(MCODE_F_FAR_GETCONFIG, key, name)
if not tp then
error("cannot get setting '"..keyname.."'", 2)
end
tp = ({"boolean","3-state","integer","string"})[tp]
if tp == "3-state" then
if val==0 or val==1 then val=(val==1) else val="other" end
end
return val,tp
end
SetProperties(Far, {
FullScreen = function() return MacroCallFar(0x80411) end,
Height = function() return MacroCallFar(0x80801) end,
IsUserAdmin = function() return MacroCallFar(0x80412) end,
PID = function() return MacroCallFar(0x80804) end,
Title = function() return MacroCallFar(0x80802) end,
UpTime = function() return MacroCallFar(0x80803) end,
Width = function() return MacroCallFar(0x80800) end,
})
--------------------------------------------------------------------------------
BM = {
Add = function(...) return MacroCallFar(0x80C35, ...) end,
Back = function(...) return MacroCallFar(0x80C3D, ...) end,
Clear = function(...) return MacroCallFar(0x80C36, ...) end,
Del = function(...) return MacroCallFar(0x80C37, ...) end,
Get = function(...) return MacroCallFar(0x80C38, ...) end,
Goto = function(...) return MacroCallFar(0x80C39, ...) end,
Next = function(...) return MacroCallFar(0x80C3A, ...) end,
Pop = function(...) return MacroCallFar(0x80C3B, ...) end,
Prev = function(...) return MacroCallFar(0x80C3C, ...) end,
Push = function(...) return MacroCallFar(0x80C3E, ...) end,
Stat = function(...) return MacroCallFar(0x80C3F, ...) end,
}
--------------------------------------------------------------------------------
Plugin = {
Call = function(...) return yieldcall(F.MPRT_PLUGINCALL, ...) end,
Command = function(...) return yieldcall(F.MPRT_PLUGINCOMMAND, ...) end,
Config = function(...) return yieldcall(F.MPRT_PLUGINCONFIG, ...) end,
Menu = function(...) return yieldcall(F.MPRT_PLUGINMENU, ...) end,
Exist = function(...) return MacroCallFar(0x80C54, ...) end,
Load = function(...) return MacroCallFar(0x80C51, ...) end,
Unload = function(...) return MacroCallFar(0x80C53, ...) end,
SyncCall = function(...)
local v = Shared.keymacro.CallPlugin(Shared.pack(...), false)
if type(v)=="userdata" then return Shared.FarMacroCallToLua(v) else return v end
end
}
--------------------------------------------------------------------------------
local function SetPath(whatpanel,path,filename)
local function IsAbsolutePath(path) return path:lower()==far.ConvertPath(path):lower() end
whatpanel=(whatpanel==0 or not whatpanel) and 1 or 0
local current=panel.GetPanelDirectory(nil,whatpanel) or {}
current.Name=path
local result=panel.SetPanelDirectory(nil,whatpanel,IsAbsolutePath(path) and path or current)
if result and type(filename)=='string' then
local info=panel.GetPanelInfo(nil,whatpanel)
if info then
filename=filename:lower()
for ii=1,info.ItemsNumber do
local item=panel.GetPanelItem(nil,whatpanel,ii)
if not item then break end
if filename==item.FileName:lower() then
panel.RedrawPanel(nil,whatpanel,{TopPanelItem=1,CurrentItem=ii})
break
end
end
end
end
return result
end
Panel = {
FAttr = function(...) return MacroCallFar(0x80C22, ...) end,
FExist = function(...) return MacroCallFar(0x80C24, ...) end,
Item = function(a,b,c)
local r = MacroCallFar(0x80C28,a,b,c)
if c==8 and r==0 then r=false end -- 8:Selected; boolean property
return r
end,
Select = function(...) return MacroCallFar(0x80C27, ...) end,
SetPath = function(...)
local status,res=pcall(SetPath,...)
if status then return res end
return false
end,
SetPos = function(...) return MacroCallFar(0x80C25, ...) end,
SetPosIdx = function(...) return MacroCallFar(0x80C26, ...) end,
}
--------------------------------------------------------------------------------
Area = SetProperties({}, prop_Area)
APanel = SetProperties({}, prop_APanel)
PPanel = SetProperties({}, prop_PPanel)
CmdLine = SetProperties({}, prop_CmdLine)
Drv = SetProperties({}, prop_Drv)
Help = SetProperties({}, prop_Help)
Mouse = SetProperties({}, prop_Mouse)
Viewer = SetProperties({}, prop_Viewer)
--------------------------------------------------------------------------------
local EVAL_SUCCESS = 0
local EVAL_SYNTAXERROR = 11
local EVAL_BADARGS = -1
local EVAL_MACRONOTFOUND = -2 -- макрос не найден среди загруженных макросов
local EVAL_MACROCANCELED = -3 -- было выведено меню выбора макроса, и пользователь его отменил
local EVAL_RUNTIMEERROR = -4 -- макрос был прерван в результате ошибки времени исполнения
local function Eval_GetData (str) -- Получение данных макроса для Eval(S,2).
local Mode=far.MacroGetArea()
local UseCommon=false
str = str:match("^%s*(.-)%s*$")
local strArea,strKey = str:match("^(.-)/(.+)$")
if strArea then
if strArea ~= "." then -- вариант "./Key" не подразумевает поиск в макрообласти Common
Mode=utils.GetAreaCode(strArea)
if Mode==nil then return end
end
else
strKey=str
UseCommon=true
end
return Mode, strKey, UseCommon
end
local function Eval_FixReturn (ok, ...)
return ok and EVAL_SUCCESS or EVAL_RUNTIMEERROR, ...
end
-- @param mode:
-- 0=Выполнить макропоследовательность str
-- 1=Проверить макропоследовательность str и вернуть код ошибки компиляции
-- 2=Выполнить макрос, назначенный на сочетание клавиш str
-- 3=Проверить макропоследовательность str и вернуть строку-сообщение с ошибкой компиляции
function mf.eval (str, mode, lang)
if type(str) ~= "string" then return EVAL_BADARGS end
mode = mode or 0
if not (mode==0 or mode==1 or mode==2 or mode==3) then return EVAL_BADARGS end
lang = lang or "lua"
if not (lang=="lua" or lang=="moonscript") then return EVAL_BADARGS end
if mode == 2 then
local area,key,usecommon = Eval_GetData(str)
if not area then return EVAL_MACRONOTFOUND end
local macro = utils.GetMacro(area,key,usecommon,false)
if not macro then return EVAL_MACRONOTFOUND end
if not macro.index then return EVAL_MACROCANCELED end
return Eval_FixReturn(yieldcall("eval", macro, key))
end
local ok, env = pcall(getfenv, 3)
local chunk, params = Shared.loadmacro(lang, str, ok and env)
if chunk then
if mode==1 then return EVAL_SUCCESS end
if mode==3 then return "" end
if params then chunk(params())
else chunk()
end
return EVAL_SUCCESS
else
local msg = params
if mode==0 then Shared.ErrMsg(msg) end
return mode==3 and msg or EVAL_SYNTAXERROR
end
end
--------------------------------------------------------------------------------
local function basicSerialize (o)
local tp = type(o)
if tp == "nil" or tp == "boolean" then
return tostring(o)
elseif tp == "number" then
if o == math.modf(o) then return tostring(o) end
return string.format("(%.17f * 2^%d)", math.frexp(o)) -- preserve accuracy
elseif tp == "string" then
return string.format("%q", o)
end
end
local function int64Serialize (o)
if bit64.type(o) then
return "bit64.new(\"" .. tostring(o) .. "\")"
end
end
local function AddToIndex (idx, t)
local n = idx[t]
if not n then
n = #idx + 1
idx[n], idx[t] = t, n
for k,v in pairs(t) do
if type(k)=="table" then AddToIndex(idx, k) end
if type(v)=="table" then AddToIndex(idx, v) end
end
if debug.getmetatable(t) then AddToIndex(idx,debug.getmetatable(t)) end
end
end
local function tableSerialize (tbl)
if type(tbl) == "table" then
local idx = {}
AddToIndex(idx, tbl)
local lines = { "local idx={}; for i=1,"..#idx.." do idx[i]={} end" }
for i,t in ipairs(idx) do
local found
lines[#lines+1] = "do local t=idx["..i.."]"
for k,v in pairs(t) do
local k2 = basicSerialize(k) or type(k)=="table" and "idx["..idx[k].."]"
if k2 then
local v2 = basicSerialize(v) or int64Serialize(v) or type(v)=="table" and "idx["..idx[v].."]"
if v2 then
found = true
lines[#lines+1] = " t["..k2.."] = "..v2
end
end
end
if found then lines[#lines+1]="end" else lines[#lines]=nil end
end
for i,t in ipairs(idx) do
local mt = debug.getmetatable(t)
if mt then
lines[#lines+1] = "setmetatable(idx["..i.."], idx["..idx[mt].."])"
end
end
lines[#lines+1] = "return idx[1]\n"
return table.concat(lines, "\n")
end
return nil
end
local function serialize (o)
local s = basicSerialize(o) or int64Serialize(o)
return s and "return "..s or tableSerialize(o)
end
function deserialize (str)
checkarg(str, 1, "string")
local chunk, err = loadstring(str)
if chunk==nil then return nil,err end
setfenv(chunk, { bit64={new=bit64.new}; setmetatable=setmetatable; })
local ok, result = pcall(chunk)
if not ok then return nil,result end
return result,nil
end
mf.serialize = serialize
mf.deserialize = deserialize
function mf.mdelete (key, name, location)
checkarg(key, 1, "string")
checkarg(name, 2, "string")
local ret = false
local obj = far.CreateSettings(nil, location=="local" and "PSL_LOCAL" or "PSL_ROAMING")
if obj then
local subkey = obj:OpenSubkey(0, key)
ret = (subkey or false) and obj:Delete(subkey, name~="*" and name or nil)
obj:Free()
end
return ret
end
function mf.msave (key, name, value, location)
checkarg(key, 1, "string")
checkarg(name, 2, "string")
local ret = false
local str = serialize(value)
if str then
local obj = far.CreateSettings(nil, location=="local" and "PSL_LOCAL" or "PSL_ROAMING")
if obj then
local subkey = obj:CreateSubkey(0, key)
ret = (subkey or false) and obj:Set(subkey, name, F.FST_DATA, str)
obj:Free()
end
end
return ret
end
function mf.mload (key, name, location)
checkarg(key, 1, "string")
checkarg(name, 2, "string")
local val, err, ok = nil, nil, nil
local obj = far.CreateSettings(nil, location=="local" and "PSL_LOCAL" or "PSL_ROAMING")
if obj then
local subkey = obj:OpenSubkey(0, key)
if subkey then
local chunk = obj:Get(subkey, name, F.FST_DATA)
if chunk then
val, err = deserialize(chunk)
else
err = "method Get() failed"
end
else
err = "method OpenSubkey() failed"
end
obj:Free()
else
err = "far.CreateSettings() failed"
end
return val, err
end
function mf.printconsole(...)
local narg = select("#", ...)
panel.GetUserScreen()
for i=1,narg do
win.WriteConsole(select(i, ...), i<narg and "\t" or "")
end
panel.SetUserScreen()
end
--------------------------------------------------------------------------------
_G.band, _G.bnot, _G.bor, _G.bxor, _G.lshift, _G.rshift =
bit64.band, bit64.bnot, bit64.bor, bit64.bxor, bit64.lshift, bit64.rshift
_G.eval, _G.msgbox, _G.prompt = mf.eval, mf.msgbox, mf.prompt
mf.Keys, mf.exit, mf.print = _G.Keys, _G.exit, _G.print
--------------------------------------------------------------------------------
| bsd-3-clause |
HEYAHONG/nodemcu-firmware | lua_examples/gossip_example.lua | 7 | 2136 | -- need a wifi connection
-- enter your wifi credentials
local credentials = {SSID = "SSID", PASS = "PASS"};
-- push a message onto the network
-- this can also be done by changing gossip.networkState[gossip.ip].data = {temperature = 78};
local function sendAlarmingData()
Gossip.pushGossip({temperature = 78});
print('Pushed alarming data');
end
local function removeAlarmingData()
Gossip.pushGossip(nil);
print('Removed alarming data from the network.');
end
-- callback function for when gossip receives an update
local function treatAlarmingData(updateData)
for k in pairs(updateData) do
if updateData[k].data then
if updateData[k].data.temperature and updateData[k].data.temperature > 30 then
print('Warning, the temp is above 30 degrees at ' .. k);
end
end
end
end
local function Startup()
-- initialize all nodes with the seed except for the seed itself
-- eventually they will all know about each other
-- enter at least one ip that will be a start seed
local startingSeed = '192.168.0.73';
-- luacheck: push allow defined
Gossip = require('gossip');
-- luacheck: pop
local config = {debug = true, seedList = {}};
if wifi.sta.getip() ~= startingSeed then
table.insert(config.seedList, startingSeed);
end
Gossip.setConfig(config);
-- add the update callback
Gossip.updateCallback = treatAlarmingData;
-- start gossiping
Gossip.start();
-- send some alarming data timer
if wifi.sta.getip() == startingSeed then
tmr.create():alarm(50000, tmr.ALARM_SINGLE, sendAlarmingData);
tmr.create():alarm(50000*3, tmr.ALARM_SINGLE, removeAlarmingData);
end
end
local function startExample()
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED,
function() print('Diconnected') end);
print("Connecting to WiFi access point...");
if wifi.sta.getip() == nil then
wifi.setmode(wifi.STATION);
wifi.sta.config({ssid = credentials.SSID, pwd = credentials.PASS});
end
print('Ip: ' .. wifi.sta.getip() .. '. Starting in 5s ..');
tmr.create():alarm(5000, tmr.ALARM_SINGLE, Startup);
end
startExample();
| mit |
mobarski/sandbox | scite/old/wscite_zzz/lexers/notused/vb.lua | 5 | 1773 | -- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- VisualBasic LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'vb'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, (P("'") + word_match({'rem'}, nil, true)) *
l.nonnewline^0)
-- Strings.
local string = token(l.STRING, l.delimited_range('"', true, true))
-- Numbers.
local number = token(l.NUMBER, (l.float + l.integer) * S('LlUuFf')^-2)
-- Keywords.
local keyword = token(l.KEYWORD, word_match({
-- Control.
'If', 'Then', 'Else', 'ElseIf', 'While', 'Wend', 'For', 'To', 'Each',
'In', 'Step', 'Case', 'Select', 'Return', 'Continue', 'Do',
'Until', 'Loop', 'Next', 'With', 'Exit',
-- Operators.
'Mod', 'And', 'Not', 'Or', 'Xor', 'Is',
-- Storage types.
'Call', 'Class', 'Const', 'Dim', 'ReDim', 'Preserve', 'Function', 'Sub',
'Property', 'End', 'Set', 'Let', 'Get', 'New', 'Randomize', 'Option',
'Explicit', 'On', 'Error', 'Execute',
-- Storage modifiers.
'Private', 'Public', 'Default',
-- Constants.
'Empty', 'False', 'Nothing', 'Null', 'True'
}, nil, true))
-- Types.
local type = token(l.TYPE, word_match({
'Boolean', 'Byte', 'Char', 'Date', 'Decimal', 'Double', 'Long', 'Object',
'Short', 'Single', 'String'
}, nil, true))
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Operators.
local operator = token(l.OPERATOR, S('=><+-*^&:.,_()'))
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'type', type},
{'comment', comment},
{'identifier', identifier},
{'string', string},
{'number', number},
{'operator', operator},
}
return M
| mit |
darkdukey/sdkbox-facebook-sample-v2 | samples/Lua/TestLua/Resources/luaScript/TransitionsTest/TransitionsTest.lua | 7 | 10467 | require "luaScript/TransitionsTest/TransitionsName"
local SceneIdx = -1
local CurSceneNo = 2
local TRANSITION_DURATION = 1.2
local s = CCDirector:sharedDirector():getWinSize()
local function switchSceneTypeNo()
if CurSceneNo == 1 then
CurSceneNo = 2
else
CurSceneNo = 1
end
end
local function backAction()
SceneIdx = SceneIdx - 1
if SceneIdx < 0 then
SceneIdx = SceneIdx + Transition_Table.MAX_LAYER
end
switchSceneTypeNo()
return generateTranScene()
end
local function restartAction()
return generateTranScene()
end
local function nextAction()
SceneIdx = SceneIdx + 1
SceneIdx = math.mod(SceneIdx, Transition_Table.MAX_LAYER)
switchSceneTypeNo()
return generateTranScene()
end
local function backCallback(sender)
local scene = backAction()
CCDirector:sharedDirector():replaceScene(scene)
end
local function restartCallback(sender)
local scene = restartAction()
CCDirector:sharedDirector():replaceScene(scene)
end
local function nextCallback(sender)
local scene = nextAction()
CCDirector:sharedDirector():replaceScene(scene)
end
-----------------------------
-- TestLayer1
-----------------------------
local function createLayer1()
local layer = CCLayer:create()
local x, y = s.width, s.height
local bg1 = CCSprite:create(s_back1)
bg1:setPosition(CCPointMake(s.width / 2, s.height / 2))
layer:addChild(bg1, -1)
local titleLabel = CCLabelTTF:create(Transition_Name[SceneIdx], "Thonburi", 32)
layer:addChild(titleLabel)
titleLabel:setColor(ccc3(255,32,32))
titleLabel:setPosition(x / 2, y - 100)
local label = CCLabelTTF:create("SCENE 1", "Marker Felt", 38)
label:setColor(ccc3(16,16,255))
label:setPosition(x / 2, y / 2)
layer:addChild(label)
-- menu
local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2)
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
local menu = CCMenu:create()
menu:addChild(item1)
menu:addChild(item2)
menu:addChild(item3)
menu:setPosition(CCPointMake(0, 0))
item1:setPosition(CCPointMake(s.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item2:setPosition(CCPointMake(s.width / 2, item2:getContentSize().height / 2))
item3:setPosition(CCPointMake(s.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2))
layer:addChild(menu, 1)
return layer
end
-----------------------------
-- TestLayer2
-----------------------------
local function createLayer2()
local layer = CCLayer:create()
local x, y = s.width, s.height
local bg1 = CCSprite:create(s_back2)
bg1:setPosition(CCPointMake(s.width / 2, s.height / 2))
layer:addChild(bg1, -1)
local titleLabel = CCLabelTTF:create(Transition_Name[SceneIdx], "Thonburi", 32 )
layer:addChild(titleLabel)
titleLabel:setColor(ccc3(255,32,32))
titleLabel:setPosition(x / 2, y - 100)
local label = CCLabelTTF:create("SCENE 2", "Marker Felt", 38)
label:setColor(ccc3(16,16,255))
label:setPosition(x / 2, y / 2)
layer:addChild(label)
-- menu
local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2)
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
local menu = CCMenu:create()
menu:addChild(item1)
menu:addChild(item2)
menu:addChild(item3)
menu:setPosition(CCPointMake(0, 0))
item1:setPosition(CCPointMake(s.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2))
item2:setPosition(CCPointMake(s.width / 2, item2:getContentSize().height / 2))
item3:setPosition(CCPointMake(s.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2))
layer:addChild(menu, 1)
return layer
end
-----------------------------
-- Create Transition Test
-----------------------------
local function createTransition(index, t, scene)
CCDirector:sharedDirector():setDepthTest(false)
if firstEnter == true then
firstEnter = false
return scene
end
if index == Transition_Table.CCTransitionJumpZoom then
scene = CCTransitionJumpZoom:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressRadialCCW then
scene = CCTransitionProgressRadialCCW:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressRadialCW then
scene = CCTransitionProgressRadialCW:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressHorizontal then
scene = CCTransitionProgressHorizontal:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressVertical then
scene = CCTransitionProgressVertical:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressInOut then
scene = CCTransitionProgressInOut:create(t, scene)
elseif index == Transition_Table.CCTransitionProgressOutIn then
scene = CCTransitionProgressOutIn:create(t, scene)
elseif index == Transition_Table.CCTransitionCrossFade then
scene = CCTransitionCrossFade:create(t, scene)
elseif index == Transition_Table.TransitionPageForward then
CCDirector:sharedDirector():setDepthTest(true)
scene = CCTransitionPageTurn:create(t, scene, false)
elseif index == Transition_Table.TransitionPageBackward then
CCDirector:sharedDirector():setDepthTest(true)
scene = CCTransitionPageTurn:create(t, scene, true)
elseif index == Transition_Table.CCTransitionFadeTR then
scene = CCTransitionFadeTR:create(t, scene)
elseif index == Transition_Table.CCTransitionFadeBL then
scene = CCTransitionFadeBL:create(t, scene)
elseif index == Transition_Table.CCTransitionFadeUp then
scene = CCTransitionFadeUp:create(t, scene)
elseif index == Transition_Table.CCTransitionFadeDown then
scene = CCTransitionFadeDown:create(t, scene)
elseif index == Transition_Table.CCTransitionTurnOffTiles then
scene = CCTransitionTurnOffTiles:create(t, scene)
elseif index == Transition_Table.CCTransitionSplitRows then
scene = CCTransitionSplitRows:create(t, scene)
elseif index == Transition_Table.CCTransitionSplitCols then
scene = CCTransitionSplitCols:create(t, scene)
elseif index == Transition_Table.CCTransitionFade then
scene = CCTransitionFade:create(t, scene)
elseif index == Transition_Table.FadeWhiteTransition then
scene = CCTransitionFade:create(t, scene, ccc3(255, 255, 255))
elseif index == Transition_Table.FlipXLeftOver then
scene = CCTransitionFlipX:create(t, scene, kCCTransitionOrientationLeftOver)
elseif index == Transition_Table.FlipXRightOver then
scene = CCTransitionFlipX:create(t, scene, kCCTransitionOrientationRightOver)
elseif index == Transition_Table.FlipYUpOver then
scene = CCTransitionFlipY:create(t, scene, kCCTransitionOrientationUpOver)
elseif index == Transition_Table.FlipYDownOver then
scene = CCTransitionFlipY:create(t, scene, kCCTransitionOrientationDownOver)
elseif index == Transition_Table.FlipAngularLeftOver then
scene = CCTransitionFlipAngular:create(t, scene, kCCTransitionOrientationLeftOver)
elseif index == Transition_Table.FlipAngularRightOver then
scene = CCTransitionFlipAngular:create(t, scene, kCCTransitionOrientationRightOver)
elseif index == Transition_Table.ZoomFlipXLeftOver then
scene = CCTransitionZoomFlipX:create(t, scene, kCCTransitionOrientationLeftOver)
elseif index == Transition_Table.ZoomFlipXRightOver then
scene = CCTransitionZoomFlipX:create(t, scene, kCCTransitionOrientationRightOver)
elseif index == Transition_Table.ZoomFlipYUpOver then
scene = CCTransitionZoomFlipY:create(t, scene, kCCTransitionOrientationUpOver)
elseif index == Transition_Table.ZoomFlipYDownOver then
scene = CCTransitionZoomFlipY:create(t, scene, kCCTransitionOrientationDownOver)
elseif index == Transition_Table.ZoomFlipAngularLeftOver then
scene = CCTransitionZoomFlipAngular:create(t, scene, kCCTransitionOrientationLeftOver)
elseif index == Transition_Table.ZoomFlipAngularRightOver then
scene = CCTransitionZoomFlipAngular:create(t, scene, kCCTransitionOrientationRightOver)
elseif index == Transition_Table.CCTransitionShrinkGrow then
scene = CCTransitionShrinkGrow:create(t, scene)
elseif index == Transition_Table.CCTransitionRotoZoom then
scene = CCTransitionRotoZoom:create(t, scene)
elseif index == Transition_Table.CCTransitionMoveInL then
scene = CCTransitionMoveInL:create(t, scene)
elseif index == Transition_Table.CCTransitionMoveInR then
scene = CCTransitionMoveInR:create(t, scene)
elseif index == Transition_Table.CCTransitionMoveInT then
scene = CCTransitionMoveInT:create(t, scene)
elseif index == Transition_Table.CCTransitionMoveInB then
scene = CCTransitionMoveInB:create(t, scene)
elseif index == Transition_Table.CCTransitionSlideInL then
scene = CCTransitionSlideInL:create(t, scene)
elseif index == Transition_Table.CCTransitionSlideInR then
scene = CCTransitionSlideInR:create(t, scene)
elseif index == Transition_Table.CCTransitionSlideInT then
scene = CCTransitionSlideInT:create(t, scene)
elseif index == Transition_Table.CCTransitionSlideInB then
scene = CCTransitionSlideInB:create(t, scene)
end
return scene
end
function generateTranScene()
local scene = CCScene:create()
local layer = nil
if CurSceneNo == 1 then
layer = createLayer1()
elseif CurSceneNo == 2 then
layer = createLayer2()
end
scene:addChild(layer)
scene:addChild(CreateBackMenuItem())
return createTransition(SceneIdx, TRANSITION_DURATION, scene)
end
function TransitionsTest()
cclog("TransitionsTest")
local scene = CCScene:create()
SceneIdx = -1
CurSceneNo = 2
firstEnter = true
return nextAction()
end
| mit |
alfredtofu/thrift | lib/lua/TBinaryProtocol.lua | 90 | 6141 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'TProtocol'
require 'libluabpack'
require 'libluabitwise'
TBinaryProtocol = __TObject.new(TProtocolBase, {
__type = 'TBinaryProtocol',
VERSION_MASK = -65536, -- 0xffff0000
VERSION_1 = -2147418112, -- 0x80010000
TYPE_MASK = 0x000000ff,
strictRead = false,
strictWrite = true
})
function TBinaryProtocol:writeMessageBegin(name, ttype, seqid)
if self.strictWrite then
self:writeI32(libluabitwise.bor(TBinaryProtocol.VERSION_1, ttype))
self:writeString(name)
self:writeI32(seqid)
else
self:writeString(name)
self:writeByte(ttype)
self:writeI32(seqid)
end
end
function TBinaryProtocol:writeMessageEnd()
end
function TBinaryProtocol:writeStructBegin(name)
end
function TBinaryProtocol:writeStructEnd()
end
function TBinaryProtocol:writeFieldBegin(name, ttype, id)
self:writeByte(ttype)
self:writeI16(id)
end
function TBinaryProtocol:writeFieldEnd()
end
function TBinaryProtocol:writeFieldStop()
self:writeByte(TType.STOP);
end
function TBinaryProtocol:writeMapBegin(ktype, vtype, size)
self:writeByte(ktype)
self:writeByte(vtype)
self:writeI32(size)
end
function TBinaryProtocol:writeMapEnd()
end
function TBinaryProtocol:writeListBegin(etype, size)
self:writeByte(etype)
self:writeI32(size)
end
function TBinaryProtocol:writeListEnd()
end
function TBinaryProtocol:writeSetBegin(etype, size)
self:writeByte(etype)
self:writeI32(size)
end
function TBinaryProtocol:writeSetEnd()
end
function TBinaryProtocol:writeBool(bool)
if bool then
self:writeByte(1)
else
self:writeByte(0)
end
end
function TBinaryProtocol:writeByte(byte)
local buff = libluabpack.bpack('c', byte)
self.trans:write(buff)
end
function TBinaryProtocol:writeI16(i16)
local buff = libluabpack.bpack('s', i16)
self.trans:write(buff)
end
function TBinaryProtocol:writeI32(i32)
local buff = libluabpack.bpack('i', i32)
self.trans:write(buff)
end
function TBinaryProtocol:writeI64(i64)
local buff = libluabpack.bpack('l', i64)
self.trans:write(buff)
end
function TBinaryProtocol:writeDouble(dub)
local buff = libluabpack.bpack('d', dub)
self.trans:write(buff)
end
function TBinaryProtocol:writeString(str)
-- Should be utf-8
self:writeI32(string.len(str))
self.trans:write(str)
end
function TBinaryProtocol:readMessageBegin()
local sz, ttype, name, seqid = self:readI32()
if sz < 0 then
local version = libluabitwise.band(sz, TBinaryProtocol.VERSION_MASK)
if version ~= TBinaryProtocol.VERSION_1 then
terror(TProtocolException:new{
message = 'Bad version in readMessageBegin: ' .. sz
})
end
ttype = libluabitwise.band(sz, TBinaryProtocol.TYPE_MASK)
name = self:readString()
seqid = self:readI32()
else
if self.strictRead then
terror(TProtocolException:new{message = 'No protocol version header'})
end
name = self.trans:readAll(sz)
ttype = self:readByte()
seqid = self:readI32()
end
return name, ttype, seqid
end
function TBinaryProtocol:readMessageEnd()
end
function TBinaryProtocol:readStructBegin()
return nil
end
function TBinaryProtocol:readStructEnd()
end
function TBinaryProtocol:readFieldBegin()
local ttype = self:readByte()
if ttype == TType.STOP then
return nil, ttype, 0
end
local id = self:readI16()
return nil, ttype, id
end
function TBinaryProtocol:readFieldEnd()
end
function TBinaryProtocol:readMapBegin()
local ktype = self:readByte()
local vtype = self:readByte()
local size = self:readI32()
return ktype, vtype, size
end
function TBinaryProtocol:readMapEnd()
end
function TBinaryProtocol:readListBegin()
local etype = self:readByte()
local size = self:readI32()
return etype, size
end
function TBinaryProtocol:readListEnd()
end
function TBinaryProtocol:readSetBegin()
local etype = self:readByte()
local size = self:readI32()
return etype, size
end
function TBinaryProtocol:readSetEnd()
end
function TBinaryProtocol:readBool()
local byte = self:readByte()
if byte == 0 then
return false
end
return true
end
function TBinaryProtocol:readByte()
local buff = self.trans:readAll(1)
local val = libluabpack.bunpack('c', buff)
return val
end
function TBinaryProtocol:readI16()
local buff = self.trans:readAll(2)
local val = libluabpack.bunpack('s', buff)
return val
end
function TBinaryProtocol:readI32()
local buff = self.trans:readAll(4)
local val = libluabpack.bunpack('i', buff)
return val
end
function TBinaryProtocol:readI64()
local buff = self.trans:readAll(8)
local val = libluabpack.bunpack('l', buff)
return val
end
function TBinaryProtocol:readDouble()
local buff = self.trans:readAll(8)
local val = libluabpack.bunpack('d', buff)
return val
end
function TBinaryProtocol:readString()
local len = self:readI32()
local str = self.trans:readAll(len)
return str
end
TBinaryProtocolFactory = TProtocolFactory:new{
__type = 'TBinaryProtocolFactory',
strictRead = false
}
function TBinaryProtocolFactory:getProtocol(trans)
-- TODO Enforce that this must be a transport class (ie not a bool)
if not trans then
terror(TProtocolException:new{
message = 'Must supply a transport to ' .. ttype(self)
})
end
return TBinaryProtocol:new{
trans = trans,
strictRead = self.strictRead,
strictWrite = true
}
end
| apache-2.0 |
sartura/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/bmx7.lua | 76 | 2091 | #!/usr/bin/lua
local json = require "cjson"
local function interpret_suffix(rate)
if rate ~= nil then
local value = string.sub(rate, 1, -2)
local suffix = string.sub(rate, -1)
if suffix == "K" then return tonumber(value) * 10^3 end
if suffix == "M" then return tonumber(value) * 10^6 end
if suffix == "G" then return tonumber(value) * 10^9 end
end
return rate
end
local function scrape()
local status = json.decode(get_contents("/var/run/bmx7/json/status")).status
local labels = {
id = status.shortId,
name = status.name,
address = status.primaryIp,
revision = status.revision,
}
metric("bmx7_status", "gauge", labels, 1)
metric("bmx7_cpu_usage", "gauge", nil, status.cpu)
metric("bmx7_mem_usage", "gauge", nil, interpret_suffix(status.mem))
local links = json.decode(get_contents("/var/run/bmx7/json/links")).links
local metric_bmx7_rxRate = metric("bmx7_link_rxRate","gauge")
local metric_bmx7_txRate = metric("bmx7_link_txRate","gauge")
for _, link in pairs(links) do
local labels = {
source = status.shortId,
target = link.shortId,
name = link.name,
dev = link.dev
}
metric_bmx7_rxRate(labels, interpret_suffix(link.rxRate))
metric_bmx7_txRate(labels, interpret_suffix(link.txRate))
end
local metric_bmx7_tunIn = metric("bmx7_tunIn", "gauge")
local parameters = json.decode(get_contents("/var/run/bmx7/json/parameters")).OPTIONS
for _, option in pairs(parameters) do
if option.name == "tunIn" then
for _, instance in pairs(option.INSTANCES) do
for _, child_instance in pairs(instance.CHILD_INSTANCES) do
local labels = {
name = instance.value,
network = child_instance.value
}
metric_bmx7_tunIn(labels, 1)
end
end
elseif option.name == "plugin" then
local metric_bmx7_plugin = metric("bmx7_plugin", "gauge")
for _, instance in pairs(option.INSTANCES) do
metric_bmx7_plugin({ name = instance.value }, 1)
end
end
end
end
return { scrape = scrape }
| gpl-2.0 |
youssef-emad/shogun | examples/undocumented/lua_modular/kernel_comm_word_string_modular.lua | 21 | 1375 | require 'modshogun'
require 'load'
traindat = load_dna('../data/fm_train_dna.dat')
testdat = load_dna('../data/fm_test_dna.dat')
parameter_list = {{traindat,testdat,4,0,false, false},{traindat,testdat,4,0,False,False}}
function kernel_comm_word_string_modular (fm_train_dna,fm_test_dna, order, gap, reverse, use_sign)
--charfeat=modshogun.StringCharFeatures(modshogun.DNA)
--charfeat:set_features(fm_train_dna)
--feats_train=modshogun.StringWordFeatures(charfeat:get_alphabet())
--feats_train:obtain_from_char(charfeat, order-1, order, gap, reverse)
--
--preproc=modshogun.SortWordString()
--preproc:init(feats_train)
--feats_train:add_preprocessor(preproc)
--feats_train:apply_preprocessor()
--
--charfeat=modshogun.StringCharFeatures(modshogun.DNA)
--charfeat:set_features(fm_test_dna)
--feats_test=modshogun.StringWordFeatures(charfeat:get_alphabet())
--feats_test:obtain_from_char(charfeat, order-1, order, gap, reverse)
--feats_test:add_preprocessor(preproc)
--feats_test:apply_preprocessor()
--
--kernel=modshogun.CommWordStringKernel(feats_train, feats_train, use_sign)
--
--km_train=kernel:get_kernel_matrix()
--kernel:init(feats_train, feats_test)
--km_test=kernel:get_kernel_matrix()
--return km_train,km_test,kernel
end
if debug.getinfo(3) == nill then
print 'CommWordString'
kernel_comm_word_string_modular(unpack(parameter_list[1]))
end
| gpl-3.0 |
Telecat-full/-Telecat-Full | plugins/feedback.lua | 3 | 1031 | do
function run(msg, matches)
local fuse = '#DearAdmin😜 we have recived a new feedback just now : #newfeedback \n\nID▶️ : ' .. msg.from.id .. '\n\nName▶ : ' .. msg.from.print_name ..'\n\nusername▶️ :@ ' .. msg.from.username ..'\n\n🅿️♏️ :\n\n\n' .. matches[1]
local fuses = '!printf user#id' .. msg.from.id
local text = matches[1]
bannedidone = string.find(msg.from.id, '123')
bannedidtwo =string.find(msg.from.id, '465')
bannedidthree =string.find(msg.from.id, '678')
print(msg.to.id)
if bannedidone or bannedidtwo or bannedidthree then --for banned people
return 'You are banned to send a feedback'
else
local sends0 = send_msg('chat#70690378', fuse, ok_cb, false)
return 'sent!'
end
end
return {
description = "Feedback",
usage = "[Ff][Ee][Ee][Dd][Bb][Aa][Cc][Kk] : send maseage to admins with bot",
patterns = {
"^[Ff][Ee][Ee][Dd][Bb][Aa][Cc][Kk] (.*)$"
},
run = run
}
end
| gpl-2.0 |
cooljeanius/CEGUI | datafiles/lua_scripts/demo8.lua | 6 | 3719 | -----------------------------------------
-- Start of handler functions
-----------------------------------------
-----------------------------------------
-- Alpha slider handler (not used!)
-----------------------------------------
function sliderHandler(args)
CEGUI.System:getSingleton():getGUISheet():setAlpha(CEGUI.toSlider(CEGUI.toWindowEventArgs(args).window):getCurrentValue())
end
-----------------------------------------
-- Handler to slide pane
--
-- Here we move the 'Demo8' sheet window
-- and re-position the scrollbar
-----------------------------------------
function panelSlideHandler(args)
local scroller = CEGUI.toScrollbar(CEGUI.toWindowEventArgs(args).window)
local demoWnd = CEGUI.WindowManager:getSingleton():getWindow("Demo8")
local relHeight = demoWnd:getHeight():asRelative(demoWnd:getParentPixelHeight())
scroller:setPosition(CEGUI.UVector2(CEGUI.UDim(0,0), CEGUI.UDim(scroller:getScrollPosition() / relHeight,0)))
demoWnd:setPosition(CEGUI.UVector2(CEGUI.UDim(0,0), CEGUI.UDim(-scroller:getScrollPosition(),0)))
end
-----------------------------------------
-- Handler to set preview colour when
-- colour selector scrollers change
-----------------------------------------
function colourChangeHandler(args)
local winMgr = CEGUI.WindowManager:getSingleton()
local r = CEGUI.toScrollbar(winMgr:getWindow("Demo8/Window1/Controls/Red")):getScrollPosition()
local g = CEGUI.toScrollbar(winMgr:getWindow("Demo8/Window1/Controls/Green")):getScrollPosition()
local b = CEGUI.toScrollbar(winMgr:getWindow("Demo8/Window1/Controls/Blue")):getScrollPosition()
local col = CEGUI.colour:new_local(r, g, b, 1)
local crect = CEGUI.ColourRect(col)
winMgr:getWindow("Demo8/Window1/Controls/ColourSample"):setProperty("ImageColours", CEGUI.PropertyHelper:colourRectToString(crect))
end
-----------------------------------------
-- Handler to add an item to the box
-----------------------------------------
function addItemHandler(args)
local winMgr = CEGUI.WindowManager:getSingleton()
local text = winMgr:getWindow("Demo8/Window1/Controls/Editbox"):getText()
local cols = CEGUI.PropertyHelper:stringToColourRect(winMgr:getWindow("Demo8/Window1/Controls/ColourSample"):getProperty("ImageColours"))
local newItem = CEGUI.createListboxTextItem(text, 0, nil, false, true)
newItem:setSelectionBrushImage("TaharezLook", "MultiListSelectionBrush")
newItem:setSelectionColours(cols)
CEGUI.toListbox(winMgr:getWindow("Demo8/Window1/Listbox")):addItem(newItem)
end
-----------------------------------------
-- Script Entry Point
-----------------------------------------
local guiSystem = CEGUI.System:getSingleton()
local schemeMgr = CEGUI.SchemeManager:getSingleton()
local winMgr = CEGUI.WindowManager:getSingleton()
-- load our demo8 scheme
schemeMgr:create("Demo8.scheme");
-- load our demo8 window layout
local root = winMgr:loadWindowLayout("Demo8.layout")
-- set the layout as the root
guiSystem:setGUISheet(root)
-- set default mouse cursor
guiSystem:setDefaultMouseCursor("TaharezLook", "MouseArrow")
-- set the Tooltip type
guiSystem:setDefaultTooltip("TaharezLook/Tooltip")
-- subscribe required events
winMgr:getWindow("Demo8/ViewScroll"):subscribeEvent("ScrollPosChanged", "panelSlideHandler")
winMgr:getWindow("Demo8/Window1/Controls/Blue"):subscribeEvent("ScrollPosChanged", "colourChangeHandler")
winMgr:getWindow("Demo8/Window1/Controls/Red"):subscribeEvent("ScrollPosChanged", "colourChangeHandler")
winMgr:getWindow("Demo8/Window1/Controls/Green"):subscribeEvent("ScrollPosChanged", "colourChangeHandler")
winMgr:getWindow("Demo8/Window1/Controls/Add"):subscribeEvent("Clicked", "addItemHandler")
| gpl-3.0 |
jithumon/Kochu | plugins/setlang.lua | 8 | 1864 | local config = require 'config'
local u = require 'utilities'
local api = require 'methods'
local plugin = {}
local function doKeyboard_lang()
local keyboard = {
inline_keyboard = {}
}
for lang, flag in pairs(config.available_languages) do
local line = {{text = flag, callback_data = 'langselected:'..lang}}
table.insert(keyboard.inline_keyboard, line)
end
return keyboard
end
function plugin.onTextMessage(msg, blocks)
if msg.chat.type == 'private' or (msg.chat.id < 0 and u.is_allowed('config', msg.chat.id, msg.from)) then
local keyboard = doKeyboard_lang()
api.sendMessage(msg.chat.id, _("*List of available languages*:"), true, keyboard)
end
end
function plugin.onCallbackQuery(msg, blocks)
if msg.chat.type ~= 'private' and not msg.from.admin then
api.answerCallbackQuery(msg.cb_id, _("You are not an admin"))
else
if blocks[1] == 'selectlang' then
local keyboard = doKeyboard_lang()
api.editMessageText(msg.chat.id, msg.message_id, _("*List of available languages*:"), true, keyboard)
else
locale.language = blocks[1]
db:set('lang:'..msg.chat.id, locale.language)
if (blocks[1] == 'ar' or blocks[1] == 'fa') and msg.chat.type ~= 'private' then
db:hset('chat:'..msg.chat.id..':char', 'Arab', 'allowed')
db:hset('chat:'..msg.chat.id..':char', 'Rtl', 'allowed')
end
-- TRANSLATORS: replace 'English' with the name of your language
api.editMessageText(msg.chat.id, msg.message_id, _("English language is *set*").._(".\nPlease note that translators are volunteers, and some strings of the translation you selected _could not have been translated yet_"), true)
end
end
end
plugin.triggers = {
onTextMessage = {config.cmd..'(lang)$'},
onCallbackQuery = {
'^###cb:(selectlang)',
'^###cb:langselected:(%l%l)$',
'^###cb:langselected:(%l%l_%u%u)$'
}
}
return plugin
| gpl-2.0 |
pratik2709/RayCasting-Engine | game/utilities.lua | 1 | 1777 | function print_r(t)
local print_r_cache = {}
local function sub_print_r(t, indent)
if (print_r_cache[tostring(t)]) then
print(indent .. "*" .. tostring(t))
else
print_r_cache[tostring(t)] = true
if (type(t) == "table") then
for pos, val in pairs(t) do
if (type(val) == "table") then
print(indent .. "[" .. pos .. "] => " .. tostring(t) .. " {")
sub_print_r(val, indent .. string.rep(" ", string.len(pos) + 8))
print(indent .. string.rep(" ", string.len(pos) + 6) .. "}")
elseif (type(val) == "string") then
print(indent .. "[" .. pos .. '] => "' .. val .. '"')
else
print(indent .. "[" .. pos .. "] => " .. tostring(val))
end
end
else
print(indent .. tostring(t))
end
end
end
if (type(t) == "table") then
print(tostring(t) .. " {")
sub_print_r(t, " ")
print("}")
else
sub_print_r(t, " ")
end
print()
end
function tcount(t)
local i = 0
for k in pairs(t) do i = i + 1 end
return i
end
function celda(x, y)
fx = math.floor(x)
fy = math.floor(y)
-- if fx>10 or fy>10 then return 0 end
-- if fx<0 or fy<0 then return 0 end
return floor_map[fx][fy]
end
function manipulate_player_plane()
local turnSpeed = rotSpeed * player.x
local oldPlaneX = player.planeX
player.planeX = player.planeX * math.cos(turnSpeed) - player.planeY * math.sin(turnSpeed)
player.planeY = oldPlaneX * math.sin(turnSpeed) + player.planeY * math.cos(turnSpeed)
end | mit |
tianxiawuzhei/cocos-quick-cpp | publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/SceneReader.lua | 19 | 1434 |
--------------------------------
-- @module SceneReader
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#SceneReader] setTarget
-- @param self
-- @param #function selector
-- @return SceneReader#SceneReader self (return value: ccs.SceneReader)
--------------------------------
--
-- @function [parent=#SceneReader] createNodeWithSceneFile
-- @param self
-- @param #string fileName
-- @param #int attachComponent
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#SceneReader] getAttachComponentType
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#SceneReader] getNodeByTag
-- @param self
-- @param #int nTag
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
-- js purge<br>
-- lua destroySceneReader
-- @function [parent=#SceneReader] destroyInstance
-- @param self
-- @return SceneReader#SceneReader self (return value: ccs.SceneReader)
--------------------------------
--
-- @function [parent=#SceneReader] sceneReaderVersion
-- @param self
-- @return char#char ret (return value: char)
--------------------------------
--
-- @function [parent=#SceneReader] getInstance
-- @param self
-- @return SceneReader#SceneReader ret (return value: ccs.SceneReader)
return nil
| mit |
Xirotegnicrev/Specialized_Industry | prototypes/recipe/recipe.lua | 1 | 2328 | data:extend({
--Train products assembling machines
{
type = "recipe",
name = "trains-rails-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "trains-rails-assembling-machine"
},
{
type = "recipe",
name = "trains-locomotives-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "trains-locomotives-assembling-machine"
},
{
type = "recipe",
name = "trains-stops-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "trains-stops-assembling-machine"
},
--Weapons products assembling machines
{
type = "recipe",
name = "weapons-guns-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "weapons-guns-assembling-machine"
},
{
type = "recipe",
name = "weapons-ammos-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "weapons-ammos-assembling-machine"
},
{
type = "recipe",
name = "weapons-capsules-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "weapons-capsules-assembling-machine"
},
--Structures assembling machines
{
type = "recipe",
name = "structures-basic-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "structures-basic-assembling-machine"
},
{
type = "recipe",
name = "structures-military-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "structures-military-assembling-machine"
},
--Vehicules products assembling machines
{
type = "recipe",
name = "vehicules-land-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "vehicules-land-assembling-machine"
},
--Modules assembling machines
{
type = "recipe",
name = "modules-modules-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "modules-modules-assembling-machine"
},
--Scientific products assembling machines
{
type = "recipe",
name = "science-sciencePacks-assembling-machine",
enabled = true,
ingredients =
{
{"iron-plate", 1},
},
result = "science-sciencePacks-assembling-machine"
},
}) | mit |
meirfaraj/tiproject | finance/src/ui/gcutils.lua | 1 | 4919 |
Color = {
["black"] = { 0, 0, 0 },
["red"] = { 255, 0, 0 },
["green"] = { 0, 255, 0 },
["blue "] = { 0, 0, 255 },
["white"] = { 255, 255, 255 },
["brown"] = { 165, 42, 42 },
["cyan"] = { 0, 255, 255 },
["darkblue"] = { 0, 0, 139 },
["darkred"] = { 139, 0, 0 },
["fuchsia"] = { 255, 0, 255 },
["gold"] = { 255, 215, 0 },
["gray"] = { 127, 127, 127 },
["grey"] = { 127, 127, 127 },
["lightblue"] = { 173, 216, 230 },
["lightgreen"] = { 144, 238, 144 },
["magenta"] = { 255, 0, 255 },
["maroon"] = { 128, 0, 0 },
["navyblue"] = { 159, 175, 223 },
["orange"] = { 255, 165, 0 },
["palegreen"] = { 152, 251, 152 },
["pink"] = { 255, 192, 203 },
["purple"] = { 128, 0, 128 },
["royalblue"] = { 65, 105, 225 },
["salmon"] = { 250, 128, 114 },
["seagreen"] = { 46, 139, 87 },
["silver"] = { 192, 192, 192 },
["turquoise"] = { 64, 224, 208 },
["violet"] = { 238, 130, 238 },
["yellow"] = { 255, 255, 0 }
}
Color.mt = { __index = function() return { 0, 0, 0 } end }
setmetatable(Color,Color.mt)
function copyTable(t)
local t2 = {}
for k,v in pairs(t) do
t2[k] = v
end
return t2
end
function deepcopy(t) -- This function recursively copies a table's contents, and ensures that metatables are preserved. That is, it will correctly clone a pure Lua object.
if type(t) ~= 'table' then return t end
local mt = getmetatable(t)
local res = {}
for k,v in pairs(t) do
if type(v) == 'table' then
v = deepcopy(v)
end
res[k] = v
end
setmetatable(res,mt)
return res
end -- from http://snippets.luacode.org/snippets/Deep_copy_of_a_Lua_Table_2
function screenRefresh()
return platform.window:invalidate()
end
function pww()
return platform.window:width()
end
function pwh()
return platform.window:height()
end
function drawPoint(gc, x, y)
gc:fillRect(x, y, 1, 1)
end
function drawCircle(gc, x, y, diameter)
gc:drawArc(x - diameter/2, y - diameter/2, diameter,diameter,0,360)
end
function drawCenteredString(gc, str)
gc:drawString(str, .5*(pww() - gc:getStringWidth(str)), .5*pwh(), "middle")
end
function drawXCenteredString(gc, str, y)
gc:drawString(str, .5*(pww() - gc:getStringWidth(str)), y, "top")
end
function setColor(gc,theColor)
if type(theColor) == "string" then
theColor = string.lower(theColor)
if type(Color[theColor]) == "table" then gc:setColorRGB(unpack(Color[theColor])) end
elseif type(theColor) == "table" then
gc:setColorRGB(unpack(theColor))
end
end
function verticalBar(gc,x)
gc:fillRect(gc,x,0,1,pwh())
end
function horizontalBar(gc,y)
gc:fillRect(gc,0,y,pww(),1)
end
function nativeBar(gc, screen, y)
gc:setColorRGB(128,128,128)
gc:fillRect(screen.x+5, screen.y+y, screen.w-10, 2)
end
function drawSquare(gc,x,y,l)
gc:drawPolyLine(gc,{(x-l/2),(y-l/2), (x+l/2),(y-l/2), (x+l/2),(y+l/2), (x-l/2),(y+l/2), (x-l/2),(y-l/2)})
end
function drawRoundRect(gc,x,y,wd,ht,rd) -- wd = width, ht = height, rd = radius of the rounded corner
x = x-wd/2 -- let the center of the square be the origin (x coord)
y = y-ht/2 -- same for y coord
if rd > ht/2 then rd = ht/2 end -- avoid drawing cool but unexpected shapes. This will draw a circle (max rd)
gc:drawLine(x + rd, y, x + wd - (rd), y);
gc:drawArc(x + wd - (rd*2), y + ht - (rd*2), rd*2, rd*2, 270, 90);
gc:drawLine(x + wd, y + rd, x + wd, y + ht - (rd));
gc:drawArc(x + wd - (rd*2), y, rd*2, rd*2,0,90);
gc:drawLine(x + wd - (rd), y + ht, x + rd, y + ht);
gc:drawArc(x, y, rd*2, rd*2, 90, 90);
gc:drawLine(x, y + ht - (rd), x, y + rd);
gc:drawArc(x, y + ht - (rd*2), rd*2, rd*2, 180, 90);
end
function fillRoundRect(gc,x,y,wd,ht,radius) -- wd = width and ht = height -- renders badly when transparency (alpha) is not at maximum >< will re-code later
if radius > ht/2 then radius = ht/2 end -- avoid drawing cool but unexpected shapes. This will draw a circle (max radius)
gc:fillPolygon({(x-wd/2),(y-ht/2+radius), (x+wd/2),(y-ht/2+radius), (x+wd/2),(y+ht/2-radius), (x-wd/2),(y+ht/2-radius), (x-wd/2),(y-ht/2+radius)})
gc:fillPolygon({(x-wd/2-radius+1),(y-ht/2), (x+wd/2-radius+1),(y-ht/2), (x+wd/2-radius+1),(y+ht/2), (x-wd/2+radius),(y+ht/2), (x-wd/2+radius),(y-ht/2)})
x = x-wd/2 -- let the center of the square be the origin (x coord)
y = y-ht/2 -- same
gc:fillArc(x + wd - (radius*2), y + ht - (radius*2), radius*2, radius*2, 1, -91);
gc:fillArc(x + wd - (radius*2), y, radius*2, radius*2,-2,91);
gc:fillArc(x, y, radius*2, radius*2, 85, 95);
gc:fillArc(x, y + ht - (radius*2), radius*2, radius*2, 180, 95);
end
function textLim(gc, text, max)
local ttext, out = "",""
local width = gc:getStringWidth(text)
if width<max then
return text, width
else
for i=1, #text do
ttext = text:usub(1, i)
if gc:getStringWidth(ttext .. "..")>max then
break
end
out = ttext
end
return out .. "..", gc:getStringWidth(out .. "..")
end
end
| apache-2.0 |
durandtibo/wsl.resnet.torch | trainMultiLabel.lua | 1 | 7235 | --
-- Copyright (c) 2016, 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.
--
-- The training loop and learning rate schedule
--
local optim = require 'optim'
local evaluation = require 'evaluation'
local csvigo = require 'csvigo'
local paths = require 'paths'
local matio = require 'matio'
local M = {}
local Trainer = torch.class('resnet.Trainer', M)
function Trainer:__init(model, criterion, opt, optimState)
self.model = model
self.criterion = criterion
self.optimState = optimState or {
learningRate = opt.LR,
learningRateDecay = 0.0,
momentum = opt.momentum,
nesterov = true,
dampening = 0.0,
weightDecay = opt.weightDecay,
}
self.opt = opt
self.params, self.gradParams = model:getParameters()
self.featureNet = opt.featureNet
end
function Trainer:train(epoch, dataloader)
-- Trains the model for a single epoch
self.optimState.learningRate = self:learningRate(epoch)
local timer = torch.Timer()
local dataTimer = torch.Timer()
local size = dataloader:size()
local function feval()
return self.criterion.output, self.gradParams
end
local nImages = dataloader:numberOfImages()
local lossSum = 0.0
local N = 0
if self.featureNet ~= nil then
self.featureNet:evaluate()
end
print('=> Training epoch # ' .. epoch)
-- set the batch norm to training mode
self.model:training()
if self.featureNet ~= nil then
self.featureNet:evaluate()
end
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
-- Copy input and target to the GPU
self:copyInputs(sample)
local target = self.target:clone()
target = torch.cmin(target:add(1), 1)
local input = self.input
if self.featureNet ~= nil then
input = self.featureNet:forward(input)
end
local output = self.model:forward(input):float()
local batchSize = output:size(1)
local loss = self.criterion:forward(self.model.output, target)
self.model:zeroGradParameters()
self.criterion:backward(self.model.output, target)
self.model:backward(input, self.criterion.gradInput)
optim.sgd(feval, self.params, self.optimState)
lossSum = lossSum + loss*batchSize
N = N + batchSize
print((' | Epoch: [%d][%d/%d] Time %.3f Data %.3f loss %7.3f (%7.3f)'):format(
epoch, n, size, timer:time().real, dataTime, loss, lossSum / N))
-- check that the storage didn't get changed do to an unfortunate getParameters call
assert(self.params:storage() == self.model:parameters()[1]:storage())
timer:reset()
dataTimer:reset()
end
return 0, 0, lossSum / N
end
function Trainer:test(epoch, dataloader)
-- Computes the top-1 and top-5 err on the validation set
local timer = torch.Timer()
local dataTimer = torch.Timer()
local size = dataloader:size()
local nImages = dataloader:numberOfImages()
local lossSum = 0.0
local scores = torch.zeros(nImages, self.opt.nClasses)
local labels = torch.zeros(nImages, self.opt.nClasses)
local N = 0
local name = {}
self.model:evaluate()
if self.featureNet ~= nil then
self.featureNet:evaluate()
end
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
-- Copy input and target to the GPU
self:copyInputs(sample)
local target = self.target:clone()
target = torch.cmin(target:add(1), 1)
local input = self.input
if self.featureNet ~= nil then
input = self.featureNet:forward(input)
end
local output = self.model:forward(input):float()
local batchSize = output:size(1)
local loss = self.criterion:forward(self.model.output, target)
scores[{{N+1,N+batchSize},{}}] = output
labels[{{N+1,N+batchSize},{}}] = self.target:float()
for i = 1,batchSize do
name[N+i] = sample.path[i]
end
lossSum = lossSum + loss*batchSize
N = N + batchSize
print((' | Test: [%d][%d/%d] Time %.3f Data %.3f loss %7.3f (%7.3f)'):format(
epoch, n, size, timer:time().real, dataTime, loss, lossSum / N))
timer:reset()
dataTimer:reset()
end
self.model:training()
map = Evaluation:computeMeanAveragePrecision(scores, labels)
print((' * Finished epoch # %d MAP: %7.3f error: %7.3f loss: %7.3f\n'):format(epoch, map, 1-map, lossSum / N))
return 1-map, lossSum / N
end
function Trainer:writeScores(epoch, dataloader, split)
-- Computes the top-1 and top-5 err on the validation set
local timer = torch.Timer()
local dataTimer = torch.Timer()
local size = dataloader:size()
local nImages = dataloader:numberOfImages()
local lossSum = 0.0
local scores = torch.zeros(nImages, self.opt.nClasses)
local labels = torch.zeros(nImages, self.opt.nClasses)
local N = 0
local pathResults = self.opt.results .. '/classification/' .. self.opt.dataset .. '/' .. self.opt.netType .. '_image_' .. self.opt.imageSize .. self.opt.pathResults .. '/LR=' .. self.opt.LR
local file = pathResults .. '/scores_' .. split .. '.csv'
local path = paths.dirname(file)
print('write scores in ' .. path)
self.model:evaluate()
if self.featureNet ~= nil then
self.featureNet:evaluate()
end
local name = {}
for n, sample in dataloader:run() do
xlua.progress(n, size)
-- Copy input and target to the GPU
self:copyInputs(sample)
local input = self.input
local target = self.target:clone()
target = torch.cmin(target:add(1), 1)
if self.featureNet ~= nil then
input = self.featureNet:forward(input)
end
local output = self.model:forward(input):float()
local batchSize = output:size(1)
local loss = self.criterion:forward(self.model.output, target)
scores[{{N+1,N+batchSize},{}}] = output
labels[{{N+1,N+batchSize},{}}] = self.target:float()
for i = 1,batchSize do
name[N+i] = sample.path[i]
end
if self.opt.localization then
output = self.model:get(self.opt.lastconv).output
for i = 1,batchSize do
local filename = pathResults .. '/localization/' .. sample.path[i] .. '.mat'
local path = paths.dirname(filename)
paths.mkdir(path)
matio.save(filename, output[{i,{},{},{}}]:float())
end
end
N = N + batchSize
end
local data = {}
-- header
data[1] = {}
data[1][1] = 'name'
for j=1,scores:size(2) do
data[1][j+1] = 'class' .. j
end
for i=1,table.getn(name) do
data[i+1] = {}
data[i+1][1] = name[i]
for j=1,scores:size(2) do
data[i+1][j+1] = scores[i][j]
end
end
paths.mkdir(path)
csvigo.save({path = file, mode = "raw", data = data})
end
function Trainer:copyInputs(sample)
-- Copies the input to a CUDA tensor, if using 1 GPU, or to pinned memory,
-- if using DataParallelTable. The target is always copied to a CUDA tensor
self.input = self.input or (self.opt.nGPU == 0 and torch.FloatTensor() or self.opt.nGPU == 1 and torch.CudaTensor() or cutorch.createCudaHostTensor())
self.target = self.target or (self.opt.nGPU == 0 and torch.FloatTensor() or torch.CudaTensor())
self.input:resize(sample.input:size()):copy(sample.input)
self.target:resize(sample.target:size()):copy(sample.target)
end
function Trainer:learningRate(epoch)
-- Training schedule
local decay = 0
return self.opt.LR * math.pow(0.1, decay)
end
return M.Trainer
| mit |
mobarski/sandbox | scite/old/wscite_zzz/lexers/notused/python.lua | 1 | 5674 | -- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Python LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'python'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, '#' * l.nonnewline_esc^0)
-- Strings.
local sq_str = P('u')^-1 * l.delimited_range("'", true)
local dq_str = P('U')^-1 * l.delimited_range('"', true)
local triple_sq_str = "'''" * (l.any - "'''")^0 * P("'''")^-1
local triple_dq_str = '"""' * (l.any - '"""')^0 * P('"""')^-1
-- TODO: raw_strs cannot end in single \.
local raw_sq_str = P('u')^-1 * 'r' * l.delimited_range("'", false, true)
local raw_dq_str = P('U')^-1 * 'R' * l.delimited_range('"', false, true)
local string = token(l.STRING, triple_sq_str + triple_dq_str + sq_str + dq_str +
raw_sq_str + raw_dq_str)
-- Numbers.
local dec = l.digit^1 * S('Ll')^-1
local bin = '0b' * S('01')^1 * ('_' * S('01')^1)^0
local oct = '0' * R('07')^1 * S('Ll')^-1
local integer = S('+-')^-1 * (bin + l.hex_num + oct + dec)
local number = token(l.NUMBER, l.float + integer)
-- Keywords.
local keyword = token(l.KEYWORD, word_match{
'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',
'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'print', 'raise',
'return', 'try', 'while', 'with', 'yield',
-- Descriptors/attr access.
'__get__', '__set__', '__delete__', '__slots__',
-- Class.
'__new__', '__init__', '__del__', '__repr__', '__str__', '__cmp__',
'__index__', '__lt__', '__le__', '__gt__', '__ge__', '__eq__', '__ne__',
'__hash__', '__nonzero__', '__getattr__', '__getattribute__', '__setattr__',
'__delattr__', '__call__',
-- Operator.
'__add__', '__sub__', '__mul__', '__div__', '__floordiv__', '__mod__',
'__divmod__', '__pow__', '__and__', '__xor__', '__or__', '__lshift__',
'__rshift__', '__nonzero__', '__neg__', '__pos__', '__abs__', '__invert__',
'__iadd__', '__isub__', '__imul__', '__idiv__', '__ifloordiv__', '__imod__',
'__ipow__', '__iand__', '__ixor__', '__ior__', '__ilshift__', '__irshift__',
-- Conversions.
'__int__', '__long__', '__float__', '__complex__', '__oct__', '__hex__',
'__coerce__',
-- Containers.
'__len__', '__getitem__', '__missing__', '__setitem__', '__delitem__',
'__contains__', '__iter__', '__getslice__', '__setslice__', '__delslice__',
-- Module and class attribs.
'__doc__', '__name__', '__dict__', '__file__', '__path__', '__module__',
'__bases__', '__class__', '__self__',
-- Stdlib/sys.
'__builtin__', '__future__', '__main__', '__import__', '__stdin__',
'__stdout__', '__stderr__',
-- Other.
'__debug__', '__doc__', '__import__', '__name__'
})
-- Functions.
local func = token(l.FUNCTION, word_match{
'abs', 'all', 'any', 'apply', 'basestring', 'bool', 'buffer', 'callable',
'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright',
'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval',
'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr',
'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern',
'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals',
'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow',
'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr',
'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod',
'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange',
'zip'
})
-- Constants.
local constant = token(l.CONSTANT, word_match{
'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception',
'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError',
'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None',
'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'Warning', 'ZeroDivisionError'
})
-- Self.
local self = token('self', P('self'))
-- Identifiers.
local identifier = token(l.IDENTIFIER, l.word)
-- Operators.
local operator = token(l.OPERATOR, S('!%^&*()[]{}-=+/|:;.,?<>~`'))
-- Decorators.
local decorator = token('decorator', l.starts_line('@') * l.nonnewline^0)
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'function', func},
{'constant', constant},
{'self', self},
{'identifier', identifier},
{'comment', comment},
{'string', string},
{'number', number},
{'decorator', decorator},
{'operator', operator},
}
M._tokenstyles = {
ws = 'fore:$(color.teal),bold',
keyword = 'fore:$(color.teal),bold',
func = 'fore:$(color.teal),bold',
constant = 'fore:$(color.teal),bold',
self = 'fore:$(color.teal),bold',
identifier = 'fore:$(color.teal),bold',
comment = 'fore:$(color.teal),bold',
string = 'fore:$(color.teal),bold',
number = 'fore:$(color.teal),bold',
decorator = 'fore:$(color.teal),bold',
operator = 'fore:$(color.teal),bold'
}
M._FOLDBYINDENTATION = true
return M
| mit |
caicloud/ingress | rootfs/etc/nginx/lua/balancer.lua | 2 | 10252 | local ngx_balancer = require("ngx.balancer")
local cjson = require("cjson.safe")
local util = require("util")
local dns_lookup = require("util.dns").lookup
local configuration = require("configuration")
local round_robin = require("balancer.round_robin")
local chash = require("balancer.chash")
local chashsubset = require("balancer.chashsubset")
local sticky_balanced = require("balancer.sticky_balanced")
local sticky_persistent = require("balancer.sticky_persistent")
local ewma = require("balancer.ewma")
local string = string
local ipairs = ipairs
local table = table
local getmetatable = getmetatable
local tostring = tostring
local pairs = pairs
local math = math
local ngx = ngx
-- measured in seconds
-- for an Nginx worker to pick up the new list of upstream peers
-- it will take <the delay until controller POSTed the backend object to the
-- Nginx endpoint> + BACKENDS_SYNC_INTERVAL
local BACKENDS_SYNC_INTERVAL = 1
local BACKENDS_FORCE_SYNC_INTERVAL = 30
local DEFAULT_LB_ALG = "round_robin"
local IMPLEMENTATIONS = {
round_robin = round_robin,
chash = chash,
chashsubset = chashsubset,
sticky_balanced = sticky_balanced,
sticky_persistent = sticky_persistent,
ewma = ewma,
}
local _M = {}
local balancers = {}
local backends_with_external_name = {}
local backends_last_synced_at = 0
local function get_implementation(backend)
local name = backend["load-balance"] or DEFAULT_LB_ALG
if backend["sessionAffinityConfig"] and
backend["sessionAffinityConfig"]["name"] == "cookie" then
if backend["sessionAffinityConfig"]["mode"] == 'persistent' then
name = "sticky_persistent"
else
name = "sticky_balanced"
end
elseif backend["upstreamHashByConfig"] and
backend["upstreamHashByConfig"]["upstream-hash-by"] then
if backend["upstreamHashByConfig"]["upstream-hash-by-subset"] then
name = "chashsubset"
else
name = "chash"
end
end
local implementation = IMPLEMENTATIONS[name]
if not implementation then
ngx.log(ngx.WARN, backend["load-balance"], "is not supported, ",
"falling back to ", DEFAULT_LB_ALG)
implementation = IMPLEMENTATIONS[DEFAULT_LB_ALG]
end
return implementation
end
local function resolve_external_names(original_backend)
local backend = util.deepcopy(original_backend)
local endpoints = {}
for _, endpoint in ipairs(backend.endpoints) do
local ips = dns_lookup(endpoint.address)
for _, ip in ipairs(ips) do
table.insert(endpoints, { address = ip, port = endpoint.port })
end
end
backend.endpoints = endpoints
return backend
end
local function format_ipv6_endpoints(endpoints)
local formatted_endpoints = {}
for _, endpoint in ipairs(endpoints) do
local formatted_endpoint = endpoint
if not endpoint.address:match("^%d+.%d+.%d+.%d+$") then
formatted_endpoint.address = string.format("[%s]", endpoint.address)
end
table.insert(formatted_endpoints, formatted_endpoint)
end
return formatted_endpoints
end
local function is_backend_with_external_name(backend)
local serv_type = backend.service and backend.service.spec
and backend.service.spec["type"]
return serv_type == "ExternalName"
end
local function sync_backend(backend)
if not backend.endpoints or #backend.endpoints == 0 then
balancers[backend.name] = nil
return
end
if is_backend_with_external_name(backend) then
backend = resolve_external_names(backend)
end
backend.endpoints = format_ipv6_endpoints(backend.endpoints)
local implementation = get_implementation(backend)
local balancer = balancers[backend.name]
if not balancer then
balancers[backend.name] = implementation:new(backend)
return
end
-- every implementation is the metatable of its instances (see .new(...) functions)
-- here we check if `balancer` is the instance of `implementation`
-- if it is not then we deduce LB algorithm has changed for the backend
if getmetatable(balancer) ~= implementation then
ngx.log(ngx.INFO,
string.format("LB algorithm changed from %s to %s, resetting the instance",
balancer.name, implementation.name))
balancers[backend.name] = implementation:new(backend)
return
end
balancer:sync(backend)
end
local function sync_backends_with_external_name()
for _, backend_with_external_name in pairs(backends_with_external_name) do
sync_backend(backend_with_external_name)
end
end
local function sync_backends()
local raw_backends_last_synced_at = configuration.get_raw_backends_last_synced_at()
ngx.update_time()
local current_timestamp = ngx.time()
if current_timestamp - backends_last_synced_at < BACKENDS_FORCE_SYNC_INTERVAL
and raw_backends_last_synced_at <= backends_last_synced_at then
return
end
local backends_data = configuration.get_backends_data()
if not backends_data then
balancers = {}
return
end
local new_backends, err = cjson.decode(backends_data)
if not new_backends then
ngx.log(ngx.ERR, "could not parse backends data: ", err)
return
end
local balancers_to_keep = {}
for _, new_backend in ipairs(new_backends) do
if is_backend_with_external_name(new_backend) then
local backend_with_external_name = util.deepcopy(new_backend)
backends_with_external_name[backend_with_external_name.name] = backend_with_external_name
else
sync_backend(new_backend)
end
balancers_to_keep[new_backend.name] = true
end
for backend_name, _ in pairs(balancers) do
if not balancers_to_keep[backend_name] then
balancers[backend_name] = nil
backends_with_external_name[backend_name] = nil
end
end
backends_last_synced_at = raw_backends_last_synced_at
end
local function route_to_alternative_balancer(balancer)
if not balancer.alternative_backends then
return false
end
-- TODO: support traffic shaping for n > 1 alternative backends
local backend_name = balancer.alternative_backends[1]
if not backend_name then
ngx.log(ngx.ERR, "empty alternative backend")
return false
end
local alternative_balancer = balancers[backend_name]
if not alternative_balancer then
ngx.log(ngx.ERR, "no alternative balancer for backend: ",
tostring(backend_name))
return false
end
local traffic_shaping_policy = alternative_balancer.traffic_shaping_policy
if not traffic_shaping_policy then
ngx.log(ngx.ERR, "traffic shaping policy is not set for balancer ",
"of backend: ", tostring(backend_name))
return false
end
local target_header = util.replace_special_char(traffic_shaping_policy.header,
"-", "_")
local header = ngx.var["http_" .. target_header]
if header then
if traffic_shaping_policy.headerValue
and #traffic_shaping_policy.headerValue > 0 then
if traffic_shaping_policy.headerValue == header then
return true
end
elseif traffic_shaping_policy.headerPattern
and #traffic_shaping_policy.headerPattern > 0 then
local m, err = ngx.re.match(header, traffic_shaping_policy.headerPattern)
if m then
return true
elseif err then
ngx.log(ngx.ERR, "error when matching canary-by-header-pattern: '",
traffic_shaping_policy.headerPattern, "', error: ", err)
return false
end
elseif header == "always" then
return true
elseif header == "never" then
return false
end
end
local target_cookie = traffic_shaping_policy.cookie
local cookie = ngx.var["cookie_" .. target_cookie]
if cookie then
if cookie == "always" then
return true
elseif cookie == "never" then
return false
end
end
if math.random(100) <= traffic_shaping_policy.weight then
return true
end
return false
end
local function get_balancer()
if ngx.ctx.balancer then
return ngx.ctx.balancer
end
local backend_name = ngx.var.proxy_upstream_name
local balancer = balancers[backend_name]
if not balancer then
return
end
if route_to_alternative_balancer(balancer) then
local alternative_backend_name = balancer.alternative_backends[1]
ngx.var.proxy_alternative_upstream_name = alternative_backend_name
balancer = balancers[alternative_backend_name]
end
ngx.ctx.balancer = balancer
return balancer
end
function _M.init_worker()
-- when worker starts, sync non ExternalName backends without delay
sync_backends()
-- we call sync_backends_with_external_name in timer because for endpoints that require
-- DNS resolution it needs to use socket which is not available in
-- init_worker phase
local ok, err = ngx.timer.at(0, sync_backends_with_external_name)
if not ok then
ngx.log(ngx.ERR, "failed to create timer: ", err)
end
ok, err = ngx.timer.every(BACKENDS_SYNC_INTERVAL, sync_backends)
if not ok then
ngx.log(ngx.ERR, "error when setting up timer.every for sync_backends: ", err)
end
ok, err = ngx.timer.every(BACKENDS_SYNC_INTERVAL, sync_backends_with_external_name)
if not ok then
ngx.log(ngx.ERR, "error when setting up timer.every for sync_backends_with_external_name: ",
err)
end
end
function _M.rewrite()
local balancer = get_balancer()
if not balancer then
ngx.status = ngx.HTTP_SERVICE_UNAVAILABLE
return ngx.exit(ngx.status)
end
end
function _M.balance()
local balancer = get_balancer()
if not balancer then
return
end
local peer = balancer:balance()
if not peer then
ngx.log(ngx.WARN, "no peer was returned, balancer: " .. balancer.name)
return
end
ngx_balancer.set_more_tries(1)
local ok, err = ngx_balancer.set_current_peer(peer)
if not ok then
ngx.log(ngx.ERR, "error while setting current upstream peer ", peer,
": ", err)
end
end
function _M.log()
local balancer = get_balancer()
if not balancer then
return
end
if not balancer.after_balance then
return
end
balancer:after_balance()
end
setmetatable(_M, {__index = {
get_implementation = get_implementation,
sync_backend = sync_backend,
route_to_alternative_balancer = route_to_alternative_balancer,
get_balancer = get_balancer,
}})
return _M
| apache-2.0 |
UB12/y_r | 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 |
ioiasff/khp | 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 |
hfjgjfg/amir2 | 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 |
shadoalzupedy/shadow | plugins/lock_emoji.lua | 17 | 2548 | --[[
#
#ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#:((
# For More Information ....!
# Developer : Aziz < @TH3_GHOST >
# our channel: @DevPointTeam
# Version: 1.1
#:))
#ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#
]]
local function run(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['emoji'] == 'yes' then
if not is_momod(msg) then
delete_msg(msg.id, ok_cb, true)
end
end
end
return {patterns = {
"😞(.+)",
"😞",
"😐(.+)",
"😐",
"🙁(.+)",
"🙁",
"🌝(.+)",
"🌝",
"🤖(.+)",
"🤖",
"😲(.+)",
"😲",
"💋(.+)",
"💋",
"🙄(.+)",
"🙄",
"🤗(.+)",
"🤗",
"😱(.+)",
"😱",
"🤐(.+)",
"🤐",
"💩(.+)",
"💩",
"🌹(.+)",
"🌹",
"🖐(.+)",
"🖐",
"❤️(.+)",
"❤️",
"💗(.+)",
"💗",
"🤔(.+)",
"🤔",
"😖(.+)",
"😖",
"☹️(.+)",
"☹️",
"😔(.+)",
"😔",
"👾(.+)",
"👾",
"🚀(.+)",
"🚀",
"🌎🌍(.+)",
"🌍",
"🍦",
"😸(.+)",
"😺",
"😯(.+)",
"😯",
"🤒(.+)",
"🤒",
"😷(.+)",
"😷",
"🙀(.+)",
"🙀",
"🎪(.+)",
"🌚",
"🌚(.+)",
"😂",
"😂(.+)",
"😳",
"😳(.+)",
"😛",
"😛(.+)",
"😢",
"😢(.+)",
"😓",
"😓(.+)",
"😾",
"😾(.+)",
"👊🏻",
"👊🏻(.+)",
"✊🏻",
"✊🏻(.+)",
"👿",
"👿(.+)",
"👅",
"👅(.+)",
"🖕🏿",
"🖕🏿(.+)",
"😲",
"😲(.+)",
"👹",
"👹(.+)",
"😴",
"😴(.+)",
"☂",
"☂(.+)",
"🗣",
"🗣(.+)",
"⛄️",
"⛄️(.+)",
"😻",
"😻(.+)",
"😀(.+)",
"😀",
"😬(.+)",
"😬",
"😁(.+)",
"😁",
"😂(.+)",
"😂",
"😃(.+)",
"😃",
"😄(.+)",
"😄",
"😅",
"😆(.+)",
"😆",
"😇(.+)",
"😇",
"😉(.+)",
"😉",
"😊(.+)",
"😊",
"🙂(.+)",
"🙂",
"🙃(.+)",
"🙃",
"☺️(.+)",
"☺️",
"😋(.+)",
"😋",
"😌",
"😍(.+)",
"😍",
"😘(.+)",
"😘",
"😗(.+)",
"😗",
"😙(.+)",
"😙",
"😚(.+)",
"😚",
"😜(.+)",
"😜",
"😝(.+)",
"😝",
"🤑(.+)",
"🤑",
"🤓(.+)",
"🤓",
"😎(.+)",
"😎",
"🤗(.+)",
"🤗",
"😏(.+)",
"😏",
"😶(.+)",
"😶",
"😺(.+)",
"😺",
"😹",
"😼",
"😿",
"🌝",
"🌚",
"🌶",
"🖐🏼",
},run = run}
| gpl-2.0 |
cyanskies/OpenRA | mods/ra/maps/soviet-06a/soviet06a.lua | 5 | 5989 | ArmorAttack = { }
AttackPaths = { { AttackWaypoint1 }, { AttackWaypoint2 } }
BaseAttackers = { BaseAttacker1, BaseAttacker2 }
InfAttack = { }
IntroAttackers = { IntroEnemy1, IntroEnemy2, IntroEnemy3 }
Trucks = { Truck1, Truck2 }
AlliedInfantryTypes = { "e1", "e1", "e3" }
AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "2tnk", "2tnk", "arty" }
SovietReinforcements1 = { "e6", "e6", "e6", "e6", "e6" }
SovietReinforcements2 = { "e4", "e4", "e2", "e2", "e2" }
SovietReinforcements1Waypoints = { McvWaypoint.Location, APCWaypoint1.Location }
SovietReinforcements2Waypoints = { McvWaypoint.Location, APCWaypoint2.Location }
TruckGoalTrigger = { CPos.New(83, 7), CPos.New(83, 8), CPos.New(83, 9), CPos.New(83, 10), CPos.New(84, 10), CPos.New(84, 11), CPos.New(84, 12), CPos.New(85, 12), CPos.New(86, 12), CPos.New(87, 12), CPos.New(87, 13), CPos.New(88, 13), CPos.New(89, 13), CPos.New(90, 13), CPos.New(90, 14), CPos.New(90, 15), CPos.New(91, 15), CPos.New(92, 15), CPos.New(93, 15), CPos.New(94, 15) }
CameraBarrierTrigger = { CPos.New(65, 39), CPos.New(65, 40), CPos.New(66, 40), CPos.New(66, 41), CPos.New(67, 41), CPos.New(67, 42), CPos.New(68, 42), CPos.New(68, 43), CPos.New(68, 44) }
CameraBaseTrigger = { CPos.New(53, 42), CPos.New(54, 42), CPos.New(54, 41), CPos.New(55, 41), CPos.New(56, 41), CPos.New(56, 40), CPos.New(57, 40), CPos.New(57, 39), CPos.New(58, 39), CPos.New(59, 39), CPos.New(59, 38), CPos.New(60, 38), CPos.New(61, 38) }
Trigger.OnEnteredFootprint(TruckGoalTrigger, function(a, id)
if not truckGoalTrigger and a.Owner == player and a.Type == "truk" then
truckGoalTrigger = true
player.MarkCompletedObjective(sovietObjective)
player.MarkCompletedObjective(SaveAllTrucks)
end
end)
Trigger.OnEnteredFootprint(CameraBarrierTrigger, function(a, id)
if not cameraBarrierTrigger and a.Owner == player then
cameraBarrierTrigger = true
local cameraBarrier = Actor.Create("camera", true, { Owner = player, Location = CameraBarrier.Location })
Trigger.AfterDelay(DateTime.Seconds(15), function()
cameraBarrier.Destroy()
end)
end
end)
Trigger.OnEnteredFootprint(CameraBaseTrigger, function(a, id)
if not cameraBaseTrigger and a.Owner == player then
cameraBaseTrigger = true
local cameraBase1 = Actor.Create("camera", true, { Owner = player, Location = CameraBase1.Location })
local cameraBase2 = Actor.Create("camera", true, { Owner = player, Location = CameraBase2.Location })
local cameraBase3 = Actor.Create("camera", true, { Owner = player, Location = CameraBase3.Location })
local cameraBase4 = Actor.Create("camera", true, { Owner = player, Location = CameraBase4.Location })
Trigger.AfterDelay(DateTime.Minutes(1), function()
cameraBase1.Destroy()
cameraBase2.Destroy()
cameraBase3.Destroy()
cameraBase4.Destroy()
end)
end
end)
Trigger.OnAllKilled(Trucks, function()
enemy.MarkCompletedObjective(alliedObjective)
end)
Trigger.OnAnyKilled(Trucks, function()
player.MarkFailedObjective(SaveAllTrucks)
end)
Trigger.OnKilled(Apwr, function(building)
BaseApwr.exists = false
end)
Trigger.OnKilled(Barr, function(building)
BaseTent.exists = false
end)
Trigger.OnKilled(Proc, function(building)
BaseProc.exists = false
end)
Trigger.OnKilled(Weap, function(building)
BaseWeap.exists = false
end)
Trigger.OnKilled(Apwr2, function(building)
BaseApwr2.exists = false
end)
Trigger.OnKilled(Dome, function()
player.MarkCompletedObjective(sovietObjective2)
Media.PlaySpeechNotification(player, "ObjectiveMet")
end)
-- Activate the AI once the player deployed the Mcv
Trigger.OnRemovedFromWorld(Mcv, function()
if not mcvDeployed then
mcvDeployed = true
BuildBase()
SendEnemies()
Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry)
Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor)
Trigger.AfterDelay(DateTime.Minutes(2), function()
Utils.Do(BaseAttackers, function(actor)
IdleHunt(actor)
end)
end)
end
end)
WorldLoaded = function()
player = Player.GetPlayer("USSR")
enemy = Player.GetPlayer("Greece")
Camera.Position = CameraStart.CenterPosition
Mcv.Move(McvWaypoint.Location)
Harvester.FindResources()
Utils.Do(IntroAttackers, function(actor)
IdleHunt(actor)
end)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == enemy and building.Health < 3/4 * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements1, SovietReinforcements1Waypoints)
Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements2, SovietReinforcements2Waypoints)
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)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
alliedObjective = enemy.AddPrimaryObjective("Destroy all Soviet troops.")
sovietObjective = player.AddPrimaryObjective("Escort the Convoy.")
sovietObjective2 = player.AddSecondaryObjective("Destroy the Allied radar dome to stop enemy\nreinforcements.")
SaveAllTrucks = player.AddSecondaryObjective("Keep all trucks alive.")
end
Tick = function()
if player.HasNoRequiredUnits() then
enemy.MarkCompletedObjective(alliedObjective)
end
if enemy.Resources >= enemy.ResourceCapacity * 0.75 then
enemy.Cash = enemy.Cash + enemy.Resources - enemy.ResourceCapacity * 0.25
enemy.Resources = enemy.ResourceCapacity * 0.25
end
end
| gpl-3.0 |
Frenzie/koreader-base | ffi/utf8proc.lua | 1 | 3144 | --[[--
Module for utf8 string operations.
This is a LuaJIT FFI wrapper for utf8proc.
@module ffi.utf8proc
]]
local ffi = require("ffi")
local C = ffi.C
require("ffi/posix_h")
require("ffi/utf8proc_h")
local libutf8proc
if ffi.os == "Windows" then
libutf8proc = ffi.load("libs/libutf8proc-2.dll")
elseif ffi.os == "OSX" then
libutf8proc = ffi.load("libs/libutf8proc.2.dylib")
else
libutf8proc = ffi.load("libs/libutf8proc.so.2")
end
local Utf8Proc = {}
--- Lowercases an utf8-encoded string
--- @string str string to lowercase
--- @bool normalize normalizes the string during operation
--- @treturn string the lowercased string
function Utf8Proc.lowercase(str, normalize)
if normalize == nil then normalize = true end
if normalize then
return Utf8Proc.lowercase_NFKC_Casefold(str)
else
return Utf8Proc.lowercase_dumb(str)
end
end
-- with normalization
function Utf8Proc.lowercase_NFKC_Casefold(str)
local folded_strz = libutf8proc.utf8proc_NFKC_Casefold(str)
local folded_str = ffi.string(folded_strz)
C.free(folded_strz)
return folded_str
end
-- no normalization here
function Utf8Proc.lowercase_dumb(str)
local lowercased = ""
local tmp_str = (" "):rep(10)
local tmp_p = ffi.cast("utf8proc_uint8_t *", tmp_str)
local str_p = ffi.cast("const utf8proc_uint8_t *", str)
local codepoint = ffi.new("utf8proc_int32_t[1]")
local count = 0
local pos = 0
local str_len = #str -- may contain NUL
while pos < str_len do
-- get codepoint
local bytes = libutf8proc.utf8proc_iterate(str_p + pos, -1, codepoint)
-- lowercase codepoint
local lower_cp = libutf8proc.utf8proc_tolower(codepoint[0])
-- encode lowercased codepoint and get length of new char*
local lower_len = libutf8proc.utf8proc_encode_char(lower_cp, tmp_p)
tmp_p[lower_len] = 0
-- append
lowercased = lowercased .. ffi.string(tmp_p)
if bytes > 0 then
count = count + 1
pos = pos + bytes
else
return lowercased
end
end
return lowercased
end
--- Normalizes an utf8-encoded string
--- @string str string to lowercase
--- @treturn string the normalized string
function Utf8Proc.normalize_NFC(str)
local normalized_strz = libutf8proc.utf8proc_NFC(str)
local normalized_str = ffi.string(normalized_strz)
C.free(normalized_strz)
return normalized_str
end
--- Counts codepoints in an utf8-encoded string
--- @string str to count codepoints in
--- @return (int, bool) number of codepoints, operation successfull
function Utf8Proc.count(str)
local str_p = ffi.cast("const utf8proc_uint8_t *", str)
local codepoint = ffi.new("utf8proc_int32_t[1]")
local count = 0
local pos = 0
local str_len = #str -- may contain NUL
while pos < str_len do
local bytes = libutf8proc.utf8proc_iterate(str_p + pos, -1, codepoint)
if bytes > 0 then
count = count + 1
pos = pos + bytes
else
return count, false
end
end
return count, true
end
return Utf8Proc
| agpl-3.0 |
snowplow/snowplow-lua-tracker | spec/unit/snowplow_spec.lua | 1 | 3247 | --- snowplow_spec.lua
--
-- Copyright (c) 2013 - 2022 Snowplow Analytics Ltd. All rights reserved.
--
-- This program is licensed to you under the Apache License Version 2.0,
-- and you may not use this file except in compliance with the Apache License Version 2.0.
-- You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the Apache License Version 2.0 is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
local snowplow = require("snowplow")
local ss = require("lib.utils").safe_string -- Alias
local TRACKER_VERSION = require("constants").TRACKER_VERSION
local function assert_tracker(tracker, collector_url)
assert.are.equal(tracker.emitter:get_collector_url(), collector_url)
assert.are.equal(tracker.config.encode_base64, true)
assert.are.equal(tracker.config.platform, "pc")
assert.are.equal(tracker.config.version, TRACKER_VERSION)
end
describe("snowplow", function()
-- --------------------------------------------------------------
-- Test error handling on constructors
it("new_tracker() should error unless passed a non-empty string", function()
local f = function(host)
return function()
snowplow.new_tracker(host)
end
end
local err = function(value)
return "url is required and must be a non-empty string, not [" .. ss(value) .. "]"
end
assert.has_error(f(""), err(""))
assert.has_error(f({}), err("{}"))
assert.has_error(f(-23.04), err("-23.04"))
end)
-- --------------------------------------------------------------
-- Verify constructed tracker tables
it("new_tracker() should correctly create a tracker", function()
local t = snowplow.new_tracker("test.invalid", "GET")
assert_tracker(t, "https://test.invalid/i")
end)
it("new_tracker_for_uri() should correctly assign default protocol https", function()
local t = snowplow.new_tracker("test.invalid")
assert.is_equal(t.emitter:get_collector_url():sub(1, 5), "https")
end)
it("new_tracker_for_uri() should correctly create url with default protocol from url with port", function()
local t = snowplow.new_tracker("http://test.invalid:9090", "GET")
assert.is_equal("http://test.invalid:9090/i", t.emitter:get_collector_url())
end)
it("new_tracker() should assign correct passed protocol", function()
local protocols = { "http", "https" }
for _, protocol in ipairs(protocols) do
local t = snowplow.new_tracker(protocol .. "://test.invalid")
assert.is_equal(t.emitter:get_collector_url():sub(1, protocol:len()), protocol)
end
end)
it("new_tracker() should error if passed an invalid protocol", function()
local protocols = { "ftp", "file" }
for _, protocol in ipairs(protocols) do
local f = function()
snowplow.new_tracker(protocol .. "://test.invalid")
end
assert.has_error(f, "protocol must be a string from the set {http, https}, not [" .. protocol .. "]")
end
end)
end)
| apache-2.0 |
gedads/Neodynamis | scripts/zones/Abyssea-Attohwa/npcs/qm3.lua | 3 | 1347 | -----------------------------------
-- Zone: Abyssea-Attohwa
-- NPC: qm3 (???)
-- Spawns Pallid Percy
-- !pos ? ? ? 215
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
if (trade:hasItemQty(3074,1) and trade:getItemCount() == 1) then -- Player has all the required items.
if (GetMobAction(17658263) == ACTION_NONE) then -- Mob not already spawned from this
SpawnMob(17658263):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:tradeComplete();
end
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(1010, 3074); -- Inform player what items they need.
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Selbina/npcs/Explorer_Moogle.lua | 17 | 1855 | -----------------------------------
-- Area: Selbina
-- NPC: Explorer Moogle
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/teleports");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
accept = 0;
event = 0x046f;
if (player:getGil() < 300) then
accept = 1;
end
if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then
event = event + 1;
end
player:startEvent(event,player:getZoneID(),0,accept);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local price = 300;
if (csid == 0x046f) then
if (option == 1 and player:delGil(price)) then
toExplorerMoogle(player,231);
elseif (option == 2 and player:delGil(price)) then
toExplorerMoogle(player,234);
elseif (option == 3 and player:delGil(price)) then
toExplorerMoogle(player,240);
elseif (option == 4 and player:delGil(price)) then
toExplorerMoogle(player,248);
elseif (option == 5 and player:delGil(price)) then
toExplorerMoogle(player,249);
end
end
end; | gpl-3.0 |
starlightknight/darkstar | scripts/globals/mobskills/spirit_tap.lua | 11 | 1292 | ---------------------------------------------
-- Spirit Tap
-- Attempts to absorb one buff from a single target, or otherwise steals HP.
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores Shadows
-- Range: Melee
-- Notes: Can be any (positive) buff, including food. Will drain about 100HP if it can't take any buffs
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:isMobType(MOBTYPE_NOTORIOUS)) then
return 1
end
return 0
end
function onMobWeaponSkill(target, mob, skill)
-- try to drain buff
local effect = mob:stealStatusEffect(target, dsp.effectFlag.DISPELABLE+dsp.effectFlag.FOOD)
local dmg = 0
if (effect ~= 0) then
skill:setMsg(dsp.msg.basic.EFFECT_DRAINED)
return 1
else
-- time to drain HP. 50-100
local power = math.random(0, 51) + 50
dmg = MobFinalAdjustments(power,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.DARK,MOBPARAM_IGNORE_SHADOWS)
skill:setMsg(MobPhysicalDrainMove(mob, target, skill, MOBDRAIN_HP, dmg))
end
return dmg
end
| gpl-3.0 |
starlightknight/darkstar | scripts/globals/spells/bluemagic/grand_slam.lua | 4 | 1517 | -----------------------------------------
-- Spell: Grand Slam
-- Delivers an area attack. Damage varies with TP
-- Spell cost: 24 MP
-- Monster Type: Beastmen
-- Spell Type: Physical (Blunt)
-- Blue Magic Points: 2
-- Stat Bonus: INT+1
-- Level: 30
-- Casting Time: 1 seconds
-- Recast Time: 14.25 seconds
-- Skillchain Element(s): Ice (can open Impaction, Compression, or Fragmentation can close Induration)
-- Combos: Defense Bonus
-----------------------------------------
require("scripts/globals/bluemagic")
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local params = {}
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_ATTACK
params.dmgtype = dsp.damageType.BLUNT
params.scattr = SC_INDURATION
params.numhits = 1
params.multiplier = 1.0
params.tp150 = 1.0
params.tp300 = 1.0
params.azuretp = 1.0
params.duppercap = 33
params.str_wsc = 0.0
params.dex_wsc = 0.0
params.vit_wsc = 0.3
params.agi_wsc = 0.0
params.int_wsc = 0.1
params.mnd_wsc = 0.1
params.chr_wsc = 0.1
damage = BluePhysicalSpell(caster, target, spell, params)
damage = BlueFinalAdjustments(caster, target, spell, damage, params)
return damage
end | gpl-3.0 |
gedads/Neodynamis | scripts/zones/West_Ronfaure/npcs/qm4.lua | 3 | 1701 | -----------------------------------
-- Area: West Ronfaure
-- NPC: qm4 (???)
-- Involved in Quest: The Dismayed Customer
-- !pos -399 -10 -438 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/West_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(SANDORIA,PRESTIGE_OF_THE_PAPSQUE) and player:getVar("MissionStatus") == 1) then
if (GetMobAction(17187273) == 0) then
if (player:getVar("Mission7-1MobKilled") == 1) then
player:addKeyItem(ANCIENT_SANDORIAN_TABLET);
player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_SANDORIAN_TABLET);
player:setVar("Mission7-1MobKilled",0);
player:setVar("MissionStatus",2);
else
SpawnMob(17187273):updateClaim(player);
end
end
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/North_Gustaberg/npcs/Quellebie_RK.lua | 3 | 3339 | -----------------------------------
-- Area: North Gustaberg
-- NPC: Quellebie, R.K.
-- Type: Border Conquest Guards
-- !pos -520.704 38.75 560.258 106
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/North_Gustaberg/TextIDs");
local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = GUSTABERG;
local csid = 0x7ffa;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Lower_Jeuno/npcs/_l09.lua | 3 | 2850 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- !pos -32 0 -28 245
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/NPCIDs");
require("scripts/zones/Lower_Jeuno/TextIDs");
-- lamp id vary from 17780881 to 17780892
-- lamp cs vary from 0x0078 to 0x0083 (120 to 131)
local lampNum = 9;
local lampId = lampIdOffset + lampNum;
local cs = lampCsOffset + lampNum;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
local playerOnQuest = GetServerVariable("[JEUNO]CommService");
-- player is on the quest
if playerOnQuest == player:getID() then
if hour >= 20 and hour < 21 then
player:startEvent(cs,4); -- It is too early to light it. You must wait until nine o'clock.
elseif hour >= 21 or hour < 1 then
if npc:getAnimation() == ANIMATION_OPEN_DOOR then
player:startEvent(cs,2); -- The lamp is already lit.
else
player:startEvent(cs,1,lampNum); -- Light the lamp? Yes/No
end
else
player:startEvent(cs,3); -- You have failed to light the lamps in time.
end
-- player is not on the quest
else
if npc:getAnimation() == ANIMATION_OPEN_DOOR then
player:startEvent(cs,5); -- The lamp is lit.
else
player:startEvent(cs,6); -- You examine the lamp. It seems that it must be lit manually.
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if csid == cs and option == 1 then
-- lamp is now lit
GetNPCByID(lampId):setAnimation(ANIMATION_OPEN_DOOR);
-- tell player how many remain
local lampsRemaining = 12;
for i=0,11 do
local lamp = GetNPCByID(lampIdOffset + i);
if lamp:getAnimation() == ANIMATION_OPEN_DOOR then
lampsRemaining = lampsRemaining - 1;
end
end
if lampsRemaining == 0 then
player:messageSpecial(LAMP_MSG_OFFSET);
else
player:messageSpecial(LAMP_MSG_OFFSET+1,lampsRemaining);
end
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Valley_of_Sorrows/npcs/relic.lua | 3 | 1876 | -----------------------------------
-- Area: Valley of Sorrows
-- NPC: <this space intentionally left blank>
-- !pos -14 -3 56 128
-----------------------------------
package.loaded["scripts/zones/Valley_of_Sorrows/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Valley_of_Sorrows/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18341 and trade:getItemCount() == 4 and trade:hasItemQty(18341,1) and
trade:hasItemQty(1584,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1451,1)) then
player:startEvent(15,18342);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 15) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18342);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1450);
else
player:tradeComplete();
player:addItem(18342);
player:addItem(1450,30);
player:messageSpecial(ITEM_OBTAINED,18342);
player:messageSpecial(ITEMS_OBTAINED,1450,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/contrib/luasrcdiet/lua/optlex.lua | 125 | 31588 | --[[--------------------------------------------------------------------
optlex.lua: does lexer-based optimizations
This file is part of LuaSrcDiet.
Copyright (c) 2008 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- NOTES:
-- * For more lexer-based optimization ideas, see the TODO items or
-- look at technotes.txt.
-- * TODO: general string delimiter conversion optimizer
-- * TODO: (numbers) warn if overly significant digit
----------------------------------------------------------------------]]
local base = _G
local string = require "string"
module "optlex"
local match = string.match
local sub = string.sub
local find = string.find
local rep = string.rep
local print
------------------------------------------------------------------------
-- variables and data structures
------------------------------------------------------------------------
-- error function, can override by setting own function into module
error = base.error
warn = {} -- table for warning flags
local stoks, sinfos, stoklns -- source lists
local is_realtoken = { -- significant (grammar) tokens
TK_KEYWORD = true,
TK_NAME = true,
TK_NUMBER = true,
TK_STRING = true,
TK_LSTRING = true,
TK_OP = true,
TK_EOS = true,
}
local is_faketoken = { -- whitespace (non-grammar) tokens
TK_COMMENT = true,
TK_LCOMMENT = true,
TK_EOL = true,
TK_SPACE = true,
}
local opt_details -- for extra information
------------------------------------------------------------------------
-- true if current token is at the start of a line
-- * skips over deleted tokens via recursion
------------------------------------------------------------------------
local function atlinestart(i)
local tok = stoks[i - 1]
if i <= 1 or tok == "TK_EOL" then
return true
elseif tok == "" then
return atlinestart(i - 1)
end
return false
end
------------------------------------------------------------------------
-- true if current token is at the end of a line
-- * skips over deleted tokens via recursion
------------------------------------------------------------------------
local function atlineend(i)
local tok = stoks[i + 1]
if i >= #stoks or tok == "TK_EOL" or tok == "TK_EOS" then
return true
elseif tok == "" then
return atlineend(i + 1)
end
return false
end
------------------------------------------------------------------------
-- counts comment EOLs inside a long comment
-- * in order to keep line numbering, EOLs need to be reinserted
------------------------------------------------------------------------
local function commenteols(lcomment)
local sep = #match(lcomment, "^%-%-%[=*%[")
local z = sub(lcomment, sep + 1, -(sep - 1)) -- remove delims
local i, c = 1, 0
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
if not p then break end -- if no matches, done
i = p + 1
c = c + 1
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
end
return c
end
------------------------------------------------------------------------
-- compares two tokens (i, j) and returns the whitespace required
-- * important! see technotes.txt for more information
-- * only two grammar/real tokens are being considered
-- * if "", no separation is needed
-- * if " ", then at least one whitespace (or EOL) is required
------------------------------------------------------------------------
local function checkpair(i, j)
local match = match
local t1, t2 = stoks[i], stoks[j]
--------------------------------------------------------------------
if t1 == "TK_STRING" or t1 == "TK_LSTRING" or
t2 == "TK_STRING" or t2 == "TK_LSTRING" then
return ""
--------------------------------------------------------------------
elseif t1 == "TK_OP" or t2 == "TK_OP" then
if (t1 == "TK_OP" and (t2 == "TK_KEYWORD" or t2 == "TK_NAME")) or
(t2 == "TK_OP" and (t1 == "TK_KEYWORD" or t1 == "TK_NAME")) then
return ""
end
if t1 == "TK_OP" and t2 == "TK_OP" then
-- for TK_OP/TK_OP pairs, see notes in technotes.txt
local op, op2 = sinfos[i], sinfos[j]
if (match(op, "^%.%.?$") and match(op2, "^%.")) or
(match(op, "^[~=<>]$") and op2 == "=") or
(op == "[" and (op2 == "[" or op2 == "=")) then
return " "
end
return ""
end
-- "TK_OP" + "TK_NUMBER" case
local op = sinfos[i]
if t2 == "TK_OP" then op = sinfos[j] end
if match(op, "^%.%.?%.?$") then
return " "
end
return ""
--------------------------------------------------------------------
else-- "TK_KEYWORD" | "TK_NAME" | "TK_NUMBER" then
return " "
--------------------------------------------------------------------
end
end
------------------------------------------------------------------------
-- repack tokens, removing deletions caused by optimization process
------------------------------------------------------------------------
local function repack_tokens()
local dtoks, dinfos, dtoklns = {}, {}, {}
local j = 1
for i = 1, #stoks do
local tok = stoks[i]
if tok ~= "" then
dtoks[j], dinfos[j], dtoklns[j] = tok, sinfos[i], stoklns[i]
j = j + 1
end
end
stoks, sinfos, stoklns = dtoks, dinfos, dtoklns
end
------------------------------------------------------------------------
-- number optimization
-- * optimization using string formatting functions is one way of doing
-- this, but here, we consider all cases and handle them separately
-- (possibly an idiotic approach...)
-- * scientific notation being generated is not in canonical form, this
-- may or may not be a bad thing, feedback welcome
-- * note: intermediate portions need to fit into a normal number range
-- * optimizations can be divided based on number patterns:
-- * hexadecimal:
-- (1) no need to remove leading zeros, just skip to (2)
-- (2) convert to integer if size equal or smaller
-- * change if equal size -> lose the 'x' to reduce entropy
-- (3) number is then processed as an integer
-- (4) note: does not make 0[xX] consistent
-- * integer:
-- (1) note: includes anything with trailing ".", ".0", ...
-- (2) remove useless fractional part, if present, e.g. 123.000
-- (3) remove leading zeros, e.g. 000123
-- (4) switch to scientific if shorter, e.g. 123000 -> 123e3
-- * with fraction:
-- (1) split into digits dot digits
-- (2) if no integer portion, take as zero (can omit later)
-- (3) handle degenerate .000 case, after which the fractional part
-- must be non-zero (if zero, it's matched as an integer)
-- (4) remove trailing zeros for fractional portion
-- (5) p.q where p > 0 and q > 0 cannot be shortened any more
-- (6) otherwise p == 0 and the form is .q, e.g. .000123
-- (7) if scientific shorter, convert, e.g. .000123 -> 123e-6
-- * scientific:
-- (1) split into (digits dot digits) [eE] ([+-] digits)
-- (2) if significand has ".", shift it out so it becomes an integer
-- (3) if significand is zero, just use zero
-- (4) remove leading zeros for significand
-- (5) shift out trailing zeros for significand
-- (6) examine exponent and determine which format is best:
-- integer, with fraction, scientific
------------------------------------------------------------------------
local function do_number(i)
local before = sinfos[i] -- 'before'
local z = before -- working representation
local y -- 'after', if better
--------------------------------------------------------------------
if match(z, "^0[xX]") then -- hexadecimal number
local v = base.tostring(base.tonumber(z))
if #v <= #z then
z = v -- change to integer, AND continue
else
return -- no change; stick to hex
end
end
--------------------------------------------------------------------
if match(z, "^%d+%.?0*$") then -- integer or has useless frac
z = match(z, "^(%d+)%.?0*$") -- int portion only
if z + 0 > 0 then
z = match(z, "^0*([1-9]%d*)$") -- remove leading zeros
local v = #match(z, "0*$")
local nv = base.tostring(v)
if v > #nv + 1 then -- scientific is shorter
z = sub(z, 1, #z - v).."e"..nv
end
y = z
else
y = "0" -- basic zero
end
--------------------------------------------------------------------
elseif not match(z, "[eE]") then -- number with fraction part
local p, q = match(z, "^(%d*)%.(%d+)$") -- split
if p == "" then p = 0 end -- int part zero
if q + 0 == 0 and p == 0 then
y = "0" -- degenerate .000 case
else
-- now, q > 0 holds and p is a number
local v = #match(q, "0*$") -- remove trailing zeros
if v > 0 then
q = sub(q, 1, #q - v)
end
-- if p > 0, nothing else we can do to simplify p.q case
if p + 0 > 0 then
y = p.."."..q
else
y = "."..q -- tentative, e.g. .000123
local v = #match(q, "^0*") -- # leading spaces
local w = #q - v -- # significant digits
local nv = base.tostring(#q)
-- e.g. compare 123e-6 versus .000123
if w + 2 + #nv < 1 + #q then
y = sub(q, -w).."e-"..nv
end
end
end
--------------------------------------------------------------------
else -- scientific number
local sig, ex = match(z, "^([^eE]+)[eE]([%+%-]?%d+)$")
ex = base.tonumber(ex)
-- if got ".", shift out fractional portion of significand
local p, q = match(sig, "^(%d*)%.(%d*)$")
if p then
ex = ex - #q
sig = p..q
end
if sig + 0 == 0 then
y = "0" -- basic zero
else
local v = #match(sig, "^0*") -- remove leading zeros
sig = sub(sig, v + 1)
v = #match(sig, "0*$") -- shift out trailing zeros
if v > 0 then
sig = sub(sig, 1, #sig - v)
ex = ex + v
end
-- examine exponent and determine which format is best
local nex = base.tostring(ex)
if ex == 0 then -- it's just an integer
y = sig
elseif ex > 0 and (ex <= 1 + #nex) then -- a number
y = sig..rep("0", ex)
elseif ex < 0 and (ex >= -#sig) then -- fraction, e.g. .123
v = #sig + ex
y = sub(sig, 1, v).."."..sub(sig, v + 1)
elseif ex < 0 and (#nex >= -ex - #sig) then
-- e.g. compare 1234e-5 versus .01234
-- gives: #sig + 1 + #nex >= 1 + (-ex - #sig) + #sig
-- -> #nex >= -ex - #sig
v = -ex - #sig
y = "."..rep("0", v)..sig
else -- non-canonical scientific representation
y = sig.."e"..ex
end
end--if sig
end
--------------------------------------------------------------------
if y and y ~= sinfos[i] then
if opt_details then
print("<number> (line "..stoklns[i]..") "..sinfos[i].." -> "..y)
opt_details = opt_details + 1
end
sinfos[i] = y
end
end
------------------------------------------------------------------------
-- string optimization
-- * note: works on well-formed strings only!
-- * optimizations on characters can be summarized as follows:
-- \a\b\f\n\r\t\v -- no change
-- \\ -- no change
-- \"\' -- depends on delim, other can remove \
-- \[\] -- remove \
-- \<char> -- general escape, remove \
-- \<eol> -- normalize the EOL only
-- \ddd -- if \a\b\f\n\r\t\v, change to latter
-- if other < ascii 32, keep ddd but zap leading zeros
-- if >= ascii 32, translate it into the literal, then also
-- do escapes for \\,\",\' cases
-- <other> -- no change
-- * switch delimiters if string becomes shorter
------------------------------------------------------------------------
local function do_string(I)
local info = sinfos[I]
local delim = sub(info, 1, 1) -- delimiter used
local ndelim = (delim == "'") and '"' or "'" -- opposite " <-> '
local z = sub(info, 2, -2) -- actual string
local i = 1
local c_delim, c_ndelim = 0, 0 -- "/' counts
--------------------------------------------------------------------
while i <= #z do
local c = sub(z, i, i)
----------------------------------------------------------------
if c == "\\" then -- escaped stuff
local j = i + 1
local d = sub(z, j, j)
local p = find("abfnrtv\\\n\r\"\'0123456789", d, 1, true)
------------------------------------------------------------
if not p then -- \<char> -- remove \
z = sub(z, 1, i - 1)..sub(z, j)
i = i + 1
------------------------------------------------------------
elseif p <= 8 then -- \a\b\f\n\r\t\v\\
i = i + 2 -- no change
------------------------------------------------------------
elseif p <= 10 then -- \<eol> -- normalize EOL
local eol = sub(z, j, j + 1)
if eol == "\r\n" or eol == "\n\r" then
z = sub(z, 1, i).."\n"..sub(z, j + 2)
elseif p == 10 then -- \r case
z = sub(z, 1, i).."\n"..sub(z, j + 1)
end
i = i + 2
------------------------------------------------------------
elseif p <= 12 then -- \"\' -- remove \ for ndelim
if d == delim then
c_delim = c_delim + 1
i = i + 2
else
c_ndelim = c_ndelim + 1
z = sub(z, 1, i - 1)..sub(z, j)
i = i + 1
end
------------------------------------------------------------
else -- \ddd -- various steps
local s = match(z, "^(%d%d?%d?)", j)
j = i + 1 + #s -- skip to location
local cv = s + 0
local cc = string.char(cv)
local p = find("\a\b\f\n\r\t\v", cc, 1, true)
if p then -- special escapes
s = "\\"..sub("abfnrtv", p, p)
elseif cv < 32 then -- normalized \ddd
s = "\\"..cv
elseif cc == delim then -- \<delim>
s = "\\"..cc
c_delim = c_delim + 1
elseif cc == "\\" then -- \\
s = "\\\\"
else -- literal character
s = cc
if cc == ndelim then
c_ndelim = c_ndelim + 1
end
end
z = sub(z, 1, i - 1)..s..sub(z, j)
i = i + #s
------------------------------------------------------------
end--if p
----------------------------------------------------------------
else-- c ~= "\\" -- <other> -- no change
i = i + 1
if c == ndelim then -- count ndelim, for switching delimiters
c_ndelim = c_ndelim + 1
end
----------------------------------------------------------------
end--if c
end--while
--------------------------------------------------------------------
-- switching delimiters, a long-winded derivation:
-- (1) delim takes 2+2*c_delim bytes, ndelim takes c_ndelim bytes
-- (2) delim becomes c_delim bytes, ndelim becomes 2+2*c_ndelim bytes
-- simplifying the condition (1)>(2) --> c_delim > c_ndelim
if c_delim > c_ndelim then
i = 1
while i <= #z do
local p, q, r = find(z, "([\'\"])", i)
if not p then break end
if r == delim then -- \<delim> -> <delim>
z = sub(z, 1, p - 2)..sub(z, p)
i = p
else-- r == ndelim -- <ndelim> -> \<ndelim>
z = sub(z, 1, p - 1).."\\"..sub(z, p)
i = p + 2
end
end--while
delim = ndelim -- actually change delimiters
end
--------------------------------------------------------------------
z = delim..z..delim
if z ~= sinfos[I] then
if opt_details then
print("<string> (line "..stoklns[I]..") "..sinfos[I].." -> "..z)
opt_details = opt_details + 1
end
sinfos[I] = z
end
end
------------------------------------------------------------------------
-- long string optimization
-- * note: warning flagged if trailing whitespace found, not trimmed
-- * remove first optional newline
-- * normalize embedded newlines
-- * reduce '=' separators in delimiters if possible
------------------------------------------------------------------------
local function do_lstring(I)
local info = sinfos[I]
local delim1 = match(info, "^%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep + 1)) -- lstring without delims
local y = ""
local i = 1
--------------------------------------------------------------------
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
-- deal with a single line
local ln
if not p then
ln = sub(z, i)
elseif p >= i then
ln = sub(z, i, p - 1)
end
if ln ~= "" then
-- flag a warning if there are trailing spaces, won't optimize!
if match(ln, "%s+$") then
warn.lstring = "trailing whitespace in long string near line "..stoklns[I]
end
y = y..ln
end
if not p then -- done if no more EOLs
break
end
-- deal with line endings, normalize them
i = p + 1
if p then
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
-- skip first newline, which can be safely deleted
if not(i == 1 and i == p) then
y = y.."\n"
end
end
end--while
--------------------------------------------------------------------
-- handle possible deletion of one or more '=' separators
if sep >= 3 then
local chk, okay = sep - 1
-- loop to test ending delimiter with less of '=' down to zero
while chk >= 2 do
local delim = "%]"..rep("=", chk - 2).."%]"
if not match(y, delim) then okay = chk end
chk = chk - 1
end
if okay then -- change delimiters
sep = rep("=", okay - 2)
delim1, delim2 = "["..sep.."[", "]"..sep.."]"
end
end
--------------------------------------------------------------------
sinfos[I] = delim1..y..delim2
end
------------------------------------------------------------------------
-- long comment optimization
-- * note: does not remove first optional newline
-- * trim trailing whitespace
-- * normalize embedded newlines
-- * reduce '=' separators in delimiters if possible
------------------------------------------------------------------------
local function do_lcomment(I)
local info = sinfos[I]
local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims
local y = ""
local i = 1
--------------------------------------------------------------------
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
-- deal with a single line, extract and check trailing whitespace
local ln
if not p then
ln = sub(z, i)
elseif p >= i then
ln = sub(z, i, p - 1)
end
if ln ~= "" then
-- trim trailing whitespace if non-empty line
local ws = match(ln, "%s*$")
if #ws > 0 then ln = sub(ln, 1, -(ws + 1)) end
y = y..ln
end
if not p then -- done if no more EOLs
break
end
-- deal with line endings, normalize them
i = p + 1
if p then
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
y = y.."\n"
end
end--while
--------------------------------------------------------------------
-- handle possible deletion of one or more '=' separators
sep = sep - 2
if sep >= 3 then
local chk, okay = sep - 1
-- loop to test ending delimiter with less of '=' down to zero
while chk >= 2 do
local delim = "%]"..rep("=", chk - 2).."%]"
if not match(y, delim) then okay = chk end
chk = chk - 1
end
if okay then -- change delimiters
sep = rep("=", okay - 2)
delim1, delim2 = "--["..sep.."[", "]"..sep.."]"
end
end
--------------------------------------------------------------------
sinfos[I] = delim1..y..delim2
end
------------------------------------------------------------------------
-- short comment optimization
-- * trim trailing whitespace
------------------------------------------------------------------------
local function do_comment(i)
local info = sinfos[i]
local ws = match(info, "%s*$") -- just look from end of string
if #ws > 0 then
info = sub(info, 1, -(ws + 1)) -- trim trailing whitespace
end
sinfos[i] = info
end
------------------------------------------------------------------------
-- returns true if string found in long comment
-- * this is a feature to keep copyright or license texts
------------------------------------------------------------------------
local function keep_lcomment(opt_keep, info)
if not opt_keep then return false end -- option not set
local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims
if find(z, opt_keep, 1, true) then -- try to match
return true
end
end
------------------------------------------------------------------------
-- main entry point
-- * currently, lexer processing has 2 passes
-- * processing is done on a line-oriented basis, which is easier to
-- grok due to the next point...
-- * since there are various options that can be enabled or disabled,
-- processing is a little messy or convoluted
------------------------------------------------------------------------
function optimize(option, toklist, semlist, toklnlist)
--------------------------------------------------------------------
-- set option flags
--------------------------------------------------------------------
local opt_comments = option["opt-comments"]
local opt_whitespace = option["opt-whitespace"]
local opt_emptylines = option["opt-emptylines"]
local opt_eols = option["opt-eols"]
local opt_strings = option["opt-strings"]
local opt_numbers = option["opt-numbers"]
local opt_keep = option.KEEP
opt_details = option.DETAILS and 0 -- upvalues for details display
print = print or base.print
if opt_eols then -- forced settings, otherwise won't work properly
opt_comments = true
opt_whitespace = true
opt_emptylines = true
end
--------------------------------------------------------------------
-- variable initialization
--------------------------------------------------------------------
stoks, sinfos, stoklns -- set source lists
= toklist, semlist, toklnlist
local i = 1 -- token position
local tok, info -- current token
local prev -- position of last grammar token
-- on same line (for TK_SPACE stuff)
--------------------------------------------------------------------
-- changes a token, info pair
--------------------------------------------------------------------
local function settoken(tok, info, I)
I = I or i
stoks[I] = tok or ""
sinfos[I] = info or ""
end
--------------------------------------------------------------------
-- processing loop (PASS 1)
--------------------------------------------------------------------
while true do
tok, info = stoks[i], sinfos[i]
----------------------------------------------------------------
local atstart = atlinestart(i) -- set line begin flag
if atstart then prev = nil end
----------------------------------------------------------------
if tok == "TK_EOS" then -- end of stream/pass
break
----------------------------------------------------------------
elseif tok == "TK_KEYWORD" or -- keywords, identifiers,
tok == "TK_NAME" or -- operators
tok == "TK_OP" then
-- TK_KEYWORD and TK_OP can't be optimized without a big
-- optimization framework; it would be more of an optimizing
-- compiler, not a source code compressor
-- TK_NAME that are locals needs parser to analyze/optimize
prev = i
----------------------------------------------------------------
elseif tok == "TK_NUMBER" then -- numbers
if opt_numbers then
do_number(i) -- optimize
end
prev = i
----------------------------------------------------------------
elseif tok == "TK_STRING" or -- strings, long strings
tok == "TK_LSTRING" then
if opt_strings then
if tok == "TK_STRING" then
do_string(i) -- optimize
else
do_lstring(i) -- optimize
end
end
prev = i
----------------------------------------------------------------
elseif tok == "TK_COMMENT" then -- short comments
if opt_comments then
if i == 1 and sub(info, 1, 1) == "#" then
-- keep shbang comment, trim whitespace
do_comment(i)
else
-- safe to delete, as a TK_EOL (or TK_EOS) always follows
settoken() -- remove entirely
end
elseif opt_whitespace then -- trim whitespace only
do_comment(i)
end
----------------------------------------------------------------
elseif tok == "TK_LCOMMENT" then -- long comments
if keep_lcomment(opt_keep, info) then
------------------------------------------------------------
-- if --keep, we keep a long comment if <msg> is found;
-- this is a feature to keep copyright or license texts
if opt_whitespace then -- trim whitespace only
do_lcomment(i)
end
prev = i
elseif opt_comments then
local eols = commenteols(info)
------------------------------------------------------------
-- prepare opt_emptylines case first, if a disposable token
-- follows, current one is safe to dump, else keep a space;
-- it is implied that the operation is safe for '-', because
-- current is a TK_LCOMMENT, and must be separate from a '-'
if is_faketoken[stoks[i + 1]] then
settoken() -- remove entirely
tok = ""
else
settoken("TK_SPACE", " ")
end
------------------------------------------------------------
-- if there are embedded EOLs to keep and opt_emptylines is
-- disabled, then switch the token into one or more EOLs
if not opt_emptylines and eols > 0 then
settoken("TK_EOL", rep("\n", eols))
end
------------------------------------------------------------
-- if optimizing whitespaces, force reinterpretation of the
-- token to give a chance for the space to be optimized away
if opt_whitespace and tok ~= "" then
i = i - 1 -- to reinterpret
end
------------------------------------------------------------
else -- disabled case
if opt_whitespace then -- trim whitespace only
do_lcomment(i)
end
prev = i
end
----------------------------------------------------------------
elseif tok == "TK_EOL" then -- line endings
if atstart and opt_emptylines then
settoken() -- remove entirely
elseif info == "\r\n" or info == "\n\r" then
-- normalize the rest of the EOLs for CRLF/LFCR only
-- (note that TK_LCOMMENT can change into several EOLs)
settoken("TK_EOL", "\n")
end
----------------------------------------------------------------
elseif tok == "TK_SPACE" then -- whitespace
if opt_whitespace then
if atstart or atlineend(i) then
-- delete leading and trailing whitespace
settoken() -- remove entirely
else
------------------------------------------------------------
-- at this point, since leading whitespace have been removed,
-- there should be a either a real token or a TK_LCOMMENT
-- prior to hitting this whitespace; the TK_LCOMMENT case
-- only happens if opt_comments is disabled; so prev ~= nil
local ptok = stoks[prev]
if ptok == "TK_LCOMMENT" then
-- previous TK_LCOMMENT can abut with anything
settoken() -- remove entirely
else
-- prev must be a grammar token; consecutive TK_SPACE
-- tokens is impossible when optimizing whitespace
local ntok = stoks[i + 1]
if is_faketoken[ntok] then
-- handle special case where a '-' cannot abut with
-- either a short comment or a long comment
if (ntok == "TK_COMMENT" or ntok == "TK_LCOMMENT") and
ptok == "TK_OP" and sinfos[prev] == "-" then
-- keep token
else
settoken() -- remove entirely
end
else--is_realtoken
-- check a pair of grammar tokens, if can abut, then
-- delete space token entirely, otherwise keep one space
local s = checkpair(prev, i + 1)
if s == "" then
settoken() -- remove entirely
else
settoken("TK_SPACE", " ")
end
end
end
------------------------------------------------------------
end
end
----------------------------------------------------------------
else
error("unidentified token encountered")
end
----------------------------------------------------------------
i = i + 1
end--while
repack_tokens()
--------------------------------------------------------------------
-- processing loop (PASS 2)
--------------------------------------------------------------------
if opt_eols then
i = 1
-- aggressive EOL removal only works with most non-grammar tokens
-- optimized away because it is a rather simple scheme -- basically
-- it just checks 'real' token pairs around EOLs
if stoks[1] == "TK_COMMENT" then
-- first comment still existing must be shbang, skip whole line
i = 3
end
while true do
tok, info = stoks[i], sinfos[i]
--------------------------------------------------------------
if tok == "TK_EOS" then -- end of stream/pass
break
--------------------------------------------------------------
elseif tok == "TK_EOL" then -- consider each TK_EOL
local t1, t2 = stoks[i - 1], stoks[i + 1]
if is_realtoken[t1] and is_realtoken[t2] then -- sanity check
local s = checkpair(i - 1, i + 1)
if s == "" then
settoken() -- remove entirely
end
end
end--if tok
--------------------------------------------------------------
i = i + 1
end--while
repack_tokens()
end
--------------------------------------------------------------------
if opt_details and opt_details > 0 then print() end -- spacing
return stoks, sinfos, stoklns
end
| gpl-2.0 |
O-P-E-N/CC-ROUTER | feeds/luci/contrib/luasrcdiet/lua/optlex.lua | 125 | 31588 | --[[--------------------------------------------------------------------
optlex.lua: does lexer-based optimizations
This file is part of LuaSrcDiet.
Copyright (c) 2008 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- NOTES:
-- * For more lexer-based optimization ideas, see the TODO items or
-- look at technotes.txt.
-- * TODO: general string delimiter conversion optimizer
-- * TODO: (numbers) warn if overly significant digit
----------------------------------------------------------------------]]
local base = _G
local string = require "string"
module "optlex"
local match = string.match
local sub = string.sub
local find = string.find
local rep = string.rep
local print
------------------------------------------------------------------------
-- variables and data structures
------------------------------------------------------------------------
-- error function, can override by setting own function into module
error = base.error
warn = {} -- table for warning flags
local stoks, sinfos, stoklns -- source lists
local is_realtoken = { -- significant (grammar) tokens
TK_KEYWORD = true,
TK_NAME = true,
TK_NUMBER = true,
TK_STRING = true,
TK_LSTRING = true,
TK_OP = true,
TK_EOS = true,
}
local is_faketoken = { -- whitespace (non-grammar) tokens
TK_COMMENT = true,
TK_LCOMMENT = true,
TK_EOL = true,
TK_SPACE = true,
}
local opt_details -- for extra information
------------------------------------------------------------------------
-- true if current token is at the start of a line
-- * skips over deleted tokens via recursion
------------------------------------------------------------------------
local function atlinestart(i)
local tok = stoks[i - 1]
if i <= 1 or tok == "TK_EOL" then
return true
elseif tok == "" then
return atlinestart(i - 1)
end
return false
end
------------------------------------------------------------------------
-- true if current token is at the end of a line
-- * skips over deleted tokens via recursion
------------------------------------------------------------------------
local function atlineend(i)
local tok = stoks[i + 1]
if i >= #stoks or tok == "TK_EOL" or tok == "TK_EOS" then
return true
elseif tok == "" then
return atlineend(i + 1)
end
return false
end
------------------------------------------------------------------------
-- counts comment EOLs inside a long comment
-- * in order to keep line numbering, EOLs need to be reinserted
------------------------------------------------------------------------
local function commenteols(lcomment)
local sep = #match(lcomment, "^%-%-%[=*%[")
local z = sub(lcomment, sep + 1, -(sep - 1)) -- remove delims
local i, c = 1, 0
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
if not p then break end -- if no matches, done
i = p + 1
c = c + 1
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
end
return c
end
------------------------------------------------------------------------
-- compares two tokens (i, j) and returns the whitespace required
-- * important! see technotes.txt for more information
-- * only two grammar/real tokens are being considered
-- * if "", no separation is needed
-- * if " ", then at least one whitespace (or EOL) is required
------------------------------------------------------------------------
local function checkpair(i, j)
local match = match
local t1, t2 = stoks[i], stoks[j]
--------------------------------------------------------------------
if t1 == "TK_STRING" or t1 == "TK_LSTRING" or
t2 == "TK_STRING" or t2 == "TK_LSTRING" then
return ""
--------------------------------------------------------------------
elseif t1 == "TK_OP" or t2 == "TK_OP" then
if (t1 == "TK_OP" and (t2 == "TK_KEYWORD" or t2 == "TK_NAME")) or
(t2 == "TK_OP" and (t1 == "TK_KEYWORD" or t1 == "TK_NAME")) then
return ""
end
if t1 == "TK_OP" and t2 == "TK_OP" then
-- for TK_OP/TK_OP pairs, see notes in technotes.txt
local op, op2 = sinfos[i], sinfos[j]
if (match(op, "^%.%.?$") and match(op2, "^%.")) or
(match(op, "^[~=<>]$") and op2 == "=") or
(op == "[" and (op2 == "[" or op2 == "=")) then
return " "
end
return ""
end
-- "TK_OP" + "TK_NUMBER" case
local op = sinfos[i]
if t2 == "TK_OP" then op = sinfos[j] end
if match(op, "^%.%.?%.?$") then
return " "
end
return ""
--------------------------------------------------------------------
else-- "TK_KEYWORD" | "TK_NAME" | "TK_NUMBER" then
return " "
--------------------------------------------------------------------
end
end
------------------------------------------------------------------------
-- repack tokens, removing deletions caused by optimization process
------------------------------------------------------------------------
local function repack_tokens()
local dtoks, dinfos, dtoklns = {}, {}, {}
local j = 1
for i = 1, #stoks do
local tok = stoks[i]
if tok ~= "" then
dtoks[j], dinfos[j], dtoklns[j] = tok, sinfos[i], stoklns[i]
j = j + 1
end
end
stoks, sinfos, stoklns = dtoks, dinfos, dtoklns
end
------------------------------------------------------------------------
-- number optimization
-- * optimization using string formatting functions is one way of doing
-- this, but here, we consider all cases and handle them separately
-- (possibly an idiotic approach...)
-- * scientific notation being generated is not in canonical form, this
-- may or may not be a bad thing, feedback welcome
-- * note: intermediate portions need to fit into a normal number range
-- * optimizations can be divided based on number patterns:
-- * hexadecimal:
-- (1) no need to remove leading zeros, just skip to (2)
-- (2) convert to integer if size equal or smaller
-- * change if equal size -> lose the 'x' to reduce entropy
-- (3) number is then processed as an integer
-- (4) note: does not make 0[xX] consistent
-- * integer:
-- (1) note: includes anything with trailing ".", ".0", ...
-- (2) remove useless fractional part, if present, e.g. 123.000
-- (3) remove leading zeros, e.g. 000123
-- (4) switch to scientific if shorter, e.g. 123000 -> 123e3
-- * with fraction:
-- (1) split into digits dot digits
-- (2) if no integer portion, take as zero (can omit later)
-- (3) handle degenerate .000 case, after which the fractional part
-- must be non-zero (if zero, it's matched as an integer)
-- (4) remove trailing zeros for fractional portion
-- (5) p.q where p > 0 and q > 0 cannot be shortened any more
-- (6) otherwise p == 0 and the form is .q, e.g. .000123
-- (7) if scientific shorter, convert, e.g. .000123 -> 123e-6
-- * scientific:
-- (1) split into (digits dot digits) [eE] ([+-] digits)
-- (2) if significand has ".", shift it out so it becomes an integer
-- (3) if significand is zero, just use zero
-- (4) remove leading zeros for significand
-- (5) shift out trailing zeros for significand
-- (6) examine exponent and determine which format is best:
-- integer, with fraction, scientific
------------------------------------------------------------------------
local function do_number(i)
local before = sinfos[i] -- 'before'
local z = before -- working representation
local y -- 'after', if better
--------------------------------------------------------------------
if match(z, "^0[xX]") then -- hexadecimal number
local v = base.tostring(base.tonumber(z))
if #v <= #z then
z = v -- change to integer, AND continue
else
return -- no change; stick to hex
end
end
--------------------------------------------------------------------
if match(z, "^%d+%.?0*$") then -- integer or has useless frac
z = match(z, "^(%d+)%.?0*$") -- int portion only
if z + 0 > 0 then
z = match(z, "^0*([1-9]%d*)$") -- remove leading zeros
local v = #match(z, "0*$")
local nv = base.tostring(v)
if v > #nv + 1 then -- scientific is shorter
z = sub(z, 1, #z - v).."e"..nv
end
y = z
else
y = "0" -- basic zero
end
--------------------------------------------------------------------
elseif not match(z, "[eE]") then -- number with fraction part
local p, q = match(z, "^(%d*)%.(%d+)$") -- split
if p == "" then p = 0 end -- int part zero
if q + 0 == 0 and p == 0 then
y = "0" -- degenerate .000 case
else
-- now, q > 0 holds and p is a number
local v = #match(q, "0*$") -- remove trailing zeros
if v > 0 then
q = sub(q, 1, #q - v)
end
-- if p > 0, nothing else we can do to simplify p.q case
if p + 0 > 0 then
y = p.."."..q
else
y = "."..q -- tentative, e.g. .000123
local v = #match(q, "^0*") -- # leading spaces
local w = #q - v -- # significant digits
local nv = base.tostring(#q)
-- e.g. compare 123e-6 versus .000123
if w + 2 + #nv < 1 + #q then
y = sub(q, -w).."e-"..nv
end
end
end
--------------------------------------------------------------------
else -- scientific number
local sig, ex = match(z, "^([^eE]+)[eE]([%+%-]?%d+)$")
ex = base.tonumber(ex)
-- if got ".", shift out fractional portion of significand
local p, q = match(sig, "^(%d*)%.(%d*)$")
if p then
ex = ex - #q
sig = p..q
end
if sig + 0 == 0 then
y = "0" -- basic zero
else
local v = #match(sig, "^0*") -- remove leading zeros
sig = sub(sig, v + 1)
v = #match(sig, "0*$") -- shift out trailing zeros
if v > 0 then
sig = sub(sig, 1, #sig - v)
ex = ex + v
end
-- examine exponent and determine which format is best
local nex = base.tostring(ex)
if ex == 0 then -- it's just an integer
y = sig
elseif ex > 0 and (ex <= 1 + #nex) then -- a number
y = sig..rep("0", ex)
elseif ex < 0 and (ex >= -#sig) then -- fraction, e.g. .123
v = #sig + ex
y = sub(sig, 1, v).."."..sub(sig, v + 1)
elseif ex < 0 and (#nex >= -ex - #sig) then
-- e.g. compare 1234e-5 versus .01234
-- gives: #sig + 1 + #nex >= 1 + (-ex - #sig) + #sig
-- -> #nex >= -ex - #sig
v = -ex - #sig
y = "."..rep("0", v)..sig
else -- non-canonical scientific representation
y = sig.."e"..ex
end
end--if sig
end
--------------------------------------------------------------------
if y and y ~= sinfos[i] then
if opt_details then
print("<number> (line "..stoklns[i]..") "..sinfos[i].." -> "..y)
opt_details = opt_details + 1
end
sinfos[i] = y
end
end
------------------------------------------------------------------------
-- string optimization
-- * note: works on well-formed strings only!
-- * optimizations on characters can be summarized as follows:
-- \a\b\f\n\r\t\v -- no change
-- \\ -- no change
-- \"\' -- depends on delim, other can remove \
-- \[\] -- remove \
-- \<char> -- general escape, remove \
-- \<eol> -- normalize the EOL only
-- \ddd -- if \a\b\f\n\r\t\v, change to latter
-- if other < ascii 32, keep ddd but zap leading zeros
-- if >= ascii 32, translate it into the literal, then also
-- do escapes for \\,\",\' cases
-- <other> -- no change
-- * switch delimiters if string becomes shorter
------------------------------------------------------------------------
local function do_string(I)
local info = sinfos[I]
local delim = sub(info, 1, 1) -- delimiter used
local ndelim = (delim == "'") and '"' or "'" -- opposite " <-> '
local z = sub(info, 2, -2) -- actual string
local i = 1
local c_delim, c_ndelim = 0, 0 -- "/' counts
--------------------------------------------------------------------
while i <= #z do
local c = sub(z, i, i)
----------------------------------------------------------------
if c == "\\" then -- escaped stuff
local j = i + 1
local d = sub(z, j, j)
local p = find("abfnrtv\\\n\r\"\'0123456789", d, 1, true)
------------------------------------------------------------
if not p then -- \<char> -- remove \
z = sub(z, 1, i - 1)..sub(z, j)
i = i + 1
------------------------------------------------------------
elseif p <= 8 then -- \a\b\f\n\r\t\v\\
i = i + 2 -- no change
------------------------------------------------------------
elseif p <= 10 then -- \<eol> -- normalize EOL
local eol = sub(z, j, j + 1)
if eol == "\r\n" or eol == "\n\r" then
z = sub(z, 1, i).."\n"..sub(z, j + 2)
elseif p == 10 then -- \r case
z = sub(z, 1, i).."\n"..sub(z, j + 1)
end
i = i + 2
------------------------------------------------------------
elseif p <= 12 then -- \"\' -- remove \ for ndelim
if d == delim then
c_delim = c_delim + 1
i = i + 2
else
c_ndelim = c_ndelim + 1
z = sub(z, 1, i - 1)..sub(z, j)
i = i + 1
end
------------------------------------------------------------
else -- \ddd -- various steps
local s = match(z, "^(%d%d?%d?)", j)
j = i + 1 + #s -- skip to location
local cv = s + 0
local cc = string.char(cv)
local p = find("\a\b\f\n\r\t\v", cc, 1, true)
if p then -- special escapes
s = "\\"..sub("abfnrtv", p, p)
elseif cv < 32 then -- normalized \ddd
s = "\\"..cv
elseif cc == delim then -- \<delim>
s = "\\"..cc
c_delim = c_delim + 1
elseif cc == "\\" then -- \\
s = "\\\\"
else -- literal character
s = cc
if cc == ndelim then
c_ndelim = c_ndelim + 1
end
end
z = sub(z, 1, i - 1)..s..sub(z, j)
i = i + #s
------------------------------------------------------------
end--if p
----------------------------------------------------------------
else-- c ~= "\\" -- <other> -- no change
i = i + 1
if c == ndelim then -- count ndelim, for switching delimiters
c_ndelim = c_ndelim + 1
end
----------------------------------------------------------------
end--if c
end--while
--------------------------------------------------------------------
-- switching delimiters, a long-winded derivation:
-- (1) delim takes 2+2*c_delim bytes, ndelim takes c_ndelim bytes
-- (2) delim becomes c_delim bytes, ndelim becomes 2+2*c_ndelim bytes
-- simplifying the condition (1)>(2) --> c_delim > c_ndelim
if c_delim > c_ndelim then
i = 1
while i <= #z do
local p, q, r = find(z, "([\'\"])", i)
if not p then break end
if r == delim then -- \<delim> -> <delim>
z = sub(z, 1, p - 2)..sub(z, p)
i = p
else-- r == ndelim -- <ndelim> -> \<ndelim>
z = sub(z, 1, p - 1).."\\"..sub(z, p)
i = p + 2
end
end--while
delim = ndelim -- actually change delimiters
end
--------------------------------------------------------------------
z = delim..z..delim
if z ~= sinfos[I] then
if opt_details then
print("<string> (line "..stoklns[I]..") "..sinfos[I].." -> "..z)
opt_details = opt_details + 1
end
sinfos[I] = z
end
end
------------------------------------------------------------------------
-- long string optimization
-- * note: warning flagged if trailing whitespace found, not trimmed
-- * remove first optional newline
-- * normalize embedded newlines
-- * reduce '=' separators in delimiters if possible
------------------------------------------------------------------------
local function do_lstring(I)
local info = sinfos[I]
local delim1 = match(info, "^%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep + 1)) -- lstring without delims
local y = ""
local i = 1
--------------------------------------------------------------------
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
-- deal with a single line
local ln
if not p then
ln = sub(z, i)
elseif p >= i then
ln = sub(z, i, p - 1)
end
if ln ~= "" then
-- flag a warning if there are trailing spaces, won't optimize!
if match(ln, "%s+$") then
warn.lstring = "trailing whitespace in long string near line "..stoklns[I]
end
y = y..ln
end
if not p then -- done if no more EOLs
break
end
-- deal with line endings, normalize them
i = p + 1
if p then
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
-- skip first newline, which can be safely deleted
if not(i == 1 and i == p) then
y = y.."\n"
end
end
end--while
--------------------------------------------------------------------
-- handle possible deletion of one or more '=' separators
if sep >= 3 then
local chk, okay = sep - 1
-- loop to test ending delimiter with less of '=' down to zero
while chk >= 2 do
local delim = "%]"..rep("=", chk - 2).."%]"
if not match(y, delim) then okay = chk end
chk = chk - 1
end
if okay then -- change delimiters
sep = rep("=", okay - 2)
delim1, delim2 = "["..sep.."[", "]"..sep.."]"
end
end
--------------------------------------------------------------------
sinfos[I] = delim1..y..delim2
end
------------------------------------------------------------------------
-- long comment optimization
-- * note: does not remove first optional newline
-- * trim trailing whitespace
-- * normalize embedded newlines
-- * reduce '=' separators in delimiters if possible
------------------------------------------------------------------------
local function do_lcomment(I)
local info = sinfos[I]
local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims
local y = ""
local i = 1
--------------------------------------------------------------------
while true do
local p, q, r, s = find(z, "([\r\n])([\r\n]?)", i)
-- deal with a single line, extract and check trailing whitespace
local ln
if not p then
ln = sub(z, i)
elseif p >= i then
ln = sub(z, i, p - 1)
end
if ln ~= "" then
-- trim trailing whitespace if non-empty line
local ws = match(ln, "%s*$")
if #ws > 0 then ln = sub(ln, 1, -(ws + 1)) end
y = y..ln
end
if not p then -- done if no more EOLs
break
end
-- deal with line endings, normalize them
i = p + 1
if p then
if #s > 0 and r ~= s then -- skip CRLF or LFCR
i = i + 1
end
y = y.."\n"
end
end--while
--------------------------------------------------------------------
-- handle possible deletion of one or more '=' separators
sep = sep - 2
if sep >= 3 then
local chk, okay = sep - 1
-- loop to test ending delimiter with less of '=' down to zero
while chk >= 2 do
local delim = "%]"..rep("=", chk - 2).."%]"
if not match(y, delim) then okay = chk end
chk = chk - 1
end
if okay then -- change delimiters
sep = rep("=", okay - 2)
delim1, delim2 = "--["..sep.."[", "]"..sep.."]"
end
end
--------------------------------------------------------------------
sinfos[I] = delim1..y..delim2
end
------------------------------------------------------------------------
-- short comment optimization
-- * trim trailing whitespace
------------------------------------------------------------------------
local function do_comment(i)
local info = sinfos[i]
local ws = match(info, "%s*$") -- just look from end of string
if #ws > 0 then
info = sub(info, 1, -(ws + 1)) -- trim trailing whitespace
end
sinfos[i] = info
end
------------------------------------------------------------------------
-- returns true if string found in long comment
-- * this is a feature to keep copyright or license texts
------------------------------------------------------------------------
local function keep_lcomment(opt_keep, info)
if not opt_keep then return false end -- option not set
local delim1 = match(info, "^%-%-%[=*%[") -- cut out delimiters
local sep = #delim1
local delim2 = sub(info, -sep, -1)
local z = sub(info, sep + 1, -(sep - 1)) -- comment without delims
if find(z, opt_keep, 1, true) then -- try to match
return true
end
end
------------------------------------------------------------------------
-- main entry point
-- * currently, lexer processing has 2 passes
-- * processing is done on a line-oriented basis, which is easier to
-- grok due to the next point...
-- * since there are various options that can be enabled or disabled,
-- processing is a little messy or convoluted
------------------------------------------------------------------------
function optimize(option, toklist, semlist, toklnlist)
--------------------------------------------------------------------
-- set option flags
--------------------------------------------------------------------
local opt_comments = option["opt-comments"]
local opt_whitespace = option["opt-whitespace"]
local opt_emptylines = option["opt-emptylines"]
local opt_eols = option["opt-eols"]
local opt_strings = option["opt-strings"]
local opt_numbers = option["opt-numbers"]
local opt_keep = option.KEEP
opt_details = option.DETAILS and 0 -- upvalues for details display
print = print or base.print
if opt_eols then -- forced settings, otherwise won't work properly
opt_comments = true
opt_whitespace = true
opt_emptylines = true
end
--------------------------------------------------------------------
-- variable initialization
--------------------------------------------------------------------
stoks, sinfos, stoklns -- set source lists
= toklist, semlist, toklnlist
local i = 1 -- token position
local tok, info -- current token
local prev -- position of last grammar token
-- on same line (for TK_SPACE stuff)
--------------------------------------------------------------------
-- changes a token, info pair
--------------------------------------------------------------------
local function settoken(tok, info, I)
I = I or i
stoks[I] = tok or ""
sinfos[I] = info or ""
end
--------------------------------------------------------------------
-- processing loop (PASS 1)
--------------------------------------------------------------------
while true do
tok, info = stoks[i], sinfos[i]
----------------------------------------------------------------
local atstart = atlinestart(i) -- set line begin flag
if atstart then prev = nil end
----------------------------------------------------------------
if tok == "TK_EOS" then -- end of stream/pass
break
----------------------------------------------------------------
elseif tok == "TK_KEYWORD" or -- keywords, identifiers,
tok == "TK_NAME" or -- operators
tok == "TK_OP" then
-- TK_KEYWORD and TK_OP can't be optimized without a big
-- optimization framework; it would be more of an optimizing
-- compiler, not a source code compressor
-- TK_NAME that are locals needs parser to analyze/optimize
prev = i
----------------------------------------------------------------
elseif tok == "TK_NUMBER" then -- numbers
if opt_numbers then
do_number(i) -- optimize
end
prev = i
----------------------------------------------------------------
elseif tok == "TK_STRING" or -- strings, long strings
tok == "TK_LSTRING" then
if opt_strings then
if tok == "TK_STRING" then
do_string(i) -- optimize
else
do_lstring(i) -- optimize
end
end
prev = i
----------------------------------------------------------------
elseif tok == "TK_COMMENT" then -- short comments
if opt_comments then
if i == 1 and sub(info, 1, 1) == "#" then
-- keep shbang comment, trim whitespace
do_comment(i)
else
-- safe to delete, as a TK_EOL (or TK_EOS) always follows
settoken() -- remove entirely
end
elseif opt_whitespace then -- trim whitespace only
do_comment(i)
end
----------------------------------------------------------------
elseif tok == "TK_LCOMMENT" then -- long comments
if keep_lcomment(opt_keep, info) then
------------------------------------------------------------
-- if --keep, we keep a long comment if <msg> is found;
-- this is a feature to keep copyright or license texts
if opt_whitespace then -- trim whitespace only
do_lcomment(i)
end
prev = i
elseif opt_comments then
local eols = commenteols(info)
------------------------------------------------------------
-- prepare opt_emptylines case first, if a disposable token
-- follows, current one is safe to dump, else keep a space;
-- it is implied that the operation is safe for '-', because
-- current is a TK_LCOMMENT, and must be separate from a '-'
if is_faketoken[stoks[i + 1]] then
settoken() -- remove entirely
tok = ""
else
settoken("TK_SPACE", " ")
end
------------------------------------------------------------
-- if there are embedded EOLs to keep and opt_emptylines is
-- disabled, then switch the token into one or more EOLs
if not opt_emptylines and eols > 0 then
settoken("TK_EOL", rep("\n", eols))
end
------------------------------------------------------------
-- if optimizing whitespaces, force reinterpretation of the
-- token to give a chance for the space to be optimized away
if opt_whitespace and tok ~= "" then
i = i - 1 -- to reinterpret
end
------------------------------------------------------------
else -- disabled case
if opt_whitespace then -- trim whitespace only
do_lcomment(i)
end
prev = i
end
----------------------------------------------------------------
elseif tok == "TK_EOL" then -- line endings
if atstart and opt_emptylines then
settoken() -- remove entirely
elseif info == "\r\n" or info == "\n\r" then
-- normalize the rest of the EOLs for CRLF/LFCR only
-- (note that TK_LCOMMENT can change into several EOLs)
settoken("TK_EOL", "\n")
end
----------------------------------------------------------------
elseif tok == "TK_SPACE" then -- whitespace
if opt_whitespace then
if atstart or atlineend(i) then
-- delete leading and trailing whitespace
settoken() -- remove entirely
else
------------------------------------------------------------
-- at this point, since leading whitespace have been removed,
-- there should be a either a real token or a TK_LCOMMENT
-- prior to hitting this whitespace; the TK_LCOMMENT case
-- only happens if opt_comments is disabled; so prev ~= nil
local ptok = stoks[prev]
if ptok == "TK_LCOMMENT" then
-- previous TK_LCOMMENT can abut with anything
settoken() -- remove entirely
else
-- prev must be a grammar token; consecutive TK_SPACE
-- tokens is impossible when optimizing whitespace
local ntok = stoks[i + 1]
if is_faketoken[ntok] then
-- handle special case where a '-' cannot abut with
-- either a short comment or a long comment
if (ntok == "TK_COMMENT" or ntok == "TK_LCOMMENT") and
ptok == "TK_OP" and sinfos[prev] == "-" then
-- keep token
else
settoken() -- remove entirely
end
else--is_realtoken
-- check a pair of grammar tokens, if can abut, then
-- delete space token entirely, otherwise keep one space
local s = checkpair(prev, i + 1)
if s == "" then
settoken() -- remove entirely
else
settoken("TK_SPACE", " ")
end
end
end
------------------------------------------------------------
end
end
----------------------------------------------------------------
else
error("unidentified token encountered")
end
----------------------------------------------------------------
i = i + 1
end--while
repack_tokens()
--------------------------------------------------------------------
-- processing loop (PASS 2)
--------------------------------------------------------------------
if opt_eols then
i = 1
-- aggressive EOL removal only works with most non-grammar tokens
-- optimized away because it is a rather simple scheme -- basically
-- it just checks 'real' token pairs around EOLs
if stoks[1] == "TK_COMMENT" then
-- first comment still existing must be shbang, skip whole line
i = 3
end
while true do
tok, info = stoks[i], sinfos[i]
--------------------------------------------------------------
if tok == "TK_EOS" then -- end of stream/pass
break
--------------------------------------------------------------
elseif tok == "TK_EOL" then -- consider each TK_EOL
local t1, t2 = stoks[i - 1], stoks[i + 1]
if is_realtoken[t1] and is_realtoken[t2] then -- sanity check
local s = checkpair(i - 1, i + 1)
if s == "" then
settoken() -- remove entirely
end
end
end--if tok
--------------------------------------------------------------
i = i + 1
end--while
repack_tokens()
end
--------------------------------------------------------------------
if opt_details and opt_details > 0 then print() end -- spacing
return stoks, sinfos, stoklns
end
| gpl-2.0 |
mishin/Algorithm-Implementations | Breadth_First_Search/Lua/Yonaba/bfs.lua | 26 | 3153 | -- Generic Breadth-First search algorithm implementation
-- See : http://en.wikipedia.org/wiki/Breadth-first_search
-- Notes : this is a generic implementation of Breadth-First search algorithm.
-- It is devised to be used on any type of graph (point-graph, tile-graph,
-- or whatever. It expects to be initialized with a handler, which acts as
-- an interface between the search algorithm and the search space.
-- This implementation uses a FIFO (First In First Out) queue, which can be
-- easily represented via a simple Lua array (see fifo.lua).
-- The BFS class expects a handler to be initialized. Roughly said, the handler
-- is an interface between your search space and the generic search algorithm.
-- This ensures flexibility, so that the generic algorithm can be adapted to
-- search on any kind of space.
-- The passed-in handler should implement those functions.
-- handler.getNode(...) -> returns a Node (instance of node.lua)
-- handler.getNeighbors(n) -> returns an array of all nodes that can be reached
-- via node n (also called successors of node n)
-- The generic Node class provided (see node.lua) should also be implemented
-- through the handler. Basically, it should describe how nodes are labelled
-- and tested for equality for a custom search space.
-- The following functions should be implemented:
-- function Node:initialize(...) -> creates a Node with custom attributes
-- function Node:isEqualTo(n) -> returns if self is equal to node n
-- function Node:toString() -> returns a unique string representation of
-- the node, for debug purposes
-- See custom handlers for reference (*_hander.lua).
-- Dependencies
local class = require 'utils.class'
local fifo = require 'utils.fifo'
-- Clears nodes data between consecutive path requests.
local function resetForNextSearch(bfs)
for node in pairs(bfs.visited) do
node.parent, node.visited = nil, nil
end
bfs.queue:clear()
bfs.visited = {}
end
-- Builds and returns the path to the goal node
local function backtrace(node)
local path = {}
repeat
table.insert(path, 1, node)
node = node.parent
until not node
return path
end
-- Initializes Breadth-Fist search with a custom handler
local BFS = class()
function BFS:initialize(handler)
self.handler = handler
self.queue = fifo()
self.visited = {}
end
-- Returns the path between start and goal locations
-- start : a Node representing the start location
-- goal : a Node representing the target location
-- returns : an array of nodes
function BFS:findPath(start, goal)
resetForNextSearch(self)
start.visited = true
self.queue:push(start)
self.visited[start] = true
while not self.queue:isEmpty() do
local node = self.queue:pop()
if node == goal then return backtrace(node) end
local neighbors = self.handler.getNeighbors(node)
for _, neighbor in ipairs(neighbors) do
if not neighbor.visited then
neighbor.visited = true
neighbor.parent = node
self.queue:push(neighbor)
self.visited[neighbor] = true
end
end
end
end
return BFS
| mit |
starlightknight/darkstar | scripts/zones/The_Garden_of_RuHmet/mobs/Ixaern_DRK.lua | 9 | 2524 | -----------------------------------
-- Area: The Garden of Ru'Hmet
-- NM: Ix'aern DRK
-- !pos -240 5.00 440 35
-- !pos -280 5.00 240 35
-- !pos -560 5.00 239 35
-- !pos -600 5.00 440 35
-----------------------------------
local ID = require("scripts/zones/The_Garden_of_RuHmet/IDs");
mixins = {require("scripts/mixins/job_special")}
require("scripts/globals/monstertpmoves");
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
function onMobInitialize(mob)
mob:addListener("DEATH", "AERN_DEATH", function(mob)
local timesReraised = mob:getLocalVar("AERN_RERAISES");
if(math.random (1,10) < 10) then
-- reraise
local target = mob:getTarget();
local targetid = 0;
if target then
targetid = target:getShortID();
end;
mob:setMobMod(dsp.mobMod.NO_DROPS, 1);
mob:timer(9000, function(mob)
mob:setHP(mob:getMaxHP());
mob:AnimationSub(3);
mob:resetAI();
mob:stun(3000);
local new_target = mob:getEntity(targetid);
if new_target and mob:checkDistance(new_target) < 40 then
mob:updateClaim(new_target);
mob:updateEnmity(new_target);
end;
mob:triggerListener("AERN_RERAISE", mob, timesReraised)
end)
else
-- death
mob:setMobMod(dsp.mobMod.NO_DROPS, 0);
DespawnMob(QnAernA);
DespawnMob(QnAernB);
end
end)
mob:addListener("AERN_RERAISE", "IX_DRK_RERAISE", function(mob, timesReraised)
mob:setLocalVar("AERN_RERAISES", timesReraised + 1);
mob:timer(5000, function(mob)
mob:AnimationSub(1);
end)
end)
end;
function onMobSpawn(mob)
mob:AnimationSub(1);
dsp.mix.jobSpecial.config(mob, {
specials =
{
{
id = dsp.jsa.BLOOD_WEAPON_IXDRK,
hpp = math.random(90, 95),
cooldown = 120,
endCode = function(mob)
mob:SetMagicCastingEnabled(false)
mob:timer(30000, function(mob)
mob:SetMagicCastingEnabled(true)
end)
end,
}
}
})
end;
function onMobDeath(mob, player, isKiller)
end;
function onMobDespawn(mob)
mob:setLocalVar("AERN_RERAISES",0);
end; | gpl-3.0 |
alomina007/asli | plugins/weather.lua | 1 | 1899 |
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
local url = BASE_URL
url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b'
url = url..'&units=metric'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'دمای شهر '..city..'\n\n🌡 دمای کنونی هوا : '..weather.main.temp..' C\n\nفشار هوا :'..weather.main.pressure..'\nرطوبت هوا : '..weather.main.humidity..' %\n\n🔻حداقل دمای امروز : '..weather.main.temp_min..'\n🔺حداکثر دمای امروز : '..weather.main.temp_min..'\n\n🌬 سرعت باد : '..weather.wind.speed..'\nدرجه وزش باد : '..weather.wind.deg..'\n\n🔸طول جغرافیایی : '..weather.coord.lon..'\n🔹عرض جغرافیایی : '..weather.coord.lat
local conditions = 'شرایط فعلی آب و هوا : '
if weather.weather[1].main == 'Clear' then
conditions = conditions .. 'آفتابی ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. 'ابری ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. 'بارانی ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. 'طوفانی 🌪🌪🌪🌪'
elseif weather.weather[1].main == 'Mist' then
conditions = conditions .. 'مه 🌫'
end
return temp .. '\n\n' .. conditions..'\n\n@➡Alominateam⬅'
end
local function run(msg, matches)
city = matches[1]
local wtext = get_weather(city)
if not wtext then
wtext = 'مکان وارد شده صحیح نیست'
end
return wtext
end
return {
patterns = {
"^[/#!]weather (.*)$",
},
run = run
}
| gpl-2.0 |
starlightknight/darkstar | scripts/zones/Throne_Room/IDs.lua | 8 | 1338 | -----------------------------------
-- Area: Throne_Room
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.THRONE_ROOM] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
CONQUEST_BASE = 7049, -- Tallying conquest results...
NO_HIDE_AWAY = 7698, -- I have not been hiding away from my troubles!
FEEL_MY_PAIN = 7699, -- Feel my twenty years of pain!
YOUR_ANSWER = 7700, -- Is that your answer!?
RETURN_TO_THE_DARKNESS = 7701, -- Return with your soul to the darkness you came from!
CANT_UNDERSTAND = 7702, -- You--a man who has never lived bound by the chains of his country--how can you understand my pain!?
BLADE_ANSWER = 7703, -- Let my blade be the answer!
},
mob =
{
SHADOW_LORD_STAGE_2_OFFSET = 17453060,
ZEID_BCNM_OFFSET = 17453064,
},
npc =
{
},
}
return zones[dsp.zone.THRONE_ROOM] | gpl-3.0 |
gedads/Neodynamis | scripts/globals/abilities/haste_samba.lua | 4 | 1434 | -----------------------------------
-- Ability: Haste Samba
-- Inflicts the next target you strike with Haste daze, increasing the attack speed of all those engaged in battle with it.
-- Obtained: Dancer Level 45
-- TP Cost: 35%
-- Recast Time: 1:00
-- Duration: 1:30
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/msg");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then
return msgBasic.UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 350) then
return msgBasic.NOT_ENOUGH_TP,0;
else
return 0,0;
end;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(350);
end;
local duration = 120 + player:getMod(MOD_SAMBA_DURATION);
duration = duration * (100 + player:getMod(MOD_SAMBA_PDURATION))/100;
player:delStatusEffect(EFFECT_DRAIN_SAMBA);
player:delStatusEffect(EFFECT_ASPIR_SAMBA);
player:addStatusEffect(EFFECT_HASTE_SAMBA,player:getMerit(MERIT_HASTE_SAMBA_EFFECT)+52,0,duration);
end;
| gpl-3.0 |
dismantl/commotion-apps | lua/commotion_helpers.lua | 1 | 1809 | function DIE(str)
luci.http.status(500, "Internal Server Error")
luci.http.write(str)
luci.http.close()
end
function uci_encode(str)
if (str) then
str = string.gsub (str, "([^%w])", function(c) return '_' .. tostring(string.byte(c)) end)
end
return str
end
function html_encode(str)
return string.gsub(str,"[<>&\n\r\"]",function(c) return html_replacements[c] or c end)
end
function url_encode(str)
return string.gsub(str,"[<>%s]",function(c) return url_replacements[c] or c end)
end
function printf(tmpl,t)
return (tmpl:gsub('($%b{})', function(w) return t[w:sub(3, -2)] or w end))
end
function log(msg)
if (type(msg) == "table") then
for key, val in pairs(msg) do
log('{')
log(key)
log(':')
log(val)
log('}')
end
else
luci.sys.exec("logger -t luci \"" .. tostring(msg) .. '"')
end
end
function is_ip4addr(str)
i,j, _1, _2, _3, _4 = string.find(str, '^(%d%d?%d?)\.(%d%d?%d?)\.(%d%d?%d?)\.(%d%d?%d?)$')
if (i and
(tonumber(_1) >= 0 and tonumber(_1) <= 255) and
(tonumber(_2) >= 0 and tonumber(_2) <= 255) and
(tonumber(_3) >= 0 and tonumber(_3) <= 255) and
(tonumber(_4) >= 0 and tonumber(_4) <= 255)) then
return true
end
return false
end
function is_uint(str)
return str:find("^%d+$")
end
function is_hex(str)
return str:find("^%x+$")
end
function is_port(str)
return is_uint(str) and tonumber(str) >= 0 and tonumber(str) <= 65535
end
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
html_replacements = {
["<"] = "<",
[">"] = ">",
["&"] = "&",
["\n"] = " ",
["\r"] = " ",
["\""] = """
}
url_replacements = {
["<"] = "%3C",
[">"] = "%3E",
[" "] = "%20",
['"'] = "%22"
} | gpl-3.0 |
XanDDemoX/ESOFasterTravel | FasterTravel/WayshrineData.lua | 1 | 17379 |
local Utils = FasterTravel.Utils
local Data = {}
-- Hardcoded lookup of all fast travel nodes in all zones =( But at least it is automatically generated by WayshrineDataGenerator =D
local _zoneNodeLookup = {
[-2147483648] =
{
},
[353] =
{
[1] =
{
["nodeIndex"] = 217,
["poiIndex"] = 45,
},
[2] =
{
["nodeIndex"] = 219,
["poiIndex"] = 46,
},
[3] =
{
["nodeIndex"] = 218,
["poiIndex"] = 47,
},
[4] =
{
["nodeIndex"] = 220,
["poiIndex"] = 50,
},
[5] =
{
["nodeIndex"] = 230,
["poiIndex"] = 60,
},
[6] =
{
["nodeIndex"] = 231,
["poiIndex"] = 61,
},
[7] =
{
["nodeIndex"] = 229,
["poiIndex"] = 62,
},
[8] =
{
["nodeIndex"] = 225,
["poiIndex"] = 63,
},
[9] =
{
["nodeIndex"] = 226,
["poiIndex"] = 64,
},
[10] =
{
["nodeIndex"] = 227,
["poiIndex"] = 65,
},
[11] =
{
["nodeIndex"] = 232,
["poiIndex"] = 85,
},
[12] =
{
["nodeIndex"] = 233,
["poiIndex"] = 86,
},
[13] =
{
["nodeIndex"] = 234,
["poiIndex"] = 87,
},
[14] =
{
["nodeIndex"] = 235,
["poiIndex"] = 88,
},
},
[2] =
{
[1] =
{
["nodeIndex"] = 1,
["poiIndex"] = 26,
},
[2] =
{
["nodeIndex"] = 2,
["poiIndex"] = 27,
},
[3] =
{
["nodeIndex"] = 3,
["poiIndex"] = 28,
},
[4] =
{
["nodeIndex"] = 4,
["poiIndex"] = 29,
},
[5] =
{
["nodeIndex"] = 5,
["poiIndex"] = 30,
},
[6] =
{
["nodeIndex"] = 6,
["poiIndex"] = 31,
},
[7] =
{
["nodeIndex"] = 7,
["poiIndex"] = 32,
},
[8] =
{
["nodeIndex"] = 8,
["poiIndex"] = 33,
},
[9] =
{
["nodeIndex"] = 20,
["poiIndex"] = 34,
},
[10] =
{
["nodeIndex"] = 62,
["poiIndex"] = 35,
},
[11] =
{
["nodeIndex"] = 64,
["poiIndex"] = 36,
},
[12] =
{
["nodeIndex"] = 193,
["poiIndex"] = 42,
},
[13] =
{
["nodeIndex"] = 210,
["poiIndex"] = 46,
},
[14] =
{
["nodeIndex"] = 216,
["poiIndex"] = 63,
},
},
[99] =
{
[1] =
{
["nodeIndex"] = 215,
["poiIndex"] = 1,
},
},
[5] =
{
[1] =
{
["nodeIndex"] = 190,
["poiIndex"] = 17,
},
[2] =
{
["nodeIndex"] = 9,
["poiIndex"] = 18,
},
[3] =
{
["nodeIndex"] = 10,
["poiIndex"] = 19,
},
[4] =
{
["nodeIndex"] = 11,
["poiIndex"] = 20,
},
[5] =
{
["nodeIndex"] = 12,
["poiIndex"] = 22,
},
[6] =
{
["nodeIndex"] = 13,
["poiIndex"] = 23,
},
[7] =
{
["nodeIndex"] = 82,
["poiIndex"] = 24,
},
[8] =
{
["nodeIndex"] = 83,
["poiIndex"] = 25,
},
[9] =
{
["nodeIndex"] = 84,
["poiIndex"] = 26,
},
[10] =
{
["nodeIndex"] = 55,
["poiIndex"] = 27,
},
[11] =
{
["nodeIndex"] = 86,
["poiIndex"] = 37,
},
[12] =
{
["nodeIndex"] = 208,
["poiIndex"] = 41,
},
},
[37] =
{
[1] =
{
["nodeIndex"] = 170,
["poiIndex"] = 52,
},
[2] =
{
["nodeIndex"] = 199,
["poiIndex"] = 53,
},
[3] =
{
["nodeIndex"] = 200,
["poiIndex"] = 54,
},
[4] =
{
["nodeIndex"] = 201,
["poiIndex"] = 55,
},
[5] =
{
["nodeIndex"] = 202,
["poiIndex"] = 56,
},
[6] =
{
["nodeIndex"] = 203,
["poiIndex"] = 57,
},
},
[294] =
{
[1] =
{
["nodeIndex"] = 141,
["poiIndex"] = 5,
},
[2] =
{
["nodeIndex"] = 142,
["poiIndex"] = 6,
},
},
[9] =
{
[1] =
{
["nodeIndex"] = 65,
["poiIndex"] = 20,
},
[2] =
{
["nodeIndex"] = 66,
["poiIndex"] = 21,
},
[3] =
{
["nodeIndex"] = 41,
["poiIndex"] = 22,
},
[4] =
{
["nodeIndex"] = 67,
["poiIndex"] = 23,
},
[5] =
{
["nodeIndex"] = 68,
["poiIndex"] = 24,
},
[6] =
{
["nodeIndex"] = 71,
["poiIndex"] = 25,
},
[7] =
{
["nodeIndex"] = 72,
["poiIndex"] = 26,
},
[8] =
{
["nodeIndex"] = 73,
["poiIndex"] = 27,
},
[9] =
{
["nodeIndex"] = 74,
["poiIndex"] = 28,
},
[10] =
{
["nodeIndex"] = 75,
["poiIndex"] = 29,
},
[11] =
{
["nodeIndex"] = 76,
["poiIndex"] = 30,
},
[12] =
{
["nodeIndex"] = 77,
["poiIndex"] = 31,
},
[13] =
{
["nodeIndex"] = 98,
["poiIndex"] = 34,
},
[14] =
{
["nodeIndex"] = 69,
["poiIndex"] = 39,
},
[15] =
{
["nodeIndex"] = 108,
["poiIndex"] = 40,
},
[16] =
{
["nodeIndex"] = 212,
["poiIndex"] = 46,
},
},
[10] =
{
[1] =
{
["nodeIndex"] = 198,
["poiIndex"] = 21,
},
[2] =
{
["nodeIndex"] = 24,
["poiIndex"] = 22,
},
[3] =
{
["nodeIndex"] = 25,
["poiIndex"] = 23,
},
[4] =
{
["nodeIndex"] = 26,
["poiIndex"] = 24,
},
[5] =
{
["nodeIndex"] = 27,
["poiIndex"] = 25,
},
[6] =
{
["nodeIndex"] = 28,
["poiIndex"] = 26,
},
[7] =
{
["nodeIndex"] = 29,
["poiIndex"] = 27,
},
[8] =
{
["nodeIndex"] = 30,
["poiIndex"] = 28,
},
[9] =
{
["nodeIndex"] = 32,
["poiIndex"] = 29,
},
[10] =
{
["nodeIndex"] = 79,
["poiIndex"] = 30,
},
[11] =
{
["nodeIndex"] = 80,
["poiIndex"] = 31,
},
[12] =
{
["nodeIndex"] = 81,
["poiIndex"] = 32,
},
[13] =
{
["nodeIndex"] = 205,
["poiIndex"] = 43,
},
},
[11] =
{
[1] =
{
["nodeIndex"] = 101,
["poiIndex"] = 2,
},
[2] =
{
["nodeIndex"] = 99,
["poiIndex"] = 3,
},
[3] =
{
["nodeIndex"] = 102,
["poiIndex"] = 4,
},
[4] =
{
["nodeIndex"] = 100,
["poiIndex"] = 5,
},
[5] =
{
["nodeIndex"] = 104,
["poiIndex"] = 6,
},
[6] =
{
["nodeIndex"] = 105,
["poiIndex"] = 7,
},
[7] =
{
["nodeIndex"] = 106,
["poiIndex"] = 8,
},
[8] =
{
["nodeIndex"] = 103,
["poiIndex"] = 9,
},
[9] =
{
["nodeIndex"] = 107,
["poiIndex"] = 10,
},
[10] =
{
["nodeIndex"] = 188,
["poiIndex"] = 41,
},
},
[109] =
{
[1] =
{
["nodeIndex"] = 172,
["poiIndex"] = 3,
},
},
[110] =
{
[1] =
{
["nodeIndex"] = 173,
["poiIndex"] = 2,
},
[2] =
{
["nodeIndex"] = 125,
["poiIndex"] = 3,
},
[3] =
{
["nodeIndex"] = 126,
["poiIndex"] = 4,
},
},
[15] =
{
[1] =
{
["nodeIndex"] = 87,
["poiIndex"] = 14,
},
[2] =
{
["nodeIndex"] = 88,
["poiIndex"] = 15,
},
[3] =
{
["nodeIndex"] = 89,
["poiIndex"] = 16,
},
[4] =
{
["nodeIndex"] = 90,
["poiIndex"] = 17,
},
[5] =
{
["nodeIndex"] = 91,
["poiIndex"] = 18,
},
[6] =
{
["nodeIndex"] = 92,
["poiIndex"] = 19,
},
[7] =
{
["nodeIndex"] = 93,
["poiIndex"] = 20,
},
[8] =
{
["nodeIndex"] = 94,
["poiIndex"] = 21,
},
[9] =
{
["nodeIndex"] = 95,
["poiIndex"] = 22,
},
[10] =
{
["nodeIndex"] = 96,
["poiIndex"] = 23,
},
[11] =
{
["nodeIndex"] = 97,
["poiIndex"] = 24,
},
[12] =
{
["nodeIndex"] = 195,
["poiIndex"] = 41,
},
},
[16] =
{
[1] =
{
["nodeIndex"] = 109,
["poiIndex"] = 14,
},
[2] =
{
["nodeIndex"] = 110,
["poiIndex"] = 15,
},
[3] =
{
["nodeIndex"] = 111,
["poiIndex"] = 16,
},
[4] =
{
["nodeIndex"] = 112,
["poiIndex"] = 17,
},
[5] =
{
["nodeIndex"] = 113,
["poiIndex"] = 23,
},
[6] =
{
["nodeIndex"] = 114,
["poiIndex"] = 24,
},
[7] =
{
["nodeIndex"] = 115,
["poiIndex"] = 25,
},
[8] =
{
["nodeIndex"] = 116,
["poiIndex"] = 26,
},
[9] =
{
["nodeIndex"] = 117,
["poiIndex"] = 27,
},
[10] =
{
["nodeIndex"] = 118,
["poiIndex"] = 28,
},
[11] =
{
["nodeIndex"] = 119,
["poiIndex"] = 29,
},
[12] =
{
["nodeIndex"] = 120,
["poiIndex"] = 30,
},
[13] =
{
["nodeIndex"] = 187,
["poiIndex"] = 42,
},
},
[17] =
{
[1] =
{
["nodeIndex"] = 42,
["poiIndex"] = 17,
},
[2] =
{
["nodeIndex"] = 43,
["poiIndex"] = 18,
},
[3] =
{
["nodeIndex"] = 44,
["poiIndex"] = 19,
},
[4] =
{
["nodeIndex"] = 45,
["poiIndex"] = 20,
},
[5] =
{
["nodeIndex"] = 46,
["poiIndex"] = 21,
},
[6] =
{
["nodeIndex"] = 57,
["poiIndex"] = 29,
},
[7] =
{
["nodeIndex"] = 58,
["poiIndex"] = 30,
},
[8] =
{
["nodeIndex"] = 59,
["poiIndex"] = 31,
},
[9] =
{
["nodeIndex"] = 137,
["poiIndex"] = 32,
},
[10] =
{
["nodeIndex"] = 60,
["poiIndex"] = 34,
},
[11] =
{
["nodeIndex"] = 61,
["poiIndex"] = 35,
},
[12] =
{
["nodeIndex"] = 196,
["poiIndex"] = 42,
},
[13] =
{
["nodeIndex"] = 155,
["poiIndex"] = 43,
},
},
[18] =
{
[1] =
{
["nodeIndex"] = 150,
["poiIndex"] = 21,
},
[2] =
{
["nodeIndex"] = 147,
["poiIndex"] = 17,
},
[3] =
{
["nodeIndex"] = 143,
["poiIndex"] = 18,
},
[4] =
{
["nodeIndex"] = 148,
["poiIndex"] = 19,
},
[5] =
{
["nodeIndex"] = 149,
["poiIndex"] = 20,
},
[6] =
{
["nodeIndex"] = 150,
["poiIndex"] = 21,
},
[7] =
{
["nodeIndex"] = 151,
["poiIndex"] = 22,
},
[8] =
{
["nodeIndex"] = 152,
["poiIndex"] = 23,
},
[9] =
{
["nodeIndex"] = 153,
["poiIndex"] = 24,
},
[10] =
{
["nodeIndex"] = 154,
["poiIndex"] = 25,
},
[11] =
{
["nodeIndex"] = 197,
["poiIndex"] = 39,
},
},
[179] =
{
[1] =
{
["nodeIndex"] = 185,
["poiIndex"] = 29,
},
[2] =
{
["nodeIndex"] = 144,
["poiIndex"] = 30,
},
[3] =
{
["nodeIndex"] = 156,
["poiIndex"] = 31,
},
[4] =
{
["nodeIndex"] = 157,
["poiIndex"] = 32,
},
[5] =
{
["nodeIndex"] = 158,
["poiIndex"] = 34,
},
[6] =
{
["nodeIndex"] = 159,
["poiIndex"] = 35,
},
[7] =
{
["nodeIndex"] = 160,
["poiIndex"] = 36,
},
[8] =
{
["nodeIndex"] = 161,
["poiIndex"] = 37,
},
[9] =
{
["nodeIndex"] = 162,
["poiIndex"] = 38,
},
[10] =
{
["nodeIndex"] = 163,
["poiIndex"] = 39,
},
},
[180] =
{
[1] =
{
["nodeIndex"] = 191,
["poiIndex"] = 8,
},
[2] =
{
["nodeIndex"] = 214,
["poiIndex"] = 15,
},
[3] =
{
["nodeIndex"] = 164,
["poiIndex"] = 16,
},
[4] =
{
["nodeIndex"] = 21,
["poiIndex"] = 17,
},
[5] =
{
["nodeIndex"] = 165,
["poiIndex"] = 18,
},
[6] =
{
["nodeIndex"] = 166,
["poiIndex"] = 19,
},
[7] =
{
["nodeIndex"] = 167,
["poiIndex"] = 20,
},
[8] =
{
["nodeIndex"] = 168,
["poiIndex"] = 21,
},
[9] =
{
["nodeIndex"] = 169,
["poiIndex"] = 22,
},
[10] =
{
["nodeIndex"] = 207,
["poiIndex"] = 40,
},
[11] =
{
["nodeIndex"] = 213,
["poiIndex"] = 41,
},
},
[14] =
{
[1] =
{
["nodeIndex"] = 33,
["poiIndex"] = 19,
},
[2] =
{
["nodeIndex"] = 34,
["poiIndex"] = 20,
},
[3] =
{
["nodeIndex"] = 35,
["poiIndex"] = 21,
},
[4] =
{
["nodeIndex"] = 36,
["poiIndex"] = 22,
},
[5] =
{
["nodeIndex"] = 37,
["poiIndex"] = 23,
},
[6] =
{
["nodeIndex"] = 38,
["poiIndex"] = 24,
},
[7] =
{
["nodeIndex"] = 39,
["poiIndex"] = 25,
},
[8] =
{
["nodeIndex"] = 40,
["poiIndex"] = 26,
},
[9] =
{
["nodeIndex"] = 63,
["poiIndex"] = 27,
},
[10] =
{
["nodeIndex"] = 186,
["poiIndex"] = 36,
},
[11] =
{
["nodeIndex"] = 204,
["poiIndex"] = 40,
},
[12] =
{
["nodeIndex"] = 206,
["poiIndex"] = 41,
},
},
[293] =
{
[1] =
{
["nodeIndex"] = 181,
["poiIndex"] = 3,
},
[2] =
{
["nodeIndex"] = 182,
["poiIndex"] = 4,
},
[3] =
{
["nodeIndex"] = 183,
["poiIndex"] = 5,
},
},
[154] =
{
[1] =
{
["nodeIndex"] = 128,
["poiIndex"] = 5,
},
[2] =
{
["nodeIndex"] = 129,
["poiIndex"] = 6,
},
[3] =
{
["nodeIndex"] = 130,
["poiIndex"] = 7,
},
[4] =
{
["nodeIndex"] = 131,
["poiIndex"] = 8,
},
[5] =
{
["nodeIndex"] = 132,
["poiIndex"] = 9,
},
[6] =
{
["nodeIndex"] = 133,
["poiIndex"] = 10,
},
[7] =
{
["nodeIndex"] = 134,
["poiIndex"] = 11,
},
[8] =
{
["nodeIndex"] = 135,
["poiIndex"] = 12,
},
[9] =
{
["nodeIndex"] = 136,
["poiIndex"] = 13,
},
[10] =
{
["nodeIndex"] = 139,
["poiIndex"] = 14,
},
[11] =
{
["nodeIndex"] = 140,
["poiIndex"] = 15,
},
[12] =
{
["nodeIndex"] = 145,
["poiIndex"] = 27,
},
[13] =
{
["nodeIndex"] = 146,
["poiIndex"] = 29,
},
[14] =
{
["nodeIndex"] = 184,
["poiIndex"] = 39,
},
},
[178] =
{
[1] =
{
["nodeIndex"] = 177,
["poiIndex"] = 20,
},
[2] =
{
["nodeIndex"] = 178,
["poiIndex"] = 23,
},
[3] =
{
["nodeIndex"] = 174,
["poiIndex"] = 24,
},
[4] =
{
["nodeIndex"] = 175,
["poiIndex"] = 25,
},
[5] =
{
["nodeIndex"] = 176,
["poiIndex"] = 26,
},
[6] =
{
["nodeIndex"] = 121,
["poiIndex"] = 27,
},
[7] =
{
["nodeIndex"] = 122,
["poiIndex"] = 28,
},
[8] =
{
["nodeIndex"] = 123,
["poiIndex"] = 29,
},
[9] =
{
["nodeIndex"] = 124,
["poiIndex"] = 30,
},
[10] =
{
["nodeIndex"] = 127,
["poiIndex"] = 33,
},
[11] =
{
["nodeIndex"] = 194,
["poiIndex"] = 41,
},
[12] =
{
["nodeIndex"] = 211,
["poiIndex"] = 42,
},
},
[19] =
{
[1] =
{
["nodeIndex"] = 47,
["poiIndex"] = 20,
},
[2] =
{
["nodeIndex"] = 48,
["poiIndex"] = 21,
},
[3] =
{
["nodeIndex"] = 49,
["poiIndex"] = 22,
},
[4] =
{
["nodeIndex"] = 171,
["poiIndex"] = 23,
},
[5] =
{
["nodeIndex"] = 50,
["poiIndex"] = 24,
},
[6] =
{
["nodeIndex"] = 51,
["poiIndex"] = 26,
},
[7] =
{
["nodeIndex"] = 52,
["poiIndex"] = 27,
},
[8] =
{
["nodeIndex"] = 53,
["poiIndex"] = 28,
},
[9] =
{
["nodeIndex"] = 78,
["poiIndex"] = 30,
},
[10] =
{
["nodeIndex"] = 85,
["poiIndex"] = 31,
},
[11] =
{
["nodeIndex"] = 192,
["poiIndex"] = 39,
},
},
[4] =
{
[1] =
{
["nodeIndex"] = 189,
["poiIndex"] = 20,
},
[2] =
{
["nodeIndex"] = 14,
["poiIndex"] = 22,
},
[3] =
{
["nodeIndex"] = 15,
["poiIndex"] = 23,
},
[4] =
{
["nodeIndex"] = 16,
["poiIndex"] = 24,
},
[5] =
{
["nodeIndex"] = 22,
["poiIndex"] = 25,
},
[6] =
{
["nodeIndex"] = 23,
["poiIndex"] = 26,
},
[7] =
{
["nodeIndex"] = 18,
["poiIndex"] = 27,
},
[8] =
{
["nodeIndex"] = 19,
["poiIndex"] = 28,
},
[9] =
{
["nodeIndex"] = 31,
["poiIndex"] = 35,
},
[10] =
{
["nodeIndex"] = 56,
["poiIndex"] = 42,
},
[11] =
{
["nodeIndex"] = 17,
["poiIndex"] = 43,
},
},
[292] =
{
[1] =
{
["nodeIndex"] = 138,
["poiIndex"] = 4,
},
[2] =
{
["nodeIndex"] = 179,
["poiIndex"] = 6,
},
[3] =
{
["nodeIndex"] = 180,
["poiIndex"] = 7,
},
},
}
-- cache for formatted wayshrine names
local _nodeNameCache = {}
local function GetNodeName(nodeIndex,name)
local localeName = _nodeNameCache[nodeIndex]
if localeName == nil then
localeName = Utils.FormatStringCurrentLanguage(name)
_nodeNameCache[nodeIndex] = localeName
end
return localeName
end
local function GetNodesByZoneIndex(zoneIndex)
if zoneIndex ~= nil then
local nodes = _zoneNodeLookup[zoneIndex]
if nodes ~= nil then
return Utils.copy(nodes)
end
end
return {}
end
local function GetNodeInfo(nodeIndex)
if nodeIndex == nil then return nil end
local known,name,normalizedX, normalizedY, textureName ,textureName,poiType,isShown = GetFastTravelNodeInfo(nodeIndex)
name = GetNodeName(nodeIndex,name)
return known,name,normalizedX, normalizedY, textureName ,textureName,poiType,isShown
end
local d = Data
d.GetNodesByZoneIndex = GetNodesByZoneIndex
d.GetNodeInfo = GetNodeInfo
FasterTravel.Wayshrine.Data = d | unlicense |
pedro-andrade-inpe/terrame | ide/zerobrane/terrame-examples/gis/06-fill.lua | 3 | 3247 | --[[ [previous](05-cellularspace.lua) | [contents](00-contents.lua) | [next](07-visualize.lua)
After creating a cellular layer, now it is possible to add attributes using the
data available. Depending on the geometric representation and the semantics of the
input data attributes, different operations can be applied. Some operations use
geometry, some use only attributes of objects with some overlap, and some combine
geometry and attributes. It is also possible to fill any geospatial data that uses
a vector format, even if it is not composed by rectangular objects. This script
describes some examples of filling some attributes.
]]
import("gis")
itaituba = Project{
file = "itaituba.tview",
clean = true,
localities = "itaituba-localities.shp",
roads = "itaituba-roads.shp",
census = "itaituba-census.shp"
}
Layer{
project = itaituba,
name = "deforestation",
file = "itaituba-deforestation.tif",
epsg = 29191
}
Layer{
project = itaituba,
name = "elevation",
file = "itaituba-elevation.tif",
epsg = 29191
}
itaitubaCells = Layer{
project = itaituba,
name = "cells",
clean = true,
file = "itaituba.shp",
input = "census",
resolution = 5000
}
--[[
Using raster data as reference layer, it is possible to compute operations based
on pixels whose centroid belongs to the cell. For example, operation average
compute the average value of such pixels for each cell. Argument attribute defines
the name of the attribute to be created, as shown below. After executing this code,
the cellular space will have an additional attribute "altim" with a number value.
]]
itaitubaCells:fill{
operation = "average",
layer = "elevation",
attribute = "elevation"
}
--[[
The main operation based on categorical raster data is coverage. It computes the
percentage of the cell's area covered by each of the available categories,
creating one attribute for each of them. It uses the attribute name plus _
followed by the attribute value as attribute names. For example, layer
"deforestation" has a tif data with two values, 0 and 254. The code below then
creates two attributes, defor_0 and defor_254, with values ranging from zero to
one for each attribute. Note that the layer might have a dummy value that will
be ignored by this operation.
]]
itaitubaCells:fill{
operation = "coverage",
layer = "deforestation",
attribute = "defor"
}
--[[
Using vector data without attributes, it is possible to compute the distance to
the nearest object using operation distance. The code below shows an example
that creates attribute "distr".
--]]
itaitubaCells:fill{
operation = "distance",
layer = "roads",
attribute = "distroad"
}
--[[
The most important operation using polygonal data with attributes is sum using
area = true. This operation distributes the values of a given select attribute
from the polygons to the cells given their intersection areas. It is particularly
useful for data such as population because it conserves the total sum of the
input in the output. See the code below.
]]
itaitubaCells:fill{
operation = "sum",
layer = "census",
attribute = "population",
select = "population",
area = true
}
| lgpl-3.0 |
keplerproject/luarocks | src/luarocks/build.lua | 2 | 14816 |
local build = {}
local path = require("luarocks.path")
local util = require("luarocks.util")
local fun = require("luarocks.fun")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local cfg = require("luarocks.core.cfg")
local vers = require("luarocks.core.vers")
local repos = require("luarocks.repos")
local writer = require("luarocks.manif.writer")
local deplocks = require("luarocks.deplocks")
build.opts = util.opts_table("build.opts", {
need_to_fetch = "boolean",
minimal_mode = "boolean",
deps_mode = "string",
build_only_deps = "boolean",
namespace = "string?",
branch = "string?",
verify = "boolean",
check_lua_versions = "boolean",
pin = "boolean",
no_install = "boolean"
})
do
--- Write to the current directory the contents of a table,
-- where each key is a file name and its value is the file content.
-- @param files table: The table of files to be written.
local function extract_from_rockspec(files)
for name, content in pairs(files) do
local fd = io.open(dir.path(fs.current_dir(), name), "w+")
fd:write(content)
fd:close()
end
end
--- Applies patches inlined in the build.patches section
-- and extracts files inlined in the build.extra_files section
-- of a rockspec.
-- @param rockspec table: A rockspec table.
-- @return boolean or (nil, string): True if succeeded or
-- nil and an error message.
function build.apply_patches(rockspec)
assert(rockspec:type() == "rockspec")
if not (rockspec.build.extra_files or rockspec.build.patches) then
return true
end
local fd = io.open(fs.absolute_name(".luarocks.patches.applied"), "r")
if fd then
fd:close()
return true
end
if rockspec.build.extra_files then
extract_from_rockspec(rockspec.build.extra_files)
end
if rockspec.build.patches then
extract_from_rockspec(rockspec.build.patches)
for patch, patchdata in util.sortedpairs(rockspec.build.patches) do
util.printout("Applying patch "..patch.."...")
local create_delete = rockspec:format_is_at_least("3.0")
local ok, err = fs.apply_patch(tostring(patch), patchdata, create_delete)
if not ok then
return nil, "Failed applying patch "..patch
end
end
end
fd = io.open(fs.absolute_name(".luarocks.patches.applied"), "w")
if fd then
fd:close()
end
return true
end
end
local function check_macosx_deployment_target(rockspec)
local target = rockspec.build.macosx_deployment_target
local function patch_variable(var)
if rockspec.variables[var]:match("MACOSX_DEPLOYMENT_TARGET") then
rockspec.variables[var] = (rockspec.variables[var]):gsub("MACOSX_DEPLOYMENT_TARGET=[^ ]*", "MACOSX_DEPLOYMENT_TARGET="..target)
else
rockspec.variables[var] = "env MACOSX_DEPLOYMENT_TARGET="..target.." "..rockspec.variables[var]
end
end
if cfg.is_platform("macosx") and rockspec:format_is_at_least("3.0") and target then
local version = util.popen_read("sw_vers -productVersion")
if version:match("^%d+%.%d+%.%d+$") or version:match("^%d+%.%d+$") then
if vers.compare_versions(target, version) then
return nil, ("This rock requires Mac OSX %s, and you are running %s."):format(target, version)
end
end
patch_variable("CC")
patch_variable("LD")
end
return true
end
local function process_dependencies(rockspec, opts)
if not opts.build_only_deps then
local ok, err, errcode = deps.check_external_deps(rockspec, "build")
if err then
return nil, err, errcode
end
end
local ok, err, errcode = deps.check_lua_incdir(rockspec.variables)
if not ok then
return nil, err, errcode
end
if cfg.link_lua_explicitly then
local ok, err, errcode = deps.check_lua_libdir(rockspec.variables)
if not ok then
return nil, err, errcode
end
end
if opts.deps_mode == "none" then
return true
end
if not opts.build_only_deps then
if next(rockspec.build_dependencies) then
local ok, err, errcode = deps.fulfill_dependencies(rockspec, "build_dependencies", opts.deps_mode, opts.verify)
if err then
return nil, err, errcode
end
end
end
ok, err, errcode = deps.fulfill_dependencies(rockspec, "dependencies", opts.deps_mode, opts.verify)
if err then
return nil, err, errcode
end
return true
end
local function fetch_and_change_to_source_dir(rockspec, opts)
if opts.minimal_mode or opts.build_only_deps then
return true
end
if opts.need_to_fetch then
if opts.branch then
rockspec.source.branch = opts.branch
end
local ok, source_dir, errcode = fetch.fetch_sources(rockspec, true)
if not ok then
return nil, source_dir, errcode
end
local err
ok, err = fs.change_dir(source_dir)
if not ok then
return nil, err
end
elseif rockspec.source.file then
local ok, err = fs.unpack_archive(rockspec.source.file)
if not ok then
return nil, err
end
end
fs.change_dir(rockspec.source.dir)
return true
end
local function prepare_install_dirs(name, version)
local dirs = {
lua = { name = path.lua_dir(name, version), is_module_path = true, perms = "read" },
lib = { name = path.lib_dir(name, version), is_module_path = true, perms = "exec" },
bin = { name = path.bin_dir(name, version), is_module_path = false, perms = "exec" },
conf = { name = path.conf_dir(name, version), is_module_path = false, perms = "read" },
}
for _, d in pairs(dirs) do
local ok, err = fs.make_dir(d.name)
if not ok then
return nil, err
end
end
return dirs
end
local function run_build_driver(rockspec, no_install)
local btype = rockspec.build.type
if btype == "none" then
return true
end
-- Temporary compatibility
if btype == "module" then
util.printout("Do not use 'module' as a build type. Use 'builtin' instead.")
btype = "builtin"
rockspec.build.type = btype
end
if cfg.accepted_build_types and not fun.contains(cfg.accepted_build_types, btype) then
return nil, "This rockspec uses the '"..btype.."' build type, which is blocked by the 'accepted_build_types' setting in your LuaRocks configuration."
end
local pok, driver = pcall(require, "luarocks.build." .. btype)
if not pok or type(driver) ~= "table" then
return nil, "Failed initializing build back-end for build type '"..btype.."': "..driver
end
local ok, err = driver.run(rockspec, no_install)
if not ok then
return nil, "Build error: " .. err
end
return true
end
local install_files
do
--- Install files to a given location.
-- Takes a table where the array part is a list of filenames to be copied.
-- In the hash part, other keys, if is_module_path is set, are identifiers
-- in Lua module format, to indicate which subdirectory the file should be
-- copied to. For example, install_files({["foo.bar"] = "src/bar.lua"}, "boo")
-- will copy src/bar.lua to boo/foo.
-- @param files table or nil: A table containing a list of files to copy in
-- the format described above. If nil is passed, this function is a no-op.
-- Directories should be delimited by forward slashes as in internet URLs.
-- @param location string: The base directory files should be copied to.
-- @param is_module_path boolean: True if string keys in files should be
-- interpreted as dotted module paths.
-- @param perms string ("read" or "exec"): Permissions of the newly created
-- files installed.
-- Directories are always created with the default permissions.
-- @return boolean or (nil, string): True if succeeded or
-- nil and an error message.
local function install_to(files, location, is_module_path, perms)
assert(type(files) == "table" or not files)
assert(type(location) == "string")
if not files then
return true
end
for k, file in pairs(files) do
local dest = location
local filename = dir.base_name(file)
if type(k) == "string" then
local modname = k
if is_module_path then
dest = dir.path(location, path.module_to_path(modname))
local ok, err = fs.make_dir(dest)
if not ok then return nil, err end
if filename:match("%.lua$") then
local basename = modname:match("([^.]+)$")
filename = basename..".lua"
end
else
dest = dir.path(location, dir.dir_name(modname))
local ok, err = fs.make_dir(dest)
if not ok then return nil, err end
filename = dir.base_name(modname)
end
else
local ok, err = fs.make_dir(dest)
if not ok then return nil, err end
end
local ok = fs.copy(dir.path(file), dir.path(dest, filename), perms)
if not ok then
return nil, "Failed copying "..file
end
end
return true
end
local function install_default_docs(name, version)
local patterns = { "readme", "license", "copying", ".*%.md" }
local dest = dir.path(path.install_dir(name, version), "doc")
local has_dir = false
for file in fs.dir() do
for _, pattern in ipairs(patterns) do
if file:lower():match("^"..pattern) then
if not has_dir then
fs.make_dir(dest)
has_dir = true
end
fs.copy(file, dest, "read")
break
end
end
end
end
install_files = function(rockspec, dirs)
local name, version = rockspec.name, rockspec.version
if rockspec.build.install then
for k, d in pairs(dirs) do
local ok, err = install_to(rockspec.build.install[k], d.name, d.is_module_path, d.perms)
if not ok then return nil, err end
end
end
local copy_directories = rockspec.build.copy_directories
local copying_default = false
if not copy_directories then
copy_directories = {"doc"}
copying_default = true
end
local any_docs = false
for _, copy_dir in pairs(copy_directories) do
if fs.is_dir(copy_dir) then
local dest = dir.path(path.install_dir(name, version), copy_dir)
fs.make_dir(dest)
fs.copy_contents(copy_dir, dest)
any_docs = true
else
if not copying_default then
return nil, "Directory '"..copy_dir.."' not found"
end
end
end
if not any_docs then
install_default_docs(name, version)
end
return true
end
end
local function write_rock_dir_files(rockspec, opts)
local name, version = rockspec.name, rockspec.version
fs.copy(rockspec.local_abs_filename, path.rockspec_file(name, version), "read")
local deplock_file = deplocks.get_abs_filename(rockspec.name)
if deplock_file then
fs.copy(deplock_file, dir.path(path.install_dir(name, version), "luarocks.lock"), "read")
end
local ok, err = writer.make_rock_manifest(name, version)
if not ok then return nil, err end
ok, err = writer.make_namespace_file(name, version, opts.namespace)
if not ok then return nil, err end
return true
end
--- Build and install a rock given a rockspec.
-- @param opts table: build options table
-- @return (string, string) or (nil, string, [string]): Name and version of
-- installed rock if succeeded or nil and an error message followed by an error code.
function build.build_rockspec(rockspec, opts)
assert(rockspec:type() == "rockspec")
assert(opts:type() == "build.opts")
if not rockspec.build then
if rockspec:format_is_at_least("3.0") then
rockspec.build = {
type = "builtin"
}
else
return nil, "Rockspec error: build table not specified"
end
end
if not rockspec.build.type then
if rockspec:format_is_at_least("3.0") then
rockspec.build.type = "builtin"
else
return nil, "Rockspec error: build type not specified"
end
end
local ok, err = fetch_and_change_to_source_dir(rockspec, opts)
if not ok then return nil, err end
if opts.pin then
deplocks.init(rockspec.name, ".")
end
ok, err = process_dependencies(rockspec, opts)
if not ok then return nil, err end
local name, version = rockspec.name, rockspec.version
if opts.build_only_deps then
if opts.pin then
deplocks.write_file()
end
return name, version
end
local dirs, err
local rollback
if not opts.no_install then
if repos.is_installed(name, version) then
repos.delete_version(name, version, opts.deps_mode)
end
dirs, err = prepare_install_dirs(name, version)
if not dirs then return nil, err end
rollback = util.schedule_function(function()
fs.delete(path.install_dir(name, version))
fs.remove_dir_if_empty(path.versions_dir(name))
end)
end
ok, err = build.apply_patches(rockspec)
if not ok then return nil, err end
ok, err = check_macosx_deployment_target(rockspec)
if not ok then return nil, err end
ok, err = run_build_driver(rockspec, opts.no_install)
if not ok then return nil, err end
if opts.no_install then
fs.pop_dir()
if opts.need_to_fetch then
fs.pop_dir()
end
return name, version
end
ok, err = install_files(rockspec, dirs)
if not ok then return nil, err end
for _, d in pairs(dirs) do
fs.remove_dir_if_empty(d.name)
end
fs.pop_dir()
if opts.need_to_fetch then
fs.pop_dir()
end
if opts.pin then
deplocks.write_file()
end
ok, err = write_rock_dir_files(rockspec, opts)
if not ok then return nil, err end
ok, err = repos.deploy_files(name, version, repos.should_wrap_bin_scripts(rockspec), opts.deps_mode)
if not ok then return nil, err end
util.remove_scheduled_function(rollback)
rollback = util.schedule_function(function()
repos.delete_version(name, version, opts.deps_mode)
end)
ok, err = repos.run_hook(rockspec, "post_install")
if not ok then return nil, err end
util.announce_install(rockspec)
util.remove_scheduled_function(rollback)
return name, version
end
return build
| mit |
starlightknight/darkstar | scripts/globals/items/lungfish.lua | 11 | 1043 | -----------------------------------------
-- ID: 4315
-- Item: Lungfish
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -2
-- Mind 4
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if (target:getRace() ~= dsp.race.MITHRA) then
result = dsp.msg.basic.CANNOT_EAT
elseif target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then
result = 0
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,300,4315)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, -2)
target:addMod(dsp.mod.MND, 4)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, -2)
target:delMod(dsp.mod.MND, 4)
end
| gpl-3.0 |
dantezhu/neon | examples/tpl/src/cocos/extension/DeprecatedExtensionEnum.lua | 62 | 1410 | if nil == cc.Control then
return
end
_G.kCCControlStepperPartMinus = cc.CONTROL_STEPPER_PART_MINUS
_G.kCCControlStepperPartPlus = cc.CONTROL_STEPPER_PART_PLUS
_G.kCCControlStepperPartNone = cc.CONTROL_STEPPER_PART_NONE
_G.CCControlEventTouchDown = cc.CONTROL_EVENTTYPE_TOUCH_DOWN
_G.CCControlEventTouchDragInside = cc.CONTROL_EVENTTYPE_DRAG_INSIDE
_G.CCControlEventTouchDragOutside = cc.CONTROL_EVENTTYPE_DRAG_OUTSIDE
_G.CCControlEventTouchDragEnter = cc.CONTROL_EVENTTYPE_DRAG_ENTER
_G.CCControlEventTouchDragExit = cc.CONTROL_EVENTTYPE_DRAG_EXIT
_G.CCControlEventTouchUpInside = cc.CONTROL_EVENTTYPE_TOUCH_UP_INSIDE
_G.CCControlEventTouchUpOutside = cc.CONTROL_EVENTTYPE_TOUCH_UP_OUTSIDE
_G.CCControlEventTouchCancel = cc.CONTROL_EVENTTYPE_TOUCH_CANCEL
_G.CCControlEventValueChanged = cc.CONTROL_EVENTTYPE_VALUE_CHANGED
_G.CCControlStateNormal = cc.CONTROL_STATE_NORMAL
_G.CCControlStateHighlighted = cc.CONTROL_STATE_HIGH_LIGHTED
_G.CCControlStateDisabled = cc.CONTROL_STATE_DISABLED
_G.CCControlStateSelected = cc.CONTROL_STATE_SELECTED
_G.kCCScrollViewDirectionHorizontal = cc.SCROLLVIEW_DIRECTION_HORIZONTAL
_G.kCCScrollViewDirectionVertical = cc.SCROLLVIEW_DIRECTION_VERTICAL
_G.kCCTableViewFillTopDown = cc.TABLEVIEW_FILL_TOPDOWN
_G.kCCTableViewFillBottomUp = cc.TABLEVIEW_FILL_BOTTOMUP
| mit |
starlightknight/darkstar | scripts/zones/QuBia_Arena/bcnms/undying_promise.lua | 9 | 1217 | -----------------------------------
-- Undying Promise
-- Qu'Bia Arena BCNM40, Star Orb
-- !additem 1131
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
battlefield:setLocalVar("lootSpawned", 1) -- this does not spawn the loot, but prevents battlefield from ending when you kill the still-to-reraise mob
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Upper_Jeuno/npcs/Emitt.lua | 3 | 2226 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Emitt
-- !pos -95 0 160 244
-------------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/conquest");
require("scripts/zones/Upper_Jeuno/TextIDs");
local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno).
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Menu1 = getArg1(guardnation,player);
local Menu3 = conquestRanking();
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
player:startEvent(0x7ffb,Menu1,0,Menu3,0,0,Menu6,Menu7,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
local inventory, size;
if (player:getNation() == 0) then
inventory = SandInv;
size = #SandInv;
elseif (player:getNation() == 1) then
inventory = BastInv;
size = #BastInv;
else
inventory = WindInv;
size = #WindInv;
end
updateConquestGuard(player,csid,option,size,inventory);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
local inventory, size;
if (player:getNation() == 0) then
inventory = SandInv;
size = #SandInv;
elseif (player:getNation() == 1) then
inventory = BastInv;
size = #BastInv;
else
inventory = WindInv;
size = #WindInv;
end
finishConquestGuard(player,csid,option,size,inventory,guardnation);
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.