repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
backburn/Probably
interface/buttons/core.lua
1
1408
-- ProbablyEngine Rotations - https://probablyengine.com/ -- Released under modified BSD, see attached LICENSE. local AceGUI = LibStub("AceGUI-3.0") ProbablyEngine.buttons.create('MasterToggle', nil, function(self, button) if button == "LeftButton" then self.checked = not self.checked self:SetChecked(self.checked) ProbablyEngine.config.write('button_states', 'MasterToggle', self.checked) if self.checked then _G['PE_Buttons_MasterToggleHotKey']:SetText('On') else _G['PE_Buttons_MasterToggleHotKey']:SetText('Off') end else local dropdown = CreateFrame("Frame", "Test_DropDown", self, "UIDropDownMenuTemplate"); UIDropDownMenu_Initialize(dropdown, ProbablyEngine.rotation.list_custom, "MENU"); ToggleDropDownMenu(1, nil, dropdown, self, 0, 0); -- Don't toggle the state, I'm not sure why a return value can't handle this self.checked = self.checked self:SetChecked(self.checked) end end, pelg('toggle'), pelg('toggle_tooltip')) ProbablyEngine.toggle.create('cooldowns', 'Interface\\ICONS\\Achievement_BG_winAB_underXminutes', pelg('cooldowns'), pelg('cooldowns_tooltip')) ProbablyEngine.toggle.create('multitarget', 'Interface\\ICONS\\Ability_Druid_Starfall', pelg('multitarget'), pelg('multitarget_tooltip')) ProbablyEngine.toggle.create('interrupt', 'Interface\\ICONS\\Ability_Kick.png', pelg('interrupt'), pelg('interrupt_tooltip'))
bsd-3-clause
Ninjistix/darkstar
scripts/zones/Windurst_Woods/npcs/Millerovieunet.lua
5
1188
----------------------------------- -- Area: Windurst_Woods -- NPC: Millerovieunet -- Only sells when Windurst controlls Qufim Region -- Confirmed shop stock, August 2013 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Woods/TextIDs"); require("scripts/globals/events/harvest_festivals") require("scripts/globals/conquest"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc); end; function onTrigger(player,npc) if (GetRegionOwner(QUFIMISLAND) ~= NATION_WINDURST) then player:showText(npc,MILLEROVIEUNET_CLOSED_DIALOG); else player:showText(npc,MILLEROVIEUNET_OPEN_DIALOG); local stock = { 954, 4032 -- Magic Pot Shard } showShop(player,WINDURST,stock); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
teran/deduplicator
deduplicator.lrdevplugin/GithubCheckUpdates.lua
1
1634
--[[---------------------------------------------------------------------------- This file is a part of Deduplicator Lightroom Classic CC plugin Licenced under GPLv2 terms GIT Repository with the code: https://github.com/teran/deduplicator ------------------------------------------------------------------------------]] local LrDialogs = import 'LrDialogs' local LrHttp = import 'LrHttp' local LrLogger = import 'LrLogger' local LrTasks = import 'LrTasks' local json = require 'JSON' json.strictTypes = true require 'Info' local logger = LrLogger(plugin_name) logger:enable(log_target) logger:trace('GithubCheckUpdates.lua invoked') function checkForUpdates() logger:debugf('Preparing to request %s', latest_release_json_url) local responseBody, headers = LrHttp.get(latest_release_json_url) r = json:decode(responseBody) logger:infof('Received latest available version as %s', r['tag_name']) if r['tag_name'] ~= plugin_version then local referToNewRelease = LrDialogs.confirm( 'Update is available!', string.format( 'Release %s is available. You have %s, wanna visit download page?', r['tag_name'], plugin_version), 'Yes, I want to download an update!', 'No, thanks.' ) if referToNewRelease == 'ok' then logger:tracef('Opening %s in system browser', r['html_url']) LrHttp.openUrlInBrowser(r['html_url']) else logger:tracef("User refused to update :'(") end else logger:infof('Deduplicator is up-to-date') LrDialogs.message('Deduplicator is up-to-date!', 'Keep it going!') end end LrTasks.startAsyncTask(checkForUpdates)
gpl-2.0
davidbuzz/ardupilot
libraries/AP_Scripting/examples/ahrs-source-gps-wheelencoders.lua
19
7934
-- This script helps vehicles move between GPS and Non-GPS environments using GPS and Wheel Encoders -- -- setup RCx_OPTION = 90 (EKF Pos Source) to select the source (low=primary, middle=secondary, high=tertiary) -- setup RCx_OPTION = 300 (Scripting1). When this switch is pulled high, the source will be automatically selected -- setup EK3_SRCn_ parameters so that GPS is the primary source, WheelEncoders are the secondary -- -- When the auxiliary switch (ZigZag Auto) is pulled high automatic source selection uses these thresholds: -- SCR_USER2 holds the threshold for GPS speed accuracy (around 0.3 is a good choice) -- SCR_USER3 holds the threshold for GPS innovations (around 0.3 is a good choice) -- if GPS speed accuracy <= SCR_USER2 and GPS innovations <= SRC_USER3 then the GPS (primary source set) will be used -- otherwise wheel encoders (secondary source set) will be used local source_prev = 0 -- previous source, defaults to primary source local sw_source_prev = -1 -- previous source switch position local sw_auto_pos_prev = -1 -- previous auto source switch position local auto_switch = false -- true when auto switching between sources is active local gps_usable_accuracy = 1.0 -- GPS is usable if speed accuracy is at or below this value local vote_counter_max = 20 -- when a vote counter reaches this number (i.e. 2sec) source may be switched local gps_vs_nongps_vote = 0 -- vote counter for GPS vs NonGPS (-20 = GPS, +20 = NonGPS) -- play tune on buzzer to alert user to change in active source set function play_source_tune(source) if (source) then if (source == 0) then notify:play_tune("L8C") -- one long lower tone elseif (source == 1) then notify:play_tune("L12DD") -- two fast medium tones elseif (source == 2) then notify:play_tune("L16FFF") -- three very fast, high tones end end end -- the main update function function update() -- check switches are configured -- at least one switch must be set -- source selection from RCx_FUNCTION = 90 (EKF Source Select) -- auto source from RCx_FUNCTION = 300 (Scripting1) local rc_function_source = rc:find_channel_for_option(90) local rc_function_auto = rc:find_channel_for_option(300) if (rc_function_source == nil) and (rc_function_auto == nil) then gcs:send_text(0, "ahrs-source-gps-wheelencoders.lua: RCx_FUNCTION=90 or 300 not set!") return update, 1000 end -- check GPS speed accuracy threshold has been set local gps_speedaccuracy_thresh = param:get('SCR_USER2') -- SCR_USER2 holds GPS speed accuracy threshold if (gps_speedaccuracy_thresh == nil) or (gps_speedaccuracy_thresh <= 0) then gcs:send_text(0, "ahrs-source-gps-wheelencoders.lua: set SCR_USER2 to GPS speed accuracy threshold") return update, 1000 end -- check GPS innovation threshold has been set local gps_innov_thresh = param:get('SCR_USER3') -- SCR_USER3 holds GPS velocity innovation if (gps_innov_thresh == nil) or (gps_innov_thresh <= 0) then gcs:send_text(0, "ahrs-source-gps-wheelencoders.lua: set SCR_USER3 to GPS innovation threshold") return update, 1000 end -- check if GPS speed accuracy is over threshold local gps_speed_accuracy = gps:speed_accuracy(gps:primary_sensor()) local gps_over_threshold = (gps_speed_accuracy == nil) or (gps:speed_accuracy(gps:primary_sensor()) > gps_speedaccuracy_thresh) -- get GPS innovations from ahrs local gps_innov = Vector3f() local gps_var = Vector3f() gps_innov, gps_var = ahrs:get_vel_innovations_and_variances_for_source(3) local gps_innov_over_threshold = (gps_innov == nil) or (gps_innov:z() == 0.0) or (math.abs(gps_innov:z()) > gps_innov_thresh) -- automatic selection logic -- -- GPS vs NonGPS vote. "-1" to move towards GPS, "+1" to move to Non-GPS if (not gps_over_threshold) and (not gps_innov_over_threshold) then -- vote for GPS if GPS accuracy good AND innovations are low gps_vs_nongps_vote = math.max(gps_vs_nongps_vote - 1, -vote_counter_max) else -- otherwise vote for NonGPS (wheel encoders) gps_vs_nongps_vote = math.min(gps_vs_nongps_vote + 1, vote_counter_max) end -- auto source vote collation local auto_source = -1 -- auto source undecided if -1 if gps_vs_nongps_vote <= -vote_counter_max then auto_source = 0 -- GPS elseif gps_vs_nongps_vote >= vote_counter_max then auto_source = 1 -- Non-GPS / wheel encoders end -- read source switch position from RCx_FUNCTION = 90 (EKF Source Select) local sw_source_pos = rc_function_source:get_aux_switch_pos() if sw_source_pos ~= sw_source_pos_prev then -- check for changes in source switch position sw_source_pos_prev = sw_source_pos -- record new switch position so we can detect changes auto_switch = false -- disable auto switching of source if source_prev ~= sw_source_pos then -- check if switch position does not match source (there is a one-to-one mapping of switch to source) source_prev = sw_source_pos -- record what source should now be (changed by ArduPilot vehicle code) gcs:send_text(0, "Pilot switched to Source " .. string.format("%d", source_prev+1)) else gcs:send_text(0, "Pilot switched but already Source " .. string.format("%d", source_prev+1)) end play_source_tune(source_prev) -- alert user of source regardless of whether it has changed or not end -- read auto source switch position from RCx_FUNCTION = 300 (Scripting1) if rc_function_auto then local sw_auto_pos = rc_function_auto:get_aux_switch_pos() if sw_auto_pos ~= sw_auto_pos_prev then -- check for changes in source auto switch position sw_auto_pos_prev = sw_auto_pos -- record new switch position so we can detect changes if sw_auto_pos == 0 then -- pilot has pulled switch low auto_switch = false -- disable auto switching of source if sw_source_pos ~= source_prev then -- check if source will change source_prev = sw_source_pos -- record pilot's selected source ahrs:set_posvelyaw_source_set(source_prev) -- switch to pilot's selected source gcs:send_text(0, "Auto source disabled, switched to Source " .. string.format("%d", source_prev+1)) else gcs:send_text(0, "Auto source disabled, already Source " .. string.format("%d", source_prev+1)) end elseif sw_auto_pos == 2 then -- pilot has pulled switch high auto_switch = true -- enable auto switching of source if auto_source < 0 then gcs:send_text(0, "Auto source enabled, undecided, Source " .. string.format("%d", source_prev+1)) elseif auto_source ~= source_prev then -- check if source will change source_prev = auto_source -- record pilot's selected source ahrs:set_posvelyaw_source_set(source_prev) -- switch to pilot's selected source gcs:send_text(0, "Auto source enabled, switched to Source " .. string.format("%d", source_prev+1)) else gcs:send_text(0, "Auto source enabled, already Source " .. string.format("%d", source_prev+1)) end end play_source_tune(source_prev) end end -- auto switching if auto_switch and (auto_source >= 0) and (auto_source ~= source_prev) then source_prev = auto_source -- record selected source ahrs:set_posvelyaw_source_set(source_prev) -- switch to pilot's selected source gcs:send_text(0, "Auto switched to Source " .. string.format("%d", source_prev+1)) play_source_tune(source_prev) end return update, 100 end return update()
gpl-3.0
Ninjistix/darkstar
scripts/zones/Beaucedine_Glacier/mobs/Calcabrina.lua
5
1719
----------------------------------- -- Area: Beaucedine Glacier -- NM: Calcabrina ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT, 1); end; function onAdditionalEffect(mob,target,damage) -- wiki just says "low proc rate". No actual data to go on - going with 15% for now. local chance = 15; local LV_diff = target:getMainLvl() - mob:getMainLvl(); if (target:getMainLvl() > mob:getMainLvl()) then chance = chance - 5 * LV_diff chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance) then return 0,0,0; else local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT); if (INT_diff > 20) then INT_diff = 20 + (INT_diff - 20) / 2; end local drain = INT_diff+LV_diff+damage/2; local params = {}; params.bonusmab = 0; params.includemab = false; drain = addBonusesAbility(mob, ELE_DARK, target, drain, params); drain = drain * applyResistanceAddEffect(mob,target,ELE_DARK,0); drain = adjustForTarget(target,drain,ELE_DARK); drain = finalMagicNonSpellAdjustments(target,mob,ELE_DARK,drain); if (drain <= 0) then drain = 0; else mob:addHP(drain); end return SUBEFFECT_HP_DRAIN, msgBasic.ADD_EFFECT_HP_DRAIN, drain; end end; function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(5400,6000)); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/bowl_of_stamina_soup.lua
3
1294
----------------------------------------- -- ID: 4337 -- Item: bowl_of_stamina_soup -- Food Effect: 4Hrs, All Races ----------------------------------------- -- HP +12% (cap 200) -- Dexterity 4 -- Vitality 6 -- Mind -3 -- HP Recovered While Healing 10 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4337); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 12); target:addMod(MOD_FOOD_HP_CAP, 200); target:addMod(MOD_DEX, 4); target:addMod(MOD_VIT, 6); target:addMod(MOD_MND, -3); target:addMod(MOD_HPHEAL, 10); end; function onEffectLose(target, effect) target:delMod(MOD_FOOD_HPP, 12); target:delMod(MOD_FOOD_HP_CAP, 200); target:delMod(MOD_DEX, 4); target:delMod(MOD_VIT, 6); target:delMod(MOD_MND, -3); target:delMod(MOD_HPHEAL, 10); end;
gpl-3.0
DGA-MI-SSI/YaCo
deps/swig-3.0.7/Examples/test-suite/lua/li_std_vector_runme.lua
6
1123
require("import") -- the import fn import("li_std_vector") -- import code for k,v in pairs(li_std_vector) do _G[k]=v end -- move to global iv = IntVector(4) for i=0,3 do iv[i] = i end for i=0,3 do assert(iv[i]==i) end x = average(iv) function near(x,y) return math.abs(x-y)<0.001 end assert(near(x,1.5)) rv = RealVector() rv:push_back(10) rv:push_back(10.5) rv:push_back(11) rv:push_back(11.5) a=half(rv) for i=0,rv:size()-1 do assert(near(a[i],rv[i]/2)) end dv = DoubleVector(10) for i=0,9 do dv[i] = i/2.0 end halve_in_place(dv) for i=0,9 do assert(near(dv[i],i/4)) end sv=StructVector(4) for i=0,3 do sv[i]=Struct(i) end for i=0,3 do assert(swig_type(sv[i]) =='Struct *' and sv[i].num==i) end -- range checking idx=0 function test_set() iv[idx]=0 end function test_get() iv[idx]=0 end idx=0 --ok assert(pcall(test_get)==true) assert(pcall(test_set)==true) idx=-1 --should error assert(pcall(test_get)==false) assert(pcall(test_set)==false) idx=3 --ok assert(pcall(test_get)==true) assert(pcall(test_set)==true) idx=4 --should error assert(pcall(test_get)==false) assert(pcall(test_set)==false)
gpl-3.0
TEAMvirus/ViRuS
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
pooya7013/anti-spam
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
ccyphers/kong
spec/01-unit/04-utils_spec.lua
1
20937
local utils = require "kong.tools.utils" describe("Utils", function() describe("get_hostname()", function() it("should retrieve the hostname", function() assert.is_string(utils.get_hostname()) end) end) describe("get_system_infos()", function() it("retrieves various host infos", function() local infos = utils.get_system_infos() assert.is_number(infos.cores) assert.is_string(infos.hostname) assert.is_string(infos.uname) assert.not_matches("\n$", infos.hostname) assert.not_matches("\n$", infos.uname) end) it("caches the result", function() assert.equal( utils.get_system_infos(), utils.get_system_infos() ) end) end) describe("is_valid_uuid()", function() it("validates UUIDs from jit-uuid", function() assert.True (utils.is_valid_uuid("cbb297c0-a956-486d-ad1d-f9b42df9465a")) assert.False(utils.is_valid_uuid("cbb297c0-a956486d-ad1d-f9b42df9465a")) end) pending("invalidates UUIDs with invalid variants", function() -- this is disabled because existing uuids in the database fail the check upon migrations -- see https://github.com/thibaultcha/lua-resty-jit-uuid/issues/8 assert.False(utils.is_valid_uuid("cbb297c0-a956-486d-dd1d-f9b42df9465a")) -- invalid variant end) it("validates UUIDs with invalid variants for backwards-compatibility reasons", function() -- See pending test just above ^^ -- see https://github.com/thibaultcha/lua-resty-jit-uuid/issues/8 assert.True(utils.is_valid_uuid("cbb297c0-a956-486d-dd1d-f9b42df9465a")) end) it("considers the null UUID a valid one", function() -- we use the null UUID for plugins' consumer_id when none is set assert.True(utils.is_valid_uuid("00000000-0000-0000-0000-000000000000")) end) end) describe("https_check", function() local old_ngx local headers = {} setup(function() old_ngx = ngx _G.ngx = { var = { scheme = nil }, req = { get_headers = function() return headers end } } end) teardown(function() _G.ngx = old_ngx end) describe("without X-Forwarded-Proto header", function() setup(function() headers["x-forwarded-proto"] = nil end) it("should validate an HTTPS scheme", function() ngx.var.scheme = "hTTps" -- mixed casing to ensure case insensitiveness assert.is.truthy(utils.check_https()) end) it("should invalidate non-HTTPS schemes", function() ngx.var.scheme = "hTTp" assert.is.falsy(utils.check_https()) ngx.var.scheme = "something completely different" assert.is.falsy(utils.check_https()) end) it("should invalidate non-HTTPS schemes with proto header allowed", function() ngx.var.scheme = "hTTp" assert.is.falsy(utils.check_https(true)) end) end) describe("with X-Forwarded-Proto header", function() teardown(function() headers["x-forwarded-proto"] = nil end) it("should validate any scheme with X-Forwarded_Proto as HTTPS", function() headers["x-forwarded-proto"] = "hTTPs" -- check mixed casing for case insensitiveness ngx.var.scheme = "hTTps" assert.is.truthy(utils.check_https(true)) ngx.var.scheme = "hTTp" assert.is.truthy(utils.check_https(true)) ngx.var.scheme = "something completely different" assert.is.truthy(utils.check_https(true)) end) it("should validate only https scheme with X-Forwarded_Proto as non-HTTPS", function() headers["x-forwarded-proto"] = "hTTP" ngx.var.scheme = "hTTps" assert.is.truthy(utils.check_https(true)) ngx.var.scheme = "hTTp" assert.is.falsy(utils.check_https(true)) ngx.var.scheme = "something completely different" assert.is.falsy(utils.check_https(true)) end) it("should return an error with multiple X-Forwarded_Proto headers", function() headers["x-forwarded-proto"] = { "hTTP", "https" } ngx.var.scheme = "hTTps" assert.is.truthy(utils.check_https(true)) ngx.var.scheme = "hTTp" assert.are.same({ nil, "Only one X-Forwarded-Proto header allowed" }, { utils.check_https(true) }) end) end) end) describe("string", function() it("checks valid UTF8 values", function() assert.True(utils.validate_utf8("hello")) assert.True(utils.validate_utf8(123)) assert.True(utils.validate_utf8(true)) assert.False(utils.validate_utf8(string.char(105, 213, 205, 149))) end) describe("random_string()", function() it("should return a random string", function() local first = utils.random_string() assert.truthy(first) assert.falsy(first:find("-")) local second = utils.random_string() assert.not_equal(first, second) end) end) describe("encode_args()", function() it("should encode a Lua table to a querystring", function() local str = utils.encode_args { foo = "bar", hello = "world" } assert.equal("foo=bar&hello=world", str) end) it("should encode multi-value query args", function() local str = utils.encode_args { foo = {"bar", "zoo"}, hello = "world" } assert.equal("foo=bar&foo=zoo&hello=world", str) end) it("should percent-encode given values", function() local str = utils.encode_args { encode = {"abc|def", ",$@|`"} } assert.equal("encode=abc%7cdef&encode=%2c%24%40%7c%60", str) end) it("should percent-encode given query args keys", function() local str = utils.encode_args { ["hello world"] = "foo" } assert.equal("hello%20world=foo", str) end) it("should support Lua numbers", function() local str = utils.encode_args { a = 1, b = 2 } assert.equal("a=1&b=2", str) end) it("should support a boolean argument", function() local str = utils.encode_args { a = true, b = 1 } assert.equal("a&b=1", str) end) it("should ignore nil and false values", function() local str = utils.encode_args { a = nil, b = false } assert.equal("", str) end) it("should encode complex query args", function() local str = utils.encode_args { multiple = {"hello, world"}, hello = "world", ignore = false, ["multiple values"] = true } assert.equal("hello=world&multiple=hello%2c%20world&multiple%20values", str) end) it("should not interpret the `%` character followed by 2 characters in the [0-9a-f] group as an hexadecimal value", function() local str = utils.encode_args { foo = "%bar%" } assert.equal("foo=%25bar%25", str) end) it("should not percent-encode if given a `raw` option", function() -- this is useful for kong.tools.http_client local str = utils.encode_args({ ["hello world"] = "foo, bar" }, true) assert.equal("hello world=foo, bar", str) end) -- while this method's purpose is to mimic 100% the behavior of ngx.encode_args, -- it is also used by Kong specs' http_client, to encode both querystrings and *bodies*. -- Hence, a `raw` parameter allows encoding for bodies. describe("raw", function() it("should not percent-encode values", function() local str = utils.encode_args({ foo = "hello world" }, true) assert.equal("foo=hello world", str) end) it("should not percent-encode keys", function() local str = utils.encode_args({ ["hello world"] = "foo" }, true) assert.equal("hello world=foo", str) end) it("should plainly include true and false values", function() local str = utils.encode_args({ a = true, b = false }, true) assert.equal("a=true&b=false", str) end) it("should prevent double percent-encoding", function() local str = utils.encode_args({ foo = "hello%20world" }, true) assert.equal("foo=hello%20world", str) end) end) end) end) describe("table", function() describe("table_contains()", function() it("should return false if a value is not contained in a nil table", function() assert.False(utils.table_contains(nil, "foo")) end) it("should return true if a value is contained in a table", function() local t = { foo = "hello", bar = "world" } assert.True(utils.table_contains(t, "hello")) end) it("should return false if a value is not contained in a table", function() local t = { foo = "hello", bar = "world" } assert.False(utils.table_contains(t, "foo")) end) end) describe("is_array()", function() it("should know when an array ", function() assert.True(utils.is_array({ "a", "b", "c", "d" })) assert.True(utils.is_array({ ["1"] = "a", ["2"] = "b", ["3"] = "c", ["4"] = "d" })) assert.False(utils.is_array({ "a", "b", "c", foo = "d" })) assert.False(utils.is_array()) assert.False(utils.is_array(false)) assert.False(utils.is_array(true)) end) end) describe("add_error()", function() local add_error = utils.add_error it("should create a table if given `errors` is nil", function() assert.same({hello = "world"}, add_error(nil, "hello", "world")) end) it("should add a key/value when the key does not exists", function() local errors = {hello = "world"} assert.same({ hello = "world", foo = "bar" }, add_error(errors, "foo", "bar")) end) it("should transform previous values to a list if the same key is given again", function() local e = nil -- initialize for luacheck e = add_error(e, "key1", "value1") e = add_error(e, "key2", "value2") assert.same({key1 = "value1", key2 = "value2"}, e) e = add_error(e, "key1", "value3") e = add_error(e, "key1", "value4") assert.same({key1 = {"value1", "value3", "value4"}, key2 = "value2"}, e) e = add_error(e, "key1", "value5") e = add_error(e, "key1", "value6") e = add_error(e, "key2", "value7") assert.same({key1 = {"value1", "value3", "value4", "value5", "value6"}, key2 = {"value2", "value7"}}, e) end) it("should also list tables pushed as errors", function() local e = nil -- initialize for luacheck e = add_error(e, "key1", "value1") e = add_error(e, "key2", "value2") e = add_error(e, "key1", "value3") e = add_error(e, "key1", "value4") e = add_error(e, "keyO", {message = "some error"}) e = add_error(e, "keyO", {message = "another"}) assert.same({ key1 = {"value1", "value3", "value4"}, key2 = "value2", keyO = {{message = "some error"}, {message = "another"}} }, e) end) end) describe("load_module_if_exists()", function() it("should return false if the module does not exist", function() local loaded, mod assert.has_no.errors(function() loaded, mod = utils.load_module_if_exists("kong.does.not.exist") end) assert.False(loaded) assert.is.string(mod) end) it("should throw an error if the module is invalid", function() assert.has.errors(function() utils.load_module_if_exists("spec.fixtures.invalid-module") end) end) it("should load a module if it was found and valid", function() local loaded, mod assert.has_no.errors(function() loaded, mod = utils.load_module_if_exists("spec.fixtures.valid-module") end) assert.True(loaded) assert.truthy(mod) assert.are.same("All your base are belong to us.", mod.exposed) end) end) end) describe("hostnames and ip addresses", function() describe("hostname_type", function() -- no check on "name" type as anything not ipv4 and not ipv6 will be labelled as 'name' anyway it("checks valid IPv4 address types", function() assert.are.same("ipv4", utils.hostname_type("123.123.123.123")) assert.are.same("ipv4", utils.hostname_type("1.2.3.4")) assert.are.same("ipv4", utils.hostname_type("1.2.3.4:80")) end) it("checks valid IPv6 address types", function() assert.are.same("ipv6", utils.hostname_type("::1")) assert.are.same("ipv6", utils.hostname_type("2345::6789")) assert.are.same("ipv6", utils.hostname_type("0001:0001:0001:0001:0001:0001:0001:0001")) assert.are.same("ipv6", utils.hostname_type("[2345::6789]:80")) end) end) describe("parsing", function() it("normalizes IPv4 address types", function() assert.are.same({"123.123.123.123"}, {utils.normalize_ipv4("123.123.123.123")}) assert.are.same({"123.123.123.123", 80}, {utils.normalize_ipv4("123.123.123.123:80")}) assert.are.same({"1.1.1.1"}, {utils.normalize_ipv4("1.1.1.1")}) assert.are.same({"1.1.1.1", 80}, {utils.normalize_ipv4("001.001.001.001:00080")}) end) it("fails normalizing bad IPv4 address types", function() assert.is_nil(utils.normalize_ipv4("123.123:80")) assert.is_nil(utils.normalize_ipv4("123.123.123.999")) assert.is_nil(utils.normalize_ipv4("123.123.123.123:80a")) assert.is_nil(utils.normalize_ipv4("123.123.123.123.123:80")) assert.is_nil(utils.normalize_ipv4("localhost:80")) assert.is_nil(utils.normalize_ipv4("[::1]:80")) assert.is_nil(utils.normalize_ipv4("123.123.123.123:99999")) end) it("normalizes IPv6 address types", function() assert.are.same({"0000:0000:0000:0000:0000:0000:0000:0001"}, {utils.normalize_ipv6("::1")}) assert.are.same({"0000:0000:0000:0000:0000:0000:0000:0001"}, {utils.normalize_ipv6("[::1]")}) assert.are.same({"0000:0000:0000:0000:0000:0000:0000:0001", 80}, {utils.normalize_ipv6("[::1]:80")}) assert.are.same({"0000:0000:0000:0000:0000:0000:0000:0001", 80}, {utils.normalize_ipv6("[0000:0000:0000:0000:0000:0000:0000:0001]:80")}) end) it("fails normalizing bad IPv6 address types", function() assert.is_nil(utils.normalize_ipv6("123.123.123.123")) assert.is_nil(utils.normalize_ipv6("localhost:80")) assert.is_nil(utils.normalize_ipv6("::x")) assert.is_nil(utils.normalize_ipv6("[::x]:80")) assert.is_nil(utils.normalize_ipv6("[::1]:80a")) assert.is_nil(utils.normalize_ipv6("1")) assert.is_nil(utils.normalize_ipv6("[::1]:99999")) end) it("validates hostnames", function() local valids = {"hello.com", "hello.fr", "test.hello.com", "1991.io", "hello.COM", "HELLO.com", "123helloWORLD.com", "mockbin.123", "mockbin-api.com", "hello.abcd", "mockbin_api.com", "localhost", -- punycode examples from RFC3492; https://tools.ietf.org/html/rfc3492#page-14 -- specifically the japanese ones as they mix ascii with escaped characters "3B-ww4c5e180e575a65lsy2b", "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n", "Hello-Another-Way--fc4qua05auwb3674vfr0b", "2-u9tlzr9756bt3uc0v", "MajiKoi5-783gue6qz075azm5e", "de-jg4avhby1noc0d", "d9juau41awczczp", } local invalids = {"/mockbin", ".mockbin", "mockbin.", "mock;bin", "mockbin.com/org", "mockbin-.org", "mockbin.org-", "hello..mockbin.com", "hello-.mockbin.com", } for _, name in ipairs(valids) do assert.are.same(name, (utils.check_hostname(name))) end for _, name in ipairs(valids) do assert.are.same({ [1] = name, [2] = 80}, { utils.check_hostname(name..":80")}) end for _, name in ipairs(valids) do assert.is_nil((utils.check_hostname(name..":xx"))) assert.is_nil((utils.check_hostname(name..":99999"))) end for _, name in ipairs(invalids) do assert.is_nil((utils.check_hostname(name))) assert.is_nil((utils.check_hostname(name..":80"))) end end) it("validates addresses", function() assert.are.same({host = "1.2.3.4", type = "ipv4", port = 80}, utils.normalize_ip("1.2.3.4:80")) assert.are.same({host = "1.2.3.4", type = "ipv4", port = nil}, utils.normalize_ip("1.2.3.4")) assert.are.same({host = "0000:0000:0000:0000:0000:0000:0000:0001", type = "ipv6", port = 80}, utils.normalize_ip("[::1]:80")) assert.are.same({host = "0000:0000:0000:0000:0000:0000:0000:0001", type = "ipv6", port = nil}, utils.normalize_ip("::1")) assert.are.same({host = "localhost", type = "name", port = 80}, utils.normalize_ip("localhost:80")) assert.are.same({host = "mashape.com", type = "name", port = nil}, utils.normalize_ip("mashape.com")) assert.is_nil((utils.normalize_ip("1.2.3.4:8x0"))) assert.is_nil((utils.normalize_ip("1.2.3.400"))) assert.is_nil((utils.normalize_ip("[::1]:8x0"))) assert.is_nil((utils.normalize_ip(":x:1"))) assert.is_nil((utils.normalize_ip("localhost:8x0"))) assert.is_nil((utils.normalize_ip("mashape..com"))) end) end) describe("formatting", function() it("correctly formats addresses", function() assert.are.equal("1.2.3.4", utils.format_host("1.2.3.4")) assert.are.equal("1.2.3.4:80", utils.format_host("1.2.3.4", 80)) assert.are.equal("[::1]", utils.format_host("::1")) assert.are.equal("[::1]:80", utils.format_host("::1", 80)) assert.are.equal("localhost", utils.format_host("localhost")) assert.are.equal("mashape.com:80", utils.format_host("mashape.com", 80)) -- passthrough (string) assert.are.equal("1.2.3.4", utils.format_host(utils.normalize_ipv4("1.2.3.4"))) assert.are.equal("1.2.3.4:80", utils.format_host(utils.normalize_ipv4("1.2.3.4:80"))) assert.are.equal("[0000:0000:0000:0000:0000:0000:0000:0001]", utils.format_host(utils.normalize_ipv6("::1"))) assert.are.equal("[0000:0000:0000:0000:0000:0000:0000:0001]:80", utils.format_host(utils.normalize_ipv6("[::1]:80"))) assert.are.equal("localhost", utils.format_host(utils.check_hostname("localhost"))) assert.are.equal("mashape.com:80", utils.format_host(utils.check_hostname("mashape.com:80"))) -- passthrough general (table) assert.are.equal("1.2.3.4", utils.format_host(utils.normalize_ip("1.2.3.4"))) assert.are.equal("1.2.3.4:80", utils.format_host(utils.normalize_ip("1.2.3.4:80"))) assert.are.equal("[0000:0000:0000:0000:0000:0000:0000:0001]", utils.format_host(utils.normalize_ip("::1"))) assert.are.equal("[0000:0000:0000:0000:0000:0000:0000:0001]:80", utils.format_host(utils.normalize_ip("[::1]:80"))) assert.are.equal("localhost", utils.format_host(utils.normalize_ip("localhost"))) assert.are.equal("mashape.com:80", utils.format_host(utils.normalize_ip("mashape.com:80"))) -- passthrough errors local one, two = utils.format_host(utils.normalize_ipv4("1.2.3.4.5")) assert.are.equal("nilstring", type(one)..type(two)) local one, two = utils.format_host(utils.normalize_ipv6("not ipv6 ...")) assert.are.equal("nilstring", type(one)..type(two)) local one, two = utils.format_host(utils.check_hostname("//bad..name\\:123")) assert.are.equal("nilstring", type(one)..type(two)) local one, two = utils.format_host(utils.normalize_ip("m a s h a p e.com:80")) assert.are.equal("nilstring", type(one)..type(two)) end) end) end) it("validate_header_name() validates header names", function() local header_chars = [[-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]] for i = 1, 255 do local c = string.char(i) if string.find(header_chars, c, nil, true) then assert(utils.validate_header_name(c) == c, "ascii character '" .. c .. "' (" .. i .. ") should have been allowed") else assert(utils.validate_header_name(c) == nil, "ascii character " .. i .. " should not have been allowed") end end end) end)
apache-2.0
Ninjistix/darkstar
scripts/globals/items/dish_of_spaghetti_pescatora_+1.lua
3
1305
----------------------------------------- -- ID: 5200 -- Item: dish_of_spaghetti_pescatora_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Health % 15 -- Health Cap 160 -- Vitality 3 -- Mind -1 -- Defense % 22 -- Defense Cap 70 -- Store TP 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5200); end; function onEffectGain(target, effect) target:addMod(MOD_FOOD_HPP, 15); target:addMod(MOD_FOOD_HP_CAP, 160); target:addMod(MOD_VIT, 3); target:addMod(MOD_MND, -1); target:addMod(MOD_FOOD_DEFP, 22); target:addMod(MOD_FOOD_DEF_CAP, 70); target:addMod(MOD_STORETP, 6); end; function onEffectLose(target, effect) target:delMod(MOD_FOOD_HPP, 15); target:delMod(MOD_FOOD_HP_CAP, 160); target:delMod(MOD_VIT, 3); target:delMod(MOD_MND, -1); target:delMod(MOD_FOOD_DEFP, 22); target:delMod(MOD_FOOD_DEF_CAP, 70); target:delMod(MOD_STORETP, 6); end;
gpl-3.0
aqasaeed/hesambot
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
fegimanam/LPT
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
Ninjistix/darkstar
scripts/globals/items/divine_sword_+1.lua
7
1045
----------------------------------------- -- ID: 16826 -- Item: Divine Sword +1 -- Additional Effect: Light Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(7,21); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg); local message = msgBasic.ADD_EFFECT_DMG; if (dmg < 0) then message = msgBasic.ADD_EFFECT_HEAL; end return SUBEFFECT_LIGHT_DAMAGE,message,dmg; end end;
gpl-3.0
yuryleb/osrm-backend
profiles/lib/relations.lua
13
6783
-- Profile functions dealing with various aspects of relation parsing -- -- You can run a selection you find useful in your profile, -- or do you own processing if/when required. Utils = require('lib/utils') Relations = {} function is_direction(role) return (role == 'north' or role == 'south' or role == 'west' or role == 'east') end -- match ref values to relations data function Relations.match_to_ref(relations, ref) function calculate_scores(refs, tag_value) local tag_tokens = Set(Utils.tokenize_common(tag_value)) local result = {} for i, r in ipairs(refs) do local ref_tokens = Utils.tokenize_common(r) local score = 0 for _, t in ipairs(ref_tokens) do if tag_tokens[t] then if Utils.is_number(t) then score = score + 2 else score = score + 1 end end end result[r] = score end return result end local references = Utils.string_list_tokens(ref) local result_match = {} local order = {} for i, r in ipairs(references) do result_match[r] = { forward = nil, backward = nil } order[i] = r end for i, rel in ipairs(relations) do local name_scores = nil local name_tokens = {} local route_name = rel["route_name"] if route_name then name_scores = calculate_scores(references, route_name) end local ref_scores = nil local ref_tokens = {} local route_ref = rel["route_ref"] if route_ref then ref_scores = calculate_scores(references, route_ref) end -- merge scores local direction = rel["route_direction"] if direction then local best_score = -1 local best_ref = nil function find_best(scores) if scores then for k ,v in pairs(scores) do if v > best_score then best_ref = k best_score = v end end end end find_best(name_scores) find_best(ref_scores) if best_ref then local result_direction = result_match[best_ref] local is_forward = rel["route_forward"] if is_forward == nil then result_direction.forward = direction result_direction.backward = direction elseif is_forward == true then result_direction.forward = direction else result_direction.backward = direction end result_match[best_ref] = result_direction end end end local result = {} for i, r in ipairs(order) do result[i] = { ref = r, dir = result_match[r] }; end return result end function get_direction_from_superrel(rel, relations) local result = nil local result_id = nil local rel_id_list = relations:get_relations(rel) function set_result(direction, current_rel) if (result ~= nil) and (direction ~= nil) then print('WARNING: relation ' .. rel:id() .. ' is a part of more then one supperrelations ' .. result_id .. ' and ' .. current_rel:id()) result = nil else result = direction result_id = current_rel:id() end end for i, rel_id in ipairs(rel_id_list) do local parent_rel = relations:relation(rel_id) if parent_rel:get_value_by_key('type') == 'route' then local role = parent_rel:get_role(rel) if is_direction(role) then set_result(role, parent_rel) else local dir = parent_rel:get_value_by_key('direction') if is_direction(dir) then set_result(dir, parent_rel) end end end -- TODO: support forward/backward end return result end function Relations.parse_route_relation(rel, way, relations) local t = rel:get_value_by_key("type") local role = rel:get_role(way) local result = {} function add_extra_data(m) local name = rel:get_value_by_key("name") if name then result['route_name'] = name end local ref = rel:get_value_by_key("ref") if ref then result['route_ref'] = ref end end if t == 'route' then local role_direction = nil local route = rel:get_value_by_key("route") if route == 'road' then -- process case, where directions set as role if is_direction(role) then role_direction = role end end local tag_direction = nil local direction = rel:get_value_by_key('direction') if direction then direction = string.lower(direction) if is_direction(direction) then tag_direction = direction end end -- determine direction local result_direction = role_direction if result_direction == nil and tag_direction ~= '' then result_direction = tag_direction end if role_direction ~= nil and tag_direction ~= nil and role_direction ~= tag_direction then result_direction = nil print('WARNING: conflict direction in role of way ' .. way:id() .. ' and direction tag in relation ' .. rel:id()) end -- process superrelations local super_dir = get_direction_from_superrel(rel, relations) -- check if there are data error if (result_direction ~= nil) and (super_dir ~= nil) and (result_direction ~= super_dir) then print('ERROR: conflicting relation directions found for way ' .. way:id() .. ' relation direction is ' .. result_direction .. ' superrelation direction is ' .. super_dir) result_direction = nil elseif result_direction == nil then result_direction = super_dir end result['route_direction'] = result_direction if role == 'forward' then result['route_forward'] = true elseif role == 'backward' then result['route_forward'] = false else result['route_forward'] = nil end add_extra_data(m) end return result end function Relations.process_way_refs(way, relations, result) local parsed_rel_list = {} local rel_id_list = relations:get_relations(way) for i, rel_id in ipairs(rel_id_list) do local rel = relations:relation(rel_id) parsed_rel_list[i] = Relations.parse_route_relation(rel, way, relations) end -- now process relations data local matched_refs = nil; if result.ref then local match_res = Relations.match_to_ref(parsed_rel_list, result.ref) function gen_ref(is_forward) local ref = '' for _, m in pairs(match_res) do if ref ~= '' then ref = ref .. '; ' end local dir = m.dir.forward if is_forward == false then dir = m.dir.backward end if dir then ref = ref .. m.ref .. ' $' .. dir else ref = ref .. m.ref end end return ref end result.forward_ref = gen_ref(true) result.backward_ref = gen_ref(false) end end return Relations
bsd-2-clause
LuaDist2/llui
src/drm.lua
3
7835
local ffi = require("ffi") local bit = require("bit") local band, bor = bit.band, bit.bor local lshift, rshift = bit.lshift, bit.rshift local Lib_drm = require("drm_ffi") local libc = require("libc") local DRM_IOCTL_BASE = 'd' local function DRM_IO(nr) return libc._IO(DRM_IOCTL_BASE,nr) end local function DRM_IOR(nr,type) return libc._IOR(DRM_IOCTL_BASE,nr,type) end local function DRM_IOW(nr,type) return libc._IOW(DRM_IOCTL_BASE,nr,type) end local function DRM_IOWR(nr,type) return libc._IOWR(DRM_IOCTL_BASE,nr,type) end local T = ffi.typeof local _DRM_LOCK_HELD =0x80000000; --*< Hardware lock is held local _DRM_LOCK_CONT =0x40000000; --*< Hardware lock is contended local exports = { Lib_drm = Lib_drm; -- drm_mode = drm_mode; DRM_NAME = "drm"; --*< Name in kernel, /dev, and /proc DRM_MIN_ORDER = 5; --*< At least 2^5 bytes = 32 bytes DRM_MAX_ORDER = 22; --*< Up to 2^22 bytes = 4MB DRM_RAM_PERCENT = 10; --*< How much system ram can we lock? _DRM_LOCK_IS_HELD = function(lock) return band(lock, _DRM_LOCK_HELD) end; _DRM_LOCK_IS_CONT = function(lock) return band(lock, _DRM_LOCK_CONT) end; _DRM_LOCKING_CONTEXT = function(lock) return band(lock, bnot(bor(_DRM_LOCK_HELD,_DRM_LOCK_CONT))) end; DRM_EVENT_VBLANK = 0x01; DRM_EVENT_FLIP_COMPLETE = 0x02; _DRM_VBLANK_HIGH_CRTC_SHIFT = 1; _DRM_VBLANK_TYPES_MASK = bor(ffi.C._DRM_VBLANK_ABSOLUTE, ffi.C._DRM_VBLANK_RELATIVE); _DRM_VBLANK_FLAGS_MASK = bor(ffi.C._DRM_VBLANK_EVENT, ffi.C._DRM_VBLANK_SIGNAL, ffi.C._DRM_VBLANK_SECONDARY, ffi.C._DRM_VBLANK_NEXTONMISS); _DRM_PRE_MODESET = 1; _DRM_POST_MODESET = 2; -- Capabilities DRM_CAP_DUMB_BUFFER = 0x1; DRM_CAP_VBLANK_HIGH_CRTC = 0x2; DRM_CAP_DUMB_PREFERRED_DEPTH = 0x3; DRM_CAP_DUMB_PREFER_SHADOW = 0x4; DRM_CAP_PRIME = 0x5; DRM_PRIME_CAP_IMPORT = 0x1; DRM_PRIME_CAP_EXPORT = 0x2; DRM_CAP_TIMESTAMP_MONOTONIC = 0x6; DRM_CAP_ASYNC_PAGE_FLIP = 0x7; DRM_CAP_CURSOR_WIDTH = 0x8; DRM_CAP_CURSOR_HEIGHT = 0x9; DRM_CAP_ADDFB2_MODIFIERS = 0x10; DRM_CLIENT_CAP_STEREO_3D = 1; DRM_CLIENT_CAP_UNIVERSAL_PLANES = 2; DRM_CLIENT_CAP_ATOMIC = 3; DRM_CLOEXEC = libc.O_CLOEXEC; -- IOCTL DRM_IOCTL_VERSION = DRM_IOWR(0x00, T'struct drm_version'); DRM_IOCTL_GET_UNIQUE = DRM_IOWR(0x01, T'struct drm_unique'); DRM_IOCTL_GET_MAGIC = DRM_IOR( 0x02, T'struct drm_auth'); DRM_IOCTL_IRQ_BUSID = DRM_IOWR(0x03, T'struct drm_irq_busid'); DRM_IOCTL_GET_MAP = DRM_IOWR(0x04, T'struct drm_map'); DRM_IOCTL_GET_CLIENT = DRM_IOWR(0x05, T'struct drm_client'); DRM_IOCTL_GET_STATS = DRM_IOR( 0x06, T'struct drm_stats'); DRM_IOCTL_SET_VERSION = DRM_IOWR(0x07, T'struct drm_set_version'); DRM_IOCTL_MODESET_CTL = DRM_IOW(0x08, T'struct drm_modeset_ctl'); DRM_IOCTL_GEM_CLOSE = DRM_IOW (0x09, T'struct drm_gem_close'); DRM_IOCTL_GEM_FLINK = DRM_IOWR(0x0a, T'struct drm_gem_flink'); DRM_IOCTL_GEM_OPEN = DRM_IOWR(0x0b, T'struct drm_gem_open'); DRM_IOCTL_GET_CAP = DRM_IOWR(0x0c, T'struct drm_get_cap'); DRM_IOCTL_SET_CLIENT_CAP= DRM_IOW( 0x0d, T'struct drm_set_client_cap'); DRM_IOCTL_SET_UNIQUE = DRM_IOW( 0x10, T'struct drm_unique'); DRM_IOCTL_AUTH_MAGIC = DRM_IOW( 0x11, T'struct drm_auth'); DRM_IOCTL_BLOCK = DRM_IOWR(0x12, T'struct drm_block'); DRM_IOCTL_UNBLOCK = DRM_IOWR(0x13, T'struct drm_block'); DRM_IOCTL_CONTROL = DRM_IOW( 0x14, T'struct drm_control'); DRM_IOCTL_ADD_MAP = DRM_IOWR(0x15, T'struct drm_map'); DRM_IOCTL_ADD_BUFS = DRM_IOWR(0x16, T'struct drm_buf_desc'); DRM_IOCTL_MARK_BUFS = DRM_IOW( 0x17, T'struct drm_buf_desc'); DRM_IOCTL_INFO_BUFS = DRM_IOWR(0x18, T'struct drm_buf_info'); DRM_IOCTL_MAP_BUFS = DRM_IOWR(0x19, T'struct drm_buf_map'); DRM_IOCTL_FREE_BUFS = DRM_IOW( 0x1a, T'struct drm_buf_free'); DRM_IOCTL_RM_MAP = DRM_IOW( 0x1b, T'struct drm_map'); DRM_IOCTL_SET_SAREA_CTX = DRM_IOW( 0x1c, T'struct drm_ctx_priv_map'); DRM_IOCTL_GET_SAREA_CTX = DRM_IOWR(0x1d, T'struct drm_ctx_priv_map'); DRM_IOCTL_SET_MASTER = DRM_IO(0x1e); DRM_IOCTL_DROP_MASTER = DRM_IO(0x1f); DRM_IOCTL_ADD_CTX =DRM_IOWR(0x20, T'struct drm_ctx'); DRM_IOCTL_RM_CTX =DRM_IOWR(0x21, T'struct drm_ctx'); DRM_IOCTL_MOD_CTX =DRM_IOW( 0x22, T'struct drm_ctx'); DRM_IOCTL_GET_CTX =DRM_IOWR(0x23, T'struct drm_ctx'); DRM_IOCTL_SWITCH_CTX =DRM_IOW( 0x24, T'struct drm_ctx'); DRM_IOCTL_NEW_CTX =DRM_IOW( 0x25, T'struct drm_ctx'); DRM_IOCTL_RES_CTX =DRM_IOWR(0x26, T'struct drm_ctx_res'); DRM_IOCTL_ADD_DRAW =DRM_IOWR(0x27, T'struct drm_draw'); DRM_IOCTL_RM_DRAW =DRM_IOWR(0x28, T'struct drm_draw'); DRM_IOCTL_DMA =DRM_IOWR(0x29, T'struct drm_dma'); DRM_IOCTL_LOCK =DRM_IOW( 0x2a, T'struct drm_lock'); DRM_IOCTL_UNLOCK =DRM_IOW( 0x2b, T'struct drm_lock'); DRM_IOCTL_FINISH =DRM_IOW( 0x2c, T'struct drm_lock'); DRM_IOCTL_PRIME_HANDLE_TO_FD = DRM_IOWR(0x2d, T'struct drm_prime_handle'); DRM_IOCTL_PRIME_FD_TO_HANDLE = DRM_IOWR(0x2e, T'struct drm_prime_handle'); DRM_IOCTL_AGP_ACQUIRE = DRM_IO( 0x30); DRM_IOCTL_AGP_RELEASE = DRM_IO( 0x31); DRM_IOCTL_AGP_ENABLE = DRM_IOW( 0x32, T'struct drm_agp_mode'); DRM_IOCTL_AGP_INFO =DRM_IOR( 0x33, T'struct drm_agp_info'); DRM_IOCTL_AGP_ALLOC =DRM_IOWR(0x34, T'struct drm_agp_buffer'); DRM_IOCTL_AGP_FREE =DRM_IOW( 0x35, T'struct drm_agp_buffer'); DRM_IOCTL_AGP_BIND =DRM_IOW( 0x36, T'struct drm_agp_binding'); DRM_IOCTL_AGP_UNBIND = DRM_IOW( 0x37, T'struct drm_agp_binding'); DRM_IOCTL_SG_ALLOC =DRM_IOWR(0x38, T'struct drm_scatter_gather'); DRM_IOCTL_SG_FREE =DRM_IOW( 0x39, T'struct drm_scatter_gather'); DRM_IOCTL_WAIT_VBLANK = DRM_IOWR(0x3a, T'union drm_wait_vblank'); DRM_IOCTL_UPDATE_DRAW = DRM_IOW(0x3f, T'struct drm_update_draw'); DRM_IOCTL_MODE_GETRESOURCES =DRM_IOWR(0xA0, T'struct drm_mode_card_res'); DRM_IOCTL_MODE_GETCRTC =DRM_IOWR(0xA1, T'struct drm_mode_crtc'); DRM_IOCTL_MODE_SETCRTC =DRM_IOWR(0xA2, T'struct drm_mode_crtc'); DRM_IOCTL_MODE_CURSOR =DRM_IOWR(0xA3, T'struct drm_mode_cursor'); DRM_IOCTL_MODE_GETGAMMA =DRM_IOWR(0xA4, T'struct drm_mode_crtc_lut'); DRM_IOCTL_MODE_SETGAMMA =DRM_IOWR(0xA5, T'struct drm_mode_crtc_lut'); DRM_IOCTL_MODE_GETENCODER =DRM_IOWR(0xA6, T'struct drm_mode_get_encoder'); DRM_IOCTL_MODE_GETCONNECTOR =DRM_IOWR(0xA7, T'struct drm_mode_get_connector'); DRM_IOCTL_MODE_GETPROPERTY =DRM_IOWR(0xAA, T'struct drm_mode_get_property'); DRM_IOCTL_MODE_SETPROPERTY =DRM_IOWR(0xAB, T'struct drm_mode_connector_set_property'); DRM_IOCTL_MODE_GETPROPBLOB =DRM_IOWR(0xAC, T'struct drm_mode_get_blob'); DRM_IOCTL_MODE_GETFB =DRM_IOWR(0xAD, T'struct drm_mode_fb_cmd'); DRM_IOCTL_MODE_ADDFB =DRM_IOWR(0xAE, T'struct drm_mode_fb_cmd'); DRM_IOCTL_MODE_RMFB =DRM_IOWR(0xAF, T'unsigned int'); DRM_IOCTL_MODE_PAGE_FLIP =DRM_IOWR(0xB0, T'struct drm_mode_crtc_page_flip'); DRM_IOCTL_MODE_DIRTYFB =DRM_IOWR(0xB1, T'struct drm_mode_fb_dirty_cmd'); DRM_IOCTL_MODE_CREATE_DUMB =DRM_IOWR(0xB2, T'struct drm_mode_create_dumb'); DRM_IOCTL_MODE_MAP_DUMB =DRM_IOWR(0xB3, T'struct drm_mode_map_dumb'); DRM_IOCTL_MODE_DESTROY_DUMB =DRM_IOWR(0xB4, T'struct drm_mode_destroy_dumb'); DRM_IOCTL_MODE_GETPLANERESOURCES =DRM_IOWR(0xB5, T'struct drm_mode_get_plane_res'); DRM_IOCTL_MODE_GETPLANE =DRM_IOWR(0xB6, T'struct drm_mode_get_plane'); DRM_IOCTL_MODE_SETPLANE =DRM_IOWR(0xB7, T'struct drm_mode_set_plane'); DRM_IOCTL_MODE_ADDFB2 = DRM_IOWR(0xB8, T'struct drm_mode_fb_cmd2'); DRM_IOCTL_MODE_OBJ_GETPROPERTIES =DRM_IOWR(0xB9, T'struct drm_mode_obj_get_properties'); DRM_IOCTL_MODE_OBJ_SETPROPERTY =DRM_IOWR(0xBA, T'struct drm_mode_obj_set_property'); DRM_IOCTL_MODE_CURSOR2 =DRM_IOWR(0xBB, T'struct drm_mode_cursor2'); DRM_IOCTL_MODE_ATOMIC =DRM_IOWR(0xBC, T'struct drm_mode_atomic'); } setmetatable(exports, { __call = function(self, ...) for k,v in pairs(self) do _G[k] = v; end return self; end, }) return exports
mit
bmddota/ContainersPlayground
game/dota_addons/containersplayground/scripts/vscripts/libraries/abilities/containers_lua_targeting.lua
1
4913
containers_lua_targeting = class({}) -------------------------------------------------------------------------------- function containers_lua_targeting:GetBehavior() local result = CustomNetTables:GetTableValue("containers_lua", tostring(self:entindex())) if result then if bit.band(result.behavior, DOTA_ABILITY_BEHAVIOR_CHANNELLED) ~= 0 then return result.behavior - DOTA_ABILITY_BEHAVIOR_CHANNELLED end --print('not channeled') return result.behavior else return self.BaseClass.GetBehavior(self) end end function containers_lua_targeting:GetAOERadius() local result = CustomNetTables:GetTableValue("containers_lua", tostring(self:entindex())) if result then return result.aoe else return self.BaseClass.GetAOERadius(self) end end function containers_lua_targeting:GetCastRange(vLocation, hTarget) local result = CustomNetTables:GetTableValue("containers_lua", tostring(self:entindex())) if result then return result.range else return self.BaseClass.GetCastRange(self, vLocation, hTarget) end end function containers_lua_targeting:GetChannelTime() local result = CustomNetTables:GetTableValue("containers_lua", tostring(self:entindex())) if result then return result.channelTime else return self.BaseClass.GetChannelTime(self) end end function containers_lua_targeting:GetChannelledManaCostPerSecond(iLevel) local result = CustomNetTables:GetTableValue("containers_lua", tostring(self:entindex())) if result then return result.channelCost else return self.BaseClass.GetChannelledManaCostPerSecond(self, iLevel) end end -------------------------------------------------------------------------------- function containers_lua_targeting:CastFilterResultTarget( hTarget ) local result = CustomNetTables:GetTableValue("containers_lua", tostring(self:entindex())) --print(result.targetTeam, result.targetType, result.targetFlags) if not result then return UF_SUCCESS end local nResult = UnitFilter( hTarget, result.targetTeam, result.targetType, result.targetFlags, self:GetCaster():GetTeamNumber() ) if nResult ~= UF_SUCCESS then return nResult end return UF_SUCCESS end -------------------------------------------------------------------------------- function containers_lua_targeting:GetCustomCastErrorTarget( hTarget ) return "" end -------------------------------------------------------------------------------- function containers_lua_targeting:OnChannelThink(flInterval) local item = self.proxyItem self.proxyItem:OnChannelThink(flInterval) end function containers_lua_targeting:OnChannelFinish(bInterrupted) local item = self.proxyItem self.proxyItem:OnChannelFinish(bInterrupted) end function containers_lua_targeting:OnSpellStart() --[[print("Onspellstart") if IsServer() then print("server:") else print("client:") end]] local target = self:GetCursorTarget() local pos = self:GetCursorPosition() local item = self.proxyItem local owner = item:GetOwner() local behavior = item:GetBehavior() local channelled = bit.band(behavior, DOTA_ABILITY_BEHAVIOR_CHANNELLED) ~= 0 item:PayGoldCost() item:PayManaCost() item:StartCooldown(item:GetCooldown(item:GetLevel())) owner:SetCursorPosition(pos) owner:SetCursorCastTarget(target) item:OnSpellStart() --[[local hCaster = self:GetCaster() local hTarget = self:GetCursorTarget() if hCaster == nil or hTarget == nil or hTarget:TriggerSpellAbsorb( this ) then return end local vPos1 = hCaster:GetOrigin() local vPos2 = hTarget:GetOrigin() GridNav:DestroyTreesAroundPoint( vPos1, 300, false ) GridNav:DestroyTreesAroundPoint( vPos2, 300, false ) hCaster:SetOrigin( vPos2 ) hTarget:SetOrigin( vPos1 ) FindClearSpaceForUnit( hCaster, vPos2, true ) FindClearSpaceForUnit( hTarget, vPos1, true ) hTarget:Interrupt() local nCasterFX = ParticleManager:CreateParticle( "particles/units/heroes/hero_vengeful/vengeful_nether_swap.vpcf", PATTACH_ABSORIGIN_FOLLOW, hCaster ) ParticleManager:SetParticleControlEnt( nCasterFX, 1, hTarget, PATTACH_ABSORIGIN_FOLLOW, nil, hTarget:GetOrigin(), false ) ParticleManager:ReleaseParticleIndex( nCasterFX ) local nTargetFX = ParticleManager:CreateParticle( "particles/units/heroes/hero_vengeful/vengeful_nether_swap_target.vpcf", PATTACH_ABSORIGIN_FOLLOW, hTarget ) ParticleManager:SetParticleControlEnt( nTargetFX, 1, hCaster, PATTACH_ABSORIGIN_FOLLOW, nil, hCaster:GetOrigin(), false ) ParticleManager:ReleaseParticleIndex( nTargetFX ) EmitSoundOn( "Hero_VengefulSpirit.NetherSwap", hCaster ) EmitSoundOn( "Hero_VengefulSpirit.NetherSwap", hTarget ) hCaster:StartGesture( ACT_DOTA_CHANNEL_END_ABILITY_4 )]] end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
apache-2.0
garlick/flux-sched
conf/cab-io.lua
5
17269
uses "Node" Hierarchy "default" { Resource{ "filesystem", name="pfs", tags = { max_bw = 48000 }, children = { Resource {"gateway", name = "gateway_node_pool", tags = { max_bw = 48000 }, children = { Resource {"core_switch", name = "core_switch_pool", tags = { max_bw = 64000 }, children = { Resource {"switch", name = "edge_switch1", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1-18", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch2", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "19-36", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch3", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "37-54", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch4", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "55-72", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch5", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "73-90", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch6", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "91-108", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch7", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "109-126", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch8", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "127-144", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch9", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "145-160", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch10", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "163-180", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch11", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "181-198", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch12", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "199-216", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch13", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "217-234", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch14", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "235-252", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch15", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "253-270", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch16", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "271-288", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch17", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "289-306", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch18", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "307-322", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch19", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "325-342", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch20", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "343-360", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch21", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "361-378", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch22", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "379-396", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch23", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "397-414", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch24", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "415-432", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch25", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "433-450", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch26", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "451-468", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch27", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "469-484", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch28", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "487-504", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch29", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "505-522", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch30", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "523-540", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch31", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "541-558", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch32", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "559-576", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch33", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "577-594", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch34", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "595-612", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch35", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "613-630", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch36", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "631-646", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch37", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "649-666", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch38", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "667-684", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch39", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "685-702", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch40", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "703-720", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch41", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "721-738", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch42", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "739-756", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch43", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "757-774", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch44", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "775-792", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch45", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "793-808", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch46", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "811-828", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch47", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "829-846", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch48", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "847-864", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch49", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "865-882", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch50", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "883-900", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch51", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "901-918", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch52", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "919-936", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch53", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "937-954", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch54", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "955-970", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch55", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "973-990", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch56", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "991-1008", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch57", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1009-1026", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch58", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1027-1044", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch59", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1045-1062", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch60", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1063-1080", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch61", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1081-1098", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch62", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1099-1116", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch63", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1117-1132", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch64", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1135-1152", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch65", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1153-1170", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch66", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1171-1188", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch67", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1189-1206", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch68", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1207-1224", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch69", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1225-1242", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch70", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1243-1260", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch71", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1261-1278", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }}, Resource {"switch", name = "edge_switch72", tags = { max_bw = 72000 }, children = { ListOf{ Node, ids = "1279-1294", args = { name = "cab", sockets = {"0-7", "8-15"}, tags = { max_bw = 4000 }}} }} }} }} }} }
gpl-2.0
hamrah12/hamrah_shoma
plugins/steam.lua
645
2117
-- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI do local BASE_URL = 'http://store.steampowered.com/api/appdetails/' local DESC_LENTH = 200 local function unescape(str) str = string.gsub( str, '&lt;', '<' ) str = string.gsub( str, '&gt;', '>' ) str = string.gsub( str, '&quot;', '"' ) str = string.gsub( str, '&apos;', "'" ) str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end ) str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end ) str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others return str end local function get_steam_data (appid) local url = BASE_URL url = url..'?appids='..appid url = url..'&cc=us' local res,code = http.request(url) if code ~= 200 then return nil end local data = json:decode(res)[appid].data return data end local function price_info (data) local price = '' -- If no data is empty if data then local initial = data.initial local final = data.final or data.initial local min = math.min(data.initial, data.final) price = tostring(min/100) if data.discount_percent and initial ~= final then price = price..data.currency..' ('..data.discount_percent..'% OFF)' end price = price..' (US)' end return price end local function send_steam_data(data, receiver) local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...' local title = data.name local price = price_info(data.price_overview) local text = title..' '..price..'\n'..description local image_url = data.header_image local cb_extra = { receiver = receiver, url = image_url } send_msg(receiver, text, send_photo_from_url_callback, cb_extra) end local function run(msg, matches) local appid = matches[1] local data = get_steam_data(appid) local receiver = get_receiver(msg) send_steam_data(data, receiver) end return { description = "Grabs Steam info for Steam links.", usage = "", patterns = { "http://store.steampowered.com/app/([0-9]+)", }, run = run } end
gpl-2.0
eugenesan/openwrt-luci
contrib/luasrcdiet/lua/LuaSrcDiet.lua
122
23773
#!/usr/bin/env lua --[[-------------------------------------------------------------------- LuaSrcDiet Compresses Lua source code by removing unnecessary characters. For Lua 5.1.x source code. 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: -- * Remember to update version and date information below (MSG_TITLE) -- * TODO: to implement pcall() to properly handle lexer etc. errors -- * TODO: verify token stream or double-check binary chunk? -- * TODO: need some automatic testing for a semblance of sanity -- * TODO: the plugin module is highly experimental and unstable ----------------------------------------------------------------------]] -- standard libraries, functions local string = string local math = math local table = table local require = require local print = print local sub = string.sub local gmatch = string.gmatch -- support modules local llex = require "llex" local lparser = require "lparser" local optlex = require "optlex" local optparser = require "optparser" local plugin --[[-------------------------------------------------------------------- -- messages and textual data ----------------------------------------------------------------------]] local MSG_TITLE = [[ LuaSrcDiet: Puts your Lua 5.1 source code on a diet Version 0.11.2 (20080608) Copyright (c) 2005-2008 Kein-Hong Man The COPYRIGHT file describes the conditions under which this software may be distributed. ]] local MSG_USAGE = [[ usage: LuaSrcDiet [options] [filenames] example: >LuaSrcDiet myscript.lua -o myscript_.lua options: -v, --version prints version information -h, --help prints usage information -o <file> specify file name to write output -s <suffix> suffix for output files (default '_') --keep <msg> keep block comment with <msg> inside --plugin <module> run <module> in plugin/ directory - stop handling arguments (optimization levels) --none all optimizations off (normalizes EOLs only) --basic lexer-based optimizations only --maximum maximize reduction of source (informational) --quiet process files quietly --read-only read file and print token stats only --dump-lexer dump raw tokens from lexer to stdout --dump-parser dump variable tracking tables from parser --details extra info (strings, numbers, locals) features (to disable, insert 'no' prefix like --noopt-comments): %s default settings: %s]] ------------------------------------------------------------------------ -- optimization options, for ease of switching on and off -- * positive to enable optimization, negative (no) to disable -- * these options should follow --opt-* and --noopt-* style for now ------------------------------------------------------------------------ local OPTION = [[ --opt-comments,'remove comments and block comments' --opt-whitespace,'remove whitespace excluding EOLs' --opt-emptylines,'remove empty lines' --opt-eols,'all above, plus remove unnecessary EOLs' --opt-strings,'optimize strings and long strings' --opt-numbers,'optimize numbers' --opt-locals,'optimize local variable names' --opt-entropy,'tries to reduce symbol entropy of locals' ]] -- preset configuration local DEFAULT_CONFIG = [[ --opt-comments --opt-whitespace --opt-emptylines --opt-numbers --opt-locals ]] -- override configurations: MUST explicitly enable/disable everything local BASIC_CONFIG = [[ --opt-comments --opt-whitespace --opt-emptylines --noopt-eols --noopt-strings --noopt-numbers --noopt-locals ]] local MAXIMUM_CONFIG = [[ --opt-comments --opt-whitespace --opt-emptylines --opt-eols --opt-strings --opt-numbers --opt-locals --opt-entropy ]] local NONE_CONFIG = [[ --noopt-comments --noopt-whitespace --noopt-emptylines --noopt-eols --noopt-strings --noopt-numbers --noopt-locals ]] local DEFAULT_SUFFIX = "_" -- default suffix for file renaming local PLUGIN_SUFFIX = "plugin/" -- relative location of plugins --[[-------------------------------------------------------------------- -- startup and initialize option list handling ----------------------------------------------------------------------]] -- simple error message handler; change to error if traceback wanted local function die(msg) print("LuaSrcDiet: "..msg); os.exit() end --die = error--DEBUG if not string.match(_VERSION, "5.1", 1, 1) then -- sanity check die("requires Lua 5.1 to run") end ------------------------------------------------------------------------ -- prepares text for list of optimizations, prepare lookup table ------------------------------------------------------------------------ local MSG_OPTIONS = "" do local WIDTH = 24 local o = {} for op, desc in gmatch(OPTION, "%s*([^,]+),'([^']+)'") do local msg = " "..op msg = msg..string.rep(" ", WIDTH - #msg)..desc.."\n" MSG_OPTIONS = MSG_OPTIONS..msg o[op] = true o["--no"..sub(op, 3)] = true end OPTION = o -- replace OPTION with lookup table end MSG_USAGE = string.format(MSG_USAGE, MSG_OPTIONS, DEFAULT_CONFIG) ------------------------------------------------------------------------ -- global variable initialization, option set handling ------------------------------------------------------------------------ local suffix = DEFAULT_SUFFIX -- file suffix local option = {} -- program options local stat_c, stat_l -- statistics tables -- function to set option lookup table based on a text list of options -- note: additional forced settings for --opt-eols is done in optlex.lua local function set_options(CONFIG) for op in gmatch(CONFIG, "(%-%-%S+)") do if sub(op, 3, 4) == "no" and -- handle negative options OPTION["--"..sub(op, 5)] then option[sub(op, 5)] = false else option[sub(op, 3)] = true end end end --[[-------------------------------------------------------------------- -- support functions ----------------------------------------------------------------------]] -- list of token types, parser-significant types are up to TTYPE_GRAMMAR -- while the rest are not used by parsers; arranged for stats display local TTYPES = { "TK_KEYWORD", "TK_NAME", "TK_NUMBER", -- grammar "TK_STRING", "TK_LSTRING", "TK_OP", "TK_EOS", "TK_COMMENT", "TK_LCOMMENT", -- non-grammar "TK_EOL", "TK_SPACE", } local TTYPE_GRAMMAR = 7 local EOLTYPES = { -- EOL names for token dump ["\n"] = "LF", ["\r"] = "CR", ["\n\r"] = "LFCR", ["\r\n"] = "CRLF", } ------------------------------------------------------------------------ -- read source code from file ------------------------------------------------------------------------ local function load_file(fname) local INF = io.open(fname, "rb") if not INF then die("cannot open \""..fname.."\" for reading") end local dat = INF:read("*a") if not dat then die("cannot read from \""..fname.."\"") end INF:close() return dat end ------------------------------------------------------------------------ -- save source code to file ------------------------------------------------------------------------ local function save_file(fname, dat) local OUTF = io.open(fname, "wb") if not OUTF then die("cannot open \""..fname.."\" for writing") end local status = OUTF:write(dat) if not status then die("cannot write to \""..fname.."\"") end OUTF:close() end ------------------------------------------------------------------------ -- functions to deal with statistics ------------------------------------------------------------------------ -- initialize statistics table local function stat_init() stat_c, stat_l = {}, {} for i = 1, #TTYPES do local ttype = TTYPES[i] stat_c[ttype], stat_l[ttype] = 0, 0 end end -- add a token to statistics table local function stat_add(tok, seminfo) stat_c[tok] = stat_c[tok] + 1 stat_l[tok] = stat_l[tok] + #seminfo end -- do totals for statistics table, return average table local function stat_calc() local function avg(c, l) -- safe average function if c == 0 then return 0 end return l / c end local stat_a = {} local c, l = 0, 0 for i = 1, TTYPE_GRAMMAR do -- total grammar tokens local ttype = TTYPES[i] c = c + stat_c[ttype]; l = l + stat_l[ttype] end stat_c.TOTAL_TOK, stat_l.TOTAL_TOK = c, l stat_a.TOTAL_TOK = avg(c, l) c, l = 0, 0 for i = 1, #TTYPES do -- total all tokens local ttype = TTYPES[i] c = c + stat_c[ttype]; l = l + stat_l[ttype] stat_a[ttype] = avg(stat_c[ttype], stat_l[ttype]) end stat_c.TOTAL_ALL, stat_l.TOTAL_ALL = c, l stat_a.TOTAL_ALL = avg(c, l) return stat_a end --[[-------------------------------------------------------------------- -- main tasks ----------------------------------------------------------------------]] ------------------------------------------------------------------------ -- a simple token dumper, minimal translation of seminfo data ------------------------------------------------------------------------ local function dump_tokens(srcfl) -------------------------------------------------------------------- -- load file and process source input into tokens -------------------------------------------------------------------- local z = load_file(srcfl) llex.init(z) llex.llex() local toklist, seminfolist = llex.tok, llex.seminfo -------------------------------------------------------------------- -- display output -------------------------------------------------------------------- for i = 1, #toklist do local tok, seminfo = toklist[i], seminfolist[i] if tok == "TK_OP" and string.byte(seminfo) < 32 then seminfo = "(".. string.byte(seminfo)..")" elseif tok == "TK_EOL" then seminfo = EOLTYPES[seminfo] else seminfo = "'"..seminfo.."'" end print(tok.." "..seminfo) end--for end ---------------------------------------------------------------------- -- parser dump; dump globalinfo and localinfo tables ---------------------------------------------------------------------- local function dump_parser(srcfl) local print = print -------------------------------------------------------------------- -- load file and process source input into tokens -------------------------------------------------------------------- local z = load_file(srcfl) llex.init(z) llex.llex() local toklist, seminfolist, toklnlist = llex.tok, llex.seminfo, llex.tokln -------------------------------------------------------------------- -- do parser optimization here -------------------------------------------------------------------- lparser.init(toklist, seminfolist, toklnlist) local globalinfo, localinfo = lparser.parser() -------------------------------------------------------------------- -- display output -------------------------------------------------------------------- local hl = string.rep("-", 72) print("*** Local/Global Variable Tracker Tables ***") print(hl.."\n GLOBALS\n"..hl) -- global tables have a list of xref numbers only for i = 1, #globalinfo do local obj = globalinfo[i] local msg = "("..i..") '"..obj.name.."' -> " local xref = obj.xref for j = 1, #xref do msg = msg..xref[j].." " end print(msg) end -- local tables have xref numbers and a few other special -- numbers that are specially named: decl (declaration xref), -- act (activation xref), rem (removal xref) print(hl.."\n LOCALS (decl=declared act=activated rem=removed)\n"..hl) for i = 1, #localinfo do local obj = localinfo[i] local msg = "("..i..") '"..obj.name.."' decl:"..obj.decl.. " act:"..obj.act.." rem:"..obj.rem if obj.isself then msg = msg.." isself" end msg = msg.." -> " local xref = obj.xref for j = 1, #xref do msg = msg..xref[j].." " end print(msg) end print(hl.."\n") end ------------------------------------------------------------------------ -- reads source file(s) and reports some statistics ------------------------------------------------------------------------ local function read_only(srcfl) local print = print -------------------------------------------------------------------- -- load file and process source input into tokens -------------------------------------------------------------------- local z = load_file(srcfl) llex.init(z) llex.llex() local toklist, seminfolist = llex.tok, llex.seminfo print(MSG_TITLE) print("Statistics for: "..srcfl.."\n") -------------------------------------------------------------------- -- collect statistics -------------------------------------------------------------------- stat_init() for i = 1, #toklist do local tok, seminfo = toklist[i], seminfolist[i] stat_add(tok, seminfo) end--for local stat_a = stat_calc() -------------------------------------------------------------------- -- display output -------------------------------------------------------------------- local fmt = string.format local function figures(tt) return stat_c[tt], stat_l[tt], stat_a[tt] end local tabf1, tabf2 = "%-16s%8s%8s%10s", "%-16s%8d%8d%10.2f" local hl = string.rep("-", 42) print(fmt(tabf1, "Lexical", "Input", "Input", "Input")) print(fmt(tabf1, "Elements", "Count", "Bytes", "Average")) print(hl) for i = 1, #TTYPES do local ttype = TTYPES[i] print(fmt(tabf2, ttype, figures(ttype))) if ttype == "TK_EOS" then print(hl) end end print(hl) print(fmt(tabf2, "Total Elements", figures("TOTAL_ALL"))) print(hl) print(fmt(tabf2, "Total Tokens", figures("TOTAL_TOK"))) print(hl.."\n") end ------------------------------------------------------------------------ -- process source file(s), write output and reports some statistics ------------------------------------------------------------------------ local function process_file(srcfl, destfl) local function print(...) -- handle quiet option if option.QUIET then return end _G.print(...) end if plugin and plugin.init then -- plugin init option.EXIT = false plugin.init(option, srcfl, destfl) if option.EXIT then return end end print(MSG_TITLE) -- title message -------------------------------------------------------------------- -- load file and process source input into tokens -------------------------------------------------------------------- local z = load_file(srcfl) if plugin and plugin.post_load then -- plugin post-load z = plugin.post_load(z) or z if option.EXIT then return end end llex.init(z) llex.llex() local toklist, seminfolist, toklnlist = llex.tok, llex.seminfo, llex.tokln if plugin and plugin.post_lex then -- plugin post-lex plugin.post_lex(toklist, seminfolist, toklnlist) if option.EXIT then return end end -------------------------------------------------------------------- -- collect 'before' statistics -------------------------------------------------------------------- stat_init() for i = 1, #toklist do local tok, seminfo = toklist[i], seminfolist[i] stat_add(tok, seminfo) end--for local stat1_a = stat_calc() local stat1_c, stat1_l = stat_c, stat_l -------------------------------------------------------------------- -- do parser optimization here -------------------------------------------------------------------- if option["opt-locals"] then optparser.print = print -- hack lparser.init(toklist, seminfolist, toklnlist) local globalinfo, localinfo = lparser.parser() if plugin and plugin.post_parse then -- plugin post-parse plugin.post_parse(globalinfo, localinfo) if option.EXIT then return end end optparser.optimize(option, toklist, seminfolist, globalinfo, localinfo) if plugin and plugin.post_optparse then -- plugin post-optparse plugin.post_optparse() if option.EXIT then return end end end -------------------------------------------------------------------- -- do lexer optimization here, save output file -------------------------------------------------------------------- optlex.print = print -- hack toklist, seminfolist, toklnlist = optlex.optimize(option, toklist, seminfolist, toklnlist) if plugin and plugin.post_optlex then -- plugin post-optlex plugin.post_optlex(toklist, seminfolist, toklnlist) if option.EXIT then return end end local dat = table.concat(seminfolist) -- depending on options selected, embedded EOLs in long strings and -- long comments may not have been translated to \n, tack a warning if string.find(dat, "\r\n", 1, 1) or string.find(dat, "\n\r", 1, 1) then optlex.warn.mixedeol = true end -- save optimized source stream to output file save_file(destfl, dat) -------------------------------------------------------------------- -- collect 'after' statistics -------------------------------------------------------------------- stat_init() for i = 1, #toklist do local tok, seminfo = toklist[i], seminfolist[i] stat_add(tok, seminfo) end--for local stat_a = stat_calc() -------------------------------------------------------------------- -- display output -------------------------------------------------------------------- print("Statistics for: "..srcfl.." -> "..destfl.."\n") local fmt = string.format local function figures(tt) return stat1_c[tt], stat1_l[tt], stat1_a[tt], stat_c[tt], stat_l[tt], stat_a[tt] end local tabf1, tabf2 = "%-16s%8s%8s%10s%8s%8s%10s", "%-16s%8d%8d%10.2f%8d%8d%10.2f" local hl = string.rep("-", 68) print("*** lexer-based optimizations summary ***\n"..hl) print(fmt(tabf1, "Lexical", "Input", "Input", "Input", "Output", "Output", "Output")) print(fmt(tabf1, "Elements", "Count", "Bytes", "Average", "Count", "Bytes", "Average")) print(hl) for i = 1, #TTYPES do local ttype = TTYPES[i] print(fmt(tabf2, ttype, figures(ttype))) if ttype == "TK_EOS" then print(hl) end end print(hl) print(fmt(tabf2, "Total Elements", figures("TOTAL_ALL"))) print(hl) print(fmt(tabf2, "Total Tokens", figures("TOTAL_TOK"))) print(hl) -------------------------------------------------------------------- -- report warning flags from optimizing process -------------------------------------------------------------------- if optlex.warn.lstring then print("* WARNING: "..optlex.warn.lstring) elseif optlex.warn.mixedeol then print("* WARNING: ".."output still contains some CRLF or LFCR line endings") end print() end --[[-------------------------------------------------------------------- -- main functions ----------------------------------------------------------------------]] local arg = {...} -- program arguments local fspec = {} set_options(DEFAULT_CONFIG) -- set to default options at beginning ------------------------------------------------------------------------ -- per-file handling, ship off to tasks ------------------------------------------------------------------------ local function do_files(fspec) for _, srcfl in ipairs(fspec) do local destfl ------------------------------------------------------------------ -- find and replace extension for filenames ------------------------------------------------------------------ local extb, exte = string.find(srcfl, "%.[^%.%\\%/]*$") local basename, extension = srcfl, "" if extb and extb > 1 then basename = sub(srcfl, 1, extb - 1) extension = sub(srcfl, extb, exte) end destfl = basename..suffix..extension if #fspec == 1 and option.OUTPUT_FILE then destfl = option.OUTPUT_FILE end if srcfl == destfl then die("output filename identical to input filename") end ------------------------------------------------------------------ -- perform requested operations ------------------------------------------------------------------ if option.DUMP_LEXER then dump_tokens(srcfl) elseif option.DUMP_PARSER then dump_parser(srcfl) elseif option.READ_ONLY then read_only(srcfl) else process_file(srcfl, destfl) end end--for end ------------------------------------------------------------------------ -- main function (entry point is after this definition) ------------------------------------------------------------------------ local function main() local argn, i = #arg, 1 if argn == 0 then option.HELP = true end -------------------------------------------------------------------- -- handle arguments -------------------------------------------------------------------- while i <= argn do local o, p = arg[i], arg[i + 1] local dash = string.match(o, "^%-%-?") if dash == "-" then -- single-dash options if o == "-h" then option.HELP = true; break elseif o == "-v" then option.VERSION = true; break elseif o == "-s" then if not p then die("-s option needs suffix specification") end suffix = p i = i + 1 elseif o == "-o" then if not p then die("-o option needs a file name") end option.OUTPUT_FILE = p i = i + 1 elseif o == "-" then break -- ignore rest of args else die("unrecognized option "..o) end elseif dash == "--" then -- double-dash options if o == "--help" then option.HELP = true; break elseif o == "--version" then option.VERSION = true; break elseif o == "--keep" then if not p then die("--keep option needs a string to match for") end option.KEEP = p i = i + 1 elseif o == "--plugin" then if not p then die("--plugin option needs a module name") end if option.PLUGIN then die("only one plugin can be specified") end option.PLUGIN = p plugin = require(PLUGIN_SUFFIX..p) i = i + 1 elseif o == "--quiet" then option.QUIET = true elseif o == "--read-only" then option.READ_ONLY = true elseif o == "--basic" then set_options(BASIC_CONFIG) elseif o == "--maximum" then set_options(MAXIMUM_CONFIG) elseif o == "--none" then set_options(NONE_CONFIG) elseif o == "--dump-lexer" then option.DUMP_LEXER = true elseif o == "--dump-parser" then option.DUMP_PARSER = true elseif o == "--details" then option.DETAILS = true elseif OPTION[o] then -- lookup optimization options set_options(o) else die("unrecognized option "..o) end else fspec[#fspec + 1] = o -- potential filename end i = i + 1 end--while if option.HELP then print(MSG_TITLE..MSG_USAGE); return true elseif option.VERSION then print(MSG_TITLE); return true end if #fspec > 0 then if #fspec > 1 and option.OUTPUT_FILE then die("with -o, only one source file can be specified") end do_files(fspec) return true else die("nothing to do!") end end -- entry point -> main() -> do_files() if not main() then die("Please run with option -h or --help for usage information") end -- end of script
apache-2.0
Ninjistix/darkstar
scripts/zones/Yuhtunga_Jungle/npcs/Uphra-Kophra_WW.lua
3
2976
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Uphra-Kophra, W.W. -- Outpost Conquest Guards -- !pos -242.487 -1 -402.772 123 ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yuhtunga_Jungle/TextIDs"); local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ELSHIMOLOWLANDS; local csid = 0x7ff7; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; 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; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; 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
makanishere/CycloneTG
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
dmccuskey/dmc-websockets
examples/dmc-websockets-autobahntestsuite/dmc_corona/lib/dmc_lua/lua_events_mix.lua
32
8316
--====================================================================-- -- dmc_lua/lua_events_mix.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2014-2015 David McCuskey. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Lua Library : Lua Events Mixin --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.2.2" --====================================================================-- --== Setup, Constants local Events local Utils = {} -- make copying from Utils easier local assert = assert local sfmt = string.format local type = type --====================================================================-- --== Support Functions --== Start: copy from lua_utils ==-- function Utils.createObjectCallback( object, method ) assert( object ~= nil, "missing object in Utils.createObjectCallback" ) assert( method ~= nil, "missing method in Utils.createObjectCallback" ) --==-- return function( ... ) return method( object, ... ) end end --== End: copy from lua_utils ==-- -- callback is either function or object (table) -- creates listener lookup key given event name and handler -- local function _createEventListenerKey( e_name, handler ) return e_name .. "::" .. tostring( handler ) end -- return event unmodified -- local function _createCoronaEvent( obj, event ) return event end -- obj, -- event type, string -- data, anything -- params, table of params -- params.merge, boolean, if to merge data (table) in with event table -- local function _createDmcEvent( obj, e_type, data, params ) params = params or {} if params.merge==nil then params.merge=false end --==-- local e if params.merge and type( data )=='table' then e = data e.name = obj.EVENT e.type = e_type e.target = obj else e = { name=obj.EVENT, type=e_type, target=obj, data=data } end return e end local function _patch( obj ) obj = obj or {} -- add properties Events.__init__( obj ) if obj.EVENT==nil then obj.EVENT = Events.EVENT -- generic event name end -- add methods obj.dispatchEvent = Events.dispatchEvent obj.dispatchRawEvent = Events.dispatchRawEvent obj.addEventListener = Events.addEventListener obj.removeEventListener = Events.removeEventListener obj.setDebug = Events.setDebug obj.setEventFunc = Events.setEventFunc obj._dispatchEvent = Events._dispatchEvent return obj end --====================================================================-- --== Events Mixin --====================================================================-- Events = {} Events.EVENT = 'event_mix_event' --======================================================-- -- Start: Mixin Setup for Lua Objects function Events.__init__( self, params ) -- print( "Events.__init__" ) params = params or {} --==-- --[[ event listeners key'd by: * <event name>::<function> * <event name>::<object> { <event name> = { 'event::function' = func, 'event::object' = object (table) } } --]] self.__event_listeners = {} -- holds event listeners self.__debug_on = false self.__event_func = params.event_func or _createDmcEvent end function Events.__undoInit__( self ) -- print( "Events.__undoInit__" ) self.__event_listeners = nil self.__debug_on = nil self.__event_func = nil end -- END: Mixin Setup for Lua Objects --======================================================-- --====================================================================-- --== Public Methods function Events.createCallback( self, method ) return Utils.createObjectCallback( self, method ) end function Events.setDebug( self, value ) assert( type( value )=='boolean', "setDebug requires boolean" ) self.__debug_on = value end function Events.setEventFunc( self, func ) assert( func and type(func)=='function', 'setEventFunc requires function' ) self.__event_func = func end function Events.createEvent( self, ... ) return self.__event_func( self, ... ) end function Events.dispatchEvent( self, ... ) -- print( "Events.dispatchEvent" ) local f = self.__event_func self:_dispatchEvent( f( self, ... ) ) end function Events.dispatchRawEvent( self, event ) -- print( "Events.dispatchRawEvent", event ) assert( type( event )=='table', "wrong type for event" ) assert( event.name, "event must have property 'name'") --==-- self:_dispatchEvent( event ) end -- addEventListener() -- function Events.addEventListener( self, e_name, listener ) -- print( "Events.addEventListener", e_name, listener ) assert( type( e_name )=='string', sfmt( "Events.addEventListener event name should be a string, received '%s'", tostring(e_name)) ) assert( type(listener)=='function' or type(listener)=='table', sfmt( "Events.addEventListener callback should be function or object, received '%s'", tostring(listener) )) -- Sanity Check if not e_name or type( e_name )~='string' then error( "ERROR addEventListener: event name must be string", 2 ) end if not listener and not Utils.propertyIn( {'function','table'}, type(listener) ) then error( "ERROR addEventListener: listener must be a function or object", 2 ) end -- Processing local events, listeners, key events = self.__event_listeners if not events[ e_name ] then events[ e_name ] = {} end listeners = events[ e_name ] key = _createEventListenerKey( e_name, listener ) if listeners[ key ] then print("WARNING:: Events:addEventListener, already have listener") else listeners[ key ] = listener end end -- removeEventListener() -- function Events.removeEventListener( self, e_name, listener ) -- print( "Events.removeEventListener" ); local listeners, key listeners = self.__event_listeners[ e_name ] if not listeners or type(listeners)~= 'table' then print( "WARNING:: Events:removeEventListener, no listeners found" ) end key = _createEventListenerKey( e_name, listener ) if not listeners[ key ] then print( "WARNING:: Events:removeEventListener, listener not found" ) else listeners[ key ] = nil end end --====================================================================-- --== Private Methods function Events:_dispatchEvent( event ) -- print( "Events:_dispatchEvent", event.name ); local e_name, listeners e_name = event.name if not e_name or not self.__event_listeners[ e_name ] then return end listeners = self.__event_listeners[ e_name ] if type( listeners )~='table' then return end for k, callback in pairs( listeners ) do if type( callback )=='function' then -- have function callback( event ) elseif type( callback )=='table' and callback[e_name] then -- have object/table local method = callback[e_name] method( callback, event ) else print( "WARNING: Events dispatchEvent", e_name ) end end end --====================================================================-- --== Events Facade --====================================================================-- return { EventsMix=Events, dmcEventFunc=_createDmcEvent, coronaEventFunc=_createCoronaEvent, patch=_patch, }
mit
EvPowerTeam/EV_OP
feeds/luci/applications/luci-openvpn/luasrc/model/cbi/openvpn-basic.lua
71
3274
--[[ 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$ ]]-- require("luci.ip") require("luci.model.uci") local basicParams = { -- -- Widget, Name, Default(s), Description -- { ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") }, { Value, "nice",0, translate("Change process priority") }, { Value,"port",1194, translate("TCP/UDP port # for both local and remote") }, { ListValue,"dev_type",{ "tun", "tap" }, translate("Type of used device") }, { Flag,"tun_ipv6",0, translate("Make tun device IPv6 capable") }, { Value,"ifconfig","10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") }, { Value,"server","10.200.200.0 255.255.255.0", translate("Configure server mode") }, { Value,"server_bridge","192.168.1.1 255.255.255.0 192.168.1.128 192.168.1.254", translate("Configure server bridge") }, { Flag,"nobind",0, translate("Do not bind to local address and port") }, { Flag,"comp_lzo",0, translate("Use fast LZO compression") }, { Value,"keepalive","10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") }, { ListValue,"proto",{ "udp", "tcp" }, translate("Use protocol") }, { Flag,"client",0, translate("Configure client mode") }, { Flag,"client_to_client",0, translate("Allow client-to-client traffic") }, { DynamicList,"remote","vpnserver.example.org", translate("Remote host name or ip address") }, { FileUpload,"secret","/etc/openvpn/secret.key 1", translate("Enable Static Key encryption mode (non-TLS)") }, { FileUpload,"pkcs12","/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") }, { FileUpload,"ca","/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") }, { FileUpload,"dh","/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") }, { FileUpload,"cert","/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") }, { FileUpload,"key","/etc/easy-rsa/keys/some-client.key", translate("Local private key") }, } local m = Map("openvpn") local p = m:section( SimpleSection ) p.template = "openvpn/pageswitch" p.mode = "basic" p.instance = arg[1] local s = m:section( NamedSection, arg[1], "openvpn" ) for _, option in ipairs(basicParams) do local o = s:option( option[1], option[2], option[2], option[4] ) o.optional = true if option[1] == DummyValue then o.value = option[3] else if option[1] == DynamicList then o.cast = nil function o.cfgvalue(...) local val = AbstractValue.cfgvalue(...) return ( val and type(val) ~= "table" ) and { val } or val end end if type(option[3]) == "table" then if o.optional then o:value("", "-- remove --") end for _, v in ipairs(option[3]) do v = tostring(v) o:value(v) end o.default = tostring(option[3][1]) else o.default = tostring(option[3]) end end for i=5,#option do if type(option[i]) == "table" then o:depends(option[i]) end end end return m
gpl-2.0
sundream/gamesrv
script/card/wood/card225007.lua
1
2258
--<<card 导表开始>> local super = require "script.card.wood.card125007" ccard225007 = class("ccard225007",super,{ sid = 225007, race = 2, name = "谦逊", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 1, crystalcost = 0, targettype = 22, halo = nil, desc = "使一个随从的攻击力变为1。", effect = { onuse = {addbuff={atk=1}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard225007:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard225007:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard225007:save() local data = super.save(self) -- todo: save data return data end return ccard225007
gpl-2.0
wez2020/bow
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
Midiman/Concrete
lib/hump/camera.lua
1
3505
--[[ Copyright (c) 2010-2013 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _PATH = (...):match('^(.*[%./])[^%.%/]+$') or '' local cos, sin = math.cos, math.sin local camera = {} camera.__index = camera local function new(x,y, zoom, rot) x,y = x or love.graphics.getWidth()/2, y or love.graphics.getHeight()/2 zoom = zoom or 1 rot = rot or 0 return setmetatable({x = x, y = y, scale = zoom, rot = rot}, camera) end function camera:lookAt(x,y) self.x, self.y = x,y return self end function camera:move(x,y) self.x, self.y = self.x + x, self.y + y return self end function camera:pos() return self.x, self.y end function camera:rotate(phi) self.rot = self.rot + phi return self end function camera:rotateTo(phi) self.rot = phi return self end function camera:zoom(mul) self.scale = self.scale * mul return self end function camera:zoomTo(zoom) self.scale = zoom return self end function camera:attach() local cx,cy = love.graphics.getWidth()/(2*self.scale), love.graphics.getHeight()/(2*self.scale) love.graphics.push() love.graphics.scale(self.scale) love.graphics.translate(cx, cy) love.graphics.rotate(self.rot) love.graphics.translate(-self.x, -self.y) end function camera:detach() love.graphics.pop() end function camera:draw(func) self:attach() func() self:detach() end function camera:cameraCoords(x,y) -- x,y = ((x,y) - (self.x, self.y)):rotated(self.rot) * self.scale + center local w,h = love.graphics.getWidth(), love.graphics.getHeight() local c,s = cos(self.rot), sin(self.rot) x,y = x - self.x, y - self.y x,y = c*x - s*y, s*x + c*y return x*self.scale + w/2, y*self.scale + h/2 end function camera:worldCoords(x,y) -- x,y = (((x,y) - center) / self.scale):rotated(-self.rot) + (self.x,self.y) local w,h = love.graphics.getWidth(), love.graphics.getHeight() local c,s = cos(-self.rot), sin(-self.rot) x,y = (x - w/2) / self.scale, (y - h/2) / self.scale x,y = c*x - s*y, s*x + c*y return x+self.x, y+self.y end function camera:mousepos() return self:worldCoords(love.mouse.getPosition()) end -- the module return setmetatable({new = new}, {__call = function(_, ...) return new(...) end})
mit
sundream/gamesrv
script/card/neutral/card163023.lua
1
2472
--<<card 导表开始>> local super = require "script.card.init" ccard163023 = class("ccard163023",super,{ sid = 163023, race = 6, name = "帝王眼镜蛇", type = 201, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 2, maxhp = 3, crystalcost = 3, targettype = 0, halo = nil, desc = "消灭任何受到该随从伤害的随从。", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard163023:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard163023:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard163023:save() local data = super.save(self) -- todo: save data return data end function ccard163023:after_hurt(obj,hurtval,srcid) if self.inarea ~= "war" then return end local owner = self:getowner() if owner:ishero(obj) then return end if self.id ~= srcid then return end obj:die() end return ccard163023
gpl-2.0
libremesh/lime-packages
packages/check-internet/tests/test_check_internet_rpcd.lua
1
1302
local utils = require "lime.utils" local test_utils = require "tests.utils" local config = require 'lime.config' local test_file_name = "packages/check-internet/files/usr/libexec/rpcd/check-internet" local check_internet = test_utils.load_lua_file_as_function(test_file_name) local rpcd_call = test_utils.rpcd_call local snapshot -- to revert luassert stubs and spies describe('check-internet tests #checkinternet', function() it('test list methods', function() local response = rpcd_call(check_internet, {'list'}) assert.is.equal(0, response.is_connected.no_params) end) it('test is_connected', function() stub(os, "execute", function () return 1 end) local response = rpcd_call(check_internet, {'call', 'is_connected'}, '') assert.is.equal("ok", response.status) assert.is_false(response.connected) end) it('test is_connected', function() stub(os, "execute", function () return 0 end) local response = rpcd_call(check_internet, {'call', 'is_connected'}, '') assert.is.equal("ok", response.status) assert.is_true(response.connected) end) before_each('', function() snapshot = assert:snapshot() end) after_each('', function() snapshot:revert() end) end)
agpl-3.0
nginxsuper/gin
spec/db/migrations_spec.lua
1
10015
require 'spec.spec_helper' local create_schema_migrations_sql = [[ CREATE TABLE schema_migrations ( version varchar(14) NOT NULL, PRIMARY KEY (version) ); ]] describe("Migrations", function() before_each(function() helper_common = require 'gin.helpers.common' helper_common.module_names_in_path = function(path) return { 'migration/1', 'migration/2' } end migrations = require 'gin.db.migrations' stub(_G, "pp_to_file") queries_1 = {} queries_2 = {} db_1 = { options = { adapter = 'mysql', database = 'mydb' }, tables = function(...) return {} end, schema = function(...) return "" end, execute = function(self, q) table.insert(queries_1, q) return {} end } db_2 = { options = { adapter = 'mysql', database = 'mydb' }, tables = function(...) return { 'schema_migrations' } end, schema = function(...) return "" end, execute = function(self, q) table.insert(queries_2, q) return {} end } migration_1 = { db = db_1, up = function(...) db_1:execute("MIGRATION 1 SQL;") end } migration_2 = { db = db_2, up = function(...) db_2:execute("MIGRATION 2 SQL;") end, down = function(...) db_2:execute("ROLLBACK 2 SQL;") end } package.loaded['migration/1'] = migration_1 package.loaded['migration/2'] = migration_2 end) after_each(function() migrations = nil helper_common = nil package.loaded['gin.db.migrations'] = nil package.loaded['migration/1'] = nil package.loaded['migration/2'] = nil queries_1 = nil queries_2 = nil db_1 = nil db_2 = nil migration_1 = nil migration_2 = nil _G.pp_to_file:revert() end) describe("up", function() describe("when both migrations are run successfully", function() it("runs them, creating the database and the schema_migration if necessary", function() migrations.up() assert.are.same(create_schema_migrations_sql, queries_1[1]) assert.are.same("SELECT version FROM schema_migrations WHERE version = '1';", queries_1[2]) assert.are.same("MIGRATION 1 SQL;", queries_1[3]) assert.are.same("INSERT INTO schema_migrations (version) VALUES ('1');", queries_1[4]) assert.are.same("SELECT version FROM schema_migrations WHERE version = '2';", queries_2[1]) assert.are.same("MIGRATION 2 SQL;", queries_2[2]) assert.are.same("INSERT INTO schema_migrations (version) VALUES ('2');", queries_2[3]) end) it("returns the results", function() local ok, response = migrations.up() assert.are.equal(true, ok) assert.are.same({ [1] = { version = '1' }, [2] = { version = '2' }, }, response) end) end) describe("when one version has already been run", function() before_each(function() migrations.version_already_run = function(_, version) return version == '1' end end) it("skips it", function() migrations.up() assert.are.same({ create_schema_migrations_sql }, queries_1) assert.are.same("MIGRATION 2 SQL;", queries_2[1]) assert.are.same("INSERT INTO schema_migrations (version) VALUES ('2');", queries_2[2]) end) it("returns the results", function() local ok, response = migrations.up() assert.are.equal(true, ok) assert.are.same({ [1] = { version = '2' }, }, response) end) end) describe("when the database does not exist", function() before_each(function() called_one = false package.loaded['migration/1'].db.tables = function(...) if called_one == false then called_one = true error("Failed to connect to database: Unknown database 'nonexistent-database'") end return {} end package.loaded['migration/1'].db.adapter = { default_database = 'mysql', db = { close = function() end } } end) after_each(function() called_one = nil end) it("creates it", function() migrations.up() assert.are.same("CREATE DATABASE mydb;", queries_1[1]) end) end) describe("when running a migration with an unsupported adapter", function() before_each(function() migration_1.db.options.adapter = 'unsupported-adapter' end) it("stops from migrating subsequent migrations", function() migrations.up() assert.are.same({}, queries_1) assert.are.same({}, queries_2) end) it("returns an error", function() local ok, response = migrations.up() err_message = "Cannot run migrations for the adapter 'unsupported-adapter'. Supported adapters are: 'mysql', 'postgresql'." assert.are.equal(false, ok) assert.are.same({ [1] = { version = '1', error = err_message } }, response) end) end) describe("when an error occurs in the migration", function() before_each(function() migration_1.db.execute = function(self, sql) if sql == "MIGRATION 1 SQL;" then error("migration error") end return {} end end) it("returns an error", function() local ok, response = migrations.up() assert.are.equal(false, ok) assert.are.equal(1, #response) assert.are.equal('1', response[1].version) assert.are.equal(true, string.find(response[1].error, "migration error") > 0) end) end) end) describe("down", function() describe("when the most recent migration has not been rolled back", function() before_each(function() migrations.version_already_run = function(_, version) return true end end) describe("and the migration rolls back succesfully", function() it("rolls back only the most recent one", function() migrations.down() assert.are.same("ROLLBACK 2 SQL;", queries_2[1]) assert.are.same("DELETE FROM schema_migrations WHERE version = '2';", queries_2[2]) assert.are.same({}, queries_1) end) it("returns the results", function() local ok, response = migrations.down() assert.are.equal(true, ok) assert.are.same({ [1] = { version = '2' } }, response) end) end) describe("when the database does not exist", function() before_each(function() migrations.version_already_run = function(...) error("no database") end end) it("blows up", function() local ok, err = pcall(function() return migrations.down() end) assert.are.equal(false, ok) assert.are.equal(true, string.find(err, "no database") > 0) end) end) describe("when running a migration with an unsupported adapter", function() before_each(function() migration_2.db.options.adapter = 'unsupported-adapter' end) it("stops the migration", function() migrations.down() assert.are.same({}, queries_1) assert.are.same({}, queries_2) end) it("returns the results", function() local ok, response = migrations.down() err_message = "Cannot run migrations for the adapter 'unsupported-adapter'. Supported adapters are: 'mysql', 'postgresql'." assert.are.equal(false, ok) assert.are.same({ [1] = { version = '2', error = err_message } }, response) end) end) describe("when an error occurs in the migration", function() before_each(function() migration_2.db.execute = function() error("migration error") end end) it("returns an error", function() local ok, response = migrations.down() assert.are.equal(false, ok) assert.are.equal(1, #response) assert.are.equal('2', response[1].version) assert.are.equal(true, string.find(response[1].error, "migration error") > 0) end) end) end) end) end)
mit
rastin45/waqer12
plugins/steam.lua
645
2117
-- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI do local BASE_URL = 'http://store.steampowered.com/api/appdetails/' local DESC_LENTH = 200 local function unescape(str) str = string.gsub( str, '&lt;', '<' ) str = string.gsub( str, '&gt;', '>' ) str = string.gsub( str, '&quot;', '"' ) str = string.gsub( str, '&apos;', "'" ) str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end ) str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end ) str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others return str end local function get_steam_data (appid) local url = BASE_URL url = url..'?appids='..appid url = url..'&cc=us' local res,code = http.request(url) if code ~= 200 then return nil end local data = json:decode(res)[appid].data return data end local function price_info (data) local price = '' -- If no data is empty if data then local initial = data.initial local final = data.final or data.initial local min = math.min(data.initial, data.final) price = tostring(min/100) if data.discount_percent and initial ~= final then price = price..data.currency..' ('..data.discount_percent..'% OFF)' end price = price..' (US)' end return price end local function send_steam_data(data, receiver) local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...' local title = data.name local price = price_info(data.price_overview) local text = title..' '..price..'\n'..description local image_url = data.header_image local cb_extra = { receiver = receiver, url = image_url } send_msg(receiver, text, send_photo_from_url_callback, cb_extra) end local function run(msg, matches) local appid = matches[1] local data = get_steam_data(appid) local receiver = get_receiver(msg) send_steam_data(data, receiver) end return { description = "Grabs Steam info for Steam links.", usage = "", patterns = { "http://store.steampowered.com/app/([0-9]+)", }, run = run } end
gpl-2.0
tomm/pioneer
scripts/wiki_commons.lua
1
1063
-- Copyright © 2008-2016 Pioneer Developers. See AUTHORS.txt for details -- Licensed under the terms of CC-BY-SA 3.0. See licenses/CC-BY-SA-3.0.txt round = function(number, significand) last_number = number * 10^(significand+1) last_number = math.floor(last_number) length = string.len(last_number) last_number = string.sub(last_number, length) number = number * 10^significand if tonumber(last_number) < 5 then number = math.floor(number) else number = math.ceil(number) end number = number / 10^significand return tonumber(number) end -- just to have something to manage the calls from ship definitions with deprecated -- values for gun_mounts and camera_offset v = function(a, b, c) return nil end thrust_empty = function(thrust, hull_mass, fuel_tank_mass) this_thrust_empty = thrust / (9.81*1000*(hull_mass + fuel_tank_mass)) return this_thrust_empty end thrust_full = function(thrust, hull_mass, fuel_tank_mass, capacity) this_thrust_empty = thrust / (9.81*1000*(hull_mass + fuel_tank_mass + capacity)) return this_thrust_empty end
gpl-3.0
jdourlens/Driver-Arduino-IDE
LoveFrames/objects/internal/closebutton.lua
6
3492
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2013 Kenny Shields -- --]]------------------------------------------------ -- closebutton class local newobject = loveframes.NewObject("closebutton", "loveframes_object_closebutton", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize() self.type = "closebutton" self.width = 16 self.height = 16 self.internal = true self.hover = false self.down = false self.OnClick = function() 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 self:CheckHover() local hover = self.hover local down = self.down local hoverobject = loveframes.hoverobject local parent = self.parent local base = loveframes.base local update = self.Update if not hover then self.down = false else if loveframes.hoverobject == self then self.down = true end end if not down and hoverobject == self then self.hover = true end -- 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.DrawCloseButton or skins[defaultskin].DrawCloseButton local draw = self.Draw -- 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) local visible = self.visible if not 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 self.down = true loveframes.hoverobject = self end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local visible = self.visible if not visible then return end local hover = self.hover local onclick = self.OnClick if hover and self.down then if button == "l" then onclick(x, y, self) end end self.down = false end
mit
EvPowerTeam/EV_OP
feeds/luci/applications/luci-olsr/luasrc/model/cbi/olsr/olsrdiface6.lua
38
6159
--[[ 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 util = require "luci.util" local ip = require "luci.ip" function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end m = Map("olsrd6", translate("OLSR Daemon - Interface"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) m.redirect = luci.dispatcher.build_url("admin/services/olsrd6") if not arg[1] or m.uci:get("olsrd6", arg[1]) ~= "Interface" then luci.http.redirect(m.redirect) return end i = m:section(NamedSection, arg[1], "Interface", translate("Interface")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) ign = i:taboption("general", Flag, "ignore", translate("Enable"), translate("Enable this interface.")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:taboption("general", Value, "interface", translate("Network"), translate("The interface OLSRd should serve.")) network.template = "cbi/network_netlist" network.widget = "radio" network.nocreate = true mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to fd91:662e:3c58::1 by half: fd91:662e:3c58::1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float return m
gpl-2.0
FizzerWL/ExampleMods
SwapTerritoriesMod/Utilities.lua
3
1934
function NewIdentity() local data = Mod.PublicGameData; local ret = data.Identity or 1; data.Identity = ret + 1; Mod.PublicGameData = data; return ret; end function Dump(obj) if obj.proxyType ~= nil then DumpProxy(obj); elseif type(obj) == 'table' then DumpTable(obj); else print('Dump ' .. type(obj)); end end function DumpTable(tbl) for k,v in pairs(tbl) do print('k = ' .. tostring(k) .. ' (' .. type(k) .. ') ' .. ' v = ' .. tostring(v) .. ' (' .. type(v) .. ')'); end end function DumpProxy(obj) print('type=' .. obj.proxyType .. ' readOnly=' .. tostring(obj.readonly) .. ' readableKeys=' .. table.concat(obj.readableKeys, ',') .. ' writableKeys=' .. table.concat(obj.writableKeys, ',')); end function split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) table.insert(t, cap) end return t end function map(array, func) local new_array = {} local i = 1; for _,v in pairs(array) do new_array[i] = func(v); i = i + 1; end return new_array end function filter(array, func) local new_array = {} local i = 1; for _,v in pairs(array) do if (func(v)) then new_array[i] = v; i = i + 1; end end return new_array end function first(array, func) for _,v in pairs(array) do if (func(v)) then return v; end end return nil; end function randomFromArray(array) local len = #array; local i = math.random(len); return array[i]; end function startsWith(str, sub) return string.sub(str, 1, string.len(sub)) == sub; end function shuffle(tbl) for i = #tbl, 2, -1 do local j = math.random(i) tbl[i], tbl[j] = tbl[j], tbl[i] end end
mit
Choumiko/Factorio-Stdlib
spec/color/color_spec.lua
1
3992
describe('Color', function () local say = require("say") setup(function() _G.defines = {} require 'stdlib/color/color' end ) local function is_near(_, arguments) if #arguments~=3 then return false end local epsilon = arguments[1] local given = arguments[2] local expected = arguments[3] for k,v in pairs(expected) do if not given[k] then return false end if math.abs(given[k] - v) > epsilon/2 then return false end end return true end say:set("assertion.is_near.positive", "Expected objects to be similar with epsilon %s.\nPassed in:\n%s\nCompared to:\n%s") say:set("assertion.is_near.negative", "Expected objects to not be similar with epsilon %s.\nPassed in:\n%s\nCompared to:\n%s") assert:register("assertion", "is_near", is_near, "assertion.is_near.positive", "assertion.is_near.negative") describe('set', function() it('should use alpha if passed', function() assert.same({r=1, a=.5}, Color.set({r=1}, .5)) end) it('should use existing alpha if not passed', function() assert.same({r=1, a=1}, Color.set({r=1, a=1})) end) it('should have no alpha at all', function() assert.same({r=1, a=1}, Color.set({r=1})) end) end) describe('to_table', function() it('should convert and array to a table', function() local c = {1, .75, .5, .25} assert.same({r=1, g=.75, b=.5, a=.25}, Color.to_table(c)) c = {1} assert.same({r=1}, Color.to_table(c)) end) end) describe('from_hex', function() it('should require hex for converting', function () assert.has_error(Color.from_hex, "missing color hex value") end) it('should require hex string for converting', function () for _,v in pairs({nil, 0, {}, {r=0.5,g=0,b=0.5}}) do assert.has_error(function() Color.from_hex(v) end) end end) it('should accept 6-length hex strings only', function () for _,v in pairs({"fff", "#fff"}) do assert.has_error(function() Color.from_hex(v) end) end end) it('should return 1 as the default alpha', function () -- should really be two separate tests, one for Color.set and one for Color.from_hex local white = Color.from_hex("#ffffff") assert.is_equal(white.a, 1) assert.is_equal(Color.set(defines.color.white).a, 1) end) it('should return the right colors', function () -- based on defines.color, converted with an external tool to the closest hex colour possible local colors = { white = "#ffffff", black = "#000000", darkgrey = "#404040", grey = "#808080", lightgrey = "#bfbfbf", red = "#ff0000", darkred = "#800000", lightred = "#ff8080", green = "#00ff00", darkgreen = "#008000", lightgreen = "#80ff80", blue = "#0000ff", darkblue = "#000080", lightblue = "#8080ff", orange = "#ff8c1a", yellow = "#ffff00", pink = "#ff00ff", purple = "#991a99", brown = "#99661a" } local epsilon = (1/255) -- because of rounding, as #000001 is b=0.003921... for k,hex in pairs(colors) do assert.is.near(epsilon, Color.from_hex(hex), Color.set(defines.color[k])) end end) it('should use alpha if defined', function () local color = Color.from_hex("#ffffff", 0.5) assert.is.truthy(color.a) assert.is.equal(color.a, 0.5) end) end) end)
isc
weera00/nodemcu-firmware
lua_modules/si7021/si7021.lua
83
2184
-- *************************************************************************** -- SI7021 module for ESP8266 with nodeMCU -- Si7021 compatible tested 2015-1-22 -- -- Written by VIP6 -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** local moduleName = ... local M = {} _G[moduleName] = M --I2C slave address of Si70xx local Si7021_ADDR = 0x40 --Commands local CMD_MEASURE_HUMIDITY_HOLD = 0xE5 local CMD_MEASURE_HUMIDITY_NO_HOLD = 0xF5 local CMD_MEASURE_TEMPERATURE_HOLD = 0xE3 local CMD_MEASURE_TEMPERATURE_NO_HOLD = 0xF3 -- temperature and pressure local t,h local init = false -- i2c interface ID local id = 0 -- 16-bit two's complement -- value: 16-bit integer local function twoCompl(value) if value > 32767 then value = -(65535 - value + 1) end return value end -- read data from si7021 -- ADDR: slave address -- commands: Commands of si7021 -- length: bytes to read local function read_data(ADDR, commands, length) i2c.start(id) i2c.address(id, ADDR, i2c.TRANSMITTER) i2c.write(id, commands) i2c.stop(id) i2c.start(id) i2c.address(id, ADDR,i2c.RECEIVER) tmr.delay(20000) c = i2c.read(id, length) i2c.stop(id) return c end -- initialize module -- sda: SDA pin -- scl SCL pin function M.init(sda, scl) i2c.setup(id, sda, scl, i2c.SLOW) --print("i2c ok..") init = true end -- read humidity from si7021 local function read_humi() dataH = read_data(Si7021_ADDR, CMD_MEASURE_HUMIDITY_HOLD, 2) UH = string.byte(dataH, 1) * 256 + string.byte(dataH, 2) h = ((UH*12500+65536/2)/65536 - 600) return(h) end -- read temperature from si7021 local function read_temp() dataT = read_data(Si7021_ADDR, CMD_MEASURE_TEMPERATURE_HOLD, 2) UT = string.byte(dataT, 1) * 256 + string.byte(dataT, 2) t = ((UT*17572+65536/2)/65536 - 4685) return(t) end -- read temperature and humidity from si7021 function M.read() if (not init) then print("init() must be called before read.") else read_humi() read_temp() end end; -- get humidity function M.getHumidity() return h end -- get temperature function M.getTemperature() return t end return M
mit
mahdikord/mahdi5
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
movb/Algorithm-Implementations
Josephus_Problem/Lua/Yonaba/josephus_test.lua
26
1233
-- Tests for josephus.lua local j = require 'josephus' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end -- Solutions for k = 2 local solutions = {1 ,1 ,3 ,1 ,3 ,5 ,7 ,1 ,3 ,5 ,7 ,9 ,11 ,13 ,15 ,1} run('Josephus recursive test', function() for n = 1,16 do assert(j.recursive(n, 2) == solutions[n]) end end) run('Josephus loop-based test', function() for n = 1,16 do assert(j.loop(n, 2) == solutions[n]) end end) run('Josephus elaborated test', function() for n = 1,16 do assert(j.elaborated(n, 2) == solutions[n]) end end) run('Josephus standard test', function() for n = 1,16 do assert(j.standard(n) == solutions[n]) end end) run('Josephus standard logarithm-based test', function() for n = 1,16 do assert(j.standard_log(n) == solutions[n]) end end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
gsingh93/ipscanner
app/src/main/assets/nmap/share/nmap/nselib/ncp.lua
2
36979
--- A tiny implementation of the Netware Core Protocol (NCP). -- While NCP was originally a Netware only protocol it's now present on -- both Linux and Windows platforms running Novell eDirectory. -- -- The library implements a small amount of NCP functions based on various -- packet dumps generated by Novell software, such as the Novell Client and -- Console One. The functions are mainly used for enumeration and discovery -- -- The library implements a number of different classes where the Helper is -- the one that should be the easiest to use from scripts. -- -- The following classes exist: -- -- * Packet -- - Implements functions for creating and serializing a NCP packet -- -- * ResponseParser -- - A static class containing a bunch of functions to decode server -- responses -- -- * Response -- - Class responsible for decoding NCP responses -- -- * NCP -- - Contains the "native" NCP functions sending the actual request to the -- server. -- -- * Socket -- - A buffered socket implementation -- -- * Helper -- - The prefered script interface to the library containing functions -- that wrap functions from the NCP class using more descriptive names -- and easier interface. -- -- * Util -- - A class containing mostly decoding and helper functions -- -- The following example code illustrates how to use the Helper class from a -- script. The example queries the server for all User objects from the root. -- -- <code> -- local helper = ncp.Helper:new(host,port) -- local status, resp = helper:connect() -- status, resp = helper:search("[Root]", "User", "*") -- status = helper:close() -- </code> -- --@author Patrik Karlsson <patrik@cqure.net> --@copyright Same as Nmap--See http://nmap.org/book/man-legal.html -- Version 0.1 -- Created 24/04/2011 - v0.1 - created by Patrik Karlsson <patrik@cqure.net> module(... or "ncp", package.seeall) require 'ipOps' NCPType = { CreateConnection = 0x1111, ServiceRequest = 0x2222, ServiceReply = 0x3333, DestroyConnection = 0x5555, } Status = { CONNECTION_OK = 0, COMPLETION_OK = 0, } NCPFunction = { GetMountVolumeList = 0x16, GetFileServerInfo = 0x17, Ping = 0x68, EnumerateNetworkAddress = 0x7b, SendFragmentedRequest = 0x68, } NCPVerb = { Resolve = 1, List = 5, Search = 6, } -- The NCP Packet Packet = { --- Creates a new instance of Packet -- @return o instance of Packet new = function(self) local o = {} setmetatable(o, self) self.__index = self o.ncp_ip = { signature = "DmdT", replybuf = 0, version = 1 } o.task = 1 o.func = 0 return o end, --- Sets the NCP Reply buffer size -- @param n number containing the buffer size setNCPReplyBuf = function(self, n) self.ncp_ip.replybuf = n end, --- Sets the NCP packet length -- @param n number containing the length setNCPLength = function(self, n) self.ncp_ip.length = n end, --- Gets the NCP packet length -- @return n number containing the NCP length getNCPLength = function(self) return self.ncp_ip.length end, --- Sets the NCP packet type -- @param t number containing the NCP packet type setType = function(self, t) self.type = t end, --- Gets the NCP packet type -- @return type number containing the NCP packet type getType = function(self) return self.type end, --- Sets the NCP packet function -- @param t number containing the NCP function setFunc = function(self, f) self.func = f end, --- Gets the NCP packet function -- @return func number containing the NCP packet function getFunc = function(self) return self.func end, --- Sets the NCP sequence number -- @param seqno number containing the sequence number setSeqNo = function(self, n) self.seqno = n end, --- Sets the NCP connection number -- @param conn number containing the connection number setConnNo = function(self, n) self.conn = n end, --- Gets the NCP connection number -- @return conn number containing the connection number getConnNo = function(self) return self.conn end, --- Sets the NCP sub function -- @param subfunc number containing the subfunction setSubFunc = function(self, n) self.subfunc = n end, --- Gets the NCP sub function -- @return subfunc number containing the subfunction getSubFunc = function(self) return self.subfunc end, --- Gets the Sequence number -- @return seqno number containing the sequence number getSeqNo = function(self) return self.seqno end, --- Sets the packet length -- @param len number containing the packet length setLength = function(self, n) self.length = n end, --- Sets the packet data -- @param data string containing the packet data setData = function(self, data) self.data = data end, --- Gets the packet data -- @return data string containing the packet data getData = function(self) return self.data end, --- Sets the packet task -- @param task number containing the packet number setTask = function(self, task) self.task = task end, --- "Serializes" the packet to a string __tostring = function(self) local UNKNOWN = 0 local data = bin.pack(">AIIISCCCCC", self.ncp_ip.signature, self.ncp_ip.length or 0, self.ncp_ip.version, self.ncp_ip.replybuf, self.type, self.seqno, self.conn, self.task, UNKNOWN, self.func ) if ( self.length ) then data = data .. bin.pack(">S", self.length) end if ( self.subfunc ) then data = data .. bin.pack("C", self.subfunc) end if ( self.data ) then data = data .. bin.pack("A", self.data) end return data end, } -- Parses different responses into suitable tables ResponseParser = { --- Determines what parser to call based on the contents of the client -- request and server response. -- @param req instance of Packet containing the request to the server -- @param resp instance of Response containing the server response -- @return status true on success, false on failure -- @return resp table (on success) containing the decoded response -- @return err string (on failure) containing the error message parse = function(req, resp) local func, subfunc, typ = req:getFunc(), req:getSubFunc(), req:getType() if ( ResponseParser[func] ) then return ResponseParser[func](resp) elseif ( NCPFunction.SendFragmentedRequest == func ) then if ( 1 == subfunc ) then return ResponseParser.Ping(resp) elseif ( 2 == subfunc ) then local data = req:getData() if ( #data < 21 ) then return false, "Invalid NCP request, could not parse" end local pos, verb = bin.unpack("<I", data, 17) if ( NCPVerb.Resolve == verb ) then return ResponseParser.Resolve(resp) elseif ( NCPVerb.List == verb ) then return ResponseParser.List(resp) elseif ( NCPVerb.Search == verb ) then return ResponseParser.Search(resp) end return false, "ResponseParser: Failed to parse response" end end return false, "ResponseParser: Failed to parse response" end, --- Decodes a GetFileServerInfo response -- @param resp string containing the response as received from the server -- @return status true on success, false on failure -- @return response table (if status is true) containing: -- <code>srvname</code> -- <code>os_major</code> -- <code>os_minor</code> -- <code>conns_supported</code> -- <code>conns_inuse</code> -- <code>vols_supported</code> -- <code>os_rev</code> -- <code>sft_support</code> -- <code>tts_level</code> -- <code>conns_max_use</code> -- <code>acct_version</code> -- <code>vap_version</code> -- <code>qms_version</code> -- <code>print_version</code> -- <code>internet_bridge_ver</code> -- <code>mixed_mode_path</code> -- <code>local_login_info</code> -- <code>product_major</code> -- <code>product_minor</code> -- <code>product_rev</code> -- <code>os_lang_id</code> -- <code>support_64_bit</code> -- @return error message (if status is false) [NCPFunction.GetFileServerInfo] = function(resp) local data = resp:getData() local len = #data if ( len < 78 ) then return false, "Failed to decode GetFileServerInfo" end local result = {} local pos pos, result.srvname, result.os_major, result.os_minor, result.conns_supported, result.conns_inuse, result.vols_supported, result.os_rev, result.sft_support, result.tts_level, result.conns_max_use, result.acct_version, result.vap_version, result.qms_version, result.print_version, result.virt_console_ver, result.sec_restrict_ver, result.internet_bridge_ver, result.mixed_mode_path, result.local_login_info, result.product_major, result.product_minor, result.product_rev, result.os_lang_id, result.support_64_bit = bin.unpack(">A48CCSSSCCCSCCCCCCCCCSSSCC", data) return true, result end, --- Decodes a GetMountVolumeList response -- @param resp string containing the response as received from the server -- @return status true on success, false on failure -- @return response table of vol entries (if status is true) -- Each vol entry is a table containing the following fields: -- <code>vol_no</code> and <code>vol_name</code> -- @return error message (if status is false) [NCPFunction.GetMountVolumeList] = function(resp) local data = resp:getData() local len = #data local pos, items, next_vol_no = bin.unpack("<II", data) local vols = {} for i=1, items do local vol = {} pos, vol.vol_no, vol.vol_name = bin.unpack("<Ip", data, pos) table.insert(vols, vol) end return true, vols end, --- Decodes a Ping response -- @param resp string containing the response as received from the server -- @return status true on success, false on failure -- @return response table (if status is true) containing: -- <code>tree_name</code> -- @return error message (if status is false) Ping = function(resp) local data = resp:getData() local len = #data local pos local result = {} if ( len < 40 ) then return false, "NCP Ping result too short" end pos, result.nds_version = bin.unpack("C", data) -- move to the offset of the pos = pos + 7 pos, result.tree_name = bin.unpack("A32", data, pos) result.tree_name = (result.tree_name:match("^([^_]*)_*$")) return true, result end, --- Decodes a EnumerateNetworkAddress response -- @param resp string containing the response as received from the server -- @return status true on success, false on failure -- @return response table (if status is true) containing: -- <code>ip</code>, <code>port</code> and <code>proto</code> -- @return error message (if status is false) [NCPFunction.EnumerateNetworkAddress] = function(resp) local pos, result = 1, {} local items local data = resp:getData() local len = #data pos, result.time_since_boot, result.console_version, result.console_revision, result.srvinfo_flags, result.guid, result.next_search, items = bin.unpack("<ICCSA16II", data) local function DecodeAddress(data, pos) local COMM_TYPES = { [5] = "udp", [6] = "tcp" } local comm_type, port, ip, _ pos, comm_type, _, _, _, port, ip = bin.unpack(">CCISS<I", data, pos) return pos, { port = port, ip = ipOps.fromdword(ip), proto = COMM_TYPES[comm_type] or "unknown" } end if ( ( pos - 1 ) + (items * 14 ) > len ) then return false, "EnumerateNetworkAddress packet too short" end result.addr = {} for i=1, items do local addr = {} pos, addr = DecodeAddress(data, pos) table.insert(result.addr, addr ) end return true, result end, --- Decodes a Resolve response -- @param resp string containing the response as received from the server -- @return status true on success, false on failure -- @return response table (if status is true) containing: -- <code>tag</code> and <code>id</code> -- @return error message (if status is false) Resolve = function(resp) local data = resp:getData() local len = #data if ( len < 12 ) then return false, "ResponseParser: NCP Resolve, packet too short" end local pos, frag_size, frag_handle, comp_code = bin.unpack("<III", data) if ( len < 38 ) then return false, "ResponseParser: message too short" end if ( comp_code ~= 0 ) then return false, ("ResponseParser: Completion code returned" .. " non-zero value (%d)"):format(comp_code) end local pos, tag, entry = bin.unpack("<II", data, pos) return true, { tag = tag, id = entry } end, --- Decodes a Search response -- @param resp string containing the response as received from the server -- @return status true on success, false on failure -- @return entries table (if status is true) as return by: -- <code>EntryDecoder</code> -- @return error message (if status is false) Search = function(resp) local data = resp:getData() local len = #data local entries = {} if ( len < 12 ) then return false, "ResponseParser: NCP Resolve, packet too short" end local pos, frag_size, frag_handle, comp_code, iter_handle = bin.unpack("<IIII", data) if ( comp_code ~= 0 ) then return false, ("ResponseParser: Completion code returned" .. " non-zero value (%d)"):format(comp_code) end pos = pos + 12 local entry_count pos, entry_count = bin.unpack("<I", data, pos) for i=1, entry_count do local entry pos, entry = ResponseParser.EntryDecoder(data, pos) -- pad for unknown trailing data in searches pos = pos + 8 table.insert(entries, entry) end return true, entries end, --- The EntryDecoder is used by the Search and List function, for decoding -- the returned entries. -- @param data containing the response as returned by the server -- @param pos number containing the offset into data to start decoding -- @return pos number containing the new offset after decoding -- @return entry table containing the decoded entry, currently it contains -- one or more of the following fields: -- <code>flags</code> -- <code>mod_time</code> -- <code>sub_count</code> -- <code>baseclass</code> -- <code>rdn</code> -- <code>name</code> EntryDecoder = function(data, pos) -- The InfoFlags class takes a numeric value and facilitates -- bit decoding into InfoFlag fields, the current supported fields -- are: -- <code>Output</code> -- <code>Entry</code> -- <code>Count</code> -- <code>ModTime</code> -- <code>BaseClass</code> -- <code>RelDN</code> -- <code>DN</code> local InfoFlags = { -- Creates a new instance -- @param val number containing the numeric representation of flags -- @return a new instance of InfoFlags new = function(self, val) local o = {} setmetatable(o, self) self.__index = self o.val = val o:parse() return o end, -- Parses the numeric value and creates a number of class fields parse = function(self) local fields = { "Output", "_u1", "Entry", "Count", "ModTime", "_u2", "_u3", "_u4", "_u5", "_u6", "_u7", "BaseClass", "RelDN", "DN" } local bits = 1 for _, field in ipairs(fields) do self[field] = ( bit.band(self.val, bits) == bits ) bits = bits * 2 end end } local entry = {} local f, len pos, f = bin.unpack("<I", data, pos) local iflags = InfoFlags:new(f) if ( iflags.Entry ) then pos, entry.flags, entry.sub_count = bin.unpack("<II", data, pos) end if ( iflags.ModTime ) then pos, entry.mod_time = bin.unpack("<I", data, pos) end if ( iflags.BaseClass ) then pos, len = bin.unpack("<I", data, pos) pos, entry.baseclass = bin.unpack("A" .. len, data, pos) entry.baseclass = Util.FromWideChar(entry.baseclass) entry.baseclass = Util.CToLuaString(entry.baseclass) pos = ( len % 4 == 0 ) and pos or pos + ( 4 - ( len % 4 ) ) end if ( iflags.RelDN ) then pos, len = bin.unpack("<I", data, pos) pos, entry.rdn = bin.unpack("A" .. len, data, pos) entry.rdn = Util.FromWideChar(entry.rdn) entry.rdn = Util.CToLuaString(entry.rdn) pos = ( len % 4 == 0 ) and pos or pos + ( 4 - ( len % 4 ) ) end if ( iflags.DN ) then pos, len = bin.unpack("<I", data, pos) pos, entry.name = bin.unpack("A" .. len, data, pos) entry.name = Util.FromWideChar(entry.name) entry.name = Util.CToLuaString(entry.name) pos = ( len % 4 == 0 ) and pos or pos + ( 4 - ( len % 4 ) ) end return pos, entry end, --- Decodes a List response -- @param resp string containing the response as received from the server -- @return status true on success, false on failure -- @return entries table (if status is true) as return by: -- <code>EntryDecoder</code> -- @return error message (if status is false) List = function(resp) local data = resp:getData() local len = #data if ( len < 12 ) then return false, "ResponseParser: NCP Resolve, packet too short" end local pos, frag_size, frag_handle, comp_code, iter_handle = bin.unpack("<IIII", data) if ( comp_code ~= 0 ) then return false, ("ResponseParser: Completion code returned" .. " non-zero value (%d)"):format(comp_code) end local entry_count pos, entry_count = bin.unpack("<I", data, pos) local entries = {} for i=1, entry_count do local entry = {} pos, entry = ResponseParser.EntryDecoder(data, pos) table.insert(entries, entry) end return true, entries end, } -- The response class holds the NCP data. An instance is usually created -- using the fromSocket static function that reads a NCP packet of the -- the socket and makes necessary parsing. Response = { --- Creates a new Response instance -- @param header string containing the header part of the response -- @param data string containing the data part of the response -- @return o new instance of Response new = function(self, header, data) local o = {} setmetatable(o, self) self.__index = self o.header = header o.data = data o:parse() return o end, --- Parses the Response parse = function(self) local pos, _ pos, self.signature, self.length, self.type, self.seqno, self.conn, _, self.compl_code, self.status_code = bin.unpack(">IISCCSCC", self.header) if ( self.data ) then local len = #self.data - pos if ( ( #self.data - pos ) ~= ( self.length - 33 ) ) then stdnse.print_debug("NCP packet length mismatched") return end end end, --- Gets the sequence number -- @return seqno number getSeqNo = function(self) return self.seqno end, --- Gets the connection number -- @return conn number getConnNo = function(self) return self.conn end, --- Gets the data portion of the response -- @return data string getData = function(self) return self.data end, --- Gets the header portion of the response getHeader = function(self) return self.header end, --- Returns true if there are any errors -- @return error true if the response error code is anything else than OK hasErrors = function(self) return not( ( self.compl_code == Status.COMPLETION_OK ) and ( self.status_code == Status.CONNECTION_OK ) ) end, --- Creates a Response instance from the data read of the socket -- @param socket socket connected to server and ready to receive data -- @return Response containing a new Response instance fromSocket = function(socket) local status, header = socket:recv(16) if ( not(status) ) then return false, "Failed to receive data" end local pos, sig, len = bin.unpack(">II", header) if ( len < 8 ) then return false, "NCP packet too short" end local data if ( 0 < len - 16 ) then status, data = socket:recv(len - 16) if ( not(status) ) then return false, "Failed to receive data" end end return true, Response:new(header, data) end, --- "Serializes" the Response instance to a string __tostring = function(self) return bin.pack("AA", self.header, self.data) end, } -- The NCP class NCP = { --- Creates a new NCP instance -- @param socket containing a socket connected to the NCP server -- @return o instance of NCP new = function(self, socket) local o = {} setmetatable(o, self) self.__index = self o.socket = socket o.seqno = -1 o.conn = 0 return o end, --- Handles sending and receiving a NCP message -- @param p Packet containing the request to send to the server -- @return status true on success false on failure -- @return response table (if status is true) containing the parsed -- response -- @return error string (if status is false) containing the error Exch = function(self, p) local status, err = self:SendPacket(p) if ( not(status) ) then return status, err end local status, resp = Response.fromSocket(self.socket) if ( not(status) or resp:hasErrors() ) then return false, resp end self.seqno = resp:getSeqNo() self.conn = resp:getConnNo() return ResponseParser.parse(p, resp) end, --- Sends a packet to the server -- @param p Packet to be sent to the server -- @return status true on success, false on failure -- @return err string containing the error message on failure SendPacket = function(self, p) if ( not(p:getSeqNo() ) ) then p:setSeqNo(self.seqno + 1) end if ( not(p:getConnNo() ) ) then p:setConnNo(self.conn) end if ( not(p:getNCPLength()) ) then local len = #(tostring(p)) p:setNCPLength(len) end local status, err = self.socket:send(tostring(p)) if ( not(status) ) then return status, "Failed to send data" end return true end, --- Creates a connection to the NCP server -- @return status true on success, false on failure CreateConnect = function(self) local p = Packet:new() p:setType(NCPType.CreateConnection) local resp = self:Exch( p ) return true end, --- Destroys a connection established with the NCP server -- @return status true on success, false on failure DestroyConnect = function(self) local p = Packet:new() p:setType(NCPType.DestroyConnection) local resp = self:Exch( p ) return true end, --- Gets file server information -- @return status true on success, false on failure -- @return response table (if status is true) containing: -- <code>srvname</code> -- <code>os_major</code> -- <code>os_minor</code> -- <code>conns_supported</code> -- <code>conns_inuse</code> -- <code>vols_supported</code> -- <code>os_rev</code> -- <code>sft_support</code> -- <code>tts_level</code> -- <code>conns_max_use</code> -- <code>acct_version</code> -- <code>vap_version</code> -- <code>qms_version</code> -- <code>print_version</code> -- <code>internet_bridge_ver</code> -- <code>mixed_mode_path</code> -- <code>local_login_info</code> -- <code>product_major</code> -- <code>product_minor</code> -- <code>product_rev</code> -- <code>os_lang_id</code> -- <code>support_64_bit</code> -- @return error message (if status is false) GetFileServerInfo = function(self) local p = Packet:new() p:setType(NCPType.ServiceRequest) p:setFunc(NCPFunction.GetFileServerInfo) p:setNCPReplyBuf(128) p:setLength(1) p:setSubFunc(17) return self:Exch( p ) end, -- NEEDS authentication, disabled for now -- -- Get the logged on user for the specified connection -- @param conn_no number containing the connection number -- GetStationLoggedInfo = function(self, conn_no) -- local p = Packet:new() -- p:setType(NCPType.ServiceRequest) -- p:setFunc(NCPFunction.GetFileServerInfo) -- p:setNCPReplyBuf(62) -- p:setLength(5) -- p:setSubFunc(28) -- p:setTask(4) -- -- local data = bin.pack("<I", conn_no) -- p:setData(data) -- return self:Exch( p ) -- end, --- Sends a PING to the server which responds with the tree name -- @return status true on success, false on failure -- @return response table (if status is true) containing: -- <code>tree_name</code> -- @return error message (if status is false) Ping = function(self) local p = Packet:new() p:setType(NCPType.ServiceRequest) p:setFunc(NCPFunction.Ping) p:setSubFunc(1) p:setNCPReplyBuf(45) p:setData("\0\0\0") return self:Exch( p ) end, --- Enumerates the IP addresses associated with the server -- @return status true on success, false on failure -- @return response table (if status is true) containing: -- <code>ip</code>, <code>port</code> and <code>proto</code> -- @return error message (if status is false) EnumerateNetworkAddress = function(self) local p = Packet:new() p:setType(NCPType.ServiceRequest) p:setFunc(NCPFunction.EnumerateNetworkAddress) p:setSubFunc(17) p:setNCPReplyBuf(4096) p:setData("\0\0\0\0") p:setLength(5) return self:Exch( p ) end, --- Resolves an directory entry id from a name -- @param name string containing the name to resolve -- @return status true on success, false on failure -- @return response table (if status is true) containing: -- <code>tag</code> and <code>id</code> -- @return error message (if status is false) ResolveName = function(self, name) local p = Packet:new() p:setType(NCPType.ServiceRequest) p:setFunc(NCPFunction.SendFragmentedRequest) p:setSubFunc(2) p:setNCPReplyBuf(4108) local pad = (4 - ( #name % 4 ) ) name = Util.ZeroPad(name, #name + pad) local w_name = Util.ToWideChar(name) local frag_handle, frag_size = 0xffffffff, 64176 local msg_size, unknown, proto_flags, nds_verb = 44 + #w_name, 0, 0, 1 local nds_reply_buf, version, flags, scope = 4096, 1, 0x2062, 0 local unknown2 = 0x0e local ZERO = 0 local data = bin.pack("<IIISSIIISSIIA", frag_handle, frag_size, msg_size, unknown, proto_flags, nds_verb, nds_reply_buf, version, flags, unknown, scope, #w_name, w_name, ZERO) local comms = { { transport = "TCP" } } local walkers= { { transport = "TCP" } } local PROTOCOLS = { ["TCP"] = 9 } data = data .. bin.pack("<I", #comms) for _, comm in ipairs(comms) do data = data .. bin.pack("<I", PROTOCOLS[comm.transport]) end data = data .. bin.pack("<I", #walkers) for _, walker in ipairs(walkers) do data = data .. bin.pack("<I", PROTOCOLS[walker.transport]) end p:setData(data) return self:Exch( p ) end, --- Gets a list of volumes from the server -- @return status true on success, false on failure -- @return response table of vol entries (if status is true) -- Each vol entry is a table containing the following fields: -- <code>vol_no</code> and <code>vol_name</code> -- @return error message (if status is false) GetMountVolumeList = function(self) local p = Packet:new() p:setType(NCPType.ServiceRequest) p:setFunc(NCPFunction.GetMountVolumeList) p:setSubFunc(52) p:setNCPReplyBuf(538) p:setTask(4) p:setLength(12) local start_vol = 0 local vol_req_flags = 1 local src_name_space = 0 local data = bin.pack("<III", start_vol, vol_req_flags, src_name_space ) p:setData(data) return self:Exch( p ) end, --- Searches the directory -- @param base entry as resolved by <code>Resolve</code> -- @param class string containing a class name (or * wildcard) -- @param name string containing a entry name (or * wildcard) -- @param options table containing one or more of the following -- <code>numobjs</code> -- @return status true on success false on failure -- @return entries table (if status is true) as return by: -- <code>ResponseDecoder.EntryDecoder</code> -- @return error string (if status is false) containing the error Search = function(self, base, class, name, options) assert( ( base and base.id ), "No base entry was specified") local class = class and class .. '\0' or '*\0' local name = name and name .. '\0' or '*\0' local w_name = Util.ToWideChar(name) local w_class = Util.ToWideChar(class) local options = options or {} local p = Packet:new() p:setType(NCPType.ServiceRequest) p:setFunc(NCPFunction.SendFragmentedRequest) p:setSubFunc(2) p:setNCPReplyBuf(64520) p:setTask(5) local frag_handle, frag_size, msg_size = 0xffffffff, 64176, 98 local unknown, proto_flags, nds_verb, version, flags = 0, 0, 6, 3, 0 local nds_reply_buf = 64520 local iter_handle = 0xffffffff local repl_type = 2 -- base and all subordinates local numobjs = options.numobjs or 0 local info_types = 1 -- Names local info_flags = 0x0000381d -- a bunch of unknowns local u2, u3, u4, u5, u6, u7, u8, u9 = 0, 0, 2, 2, 0, 0x10, 0, 0x11 local data = bin.pack("<IIISSIIIIIIIIIIIIIIIIIAIIIA", frag_handle, frag_size, msg_size, unknown, proto_flags, nds_verb, nds_reply_buf, version, flags, iter_handle, base.id, repl_type, numobjs, info_types, info_flags, u2, u3, u4, u5, u6, u7, #w_name, w_name, u8, u9, #w_class, w_class ) p:setData(data) return self:Exch( p ) end, --- Lists the contents of entry -- @param entry entry as resolved by <code>Resolve</code> -- @return status true on success false on failure -- @return entries table (if status is true) as return by: -- <code>ResponseDecoder.EntryDecoder</code> -- @return error string (if status is false) containing the error List = function(self, entry) local p = Packet:new() p:setType(NCPType.ServiceRequest) p:setFunc(NCPFunction.SendFragmentedRequest) p:setSubFunc(2) p:setNCPReplyBuf(4112) p:setTask(2) local frag_handle, frag_size = 0xffffffff, 64176 local msg_size, unknown, proto_flags, nds_verb = 40, 0, 0, 5 local nds_reply_buf, version, flags = 4100, 1, 0x0001 local iter_handle = 0xffffffff local unknown2 = 0x0e local ZERO = 0 local info_flags = 0x0000381d local data = bin.pack("<IIISSIIISSIII", frag_handle, frag_size, msg_size, unknown, proto_flags, nds_verb, nds_reply_buf, version, flags, unknown, iter_handle, entry.id, info_flags ) -- no name filter data = data .. "\0\0\0\0" -- no class filter data = data .. "\0\0\0\0" p:setData(data) local status, entries = self:Exch( p ) if ( not(status) ) then return false, entries end return true, entries end, } Helper = { --- Creates a new Helper instance -- @return a new Helper instance new = function(self, host, port) local o = {} setmetatable(o, self) self.__index = self o.host = host o.port = port return o end, --- Connect the socket and creates a NCP connection -- @return true on success false on failure connect = function(self) self.socket = Socket:new() local status, err = self.socket:connect(self.host, self.port) if ( not(status) ) then return status, err end self.ncp = NCP:new(self.socket) return self.ncp:CreateConnect() end, --- Closes the helper connection close = function(self) self.ncp:DestroyConnect() self.socket:close() end, --- Performs a directory search -- @param base string containing the name of the base to search -- @param class string containing the type of class to search -- @param name string containing the name of the object to find -- @param options table containing on or more of the following -- <code>numobjs</code> - number of objects to limit the search to search = function(self, base, class, name, options) local base = base or "[Root]" local status, entry = self.ncp:ResolveName(base) if ( not(status) ) then return false, "Search failed, base could not be resolved" end local status, result = self.ncp:Search(entry, class, name, options) if (not(status)) then return false, result end return status, result end, --- Retrieves some information from the server using the following NCP -- functions: -- <code>GetFileServerInfo</code> -- <code>Ping</code> -- <code>EnumerateNetworkAddress</code> -- <code>GetMountVolumeList</code> -- The result contains the Tree name, product versions and mounts getServerInfo = function(self) local status, srv_info = self.ncp:GetFileServerInfo() if ( not(status) ) then return false, srv_info end local status, ping_info = self.ncp:Ping() if ( not(status) ) then return false, ping_info end local status, net_info = self.ncp:EnumerateNetworkAddress() if ( not(status) ) then return false, net_info end local status, mnt_list = self.ncp:GetMountVolumeList() if ( not(status) ) then return false, mnt_list end local output = {} table.insert(output, ("Server name: %s"):format(srv_info.srvname)) table.insert(output, ("Tree Name: %s"):format(ping_info.tree_name)) table.insert(output, ("OS Version: %d.%d (rev %d)"):format(srv_info.os_major, srv_info.os_minor, srv_info.os_rev)) table.insert(output, ("Product version: %d.%d (rev %d)"):format(srv_info.product_major, srv_info.product_minor, srv_info.product_rev)) table.insert(output, ("OS Language ID: %d"):format(srv_info.os_lang_id)) local niceaddr = {} for _, addr in ipairs(net_info.addr) do table.insert(niceaddr, ("%s %d/%s"):format(addr.ip,addr.port, addr.proto)) end niceaddr.name = "Addresses" table.insert(output, niceaddr) local mounts = {} for _, mount in ipairs(mnt_list) do table.insert(mounts, mount.vol_name) end mounts.name = "Mounts" table.insert(output, mounts) if ( nmap.debugging() > 0 ) then table.insert(output, ("Acct version: %d"):format(srv_info.acct_version)) table.insert(output, ("VAP version: %d"):format(srv_info.vap_version)) table.insert(output, ("QMS version: %d"):format(srv_info.qms_version)) table.insert(output, ("Print server version: %d"):format(srv_info.print_version)) table.insert(output, ("Virtual console version: %d"):format(srv_info.virt_console_ver)) table.insert(output, ("Security Restriction Version: %d"):format(srv_info.sec_restrict_ver)) table.insert(output, ("Internet Bridge Version: %d"):format(srv_info.internet_bridge_ver)) end return true, output end, } Socket = { new = function(self) local o = {} setmetatable(o, self) self.__index = self o.Socket = nmap.new_socket() o.Buffer = nil return o end, --- Sets the socket timeout (@see nmap.set_timeout) -- @param tm number containing the socket timeout in ms set_timeout = function(self, tm) self.Socket:set_timeout(tm) end, --- Establishes a connection. -- -- @param hostid Hostname or IP address. -- @param port Port number. -- @param protocol <code>"tcp"</code>, <code>"udp"</code>, or -- @return Status (true or false). -- @return Error code (if status is false). connect = function( self, hostid, port, protocol ) self.Socket:set_timeout(5000) return self.Socket:connect( hostid, port, protocol ) end, --- Closes an open connection. -- -- @return Status (true or false). -- @return Error code (if status is false). close = function( self ) return self.Socket:close() end, --- Opposed to the <code>socket:receive_bytes</code> function, that returns -- at least x bytes, this function returns the amount of bytes requested. -- -- @param count of bytes to read -- @return true on success, false on failure -- @return data containing bytes read from the socket -- err containing error message if status is false recv = function( self, count ) local status, data self.Buffer = self.Buffer or "" if ( #self.Buffer < count ) then status, data = self.Socket:receive_bytes( count - #self.Buffer ) if ( not(status) or #data < count - #self.Buffer ) then return false, data end self.Buffer = self.Buffer .. data end data = self.Buffer:sub( 1, count ) self.Buffer = self.Buffer:sub( count + 1) return true, data end, --- Sends data over the socket -- -- @return Status (true or false). -- @return Error code (if status is false). send = function( self, data ) return self.Socket:send( data ) end, } --- "static" Utility class containing mostly conversion functions Util = { --- Converts a string to a wide string -- -- @param str string to be converted -- @return string containing a two byte representation of str where a zero -- byte character has been tagged on to each character. ToWideChar = function( str ) return str:gsub("(.)", "%1" .. string.char(0x00) ) end, --- Concerts a wide string to string -- -- @param wstr containing the wide string to convert -- @return string with every other character removed FromWideChar = function( wstr ) local str = "" if ( nil == wstr ) then return nil end for i=1, wstr:len(), 2 do str = str .. wstr:sub(i, i) end return str end, --- Pads a string with zeroes -- -- @param str string containing the string to be padded -- @param len number containing the length of the new string -- @return str string containing the new string ZeroPad = function( str, len ) if len < str:len() then return end for i=1, len - str:len() do str = str .. string.char(0) end return str end, -- Removes trailing nulls -- -- @param str containing the string -- @return ret the string with any trailing nulls removed CToLuaString = function( str ) local ret if ( not(str) ) then return "" end if ( str:sub(-1, -1 ) ~= "\0" ) then return str end for i=1, #str do if ( str:sub(-i,-i) == "\0" ) then ret = str:sub(1, -i - 1) else break end end return ret end, }
mit
dojoteef/loltorch
processmatches.lua
1
11651
local cjson = require('cjson') local dataset = require('dataset') local file = require('pl.file') local path = require('pl.path') local tds = require('tds') local threads = require('threads') local torch = require('torch') local utils = require('utils') require('tds') local cmd = torch.CmdLine() cmd:text() cmd:text('Get matches from the League of Legends API') cmd:text() cmd:text('Options') cmd:option('-matchfile','matches.t7','the directory where the matches are located') cmd:option('-datadir','dataset','the directory where to store the serialized dataset') cmd:option('-threads',8,'the number of threads to use when processing the dataset') cmd:option('-progress',100000,'display a progress update after x number of participants being processed') cmd:option('-tensortype','torch.FloatTensor','what type of tensor to use') cmd:text() -- parse input opt local opt = cmd:parse(arg) local function clearTable(t) for i=1, #t do t[i] = nil end for _,v in pairs(t) do if type(v) == 'table' then clearTable(v) end end end local spells = {} local function addSpells(embeddings, participant, target, offset) clearTable(spells) for i=1, dataset.maxSpellCount do local spellId = participant['spell'..i..'Id'] if spellId then table.insert(spells, spellId) end end -- sort spells so they are in a consistent ordering table.sort(spells) for i=1,#spells do target[i+offset] = embeddings['s'..spells[i]] end return offset+dataset.maxSpellCount end local items = {} local function addItems(embeddings, stats, target, offset) clearTable(items) for i=0, dataset.maxItemCount-1 do local itemId = stats['item'..i] if itemId and itemId > 0 then table.insert(items, itemId) end end -- sort items so they are in a consistent ordering table.sort(items) for i=1,#items do target[i+offset] = embeddings[dataset.itemId(items[i])] end return offset+dataset.maxItemCount end local runes = {blue={max=9},red={max=9},yellow={max=9},black={max=3}} local function addRunes(embeddings, participant, target, offset, runeTypes) if participant.runes then clearTable(runes) for _,rune in ipairs(participant.runes) do local runeType = runeTypes[rune.runeId] table.insert(runes[runeType], rune) end local i = 1 for _, runeType in ipairs(dataset.runeOrder) do -- sort runes so they are in a consistent ordering local runeList = runes[runeType] table.sort(runeList, function(r1, r2) return r1.runeId < r2.runeId end) local start = i for _,rune in ipairs(runeList) do for _=1, rune.rank do target[i+offset] = embeddings[dataset.runeId(rune)] i = i + 1 end end i = start + runeList.max end end return offset+dataset.maxRuneCount end local masteries = {Ferocity={},Resolve={},Cunning={}} local function addMasteries(embeddings, participant, target, offset, masteryTypes) if participant.masteries then clearTable(masteries) local i = 1 for _,mastery in ipairs(participant.masteries) do local masteryType = masteryTypes[mastery.masteryId] table.insert(masteries[masteryType], mastery) end for _, masteryType in ipairs(dataset.masteryOrder) do -- sort masteries so they are in a consistent ordering local masteryList = masteries[masteryType] table.sort(masteryList, function(m1, m2) return m1.masteryId < m2.masteryId end) for _,mastery in ipairs(masteryList) do for _=1, mastery.rank do target[i+offset] = embeddings[dataset.masteryId(mastery)] i = i + 1 end end end end return offset+dataset.maxMasteryCount end local function getRuneTypes(datadir) local runeFile = path.join(datadir, 'runes.json') local data = file.read(runeFile) local ok,runeInfo = pcall(function() return cjson.decode(data) end) if not ok then error('Unable to load: '..runeFile) end local runeTypes = {} for id,rune in pairs(runeInfo.data) do runeTypes[tonumber(id)] = rune.rune.type end return runeTypes end local function getMasteryTypes(datadir) local masteryFile = path.join(datadir, 'masteries.json') local data = file.read(masteryFile) local ok,masteryInfo = pcall(function() return cjson.decode(data) end) if not ok then error('Unable to load: '..masteryFile) end local masteryTypes = {} for tree, masteryList in pairs(masteryInfo.tree) do for _, masteryGroup in ipairs(masteryList) do for _,mastery in ipairs(masteryGroup) do if mastery ~= cjson.null then masteryTypes[tonumber(mastery.masteryId)] = tree end end end end return masteryTypes end local function validParticipant(participant) return participant.stats ~= nil end local function countParticipants(matchlist) threads.serialization('threads.sharedserialize') local pool = threads.Threads( opt.threads, function() _G.cjson = require('cjson') _G.file = require('pl.file') _G.tds = require('tds') end ) local participantsProcessed = tds.AtomicCounter() local participantsPerThread = torch.LongTensor(opt.threads) for i=1,opt.threads do pool:addjob( function(first,last) local threadid = _G.__threadid local participantCount = 0 for j=first,last do local data = _G.file.read(matchlist[j]) local ok,match = pcall(function() return _G.cjson.decode(data) end) if ok then for _,participant in ipairs(match.participants) do if validParticipant(participant) then participantCount = participantCount + 1 end local processed = participantsProcessed:inc() + 1 if processed % opt.progress == 0 then print('Processed '..processed..' participants') end end end end participantsPerThread[threadid] = participantCount end, nil, utils.sliceIndices(i, opt.threads, matchlist) ) end pool:synchronize() pool:terminate() return participantsPerThread end local function processMatches(matchlist, participantsPerThread, embeddings, datadir) local _,embedding = next(embeddings) local embeddingSize = embedding:size(1) local inputLen = 6 local targetlen = dataset.maxSpellCount + dataset.maxItemCount + dataset.maxRuneCount + dataset.maxMasteryCount local participantCount = torch.sum(participantsPerThread) local inputs = torch.Tensor(participantCount, inputLen, embeddingSize):zero() local targets = torch.Tensor(participantCount, targetlen, embeddingSize):zero() local outcomes = torch.Tensor(participantCount) threads.serialization('threads.sharedserialize') local pool = threads.Threads( opt.threads, function() _G.cjson = require('cjson') _G.file = require('pl.file') _G.path = require('pl.path') _G.tds = require('tds') end ) local runeTypes = getRuneTypes(datadir) local masteryTypes = getMasteryTypes(datadir) local participantsProcessed = tds.AtomicCounter() for i=1,opt.threads do pool:addjob( function(first,last) local threadid = _G.__threadid local dataOffset = 0 for t=1,threadid-1 do dataOffset = dataOffset + participantsPerThread[t] end local dataIndex = dataOffset + 1 for j=first,last do local data = _G.file.read(matchlist[j]) local ok,match = pcall(function() return _G.cjson.decode(data) end) if ok then for _,participant in ipairs(match.participants) do if validParticipant(participant) then local input = inputs[dataIndex] local target = targets[dataIndex] local lane = dataset.normalizeLane(participant.timeline.lane) local role = dataset.normalizeRole(lane, participant.timeline.role) outcomes[dataIndex] = participant.stats.winner and 1 or -1 input[1] = embeddings[lane] input[2] = embeddings[role] input[3] = embeddings[dataset.championId(participant)] input[4] = embeddings[dataset.versionFromString(match.matchVersion)] input[5] = embeddings[string.lower(match.region)] input[6] = embeddings[participant.highestAchievedSeasonTier or 'UNRANKED'] local offset = 0 offset = addSpells(embeddings, participant, target, offset) offset = addItems(embeddings, participant.stats, target, offset) offset = addRunes(embeddings, participant, target, offset, runeTypes) addMasteries(embeddings, participant, target, offset, masteryTypes) dataIndex = dataIndex + 1 end local processed = participantsProcessed:inc() + 1 if processed % opt.progress == 0 then print('Processed '..processed..' participants') end end end end end, nil, utils.sliceIndices(i, opt.threads, matchlist) ) end pool:synchronize() pool:terminate() return inputs, targets, outcomes end local function matchesToTensor() local timer = torch.Timer() torch.setdefaulttensortype(opt.tensortype) print('Count participants...') local matchlist = torch.load(opt.matchfile) local participantsPerThread = countParticipants(matchlist) print('Process matches...') local embeddings = torch.load(path.join(opt.datadir, 'embeddings.t7')) local inputs, targets, outcomes = processMatches(matchlist, participantsPerThread, embeddings, opt.datadir) print('Saving tensors...') torch.save(path.join(opt.datadir,'inputs.t7'), inputs) torch.save(path.join(opt.datadir,'targets.t7'), targets) torch.save(path.join(opt.datadir,'outcomes.t7'), outcomes) print(string.format('Done in %s', utils.formatTime(timer))) end local function errorHandler(errmsg) errmsg = errmsg..'\n'..debug.traceback() print(errmsg) end local ok, errmsg = xpcall(matchesToTensor, errorHandler) if not ok then print('Failed to process matches!') print(errmsg) os.exit() end
mit
dmccuskey/dmc-websockets
examples/dmc-websockets-pusher/main.lua
1
1916
--====================================================================-- -- DMC WebSockets Pusher -- -- Communicate with Pusher.com server -- -- Sample code is MIT licensed, the same license which covers Lua itself -- http://en.wikipedia.org/wiki/MIT_License -- Copyright (C) 2014-2015 David McCuskey. All Rights Reserved. --====================================================================-- print( '\n\n##############################################\n\n' ) --====================================================================-- --== Imports local WebSockets = require 'dmc_corona.dmc_websockets' local SSLParams = require 'dmc_corona.dmc_sockets.ssl_params' -- local Utils = require( "dmc_corona.dmc_utils" ) --====================================================================-- --== Setup, Constants local ws --====================================================================-- --== Main Functions local function webSocketsEvent_handler( event ) print( "webSocketsEvent_handler", event.type ) local evt_type = event.type if evt_type == ws.ONOPEN then print( 'Received event: ONOPEN' ) elseif evt_type == ws.ONMESSAGE then local msg = event.message print( "Received event: ONMESSAGE" ) print( "message: '" .. tostring( msg.data ) .. "'\n\n" ) elseif evt_type == ws.ONCLOSE then print( "Received event: ONCLOSE" ) print( 'code:reason', event.code, event.reason ) elseif evt_type == ws.ONERROR then print( "Received event: ONERROR" ) end end ws = WebSockets{ -- non-secure -- uri='ws://ws.pusherapp.com:80/app/a6fc0e5ee5adc489d1ac?client=lua&version=1.0&protocol=7', -- secure (SSL/TLS) uri='wss://ws.pusherapp.com:443/app/a6fc0e5ee5adc489d1ac?client=lua&version=1.0&protocol=7', -- port can be here, or in URI -- port=443, -- 80/443 ssl_params = {protocol=SSLParams.TLS_V1}, protocols='7' } ws:addEventListener( ws.EVENT, webSocketsEvent_handler )
mit
dylanwh/moonshine
runtime/moonshine/object.lua
2
1742
--[[ vim: set ft=lua sw=4 ts=4 expandtab: - Moonshine - a Lua-based chat client - - Copyright (C) 2010 Dylan William Hardison - - This file is part of Moonshine. - - Moonshine 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 of the License, or - (at your option) any later version. - - Moonshine 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 Moonshine. If not, see <http://www.gnu.org/licenses/>. ]] local Object = { } local mt = { } setmetatable(Object, mt) function mt.__index(self, slot) local parent = rawget(self, '__parent') if parent then return parent[slot] end end function Object.clone(parent) return setmetatable( { __parent = parent }, getmetatable(parent) ) end function Object.new(parent, ...) local self = parent:clone() local init = self.__init if init then init(self, ...) end return self end function Object:new_mt() local new_mt = {} for k, v in pairs(getmetatable(self)) do new_mt[k] = v end setmetatable(self, new_mt) return new_mt end function Object:callback(name, ...) local cb_args = { ... } return function(...) local args = { ... } for i, arg in ipairs(cb_args) do table.insert(args, i, arg) end return self[name](self, unpack(args)) end end return Object
gpl-3.0
mogh77/merseed
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
hfjgjfg/spam1111
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
alireza1998/mega
plugins/help.lua
44
5047
do function pairsByKeys(t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end -- Returns true if is not empty local function has_usage_data(dict) if (dict.usage == nil or dict.usage == '') then return false end return true end -- Get commands for that plugin local function plugin_help(name,number,requester) local plugin = "" if number then local i = 0 for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else i = i + 1 if i == tonumber(number) then plugin = plugins[name] end end end else plugin = plugins[name] if not plugin then return nil end end local text = "" if (type(plugin.usage) == "table") then for ku,usage in pairs(plugin.usage) do if ku == 'user' then -- usage for user if (type(plugin.usage.user) == "table") then for k,v in pairs(plugin.usage.user) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.user..'\n' end elseif ku == 'moderator' then -- usage for moderator if requester == 'moderator' or requester == 'admin' or requester == 'sudo' then if (type(plugin.usage.moderator) == "table") then for k,v in pairs(plugin.usage.moderator) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.moderator..'\n' end end elseif ku == 'admin' then -- usage for admin if requester == 'admin' or requester == 'sudo' then if (type(plugin.usage.admin) == "table") then for k,v in pairs(plugin.usage.admin) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.admin..'\n' end end elseif ku == 'sudo' then -- usage for sudo if requester == 'sudo' then if (type(plugin.usage.sudo) == "table") then for k,v in pairs(plugin.usage.sudo) do text = text..v..'\n' end elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage.sudo..'\n' end end else text = text..usage..'\n' end end text = text..'======================\n' elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage..'\n======================\n' end return text end -- !help command local function telegram_help() local i = 0 local text = "Plugins list:\n\n" -- Plugins names for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else i = i + 1 text = text..i..'. '..name..'\n' end end text = text..'\n'..'There are '..i..' plugins help available.' text = text..'\n'..'Write "!help [plugin name]" or "!help [plugin number]" for more info.' text = text..'\n'..'Or "!help all" to show all info.' return text end -- !help all command local function help_all(requester) local ret = "" for name in pairsByKeys(plugins) do if plugins[name].hidden then name = nil else ret = ret .. plugin_help(name, nil, requester) end end return ret end local function run(msg, matches) if not is_momod(msg) then return "" end if is_sudo(msg) then requester = "sudo" elseif is_admin(msg) then requester = "admin" elseif is_momod(msg) then requester = "moderator" else requester = "user" end if matches[1] == "help" then return telegram_help() elseif matches[1] == "help all" then return help_all(requester) else local text = "" if tonumber(matches[1]) then text = plugin_help(nil, matches[1], requester) else text = plugin_help(matches[1], nil, requester) end if not text then text = telegram_help() end return text end end return { description = "Help plugin. Get info from other plugins. ", usage = { "help: Show list of plugins.", "help all: Show all commands for every plugin.", "help [plugin name]: Commands for that plugin.", "help [number]: Commands for that plugin. Type !help to get the plugin number." }, patterns = { "^help$", "^help all", "^help (.+)" }, run = run } end
gpl-2.0
EvPowerTeam/EV_OP
feeds/luci/protocols/ipv6/luasrc/model/cbi/admin_network/proto_dslite.lua
63
1662
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Copyright 2013 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 ]]-- local map, section, net = ... local peeraddr, ip6addr local tunlink, defaultroute, metric, ttl, mtu peeraddr = section:taboption("general", Value, "peeraddr", translate("DS-Lite AFTR address")) peeraddr.rmempty = false peeraddr.datatype = "ip6addr" ip6addr = section:taboption("general", Value, "ip6addr", translate("Local IPv6 address"), translate("Leave empty to use the current WAN address")) ip6addr.datatype = "ip6addr" tunlink = section:taboption("advanced", DynamicList, "tunlink", translate("Tunnel Link")) tunlink.template = "cbi/network_netlist" tunlink.nocreate = true defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("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) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
gpl-2.0
digitalloggers/nodemcu-firmware
lua_examples/u8glib/u8g_rotation.lua
43
2088
-- setup I2c and connect display function init_i2c_display() -- SDA and SCL can be assigned freely to available GPIOs local sda = 5 -- GPIO14 local scl = 6 -- GPIO12 local sla = 0x3c i2c.setup(0, sda, scl, i2c.SLOW) disp = u8g.ssd1306_128x64_i2c(sla) end -- setup SPI and connect display function init_spi_display() -- Hardware SPI CLK = GPIO14 -- Hardware SPI MOSI = GPIO13 -- Hardware SPI MISO = GPIO12 (not used) -- CS, D/C, and RES can be assigned freely to available GPIOs local cs = 8 -- GPIO15, pull-down 10k to GND local dc = 4 -- GPIO2 local res = 0 -- GPIO16 spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, spi.DATABITS_8, 0) disp = u8g.ssd1306_128x64_spi(cs, dc, res) end -- the draw() routine function draw() disp:setFont(u8g.font_6x10) disp:drawStr( 0+0, 20+0, "Hello!") disp:drawStr( 0+2, 20+16, "Hello!") disp:drawBox(0, 0, 3, 3) disp:drawBox(disp:getWidth()-6, 0, 6, 6) disp:drawBox(disp:getWidth()-9, disp:getHeight()-9, 9, 9) disp:drawBox(0, disp:getHeight()-12, 12, 12) end function rotate() if (next_rotation < tmr.now() / 1000) then if (dir == 0) then disp:undoRotation() elseif (dir == 1) then disp:setRot90() elseif (dir == 2) then disp:setRot180() elseif (dir == 3) then disp:setRot270() end dir = dir + 1 dir = bit.band(dir, 3) -- schedule next rotation step in 1000ms next_rotation = tmr.now() / 1000 + 1000 end end function rotation_test() print("--- Starting Rotation Test ---") dir = 0 next_rotation = 0 local loopcnt for loopcnt = 1, 100, 1 do rotate() disp:firstPage() repeat draw(draw_state) until disp:nextPage() == false tmr.delay(100000) tmr.wdclr() end print("--- Rotation Test done ---") end --init_i2c_display() init_spi_display() rotation_test()
mit
siggame/Joueur.lua
games/saloon/tile.lua
1
4649
-- Tile: A Tile in the game that makes up the 2D map grid. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local GameObject = require("games.saloon.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- A Tile in the game that makes up the 2D map grid. -- @classmod Tile local Tile = class(GameObject) -- initializes a Tile with basic logic as provided by the Creer code generator function Tile:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- The beer Bottle currently flying over this Tile, nil otherwise. self.bottle = nil --- The Cowboy that is on this Tile, nil otherwise. self.cowboy = nil --- The furnishing that is on this Tile, nil otherwise. self.furnishing = nil --- If this Tile is pathable, but has a hazard that damages Cowboys that path through it. self.hasHazard = false --- If this Tile is a balcony of the Saloon that YoungGuns walk around on, and can never be pathed through by Cowboys. self.isBalcony = false --- The Tile to the 'East' of this one (x+1, y). nil if out of bounds of the map. self.tileEast = nil --- The Tile to the 'North' of this one (x, y-1). nil if out of bounds of the map. self.tileNorth = nil --- The Tile to the 'South' of this one (x, y+1). nil if out of bounds of the map. self.tileSouth = nil --- The Tile to the 'West' of this one (x-1, y). nil if out of bounds of the map. self.tileWest = nil --- The x (horizontal) position of this Tile. self.x = 0 --- The y (vertical) position of this Tile. self.y = 0 --- The YoungGun on this tile, nil otherwise. self.youngGun = nil --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Tile:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. --- The valid directions that tiles can be in, "North", "East", "South", or "West" Tile.directions = Table("North", "East", "South", "West") --- Gets the neighbors of this Tile -- @treturns Table(Tile) The neighboring (adjacent) Tiles to this tile function Tile:getNeighbors() local neighbors = Table() for i, direction in ipairs(self.directions) do local neighbor = self["tile" .. direction] if neighbor then neighbors:insert(neighbor) end end return neighbors end --- Checks if a Tile is pathable to units -- @treturns bool True if pathable, false otherwise function Tile:isPathable() -- <<-- Creer-Merge: is_pathable_builtin -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. return false -- DEVELOPER ADD LOGIC HERE -- <<-- /Creer-Merge: is_pathable_builtin -->> end --- Checks if this Tile has a specific neighboring Tile -- @tparam Tile tile the tile to check against -- @treturns bool true if the tile is a neighbor of this Tile, false otherwise function Tile:hasNeighbor(tile) if tile then return self.tileNorth == tile or self.tileEast == tile or self.tileSouth == tile or self.tileEast == tile else return false end end -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return Tile
mit
sami2448/set
plugins/rae.lua
15
1313
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
HubertRonald/FoulJob
Library/easing.lua
1
4735
--[[ Author of this easing functions for Lua is Josh Tynjala https://github.com/joshtynjala/gtween.lua Licensed under the MIT license. Easing functions adapted from Robert Penner's AS3 tweening equations. ]] --------------------------- -- math functions --------------------------- local sin = math.sin local cos = math.cos local pow = math.pow local sqrt = math.sqrt local npi = math.pi --------------------------- local backS = 1.70158 easing = {}; easing.inBack = function(ratio) return ratio*ratio*((backS+1)*ratio-backS) end easing.outBack = function(ratio) ratio = ratio - 1 return ratio*ratio*((backS+1)*ratio+backS)+1 end easing.inOutBack = function(ratio) ratio = ratio * 2 if ratio < 1 then return 0.5*(ratio*ratio*((backS*1.525+1)*ratio-backS*1.525)) else ratio = ratio - 2 return 0.5*(ratio*ratio*((backS*1.525+1)*ratio+backS*1.525)+2) end end easing.inBounce = function(ratio) return 1-easing.outBounce(1-ratio,0,0,0) end easing.outBounce = function(ratio) if ratio < 1/2.75 then return 7.5625*ratio*ratio elseif ratio < 2/2.75 then ratio = ratio - 1.5/2.75 return 7.5625*ratio*ratio+0.75 elseif ratio < 2.5/2.75 then ratio= ratio - 2.25/2.75 return 7.5625*ratio*ratio+0.9375 else ratio = ratio - 2.625/2.75 return 7.5625*ratio*ratio+0.984375 end end easing.inOutBounce = function(ratio) ratio = ratio * 2 if ratio < 1 then return 0.5*easing.inBounce(ratio,0,0,0) else return 0.5*easing.outBounce(ratio-1,0,0,0)+0.5 end end easing.inCircular = function(ratio) return -(sqrt(1-ratio*ratio)-1) end easing.outCircular = function(ratio) return sqrt(1-(ratio-1)*(ratio-1)) end easing.inOutCircular = function(ratio) ratio = ratio * 2 if ratio < 1 then return -0.5*(sqrt(1-ratio*ratio)-1) else ratio = ratio - 2 return 0.5*(sqrt(1-ratio*ratio)+1) end end easing.inCubic = function(ratio) return ratio*ratio*ratio end easing.outCubic = function(ratio) ratio = ratio - 1 return ratio*ratio*ratio+1 end easing.inOutCubic = function(ratio) if ratio < 0.5 then return 4*ratio*ratio*ratio else ratio = ratio - 1 return 4*ratio*ratio*ratio+1 end end local elasticA = 1; local elasticP = 0.3; local elasticS = elasticP/4; easing.inElastic = function(ratio) if ratio == 0 or ratio == 1 then return ratio end ratio = ratio - 1 return -(elasticA * pow(2, 10 * ratio) * sin((ratio - elasticS) * (2 * npi) / elasticP)); end easing.outElastic = function(ratio) if ratio == 0 or ratio == 1 then return ratio end return elasticA * pow(2, -10 * ratio) * sin((ratio - elasticS) * (2 * npi) / elasticP) + 1; end easing.inOutElastic = function(ratio) if ratio == 0 or ratio == 1 then return ratio end ratio = ratio*2-1 if ratio < 0 then return -0.5 * (elasticA * pow(2, 10 * ratio) * sin((ratio - elasticS*1.5) * (2 * npi) /(elasticP*1.5))); end return 0.5 * elasticA * pow(2, -10 * ratio) * sin((ratio - elasticS*1.5) * (2 * npi) / (elasticP*1.5)) + 1; end easing.inExponential = function(ratio) if ratio == 0 then return 0 end return pow(2, 10 * (ratio - 1)) end easing.outExponential = function(ratio) if ratio == 1 then return 1 end return 1-pow(2, -10 * ratio) end easing.inOutExponential = function(ratio) if ratio == 0 or ratio == 1 then return ratio end ratio = ratio*2-1 if 0 > ratio then return 0.5*pow(2, 10*ratio) end return 1-0.5*pow(2, -10*ratio) end easing.linear = function(ratio) return ratio end easing.inQuadratic = function(ratio) return ratio*ratio end easing.outQuadratic = function(ratio) return -ratio*(ratio-2) end easing.inOutQuadratic = function(ratio) if ratio < 0.5 then return 2*ratio*ratio end return -2*ratio*(ratio-2)-1 end easing.inQuartic = function(ratio) return ratio*ratio*ratio*ratio end easing.outQuartic = function(ratio) ratio = ratio - 1 return 1-ratio*ratio*ratio*ratio end easing.inOutQuartic = function(ratio) if ratio < 0.5 then return 8*ratio*ratio*ratio*ratio end ratio = ratio - 1 return -8*ratio*ratio*ratio*ratio+1 end easing.inQuintic = function(ratio) return ratio*ratio*ratio*ratio*ratio end easing.outQuintic = function(ratio) ratio = ratio - 1 return 1+ratio*ratio*ratio*ratio*ratio end easing.inOutQuintic = function(ratio) if ratio < 0.5 then return 16*ratio*ratio*ratio*ratio*ratio end ratio = ratio - 1 return 16*ratio*ratio*ratio*ratio*ratio+1 end easing.inSine = function(ratio) return 1-cos(ratio * (npi / 2)) end easing.outSine = function(ratio) return sin(ratio * (npi / 2)) end easing.inOutSine = function(ratio) return -0.5*(cos(ratio*npi)-1) end
mit
EvPowerTeam/EV_OP
feeds/luci/applications/luci-firewall/luasrc/model/cbi/firewall/forward-details.lua
65
3931
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" local dsp = require "luci.dispatcher" local ft = require "luci.tools.firewall" local m, s, o arg[1] = arg[1] or "" m = Map("firewall", translate("Firewall - Port Forwards"), translate("This page allows you to change advanced properties of the port \ forwarding entry. In most cases there is no need to modify \ those settings.")) m.redirect = dsp.build_url("admin/network/firewall/forwards") if m.uci:get("firewall", arg[1]) ~= "redirect" then luci.http.redirect(m.redirect) return else local name = m:get(arg[1], "name") or m:get(arg[1], "_name") if not name or #name == 0 then name = translate("(Unnamed Entry)") end m.title = "%s - %s" %{ translate("Firewall - Port Forwards"), name } end s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false ft.opt_enabled(s, Button) ft.opt_name(s, Value, translate("Name")) o = s:option(Value, "proto", translate("Protocol")) o:value("tcp udp", "TCP+UDP") o:value("tcp", "TCP") o:value("udp", "UDP") o:value("icmp", "ICMP") function o.cfgvalue(...) local v = Value.cfgvalue(...) if not v or v == "tcpudp" then return "tcp udp" end return v end o = s:option(Value, "src", translate("Source zone")) o.nocreate = true o.default = "wan" o.template = "cbi/firewall_zonelist" o = s:option(DynamicList, "src_mac", translate("Source MAC address"), translate("Only match incoming traffic from these MACs.")) o.rmempty = true o.datatype = "neg(macaddr)" o.placeholder = translate("any") luci.sys.net.mac_hints(function(mac, name) o:value(mac, "%s (%s)" %{ mac, name }) end) o = s:option(Value, "src_ip", translate("Source IP address"), translate("Only match incoming traffic from this IP or range.")) o.rmempty = true o.datatype = "neg(ip4addr)" o.placeholder = translate("any") luci.sys.net.ipv4_hints(function(ip, name) o:value(ip, "%s (%s)" %{ ip, name }) end) o = s:option(Value, "src_port", translate("Source port"), translate("Only match incoming traffic originating from the given source port or port range on the client host")) o.rmempty = true o.datatype = "neg(portrange)" o.placeholder = translate("any") o = s:option(Value, "src_dip", translate("External IP address"), translate("Only match incoming traffic directed at the given IP address.")) luci.sys.net.ipv4_hints(function(ip, name) o:value(ip, "%s (%s)" %{ ip, name }) end) o.rmempty = true o.datatype = "neg(ip4addr)" o.placeholder = translate("any") o = s:option(Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) o.datatype = "neg(portrange)" o = s:option(Value, "dest", translate("Internal zone")) o.nocreate = true o.default = "lan" o.template = "cbi/firewall_zonelist" o = s:option(Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified \ internal host")) o.datatype = "ip4addr" luci.sys.net.ipv4_hints(function(ip, name) o:value(ip, "%s (%s)" %{ ip, name }) end) o = s:option(Value, "dest_port", translate("Internal port"), translate("Redirect matched incoming traffic to the given port on \ the internal host")) o.placeholder = translate("any") o.datatype = "portrange" o = s:option(Flag, "reflection", translate("Enable NAT Loopback")) o.rmempty = true o.default = o.enabled o.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end s:option(Value, "extra", translate("Extra arguments"), translate("Passes additional arguments to iptables. Use with care!")) return m
gpl-2.0
dylanwh/moonshine
runtime/moonshine/parseopt.lua
1
2084
local core = require "moonshine.parseopt.core" local types = require "moonshine.parseopt.types" local spec_parser = require "moonshine.parseopt.spec_parser" local NOARG, EATARG, STOP = core.NOARG, core.EATARG, core.STOP function prefix_match(str, prefix) return #prefix <= #str and str:sub(1, #prefix) == prefix end local function find(keys, alias_keys, name, seen) seen = seen or {} seen[name] = true if alias_keys[name] and not seen[alias_keys[name]] then return find(keys, alias_keys, alias_keys[name], seen) elseif keys[name] then return name, keys[name] elseif #name > 1 then -- for more than one letter options, we attempt to match -- by prefix. local matches = {} for k, v in pairs(alias_keys) do if prefix_match(k, name) then table.insert(matches, v) end end for k, v in pairs(keys) do if prefix_match(k, name) then table.insert(matches, k) end end if #matches == 1 then return find(keys, alias_keys, matches[1], seen) else return nil end end end -- --options and arguments local function parse(spec, text) assert(type(spec) == 'table') local argc = spec.argc local keys = spec.keys local alias_keys = spec.alias_keys local vars = {} local args = {} local unknown_option local function callback(name, value) if name == nil then if argc < 0 or #args < argc then table.insert(args, value) return EATARG else return STOP end else local key, f = find(keys, alias_keys, name) if key then local flag flag, vars[key] = f(value, vars[key]) return flag else print("unknown option: ", name) return STOP end end end local rest = core.parse(text, callback) if argc >= 0 then table.insert(args, rest) end return vars, unpack(args) end local function build_parser(spec) if type(spec) == 'string' then spec = spec_parser.parse(spec) end return function(text) return parse(spec, text) end end return { parse_spec = spec_parser.parse, types = types, parse = parse, build_parser = build_parser, }
gpl-3.0
Android-AOSP/external_skia
tools/lua/bbh_filter.lua
207
4407
-- bbh_filter.lua -- -- This script outputs info about 'interesting' skp files, -- where the definition of 'interesting' changes but is roughly: -- "Interesting for bounding box hierarchy benchmarks." -- -- Currently, the approach is to output, in equal ammounts, the names of the files that -- have most commands, and the names of the files that use the least popular commands. function count_entries(table) local count = 0 for _,_ in pairs(table) do count = count + 1 end return count end verbCounts = {} function reset_current() -- Data about the skp in transit currentInfo = { fileName = '', verbs = {}, numOps = 0 } end reset_current() numOutputFiles = 10 -- This is per measure. globalInfo = {} -- Saves currentInfo for each file to be used at the end. output = {} -- Stores {fileName, {verb, count}} tables. function tostr(t) local str = "" for k, v in next, t do if #str > 0 then str = str .. ", " end if type(k) == "number" then str = str .. "[" .. k .. "] = " else str = str .. tostring(k) .. " = " end if type(v) == "table" then str = str .. "{ " .. tostr(v) .. " }" else str = str .. tostring(v) end end return str end function sk_scrape_startcanvas(c, fileName) end function sk_scrape_endcanvas(c, fileName) globalInfo[fileName] = currentInfo globalInfo[fileName].fileName = fileName reset_current() end function sk_scrape_accumulate(t) -- dump the params in t, specifically showing the verb first, which we -- then nil out so it doesn't appear in tostr() -- verbCounts[t.verb] = (verbCounts[t.verb] or 0) + 1 currentInfo.verbs[t.verb] = (currentInfo.verbs[t.verb] or 0) + 1 currentInfo.numOps = currentInfo.numOps + 1 t.verb = nil end function sk_scrape_summarize() verbWeights = {} -- {verb, weight}, where 0 < weight <= 1 meta = {} for k,v in pairs(verbCounts) do table.insert(meta, {key=k, value=v}) end table.sort(meta, function (a,b) return a.value > b.value; end) maxValue = meta[1].value io.write("-- ==================\n") io.write("------------------------------------------------------------------ \n") io.write("-- Command\t\t\tNumber of calls\t\tPopularity\n") io.write("------------------------------------------------------------------ \n") for k, v in pairs(meta) do verbWeights[v.key] = v.value / maxValue -- Poor man's formatting: local padding = "\t\t\t" if (#v.key + 3) < 8 then padding = "\t\t\t\t" end if (#v.key + 3) >= 16 then padding = "\t\t" end io.write ("-- ",v.key, padding, v.value, '\t\t\t', verbWeights[v.key], "\n") end meta = {} function calculate_weight(verbs) local weight = 0 for name, count in pairs(verbs) do weight = weight + (1 / verbWeights[name]) * count end return weight end for n, info in pairs(globalInfo) do table.insert(meta, info) end local visitedFiles = {} -- Prints out information in lua readable format function output_with_metric(metric_func, description, numOutputFiles) table.sort(meta, metric_func) print(description) local iter = 0 for i, t in pairs(meta) do if not visitedFiles[t.fileName] then visitedFiles[t.fileName] = true io.write ("{\nname = \"", t.fileName, "\", \nverbs = {\n") for verb,count in pairs(globalInfo[t.fileName].verbs) do io.write(' ', verb, " = ", count, ",\n") end io.write("}\n},\n") iter = iter + 1 if iter >= numOutputFiles then break end end end end output_with_metric( function(a, b) return calculate_weight(a.verbs) > calculate_weight(b.verbs); end, "\n-- ================== skps with calling unpopular commands.", 10) output_with_metric( function(a, b) return a.numOps > b.numOps; end, "\n-- ================== skps with the most calls.", 50) local count = count_entries(visitedFiles) print ("-- Spat", count, "files") end
bsd-3-clause
sev-/scummvm
devtools/create_ultima/files/ultima6/scripts/u6/init.lua
18
13035
local lua_file = nil --load common functions lua_file = nuvie_load("common/common.lua"); lua_file(); SFX_BLOCKED = 0 SFX_HIT = 1 SFX_FOUNTAIN = 2 SFX_DEATH = 3 SFX_RUBBER_DUCK = 4 SFX_BROKEN_GLASS = 5 SFX_BELL = 6 SFX_FIRE = 7 SFX_CLOCK = 8 SFX_PROTECTION_FIELD = 9 SFX_WATER_WHEEL = 10 SFX_MISSLE = 11 SFX_EXPLOSION = 12 SFX_ATTACK_SWING = 13 SFX_SUCCESS = 14 SFX_FAILURE = 15 SFX_CORPSER_DRAGGED_UNDER = 16 SFX_CORPSER_REGURGITATE = 17 SFX_CASTING_MAGIC_P1 = 18 SFX_CASTING_MAGIC_P1_2 = 19 SFX_CASTING_MAGIC_P1_3 = 20 SFX_CASTING_MAGIC_P1_4 = 21 SFX_CASTING_MAGIC_P1_5 = 22 SFX_CASTING_MAGIC_P1_6 = 23 SFX_CASTING_MAGIC_P1_7 = 24 SFX_CASTING_MAGIC_P1_8 = 25 SFX_CASTING_MAGIC_P2 = 26 SFX_CASTING_MAGIC_P2_2 = 27 SFX_CASTING_MAGIC_P2_3 = 28 SFX_CASTING_MAGIC_P2_4 = 29 SFX_CASTING_MAGIC_P2_5 = 30 SFX_CASTING_MAGIC_P2_6 = 31 SFX_CASTING_MAGIC_P2_7 = 32 SFX_CASTING_MAGIC_P2_8 = 33 SFX_AVATAR_DEATH = 34 SFX_KAL_LOR = 35 SFX_SLUG_DISSOLVE = 36 SFX_HAIL_STONE = 37 SFX_EARTH_QUAKE = 39 FADE_COLOR_RED = 12 FADE_COLOR_BLUE = 9 TIMER_LIGHT = 0 TIMER_INFRAVISION = 1 TIMER_STORM = 13 TIMER_TIME_STOP = 14 TIMER_ECLIPSE = 15 OBJLIST_OFFSET_VANISH_OBJ = 0x1c13 OBJLIST_OFFSET_MOONSTONES = 0x1c1b OBJLIST_OFFSET_KEG_TIMER = 0x1c4b g_vanish_obj = {["obj_n"] = 0, ["frame_n"] = 0} g_keg_timer = 0 g_armageddon = false g_avatar_died = false -- used so we don't keep casting once Avatar is dead function is_avatar_dead() return g_avatar_died end --used with triple crossbow and magic wind spells. g_projectile_offset_tbl = { { 4,5,5,5,5,6,6,6,6,6,6, 4,4,5,5,5,6,6,6,6,6,7, 4,4,4,5,5,6,6,6,6,7,7, 4,4,4,4,5,6,6,6,7,7,7, 4,4,4,4,4,6,6,7,7,7,7, 4,4,4,4,4,0,0,0,0,0,0, 3,3,3,3,2,2,0,0,0,0,0, 3,3,3,2,2,2,1,0,0,0,0, 3,3,2,2,2,2,1,1,0,0,0, 3,2,2,2,2,2,1,1,1,0,0, 2,2,2,2,2,2,1,1,1,1,0 }, { 2,2,2,2,2,2,3,3,3,3,4, 1,2,2,2,2,2,3,3,3,4,4, 1,1,2,2,2,2,3,3,4,4,4, 1,1,1,2,2,2,3,4,4,4,4, 1,1,1,1,2,2,4,4,4,4,4, 0,0,0,0,0,0,4,4,4,4,4, 0,0,0,0,0,6,6,5,5,5,5, 0,0,0,0,7,6,6,6,5,5,5, 0,0,0,7,7,6,6,6,6,5,5, 0,0,7,7,7,6,6,6,6,6,5, 0,7,7,7,7,6,6,6,6,6,6 } } --moonstone data is loaded from objlist in load_game() g_moonstone_loc_tbl = { {x=0x3A7, y=0x106, z=0}, {x=0x1F7, y=0x166, z=0}, {x=0x9F, y=0x3AE, z=0}, {x=0x127, y=0x26, z=0}, {x=0x33F, y=0x0A6, z=0}, {x=0x147, y=0x336, z=0}, {x=0x17, y=0x16, z=1}, {x=0x397, y=0x3A6, z=0} } g_show_stealing = config_get_boolean_value("config/ultima6/show_stealing") -- some common functions function set_g_show_stealing(stealing) g_show_stealing = stealing end function dbg(msg_string) --io.stderr:write(msg_string) end function alignment_is_evil(align) if align == ALIGNMENT_EVIL or align == ALIGNMENT_CHAOTIC then return true end return false end function advance_game_time(nturns) if nturns == 0 then return end coroutine.yield("adv_game_time", nturns); end function get_obj_from_inventory(actor) local obj = coroutine.yield("inv_obj", actor) return obj end function get_obj() local obj = coroutine.yield("obj") return obj end function actor_talk(actor) coroutine.yield("talk", actor) return end function get_spell() local spell_num = coroutine.yield("spell") return spell_num end function obj_new(obj_n, frame_n, status, qty, quality, x, y, z) local obj = {} obj["obj_n"] = obj_n or 0 obj["frame_n"] = frame_n or 0 obj["status"] = status or 0 obj["qty"] = qty or 0 obj["quality"] = quality or 0 obj["x"] = x or 0 obj["y"] = y or 0 obj["z"] = z or 0 return obj end --FIXME need a better way of doing this. Remove need for deprecated setfenv() function. function run_script(script) local t = {}; setmetatable(t, {__index = _G}); local body = nuvie_load(script); setfenv(body, t); body(); end function look_obj(obj) print("Thou dost see " .. obj.look_string); local weight = obj.weight; --FIXME this could be a problem if we want to change Lua_number type to int. if weight ~= 0 then if obj.qty > 1 and obj.stackable then print(". They weigh"); else print(". It weighs"); end print(string.format(" %.1f", weight).." stones"); end --FIXME usecode look description should be lua code. if usecode_look(obj) then print("\n") return false end local dmg = weapon_dmg_tbl[obj.obj_n]; if dmg ~= nil then if weight ~= 0 then print(" and") else print(". It") end print(" can do "..dmg.." point") if dmg > 1 then print("s") end print(" of damage") end local ac = armour_tbl[obj.obj_n] if ac ~= nil then if weight ~= 0 or dmg ~= 0 then print(" and") else print(". It") end print(" can absorb "..ac.." point") if ac > 1 then print("s") end print(" of damage") end print(".\n"); local player_loc = player_get_location(); if g_show_stealing == true and obj.getable == true and player_loc.z == 0 and obj.ok_to_take == false then if math.abs(player_loc.x - obj.x) > 1 or math.abs(player_loc.y - obj.y) > 1 then print("PRIVATE PROPERTY\n") else print("PRIVATE PROPERTY") end end return true end function player_subtract_karma(k) local karma = player_get_karma() - k if karma < 0 then karma = 0 end player_set_karma(karma) end function player_add_karma(k) local karma = player_get_karma() + k if karma >= 100 then karma = 99 end player_set_karma(karma) end function party_heal() for actor in party_members() do actor.asleep = false actor.poisoned = false actor.paralyzed = false actor_remove_charm(actor) actor.hp = actor.max_hp end end function explosion(tile_num, x, y) play_sfx(SFX_EXPLOSION) return explosion_start(tile_num, x, y) end function projectile(tile_num, start_x, start_y, end_x, end_y, speed, spin) if spin == nil then spin = 0 end local rotate_offset = 0 local src_tile_y_offset = 0 if tile_num == 547 then --spear rotate_offset = 45 elseif tile_num == 566 then --bow rotate_offset = 90 src_tile_y_offset = 4 elseif tile_num == 567 then --crossbow rotate_offset = 90 src_tile_y_offset = 3 end play_sfx(SFX_MISSLE) projectile_anim(tile_num, start_x, start_y, end_x, end_y, speed, false, rotate_offset, spin, src_tile_y_offset) end function fade_obj_blue(obj) fade_obj(obj, FADE_COLOR_BLUE, 20) end function fade_actor_blue(actor) Actor.black_fade_effect(actor, FADE_COLOR_BLUE, 20) end function fade_obj_out(obj) obj.invisible = true fade_tile(obj.x, obj.y, obj.z, obj.tile_num) obj.invisible = false end function fade_obj_in(obj) obj.invisible = true fade_tile(obj.x, obj.y, obj.z, nil, obj.tile_num) obj.invisible = false end function fade_actor_in(actor) local new_tile_num = actor.tile_num actor.visible = false fade_tile(actor.x, actor.y, actor.z, nil, new_tile_num) actor.visible = true end --tile_num, readied location local g_readiable_objs_tbl = { [0x200] = 0, [0x201] = 0, [0x202] = 0, [0x203] = 0, [0x204] = 0, [0x205] = 0, [0x206] = 0, [0x207] = 0, [0x219] = 1, [0x250] = 1, [0x251] = 1, [0x252] = 1, [0x217] = 1, [0x101] = 1, [0x220] = 2, [0x221] = 2, [0x223] = 2, [0x224] = 2, [0x225] = 2, [0x226] = 2, [0x227] = 2, [0x22A] = 2, [0x22F] = 2, [0x230] = 2, [0x238] = 2, [0x254] = 2, [0x256] = 2, [0x255] = 2, [0x259] = 2, [0x262] = 2, [0x263] = 2, [0x264] = 2, [0x270] = 2, [0x271] = 2, [0x272] = 2, [0x273] = 2, [0x274] = 2, [0x275] = 2, [0x279] = 2, [0x27D] = 2, [0x27E] = 2, [0x27F] = 2, [0x280] = 2, [0x281] = 2, [0x28C] = 2, [0x28E] = 2, [0x29D] = 2, [0x2A2] = 2, [0x2A3] = 2, [0x2B9] = 2, [0x210] = 4, [0x211] = 4, [0x212] = 4, [0x213] = 4, [0x214] = 4, [0x215] = 4, [0x216] = 4, [0x218] = 4, [0x219] = 4, [0x28c] = 4, [0x28e] = 4, [0x29d] = 4, [0x257] = 4, [0x208] = 5, [0x209] = 5, [0x20a] = 5, [0x20b] = 5, [0x20c] = 5, [0x20d] = 5, [0x20e] = 5, [0x20f] = 5, [0x222] = 5, [0x21a] = 7, [0x21b] = 7, [0x228] = 8, [0x229] = 8, [0x231] = 8, [0x235] = 8, [0x22b] = 8, [0x22c] = 8, [0x22d] = 8, [0x22e] = 8, [0x258] = 9, [0x37d] = 9, [0x37e] = 9, [0x37f] = 9 } function actor_is_readiable_obj(actor) if g_readiable_objs_tbl[actor.tile_num] ~= nil then return true end return false end function obj_is_readiable(obj) if g_readiable_objs_tbl[obj.tile_num] ~= nil then return true end return false end function is_time_stopped() if timer_get(TIMER_TIME_STOP) ~= 0 then return true end return false end function load_game() objlist_seek(OBJLIST_OFFSET_VANISH_OBJ) local tmp_obj_dat = objlist_read2() local obj_n = tmp_obj_dat local frame_n = 0 if tmp_obj_dat > 1023 then frame_n = tmp_obj_dat - 1023 obj_n = tmp_obj_dat - frame_n end g_vanish_obj.obj_n = obj_n g_vanish_obj.frame_n = frame_n --Load moonstone locations. objlist_seek(OBJLIST_OFFSET_MOONSTONES) for i=1,8 do local x = objlist_read2() local y = objlist_read2() local z = objlist_read2() dbg("moonstone["..i.."] at ("..x..","..y..","..z..")\n") g_moonstone_loc_tbl[i] = {x=x, y=y, z=z} end objlist_seek(OBJLIST_OFFSET_KEG_TIMER) g_keg_timer = objlist_read2() set_g_armageddon(false) g_avatar_died = false end function save_game() objlist_seek(OBJLIST_OFFSET_VANISH_OBJ) local tmp_obj_dat = g_vanish_obj.obj_n local frame_n = g_vanish_obj.frame_n if frame_n > 0 then tmp_obj_dat = tmp_obj_dat + (frame_n + 1023) end objlist_write2(tmp_obj_dat) --Save moonstone locations objlist_seek(OBJLIST_OFFSET_MOONSTONES) for i=1,8 do local loc = g_moonstone_loc_tbl[i] objlist_write2(loc.x) objlist_write2(loc.y) objlist_write2(loc.z) end objlist_seek(OBJLIST_OFFSET_KEG_TIMER) objlist_write2(g_keg_timer) end function moonstone_set_loc(phase, x, y, z) if phase < 1 or phase > 8 then return false end g_moonstone_loc_tbl[phase] = {x=x, y=y, z=z} return true end function moonstone_get_loc(phase) if phase < 1 or phase > 8 then return nil end return g_moonstone_loc_tbl[phase] end function update_moongates(show_moongates) local i, loc for i,loc in ipairs(g_moonstone_loc_tbl) do local moongate = map_get_obj(loc.x, loc.y, loc.z, 0x55) --moongate if show_moongates == true then if moongate == nil and loc.x ~= 0 then moongate = Obj.new(0x55, 1) Obj.moveToMap(moongate, loc) end else --hide moongate if moongate ~= nil then map_remove_obj(moongate) end end end end function use_keg(obj) if obj.frame_n ~= 0 then print("\nNo effect\n") return end if g_keg_timer > 0 then print("\nNot now\n") else obj.frame_n = 1 print("\nPowder lit!\n") g_keg_timer = 3 end end function explode_keg() --try to find lit keg on the current game map. local loc = player_get_location() for obj in find_obj(loc.z, 223, 1) do --keg obj, frame_n = 1 if obj ~= nil then explode_obj(obj) end end --try to explode lit kegs in the party's inventory local party_actor for party_actor in party_members() do local obj = Actor.inv_get_obj_n(party_actor, 223, 1) --keg with frame_n = 1 if obj ~= nil then explode_obj(obj, party_actor) end end end function explode_obj(obj, actor) dbg("Exploding "..obj.name.."\n") local x, y, z if actor ~= nil then x = actor.x y = actor.y z = actor.z else x = obj.x y = obj.y z = obj.z end Obj.removeFromEngine(obj) local hit_items = explosion(0x189, x, y) local random = math.random local k, v for k,v in pairs(hit_items) do if v.luatype == "actor" then actor_hit(v, random(1, 0x3c)) end if g_avatar_died == true then explode_surrounding_objects(x, y, z) actor_avatar_death(Actor.get(1)) return -- don't keep exploding once Avatar is dead end end explode_surrounding_objects(x, y, z) end function explode_surrounding_objects(x, y, z) --blow up doors and other kegs for x = x - 2,x + 2 do for y = y - 2,y + 2 do local map_obj = map_get_obj(x, y, z, 223) if map_obj ~= nil then explode_obj(map_obj) end map_obj = map_get_obj(x, y, z, 0x12c) --steel door if map_obj == nil or map_obj.frame_n == 0xc then map_obj = map_get_obj(x, y, z, 0x129) --oaken door if map_obj == nil or map_obj.frame_n == 0xc then map_obj = map_get_obj(x, y, z, 0x12a) --windowed door if map_obj == nil or map_obj.frame_n == 0xc then map_obj = map_get_obj(x, y, z, 0x12b) --cedar door end end end if map_obj ~= nil and map_obj.frame_n <= 0xc then Obj.removeFromEngine(map_obj) print("\nThe door is blown up!\n") end end end end function set_g_armageddon(val) g_armageddon = val set_armageddon(val) end function create_object_needs_quan(obj_n) -- obj.stackable is already checked return false end --load actor functions actor_load = nuvie_load("u6/actor.lua"); if type(actor_load) == "function" then actor_load() else if type(actor_load) == "string" then io.stderr:write(actor_load); end end -- init magic magic_init = nuvie_load("u6/magic.lua"); magic_init(); -- init usecode usecode_init = nuvie_load("u6/usecode.lua"); usecode_init(); player_init = nuvie_load("u6/player.lua"); player_init();
gpl-3.0
alireasuzuki/LIZARD
bot/utils.lua
494
23873
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) if user_info and user_info.print_name then text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n" else text = text..k.." - "..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) if user_info and user_info.print_name then text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n" else text = text..k.." - "..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
ctozlm/Dato-Core
src/unity/python/graphlab/lua/pl/array2d.lua
26
13368
--- Operations on two-dimensional arrays. -- See @{02-arrays.md.Operations_on_two_dimensional_tables|The Guide} -- -- Dependencies: `pl.utils`, `pl.tablex`, `pl.types` -- @module pl.array2d local type,tonumber,assert,tostring,io,ipairs,string,table = _G.type,_G.tonumber,_G.assert,_G.tostring,_G.io,_G.ipairs,_G.string,_G.table local setmetatable,getmetatable = setmetatable,getmetatable local tablex = require 'pl.tablex' local utils = require 'pl.utils' local types = require 'pl.types' local imap,tmap,reduce,keys,tmap2,tset,index_by = tablex.imap,tablex.map,tablex.reduce,tablex.keys,tablex.map2,tablex.set,tablex.index_by local remove = table.remove local splitv,fprintf,assert_arg = utils.splitv,utils.fprintf,utils.assert_arg local byte = string.byte local stdout = io.stdout local array2d = {} local function obj (int,out) local mt = getmetatable(int) if mt then setmetatable(out,mt) end return out end local function makelist (res) return setmetatable(res,utils.stdmt.List) end local function index (t,k) return t[k] end --- return the row and column size. -- @array2d t a 2d array -- @treturn int number of rows -- @treturn int number of cols function array2d.size (t) assert_arg(1,t,'table') return #t,#t[1] end --- extract a column from the 2D array. -- @array2d a 2d array -- @param key an index or key -- @return 1d array function array2d.column (a,key) assert_arg(1,a,'table') return makelist(imap(index,a,key)) end local column = array2d.column --- map a function over a 2D array -- @func f a function of at least one argument -- @array2d a 2d array -- @param arg an optional extra argument to be passed to the function. -- @return 2d array function array2d.map (f,a,arg) assert_arg(1,a,'table') f = utils.function_arg(1,f) return obj(a,imap(function(row) return imap(f,row,arg) end, a)) end --- reduce the rows using a function. -- @func f a binary function -- @array2d a 2d array -- @return 1d array -- @see pl.tablex.reduce function array2d.reduce_rows (f,a) assert_arg(1,a,'table') return tmap(function(row) return reduce(f,row) end, a) end --- reduce the columns using a function. -- @func f a binary function -- @array2d a 2d array -- @return 1d array -- @see pl.tablex.reduce function array2d.reduce_cols (f,a) assert_arg(1,a,'table') return tmap(function(c) return reduce(f,column(a,c)) end, keys(a[1])) end --- reduce a 2D array into a scalar, using two operations. -- @func opc operation to reduce the final result -- @func opr operation to reduce the rows -- @param a 2D array function array2d.reduce2 (opc,opr,a) assert_arg(3,a,'table') local tmp = array2d.reduce_rows(opr,a) return reduce(opc,tmp) end local function dimension (t) return type(t[1])=='table' and 2 or 1 end --- map a function over two arrays. -- They can be both or either 2D arrays -- @func f function of at least two arguments -- @int ad order of first array (1 or 2) -- @int bd order of second array (1 or 2) -- @tab a 1d or 2d array -- @tab b 1d or 2d array -- @param arg optional extra argument to pass to function -- @return 2D array, unless both arrays are 1D function array2d.map2 (f,ad,bd,a,b,arg) assert_arg(1,a,'table') assert_arg(2,b,'table') f = utils.function_arg(1,f) if ad == 1 and bd == 2 then return imap(function(row) return tmap2(f,a,row,arg) end, b) elseif ad == 2 and bd == 1 then return imap(function(row) return tmap2(f,row,b,arg) end, a) elseif ad == 1 and bd == 1 then return tmap2(f,a,b) elseif ad == 2 and bd == 2 then return tmap2(function(rowa,rowb) return tmap2(f,rowa,rowb,arg) end, a,b) end end --- cartesian product of two 1d arrays. -- @func f a function of 2 arguments -- @array t1 a 1d table -- @array t2 a 1d table -- @return 2d table -- @usage product('..',{1,2},{'a','b'}) == {{'1a','2a'},{'1b','2b'}} function array2d.product (f,t1,t2) f = utils.function_arg(1,f) assert_arg(2,t1,'table') assert_arg(3,t2,'table') local res, map = {}, tablex.map for i,v in ipairs(t2) do res[i] = map(f,t1,v) end return res end --- flatten a 2D array. -- (this goes over columns first.) -- @array2d t 2d table -- @return a 1d table -- @usage flatten {{1,2},{3,4},{5,6}} == {1,2,3,4,5,6} function array2d.flatten (t) local res = {} local k = 1 for _,a in ipairs(t) do -- for all rows for i = 1,#a do res[k] = a[i] k = k + 1 end end return makelist(res) end --- reshape a 2D array. -- @array2d t 2d array -- @int nrows new number of rows -- @bool co column-order (Fortran-style) (default false) -- @return a new 2d array function array2d.reshape (t,nrows,co) local nr,nc = array2d.size(t) local ncols = nr*nc / nrows local res = {} local ir,ic = 1,1 for i = 1,nrows do local row = {} for j = 1,ncols do row[j] = t[ir][ic] if not co then ic = ic + 1 if ic > nc then ir = ir + 1 ic = 1 end else ir = ir + 1 if ir > nr then ic = ic + 1 ir = 1 end end end res[i] = row end return obj(t,res) end --- swap two rows of an array. -- @array2d t a 2d array -- @int i1 a row index -- @int i2 a row index function array2d.swap_rows (t,i1,i2) assert_arg(1,t,'table') t[i1],t[i2] = t[i2],t[i1] end --- swap two columns of an array. -- @array2d t a 2d array -- @int j1 a column index -- @int j2 a column index function array2d.swap_cols (t,j1,j2) assert_arg(1,t,'table') for i = 1,#t do local row = t[i] row[j1],row[j2] = row[j2],row[j1] end end --- extract the specified rows. -- @array2d t 2d array -- @tparam {int} ridx a table of row indices function array2d.extract_rows (t,ridx) return obj(t,index_by(t,ridx)) end --- extract the specified columns. -- @array2d t 2d array -- @tparam {int} cidx a table of column indices function array2d.extract_cols (t,cidx) assert_arg(1,t,'table') local res = {} for i = 1,#t do res[i] = index_by(t[i],cidx) end return obj(t,res) end --- remove a row from an array. -- @function array2d.remove_row -- @array2d t a 2d array -- @int i a row index array2d.remove_row = remove --- remove a column from an array. -- @array2d t a 2d array -- @int j a column index function array2d.remove_col (t,j) assert_arg(1,t,'table') for i = 1,#t do remove(t[i],j) end end local Ai = byte 'A' local function _parse (s) local c,r if s:sub(1,1) == 'R' then r,c = s:match 'R(%d+)C(%d+)' r,c = tonumber(r),tonumber(c) else c,r = s:match '(.)(.)' c = byte(c) - byte 'A' + 1 r = tonumber(r) end assert(c ~= nil and r ~= nil,'bad cell specifier: '..s) return r,c end --- parse a spreadsheet range. -- The range can be specified either as 'A1:B2' or 'R1C1:R2C2'; -- a special case is a single element (e.g 'A1' or 'R1C1') -- @string s a range. -- @treturn int start col -- @treturn int start row -- @treturn int end col -- @treturn int end row function array2d.parse_range (s) if s:find ':' then local start,finish = splitv(s,':') local i1,j1 = _parse(start) local i2,j2 = _parse(finish) return i1,j1,i2,j2 else -- single value local i,j = _parse(s) return i,j end end --- get a slice of a 2D array using spreadsheet range notation. @see parse_range -- @array2d t a 2D array -- @string rstr range expression -- @return a slice -- @see array2d.parse_range -- @see array2d.slice function array2d.range (t,rstr) assert_arg(1,t,'table') local i1,j1,i2,j2 = array2d.parse_range(rstr) if i2 then return array2d.slice(t,i1,j1,i2,j2) else -- single value return t[i1][j1] end end local function default_range (t,i1,j1,i2,j2) local nr, nc = array2d.size(t) i1,j1 = i1 or 1, j1 or 1 i2,j2 = i2 or nr, j2 or nc if i2 < 0 then i2 = nr + i2 + 1 end if j2 < 0 then j2 = nc + j2 + 1 end return i1,j1,i2,j2 end --- get a slice of a 2D array. Note that if the specified range has -- a 1D result, the rank of the result will be 1. -- @array2d t a 2D array -- @int i1 start row (default 1) -- @int j1 start col (default 1) -- @int i2 end row (default N) -- @int j2 end col (default M) -- @return an array, 2D in general but 1D in special cases. function array2d.slice (t,i1,j1,i2,j2) assert_arg(1,t,'table') i1,j1,i2,j2 = default_range(t,i1,j1,i2,j2) local res = {} for i = i1,i2 do local val local row = t[i] if j1 == j2 then val = row[j1] else val = {} for j = j1,j2 do val[#val+1] = row[j] end end res[#res+1] = val end if i1 == i2 then res = res[1] end return obj(t,res) end --- set a specified range of an array to a value. -- @array2d t a 2D array -- @param value the value (may be a function) -- @int i1 start row (default 1) -- @int j1 start col (default 1) -- @int i2 end row (default N) -- @int j2 end col (default M) -- @see tablex.set function array2d.set (t,value,i1,j1,i2,j2) i1,j1,i2,j2 = default_range(t,i1,j1,i2,j2) for i = i1,i2 do tset(t[i],value,j1,j2) end end --- write a 2D array to a file. -- @array2d t a 2D array -- @param f a file object (default stdout) -- @string fmt a format string (default is just to use tostring) -- @int i1 start row (default 1) -- @int j1 start col (default 1) -- @int i2 end row (default N) -- @int j2 end col (default M) function array2d.write (t,f,fmt,i1,j1,i2,j2) assert_arg(1,t,'table') f = f or stdout local rowop if fmt then rowop = function(row,j) fprintf(f,fmt,row[j]) end else rowop = function(row,j) f:write(tostring(row[j]),' ') end end local function newline() f:write '\n' end array2d.forall(t,rowop,newline,i1,j1,i2,j2) end --- perform an operation for all values in a 2D array. -- @array2d t 2D array -- @func row_op function to call on each value -- @func end_row_op function to call at end of each row -- @int i1 start row (default 1) -- @int j1 start col (default 1) -- @int i2 end row (default N) -- @int j2 end col (default M) function array2d.forall (t,row_op,end_row_op,i1,j1,i2,j2) assert_arg(1,t,'table') i1,j1,i2,j2 = default_range(t,i1,j1,i2,j2) for i = i1,i2 do local row = t[i] for j = j1,j2 do row_op(row,j) end if end_row_op then end_row_op(i) end end end local min, max = math.min, math.max ---- move a block from the destination to the source. -- @array2d dest a 2D array -- @int di start row in dest -- @int dj start col in dest -- @array2d src a 2D array -- @int i1 start row (default 1) -- @int j1 start col (default 1) -- @int i2 end row (default N) -- @int j2 end col (default M) function array2d.move (dest,di,dj,src,i1,j1,i2,j2) assert_arg(1,dest,'table') assert_arg(4,src,'table') i1,j1,i2,j2 = default_range(src,i1,j1,i2,j2) local nr,nc = array2d.size(dest) i2, j2 = min(nr,i2), min(nc,j2) --i1, j1 = max(1,i1), max(1,j1) dj = dj - 1 for i = i1,i2 do local drow, srow = dest[i+di-1], src[i] for j = j1,j2 do drow[j+dj] = srow[j] end end end --- iterate over all elements in a 2D array, with optional indices. -- @array2d a 2D array -- @tparam {int} indices with indices (default false) -- @int i1 start row (default 1) -- @int j1 start col (default 1) -- @int i2 end row (default N) -- @int j2 end col (default M) -- @return either value or i,j,value depending on indices function array2d.iter (a,indices,i1,j1,i2,j2) assert_arg(1,a,'table') local norowset = not (i2 and j2) i1,j1,i2,j2 = default_range(a,i1,j1,i2,j2) local n,i,j = i2-i1+1,i1-1,j1-1 local row,nr = nil,0 local onr = j2 - j1 + 1 return function() j = j + 1 if j > nr then j = j1 i = i + 1 if i > i2 then return nil end row = a[i] nr = norowset and #row or onr end if indices then return i,j,row[j] else return row[j] end end end --- iterate over all columns. -- @array2d a a 2D array -- @return each column in turn function array2d.columns (a) assert_arg(1,a,'table') local n = a[1][1] local i = 0 return function() i = i + 1 if i > n then return nil end return column(a,i) end end --- new array of specified dimensions -- @int rows number of rows -- @int cols number of cols -- @param val initial value; if it's a function then use `val(i,j)` -- @return new 2d array function array2d.new(rows,cols,val) local res = {} local fun = types.is_callable(val) for i = 1,rows do local row = {} if fun then for j = 1,cols do row[j] = val(i,j) end else for j = 1,cols do row[j] = val end end res[i] = row end return res end return array2d
agpl-3.0
ryangmor/bsoeted
plugins/ingroup.lua
11
27638
do local name_log = user_print_name(msg.from) 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 -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as The owner.') 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}) end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end 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_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end 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 get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end 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) if not is_momod(msg) then return "For moderators only!" end 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) if not is_owner(msg) then return "Only admins can do it for now" end 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) if not is_owner(msg) then return "Only admins can do it for now" end 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) if not is_momod(msg) then return "For moderators only!" end 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) if not is_momod(msg) then return "For moderators only!" end 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) if not is_momod(msg) then return "For moderators only!" end 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 set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end 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 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) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return 'Group has been added.' end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end 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 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) 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 = '\nList 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 callbackres(extra, success, result) local user = result.id local name = result.print_name local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) if msg.from.id ~= 0 and not is_owner(msg) then chat_add_user(chat, user, ok_cb, true) end end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) 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_owner(msg) then return "Only owner 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], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id send_large_msg(receiver, "Created a new new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { patterns = { "^[!/](add)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](demote) (.*)$", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
movb/Algorithm-Implementations
Rabin_Karp/Lua/Yonaba/rabin_karp_test.lua
26
1214
-- Tests for rabin_karp.lua local rabin_karp = require 'rabin_karp' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end local function same(t, b) if #t ~= #b then return false end for k,v in ipairs(t) do if b[k] ~= v then return false end end return true end run('Testing Rabin_Karp', function() assert(same(rabin_karp('abcde', 'abcabcdabcde'),{8})) assert(same(rabin_karp('t', 'test'),{1,4})) assert(same(rabin_karp('lua', 'lua lua lua lu lua'), {1,5,9,16})) end) run('Can also take an optional prime number for hashing Rabin_Karp', function() assert(same(rabin_karp('abcde', 'abcabcdabcde',23),{8})) assert(same(rabin_karp('t', 'test',13),{1,4})) assert(same(rabin_karp('lua', 'lua lua lua lu lua',19), {1,5,9,16})) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
magnum357i/Magnum-s-Aegisub-Scripts
automation/autoload/mag.create_lines.lua
1
9865
function lang_switch_keys(lang) local in_lang = {} local langs = { [1] = {lang_key = "tr", lang_name = "Türkçe", script_name = "Satır Oluştur", sub_menu = "Satır/Oluştur"}, [2] = {lang_key = "en", lang_name = "English", script_name = "Create Lines", sub_menu = "Lines/Create"} } local lang_list = {} local script_name_list = {} local sub_menu_list = {} for i = 1, #langs do lang_list[langs[i].lang_key] = langs[i].lang_name script_name_list[langs[i].lang_key] = langs[i].script_name sub_menu_list[langs[i].lang_key] = langs[i].sub_menu end if lang == langs[1].lang_key then in_lang["module_incompatible"] = "Mag modülünün kurulu sürümü bu lua dosyası ile uyumsuz!\n\nModül dosyasının en az \"%s\" sürümü veya daha üstü gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?" in_lang["module_not_found"] = "Mag modülü bulunamadı!\n\nBu lua dosyasını kullanmak için Mag modülünü indirip Aegisub programı kapalıyken\n\"Aegisub/automation/include/\" dizinine taşımanız gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?" in_lang["module_yes"] = "Git" in_lang["module_no"] = "Daha Sonra" in_lang["sub_menu"] = langs[1].sub_menu in_lang["s_name"] = langs[1].script_name in_lang["s_desc"] = "Satır oluşturmaya yardım eder." in_lang["tabKey1"] = "Gömülü Yazı" in_lang["tabKey2"] = "Şarkı" in_lang["key1"] = "Başlangıç süresi ({%s}), bitiş süresinden ({%s}) büyük." in_lang["guiLabelKey1"] = "Başlangıç zamanı:" in_lang["guiLabelKey2"] = "Bitiş zamanı:" in_lang["guiLabelKey3"] = "Bir metin girin:" in_lang["guiLabelKey4"] = "Satır başlangıç zamanı:" in_lang["guiLabelKey5"] = "Satır süresi:" in_lang["buttonKey1"] = "Satır Oluştur" in_lang["buttonKey2"] = "Kapat" in_lang["buttonKey3"] = "Panoyu Yapıştır" elseif lang == langs[2].lang_key then in_lang["module_incompatible"] = "The installed version of the Mag module is incompatible with this lua file!\n\nAt least \"%s\" version or higher of the module file is required.\n\n\nWould you like to go to the download page now?" in_lang["module_not_found"] = "The module named Mag could not be found!\n\nTo use this file, you need to download the module named mag\nand move it to \"Aegisub/automation/include/\" directory when Aegisub is off.\n\n\nDo you want to go to download page now?" in_lang["module_yes"] = "Go" in_lang["module_no"] = "Later" in_lang["sub_menu"] = langs[2].sub_menu in_lang["s_name"] = langs[2].script_name in_lang["s_desc"] = "Helps to create a line." in_lang["tabKey1"] = "Hardsub" in_lang["tabKey2"] = "Karaoke" in_lang["key1"] = "Start time ({%s}) is bigger than end time ({%s})." in_lang["guiLabelKey1"] = "Start time:" in_lang["guiLabelKey2"] = "End time:" in_lang["guiLabelKey3"] = "Type a text:" in_lang["guiLabelKey4"] = "Line start time:" in_lang["guiLabelKey5"] = "Line duration:" in_lang["buttonKey1"] = "Create Line" in_lang["buttonKey2"] = "Close" in_lang["buttonKey3"] = "Paste Clipboard" end return in_lang, lang_list, script_name_list, sub_menu_list end c_lang_switch = "en" c_lang, c_lang_list, c_script_name_list, c_sub_name_list = lang_switch_keys(c_lang_switch) script_name = c_lang.s_name script_description = c_lang.s_desc script_version = "1.3" script_author = "Magnum357" script_mag_version = "1.1.5.0" script_file_name = "mag.create_lines" script_file_ext = ".lua" include_unicode = true include_clipboard = true include_karaskel = true mag_import, mag = pcall(require, "mag") if mag_import then mag.lang = c_lang_switch c_lock_gui = false c_buttons1 = {c_lang.buttonKey1, c_lang.buttonKey2} c_buttons2 = {c_lang.buttonKey1, c_lang.buttonKey3, c_lang.buttonKey2} c_hardsub_start_time = 0 c_hardsub_end_time = 0 c = {} c.kdur = "30000" gui = { main1 = { {class = "label", x = 0, y = 0, width = 1, height = 1, label = c_lang.guiLabelKey1}, {class = "label", x = 0, y = 1, width = 1, height = 1, label = c_lang.guiLabelKey2}, label1 = {class = "label", x = 1, y = 0, width = 10, height = 1}, label2 = {class = "label", x = 1, y = 1, width = 10, height = 1}, {class = "label", x = 0, y = 2, width = 1, height = 1, label = c_lang.guiLabelKey3}, text = {class = "edit", name = "u_text", x = 1, y = 2, width = 10, height = 1}, }, main2 = { label1 = {class = "label", x = 0, y = 0, width = 1, height = 1, label = c_lang.guiLabelKey4}, label2 = {class = "label", x = 1, y = 0, width = 1, height = 1}, {class = "label", x = 0, y = 1, width = 1, height = 1, label = c_lang.guiLabelKey5}, duration = {class = "edit", name = "u_duration", x = 1, y = 1, width = 1, height = 1}, {class = "label", x = 0, y = 2, width = 1, height = 1, label = c_lang.guiLabelKey3}, text = {class = "edit", name = "u_text", x = 1, y = 2, width = 1, height = 1}, } } end function hardsub(subs,sel,act) if not mag.is.video() then mag.show.log(1, mag.window.lang.message("is_video")) else local current_time = mag.convert.ms_from_frame(aegisub.project_properties().video_position) if current_time < 0 then current_time = 1 end if c_hardsub_start_time == 0 and c_hardsub_end_time == 0 then c_hardsub_start_time = current_time elseif c_hardsub_start_time > 0 and c_hardsub_end_time == 0 then c_hardsub_end_time = current_time local jump if c_hardsub_start_time > c_hardsub_end_time then mag.show.log(1, mag.string.format(c_lang.key1, mag.convert.ms_to_time(c_hardsub_start_time), mag.convert.ms_to_time(c_hardsub_end_time))) else local ok, config gui.main1.label1.label = mag.convert.ms_to_time(c_hardsub_start_time) gui.main1.label2.label = mag.convert.ms_to_time(c_hardsub_end_time) repeat ok, config = mag.window.dialog(gui.main1, c_buttons1) until ok == mag.convert.ascii(c_buttons1[1]) and not mag.is.empty(config.u_text) or ok == mag.convert.ascii(c_buttons1[2]) if ok == mag.convert.ascii(c_buttons1[1]) then local l = table.copy(subs[act]) l.layer = 0 l.start_time = c_hardsub_start_time l.end_time = c_hardsub_end_time l.text = config.u_text l.actor = "" l.effect = "" l.margin_l = 0 l.margin_r = 0 l.margin_t = 0 jump = act + 1 subs.insert(jump, l) end end c_hardsub_start_time = 0 c_hardsub_end_time = 0 if jump ~= nil then return {jump} end end end end function karaoke(subs,sel,act) if not mag.is.video() then mag.show.log(1, mag.window.lang.message("is_video")) else local ok, config local line_end_time = subs[act].end_time gui.main2.label2.label = mag.convert.ms_to_time(line_end_time) gui.main2.text.value = "" repeat if ok == mag.convert.ascii(c_buttons2[2]) then gui.main2.text.value = mag.clip.get() end gui.main2.duration.value = mag.convert.ms_to_time(c.kdur) ok, config = mag.window.dialog(gui.main2, c_buttons2) c.kdur = mag.convert.time_to_ms(config.u_duration) until ok == mag.convert.ascii(c_buttons2[1]) and not mag.is.empty(config.u_text) or ok == mag.convert.ascii(c_buttons2[3]) if ok == mag.convert.ascii(c_buttons1[1]) then local l = table.copy(subs[act]) l.layer = 0 l.start_time = line_end_time l.end_time = line_end_time + c.kdur l.text = config.u_text l.actor = "" l.effect = "" l.margin_l = 0 l.margin_r = 0 l.margin_t = 0 subs.insert(act + 1, l) return {act + 1} end end end function check_macro1(subs,sel,act) if c_lock_gui then mag.show.log(1, mag.window.lang.message("restart_aegisub")) else local fe, fee = pcall(hardsub, subs, sel, act) mag.window.funce(fe, fee) mag.window.undo_point() return fee end end function check_macro2(subs, sel, act) if c_lock_gui then mag.show.log(1, mag.window.lang.message("restart_aegisub")) else mag.config.get(c) local fe, fee = pcall(karaoke, subs, sel, act) mag.window.funce(fe, fee) mag.window.undo_point() mag.config.set(c) return fee end end function mag_redirect_gui() local mag_module_link = "https://github.com/magnum357i/Magnum-s-Aegisub-Scripts" local k = aegisub.dialog.display({{class = "label", label = mag_gui_message}}, {c_lang.module_yes, c_lang.module_no}) if k == c_lang.module_yes then os.execute("start "..mag_module_link) end end if mag_import then if mag_module_version:gsub("%.", "") < script_mag_version:gsub("%.", "") then mag_gui_message = string.format(c_lang.module_incompatible, script_mag_version) aegisub.register_macro(script_name, script_desription, mag_redirect_gui) else mag.window.register(c_sub_name_list[c_lang_switch].."/"..c_lang.tabKey1, check_macro1) mag.window.register(c_sub_name_list[c_lang_switch].."/"..c_lang.tabKey2, check_macro2) mag.window.lang.register(c_sub_name_list[c_lang_switch]) end else mag_gui_message = c_lang.module_not_found aegisub.register_macro(script_name, script_desription, mag_redirect_gui) end
mit
projexsys/hua-client-demos
ios/cortex/theme_ios.lua
2
10288
----------------------------------------------------------------------------------------- -- -- theme_ios.lua -- ----------------------------------------------------------------------------------------- local modname = ... local themeTable = {} package.loaded[modname] = themeTable local assetDir = "widget_ios" local imageSuffix = display.imageSuffix or "" ----------------------------------------------------------------------------------------- -- -- button -- ----------------------------------------------------------------------------------------- -- -- specify a "style" option to use different button styles on a per-button basis -- -- example: -- local button = widget.newButton{ style="blue1Small" } -- -- NOTE: using a "style" is not required (default options will be used). -- ----------------------------------------------------------------------------------------- themeTable.button = { -- if no style is specified, will use default: default = assetDir .. "/button/default.png", over = assetDir .. "/button/over.png", width = 278, height = 46, font = "Helvetica-Bold", fontSize = 20, labelColor = { default={0}, over={255} }, emboss = true, -- button styles blue1Small = { default = assetDir .. "/button/blue1Small/default.png", over = assetDir .. "/button/blue1Small/over.png", width = 60, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, blue1Large = { default = assetDir .. "/button/blue1Large/default.png", over = assetDir .. "/button/blue1Large/over.png", width = 90, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, blue2Small = { default = assetDir .. "/button/blue2Small/default.png", over = assetDir .. "/button/blue2Small/over.png", width = 60, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, blue2Large = { default = assetDir .. "/button/blue2Large/default.png", over = assetDir .. "/button/blue2Large/over.png", width = 90, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, blackSmall = { default = assetDir .. "/button/blackSmall/default.png", over = assetDir .. "/button/blackSmall/over.png", width = 60, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, blackLarge = { default = assetDir .. "/button/blackLarge/default.png", over = assetDir .. "button/blackLarge/over.png", width = 90, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, redSmall = { default = assetDir .. "/button/redSmall/default.png", over = assetDir .. "/button/redSmall/over.png", width = 60, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, redLarge = { default = assetDir .. "/button/redLarge/default.png", over = assetDir .. "/button/redLarge/over.png", width = 90, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, backSmall = { default = assetDir .. "/button/backSmall/default.png", over = assetDir .. "/button/backSmall/over.png", width = 60, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, backLarge = { default = assetDir .. "/button/backLarge/default.png", over = assetDir .. "/button/backLarge/over.png", width = 90, height = 30, font = "HelveticaNeue-Bold", fontSize = 12, labelColor = { default={255}, over={255} }, emboss = true, }, sheetGreen = { default = assetDir .. "/button/sheetGreen/default.png", over = assetDir .. "button/sheetGreen/over.png", width = 278, height = 46, font = "HelveticaNeue-Bold", fontSize = 20, labelColor = { default={255}, over={255} }, emboss = true, }, sheetRed = { default = assetDir .. "/button/sheetRed/default.png", over = assetDir .. "/button/sheetRed/over.png", width = 278, height = 46, font = "HelveticaNeue-Bold", fontSize = 20, labelColor = { default={255}, over={255} }, emboss = true, }, sheetBlack = { default = assetDir .. "/button/sheetBlack/default.png", over = assetDir .. "/button/sheetBlack/over.png", width = 278, height = 46, font = "HelveticaNeue-Bold", fontSize = 20, labelColor = { default={255}, over={255} }, emboss = true, }, sheetYellow = { default = assetDir .. "/button/sheetYellow/default.png", over = assetDir .. "/button/sheetYellow/over.png", width = 278, height = 46, font = "HelveticaNeue-Bold", fontSize = 20, labelColor = { default={255}, over={255} }, emboss = true, } } ----------------------------------------------------------------------------------------- -- -- slider -- ----------------------------------------------------------------------------------------- themeTable.slider = { -- default style width = 220, height = 10, background = assetDir .. "/slider/sliderBg.png", fillImage = assetDir .. "/slider/sliderFill.png", fillWidth = 2, leftWidth = 16, handle = assetDir .. "/slider/handle.png", handleWidth = 32, handleHeight = 32, -- slider styles small120 = { width = 120, 10, background = assetDir .. "/slider/small120/sliderBg.png", fillImage = assetDir .. "/slider/sliderFill.png", fillWidth = 2, leftWidth = 16, handle = assetDir .. "/slider/handle.png", handleWidth = 32, handleHeight = 32 } } ----------------------------------------------------------------------------------------- -- -- pickerWheel -- ----------------------------------------------------------------------------------------- themeTable.pickerWheel = { width = 296, height = 222, maskFile=assetDir .. "/pickerWheel/wheelmask.png", overlayImage=assetDir .. "/pickerWheel/overlay.png", overlayWidth=320, overlayHeight=222, bgImage=assetDir .. "/pickerWheel/bg.png", bgImageWidth=1, bgImageHeight=222, separator=assetDir .. "/pickerWheel/separator.png", separatorWidth=8, separatorHeight=1, font = "HelveticaNeue-Bold", fontSize = 22 } ----------------------------------------------------------------------------------------- -- -- spinner -- ----------------------------------------------------------------------------------------- themeTable.spinner = { sheet = assetDir .. "/assets.png", data = assetDir .. ".assets", startFrame = "spinner_spinner", width = 40, height = 40, incrementEvery = 50, deltaAngle = 30, } ----------------------------------------------------------------------------------------- -- -- switch -- ----------------------------------------------------------------------------------------- themeTable.switch = { -- Default (on/off switch) sheet = assetDir .. "/assets.png", data = assetDir .. ".assets", backgroundFrame = "switch_background", backgroundWidth = 165, backgroundHeight = 31, overlayFrame = "switch_overlay", overlayWidth = 83, overlayHeight = 31, handleDefaultFrame = "switch_handle", handleOverFrame = "switch_handleOver", mask = assetDir .. "/masks/switch/onOffMask.png", radio = { sheet = assetDir .. "/assets.png", data = assetDir .. ".assets", width = 33, height = 34, frameOff = "switch_radioButtonDefault", frameOn = "switch_radioButtonSelected", }, checkbox = { sheet = assetDir .. "/assets.png", data = assetDir .. ".assets", width = 33, height = 33, frameOff = "switch_checkboxDefault", frameOn = "switch_checkboxSelected", }, } ----------------------------------------------------------------------------------------- -- -- stepper -- ----------------------------------------------------------------------------------------- themeTable.stepper = { sheet = assetDir .. "/assets.png", data = assetDir .. ".assets", defaultFrame = "stepper_nonActive", noMinusFrame = "stepper_noMinus", noPlusFrame = "stepper_noPlus", minusActiveFrame = "stepper_minusActive", plusActiveFrame = "stepper_plusActive", width = 102, height = 38, } ----------------------------------------------------------------------------------------- -- -- progressView -- ----------------------------------------------------------------------------------------- themeTable.progressView = { sheet = assetDir .. "/assets.png", data = assetDir .. ".assets", fillXOffset = 2, fillYOffset = 0, fillOuterFrame = "progressView_outerFrame", fillOuterWidth = 182, fillOuterHeight = 14, fillInnerLeftFrame = "progressView_leftFill", fillInnerLeftWidth = 12, fillInnerLeftHeight = 10, fillInnerMiddleFrame = "progressView_middleFill", fillInnerMiddleWidth = 35, fillInnerMiddleHeight = 10, fillInnerRightFrame = "progressView_rightFill", fillInnerRightWidth = 12, fillInnerRightHeight = 10, } ----------------------------------------------------------------------------------------- -- -- segmentedControl -- ----------------------------------------------------------------------------------------- themeTable.segmentedControl = { sheet = assetDir .. "/assets.png", data = assetDir .. ".assets", width = 12, height = 29, leftSegmentFrame = "segmentedControl_left", leftSegmentSelectedFrame = "segmentedControl_leftOn", rightSegmentFrame = "segmentedControl_right", rightSegmentSelectedFrame = "segmentedControl_rightOn", middleSegmentFrame = "segmentedControl_middle", middleSegmentSelectedFrame = "segmentedControl_middleOn", dividerFrame = "segmentedControl_divider", } ----------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------- -- -- searchField -- ----------------------------------------------------------------------------------------- themeTable.searchField = { sheet = assetDir .. "/assets.png", data = assetDir .. ".assets", defaultFrame = "searchField_bar", cancelFrame = "searchField_remove", defaultFrameWidth = 207, defaultFrameHeight = 33, cancelFrameWidth = 19, cancelFrameHeight = 19, } return themeTable
mit
EvPowerTeam/EV_OP
feeds/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/collectd.lua
69
2332
--[[ Luci configuration model for statistics - general collectd configuration (c) 2008 Freifunk Leipzig / 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$ ]]-- require("luci.sys") m = Map("luci_statistics", translate("Collectd Settings"), translate( "Collectd is a small daemon for collecting data from " .. "various sources through different plugins. On this page " .. "you can change general settings for the collectd daemon." )) -- general config section s = m:section( NamedSection, "collectd", "luci_statistics" ) -- general.hostname (Hostname) hostname = s:option( Value, "Hostname", translate("Hostname") ) hostname.default = luci.sys.hostname() hostname.optional = true -- general.basedir (BaseDir) basedir = s:option( Value, "BaseDir", translate("Base Directory") ) basedir.default = "/var/run/collectd" -- general.include (Include) include = s:option( Value, "Include", translate("Directory for sub-configurations") ) include.default = "/etc/collectd/conf.d/*.conf" -- general.plugindir (PluginDir) plugindir = s:option( Value, "PluginDir", translate("Directory for collectd plugins") ) plugindir.default = "/usr/lib/collectd/" -- general.pidfile (PIDFile) pidfile = s:option( Value, "PIDFile", translate("Used PID file") ) pidfile.default = "/var/run/collectd.pid" -- general.typesdb (TypesDB) typesdb = s:option( Value, "TypesDB", translate("Datasets definition file") ) typesdb.default = "/etc/collectd/types.db" -- general.interval (Interval) interval = s:option( Value, "Interval", translate("Data collection interval"), translate("Seconds") ) interval.default = 60 interval.isnumber = true -- general.readthreads (ReadThreads) readthreads = s:option( Value, "ReadThreads", translate("Number of threads for data collection") ) readthreads.default = 5 readthreads.isnumber = true -- general.fqdnlookup (FQDNLookup) fqdnlookup = s:option( Flag, "FQDNLookup", translate("Try to lookup fully qualified hostname") ) fqdnlookup.enabled = "true" fqdnlookup.disabled = "false" fqdnlookup.default = "false" fqdnlookup.optional = true fqdnlookup:depends( "Hostname", "" ) return m
gpl-2.0
erfan1292/sezar3
bot/utils.lua
36
16426
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")() 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 if msg.to.type == 'channel' then return 'channel#id'..msg.to.id 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 -- Workarrond to format the message as previously was received function backward_msg_format (msg) for k,name in ipairs({'from', 'to'}) do local longid = msg[name].id msg[name].id = msg[name].peer_id msg[name].peer_id = longid msg[name].type = msg[name].peer_type end if msg.action and (msg.action.user or msg.action.link_issuer) then local user = msg.action.user or msg.action.link_issuer local longid = user.id user.id = user.peer_id user.peer_id = longid user.type = user.peer_type end return msg end function is_admin(user_id) for v,user in pairs(_config.admin_users) do print(user[1]) if user[1] == user_id then return true end end return false end function is_id(name_id) local var = tonumber(name_id) if var then return true else return false end end function lang_text(chat_id, keyword) local hash = 'langset:'..chat_id local lang = redis:get(hash) if not lang then redis:set(hash,'en') lang = redis:get(hash) end local hashtext = 'lang:'..lang..':'..keyword if redis:get(hashtext) then return redis:get(hashtext) else return 'Please, install your selected "'..lang..'" language by #install [archive_name(english_lang, spanish_lang...)]. First, active your language package like a normal plugin by it\'s name. For example, #plugins enable english_lang. Or set another one by typing #lang [language(en, es...)].' end end function set_text(lang, keyword, text) local hash = 'lang:'..lang..':'..keyword redis:set(hash, text) end function is_mod(chat_id, user_id) local hash = 'mod:'..chat_id..':'..user_id if redis:get(hash) then return true else return false end end function send_report(msg) local text = '👤 '..lang_text(msg.to.id, 'reportUser')..': '..msg.from.username..' ('..msg.from.id..')\n‼ '..lang_text(msg.to.id, 'reportReason')..': Link\n💬 '..lang_text(msg.to.id, 'reportGroup')..': "'..msg.to.title..'" ('..msg.to.id..')\n✉ '..lang_text(msg.to.id, 'reportMessage')..': '..msg.text for v,user in pairs(_config.sudo_users) do send_msg('user#id'..user, text, ok_cb, true) end end function is_gbanned_table(user_id) for v,user in pairs(_gbans.gbans_users) do if tonumber(user) == tonumber(user_id) then return true end end return false end function gban_id(user_id) local hash = 'gban:'..user_id redis:set(hash, true) if not is_gbanned_table(user_id) then table.insert(_gbans.gbans_users, tonumber(user_id)) print(user_id..' added to _gbans table') save_gbans() end end function new_is_sudo(user_id) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end
gpl-2.0
DmitryUlyanov/texture_nets
train.lua
1
7798
require 'torch' require 'nn' require 'image' require 'optim' require 'cudnn' require 'src/utils' require 'src/descriptor_net' require 'src/preprocess_criterion' local DataLoader = require 'dataloader' use_display, display = pcall(require, 'display') if not use_display then print('torch.display not found. unable to plot') end function nn.MultiCriterion:replace(f) for i=1,#self.criterions do self.criterions[i] = self.criterions[i]:replace(f) end return self end function printCriterion(criterion) if (type(criterion) == 'nn.MultiCriterion') then for i=1,#self.criterions do printCriterion(self.criterions[i]) end elseif (type(criterion) == 'nn.PreprocessCriterion') then print(criterion.preprocessing) print(criterion.criterion) else print(criterion) end end ---------------------------------------------------------- -- Parameters ---------------------------------------------------------- local cmd = torch.CmdLine() cmd:option('-content_layers', 'relu4_2', 'Layer to attach content loss.') cmd:option('-style_layers', 'relu1_1,relu2_1,relu3_1,relu4_1', 'Layer to attach style loss.') cmd:option('-learning_rate', 1e-3) cmd:option('-num_iterations', 50000, 'Number of steps to perform.') cmd:option('-save_every', 1000, 'Save model every N iterations.') cmd:option('-batch_size', 1) cmd:option('-image_size', 256, 'Training images size') cmd:option('-content_weight', 1) cmd:option('-style_weight', 1) cmd:option('-tv_weight', 0, 'Total variation weight.') cmd:option('-style_image', '', 'Path to style image') cmd:option('-style_size', 256, 'Resize style image to this size, no resize if 0.') cmd:option('-mode', 'style', 'style|texture') cmd:option('-checkpoints_path', 'data/checkpoints/', 'Directory to store intermediate results.') cmd:option('-model', 'pyramid', 'Path to generator model description file.') cmd:option('-vgg_no_pad', 'false') cmd:option('-normalization', 'instance', 'batch|instance') cmd:option('-proto_file', 'data/pretrained/VGG_ILSVRC_19_layers_deploy.prototxt', 'Pretrained') cmd:option('-model_file', 'data/pretrained/VGG_ILSVRC_19_layers.caffemodel') cmd:option('-backend', 'cudnn', 'nn|cudnn') -- Dataloader cmd:option('-dataset', 'style') cmd:option('-data', '', 'Path to dataset. Structure like in fb.resnet.torch repo.') cmd:option('-manualSeed', 0) cmd:option('-nThreads', 4, 'Data loading threads.') cmd:option('-cpu', false, 'use this flag to run on CPU') cmd:option('-gpu', 0, 'specify which GPU to use') cmd:option('-display_port', 8000, 'specify port to show graphs') cmd:option('-pyramid_loss', 1, 'number of pyramidal downscales in the loss function') cmd:option('-pyramid_decay', 0.9, 'weight decay of pyramidal downscales in the loss function') params = cmd:parse(arg) if params.cpu then dtype = 'torch.FloatTensor' params.backend = 'nn' backend = nn else dtype = 'torch.CudaTensor' require 'cutorch' require 'cunn' cutorch.setDevice(params.gpu) torch.CudaTensor.add_dummy = torch.FloatTensor.add_dummy if params.backend == 'cudnn' then cudnn.fastest = true cudnn.benchmark = true backend = cudnn else backend = nn end end assert(params.mode == 'style', 'Only stylization is implemented in master branch. You can find texture generation in texture_nets_v1 branch.') if use_display then display.configure({port=params.display_port}) end params.normalize_gradients = params.normalize_gradients ~= 'false' params.vgg_no_pad = params.vgg_no_pad ~= 'false' params.circular_padding = params.circular_padding ~= 'false' -- For compatibility with Justin Johnsons code params.texture_weight = params.style_weight params.texture_layers = params.style_layers params.texture = params.style_image if params.normalization == 'instance' then require 'InstanceNormalization' normalization = nn.InstanceNormalization elseif params.normalization == 'batch' then normalization = nn.SpatialBatchNormalization end if params.mode == 'texture' then params.content_layers = '' pad = nn.SpatialCircularPadding -- Use circular padding conv = convc else pad = nn.SpatialReplicationPadding end trainLoader, valLoader = DataLoader.create(params) -- load network local cnn = loadcaffe.load(params.proto_file, params.model_file, 'nn') cnn = cudnn.convert(cnn, nn):float() -- load texture local texture_image = image.load(params.texture, 3) if params.style_size > 0 then texture_image = image.scale(texture_image, params.style_size, 'bicubic') end texture_image = texture_image:float() local texture_image = preprocess(texture_image) -- Define model local net = require('models/' .. params.model):type(dtype) local criterion = nil if params.pyramid_loss > 1 then criterion = nn.MultiCriterion() local w = 1.0 local s = 1.0 criterion:add(nn.ArtisticCriterion(params, cnn:clone(), texture_image:clone()), w) for i = 2,params.pyramid_loss do w = w * params.pyramid_decay s = s * 2 local local_texture_image = image.scale(texture_image, texture_image:size(3)/s, texture_image:size(2)/s, 'bicubic'):float() criterion:add(nn.PreprocessCriterion(nn.ArtisticCriterion(params, cnn:clone(), local_texture_image:clone()), nn.SpatialAveragePooling(s, s, s, s)), w) end else criterion = nn.ArtisticCriterion(params, cnn, texture_image) end if not params.cpu then criterion = cudnn.convert(criterion, cudnn):cuda() printCriterion(criterion) --criterion:cuda():type(dtype) end ---------------------------------------------------------- -- feval ---------------------------------------------------------- local iteration = 0 local parameters, gradParameters = net:getParameters() local loss_history = {} function feval(x) iteration = iteration + 1 if x ~= parameters then parameters:copy(x) end gradParameters:zero() local loss = 0 -- Get batch local images = trainLoader:get() target_for_display = images.target local images_target = preprocess_many(images.target):type(dtype) local images_input = images.input:type(dtype) -- Forward local out = net:forward(images_input) loss = loss + criterion:forward(out, images_target) -- Backward local grad = criterion:backward(out, images_target) net:backward(images_input, grad) loss = loss/params.batch_size table.insert(loss_history, {iteration,loss}) print('#it: ', iteration, 'loss: ', loss) return loss, gradParameters end ---------------------------------------------------------- -- Optimize ---------------------------------------------------------- print(' Optimize ') style_weight_cur = params.style_weight content_weight_cur = params.content_weight local optim_method = optim.adam local state = { learningRate = params.learning_rate, } for it = 1, params.num_iterations do -- Optimization step optim_method(feval, parameters, state) -- Visualize if it%50 == 0 then collectgarbage() local output = net.output:double() local imgs = {} for i = 1, output:size(1) do local img = deprocess(output[i]) table.insert(imgs, torch.clamp(img,0,1)) end if use_display then display.image(target_for_display, {win=1, width=512,title = 'Target'}) display.image(imgs, {win=0, width=512}) display.plot(loss_history, {win=2, labels={'iteration', 'Loss'}}) end end if it%2000 == 0 then state.learningRate = state.learningRate*0.8 end -- Dump net if it%params.save_every == 0 or it == params.num_iterations then net:clearState() local net_to_save = deepCopy(net):float():clearState() if params.backend == 'cudnn' then net_to_save = cudnn.convert(net_to_save, nn) end torch.save(paths.concat(params.checkpoints_path, 'model_' .. it .. '.t7'), net_to_save) end end
apache-2.0
sundream/gamesrv
script/mail/mailmgr.lua
1
1664
mailmgr = mailmgr or {} function mailmgr.init() mailmgr.mailboxs = {} end function mailmgr.onlogin(player) local pid = player.pid mailmgr.getmailbox(pid) -- preload mailbox end function mailmgr.onlogoff(player) local pid = player.pid mailmgr.unloadmailbox(pid) end function mailmgr.loadmailbox(pid) require "script.mail.mailbox" local mailbox = cmailbox.new(pid) mailbox:loadfromdatabase() mailmgr.mailboxs[pid] = mailbox mailbox.savename = string.format("%s.%s",mailbox.flag,mailbox.pid) autosave(mailbox) return mailbox end function mailmgr.unloadmailbox(pid) local mailbox = mailmgr.mailboxs[pid] if mailbox then closesave(mailbox) mailbox:savetodatabase() mailmgr.mailboxs[pid] = nil end end function mailmgr.getmailbox(pid) if not mailmgr.mailboxs[pid] then return mailmgr.loadmailbox(pid) end return mailmgr.mailboxs[pid] end -- 支持跨服邮件 function mailmgr.sendmail(pid,amail) local self_srvname = cserver.getsrvname() local srvname = route.getsrvname(pid) if not srvname then -- non-exist pid return false end if srvname ~= self_srvname then cluster.call(srvname,"modmethod","mail.mailmgr",".sendmail",pid,amail) return true end amail = deepcopy(amail) -- 防止多个玩家修改同一份邮件 amail.sendtime = amail.sendtime or os.time() local mailbox = mailmgr.getmailbox(pid) amail.mailid = amail.mailid or mailbox:genid() local mail = cmail.new(amail) mail = mailbox:addmail(mail) if mail then net.mail.syncmail(pid,mail:pack()) end return mail.mailid,mail end function mailmgr.sendmails(pids,amail) for i,pid in ipairs(pids) do mailmgr.sendmail(pid,amail) end end return mailmgr
gpl-2.0
ctozlm/Dato-Core
src/unity/python/graphlab/lua/pl/utils.lua
14
14912
--- Generally useful routines. -- See @{01-introduction.md.Generally_useful_functions|the Guide}. -- @module pl.utils local format,gsub,byte = string.format,string.gsub,string.byte local compat = require 'pl.compat' local clock = os.clock local stdout = io.stdout local append = table.insert local unpack = rawget(_G,'unpack') or rawget(table,'unpack') local collisions = {} local utils = { _VERSION = "1.2.1", lua51 = compat.lua51, setfenv = compat.setfenv, getfenv = compat.getfenv, load = compat.load, execute = compat.execute, dir_separator = _G.package.config:sub(1,1), unpack = unpack } --- end this program gracefully. -- @param code The exit code or a message to be printed -- @param ... extra arguments for message's format' -- @see utils.fprintf function utils.quit(code,...) if type(code) == 'string' then utils.fprintf(io.stderr,code,...) code = -1 else utils.fprintf(io.stderr,...) end io.stderr:write('\n') os.exit(code) end --- print an arbitrary number of arguments using a format. -- @param fmt The format (see string.format) -- @param ... Extra arguments for format function utils.printf(fmt,...) utils.assert_string(1,fmt) utils.fprintf(stdout,fmt,...) end --- write an arbitrary number of arguments to a file using a format. -- @param f File handle to write to. -- @param fmt The format (see string.format). -- @param ... Extra arguments for format function utils.fprintf(f,fmt,...) utils.assert_string(2,fmt) f:write(format(fmt,...)) end local function import_symbol(T,k,v,libname) local key = rawget(T,k) -- warn about collisions! if key and k ~= '_M' and k ~= '_NAME' and k ~= '_PACKAGE' and k ~= '_VERSION' then utils.printf("warning: '%s.%s' overrides existing symbol\n",libname,k) end rawset(T,k,v) end local function lookup_lib(T,t) for k,v in pairs(T) do if v == t then return k end end return '?' end local already_imported = {} --- take a table and 'inject' it into the local namespace. -- @param t The Table -- @param T An optional destination table (defaults to callers environment) function utils.import(t,T) T = T or _G t = t or utils if type(t) == 'string' then t = require (t) end local libname = lookup_lib(T,t) if already_imported[t] then return end already_imported[t] = libname for k,v in pairs(t) do import_symbol(T,k,v,libname) end end utils.patterns = { FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*', INTEGER = '[+%-%d]%d*', IDEN = '[%a_][%w_]*', FILE = '[%a%.\\][:%][%w%._%-\\]*' } --- escape any 'magic' characters in a string -- @param s The input string function utils.escape(s) utils.assert_string(1,s) return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1')) end --- return either of two values, depending on a condition. -- @param cond A condition -- @param value1 Value returned if cond is true -- @param value2 Value returned if cond is false (can be optional) function utils.choose(cond,value1,value2) if cond then return value1 else return value2 end end local raise --- return the contents of a file as a string -- @param filename The file path -- @param is_bin open in binary mode -- @return file contents function utils.readfile(filename,is_bin) local mode = is_bin and 'b' or '' utils.assert_string(1,filename) local f,err = io.open(filename,'r'..mode) if not f then return utils.raise (err) end local res,err = f:read('*a') f:close() if not res then return raise (err) end return res end --- write a string to a file -- @param filename The file path -- @param str The string -- @return true or nil -- @return error message -- @raise error if filename or str aren't strings function utils.writefile(filename,str) utils.assert_string(1,filename) utils.assert_string(2,str) local f,err = io.open(filename,'w') if not f then return raise(err) end f:write(str) f:close() return true end --- return the contents of a file as a list of lines -- @param filename The file path -- @return file contents as a table -- @raise errror if filename is not a string function utils.readlines(filename) utils.assert_string(1,filename) local f,err = io.open(filename,'r') if not f then return raise(err) end local res = {} for line in f:lines() do append(res,line) end f:close() return res end --- split a string into a list of strings separated by a delimiter. -- @param s The input string -- @param re A Lua string pattern; defaults to '%s+' -- @param plain don't use Lua patterns -- @param n optional maximum number of splits -- @return a list-like table -- @raise error if s is not a string function utils.split(s,re,plain,n) utils.assert_string(1,s) local find,sub,append = string.find, string.sub, table.insert local i1,ls = 1,{} if not re then re = '%s+' end if re == '' then return {s} end while true do local i2,i3 = find(s,re,i1,plain) if not i2 then local last = sub(s,i1) if last ~= '' then append(ls,last) end if #ls == 1 and ls[1] == '' then return {} else return ls end end append(ls,sub(s,i1,i2-1)) if n and #ls == n then ls[#ls] = sub(s,i1) return ls end i1 = i3+1 end end --- split a string into a number of values. -- @param s the string -- @param re the delimiter, default space -- @return n values -- @usage first,next = splitv('jane:doe',':') -- @see split function utils.splitv (s,re) return unpack(utils.split(s,re)) end --- convert an array of values to strings. -- @param t a list-like table -- @param temp buffer to use, otherwise allocate -- @param tostr custom tostring function, called with (value,index). -- Otherwise use `tostring` -- @return the converted buffer function utils.array_tostring (t,temp,tostr) temp, tostr = temp or {}, tostr or tostring for i = 1,#t do temp[i] = tostr(t[i],i) end return temp end --- execute a shell command and return the output. -- This function redirects the output to tempfiles and returns the content of those files. -- @param cmd a shell command -- @param bin boolean, if true, read output as binary file -- @return true if successful -- @return actual return code -- @return stdout output (string) -- @return errout output (string) function utils.executeex(cmd, bin) local mode local outfile = os.tmpname() local errfile = os.tmpname() if utils.dir_separator == '\\' then outfile = os.getenv('TEMP')..outfile errfile = os.getenv('TEMP')..errfile end cmd = cmd .. [[ >"]]..outfile..[[" 2>"]]..errfile..[["]] local success, retcode = utils.execute(cmd) local outcontent = utils.readfile(outfile, bin) local errcontent = utils.readfile(errfile, bin) os.remove(outfile) os.remove(errfile) return success, retcode, (outcontent or ""), (errcontent or "") end --- 'memoize' a function (cache returned value for next call). -- This is useful if you have a function which is relatively expensive, -- but you don't know in advance what values will be required, so -- building a table upfront is wasteful/impossible. -- @param func a function of at least one argument -- @return a function with at least one argument, which is used as the key. function utils.memoize(func) return setmetatable({}, { __index = function(self, k, ...) local v = func(k,...) self[k] = v return v end, __call = function(self, k) return self[k] end }) end utils.stdmt = { List = {_name='List'}, Map = {_name='Map'}, Set = {_name='Set'}, MultiMap = {_name='MultiMap'} } local _function_factories = {} --- associate a function factory with a type. -- A function factory takes an object of the given type and -- returns a function for evaluating it -- @tab mt metatable -- @func fun a callable that returns a function function utils.add_function_factory (mt,fun) _function_factories[mt] = fun end local function _string_lambda(f) local raise = utils.raise if f:find '^|' or f:find '_' then local args,body = f:match '|([^|]*)|(.+)' if f:find '_' then args = '_' body = f else if not args then return raise 'bad string lambda' end end local fstr = 'return function('..args..') return '..body..' end' local fn,err = utils.load(fstr) if not fn then return raise(err) end fn = fn() return fn else return raise 'not a string lambda' end end --- an anonymous function as a string. This string is either of the form -- '|args| expression' or is a function of one argument, '_' -- @param lf function as a string -- @return a function -- @usage string_lambda '|x|x+1' (2) == 3 -- @usage string_lambda '_+1 (2) == 3 -- @function utils.string_lambda utils.string_lambda = utils.memoize(_string_lambda) local ops --- process a function argument. -- This is used throughout Penlight and defines what is meant by a function: -- Something that is callable, or an operator string as defined by <code>pl.operator</code>, -- such as '>' or '#'. If a function factory has been registered for the type, it will -- be called to get the function. -- @param idx argument index -- @param f a function, operator string, or callable object -- @param msg optional error message -- @return a callable -- @raise if idx is not a number or if f is not callable function utils.function_arg (idx,f,msg) utils.assert_arg(1,idx,'number') local tp = type(f) if tp == 'function' then return f end -- no worries! -- ok, a string can correspond to an operator (like '==') if tp == 'string' then if not ops then ops = require 'pl.operator'.optable end local fn = ops[f] if fn then return fn end local fn, err = utils.string_lambda(f) if not fn then error(err..': '..f) end return fn elseif tp == 'table' or tp == 'userdata' then local mt = getmetatable(f) if not mt then error('not a callable object',2) end local ff = _function_factories[mt] if not ff then if not mt.__call then error('not a callable object',2) end return f else return ff(f) -- we have a function factory for this type! end end if not msg then msg = " must be callable" end if idx > 0 then error("argument "..idx..": "..msg,2) else error(msg,2) end end --- bind the first argument of the function to a value. -- @param fn a function of at least two values (may be an operator string) -- @param p a value -- @return a function such that f(x) is fn(p,x) -- @raise same as @{function_arg} -- @see func.bind1 function utils.bind1 (fn,p) fn = utils.function_arg(1,fn) return function(...) return fn(p,...) end end --- bind the second argument of the function to a value. -- @param fn a function of at least two values (may be an operator string) -- @param p a value -- @return a function such that f(x) is fn(x,p) -- @raise same as @{function_arg} function utils.bind2 (fn,p) fn = utils.function_arg(1,fn) return function(x,...) return fn(x,p,...) end end --- assert that the given argument is in fact of the correct type. -- @param n argument index -- @param val the value -- @param tp the type -- @param verify an optional verfication function -- @param msg an optional custom message -- @param lev optional stack position for trace, default 2 -- @raise if the argument n is not the correct type -- @usage assert_arg(1,t,'table') -- @usage assert_arg(n,val,'string',path.isdir,'not a directory') function utils.assert_arg (n,val,tp,verify,msg,lev) if type(val) ~= tp then error(("argument %d expected a '%s', got a '%s'"):format(n,tp,type(val)),lev or 2) end if verify and not verify(val) then error(("argument %d: '%s' %s"):format(n,val,msg),lev or 2) end end --- assert the common case that the argument is a string. -- @param n argument index -- @param val a value that must be a string -- @raise val must be a string function utils.assert_string (n,val) utils.assert_arg(n,val,'string',nil,nil,3) end local err_mode = 'default' --- control the error strategy used by Penlight. -- Controls how <code>utils.raise</code> works; the default is for it -- to return nil and the error string, but if the mode is 'error' then -- it will throw an error. If mode is 'quit' it will immediately terminate -- the program. -- @param mode - either 'default', 'quit' or 'error' -- @see utils.raise function utils.on_error (mode) if ({['default'] = 1, ['quit'] = 2, ['error'] = 3})[mode] then err_mode = mode else -- fail loudly if err_mode == 'default' then err_mode = 'error' end utils.raise("Bad argument expected string; 'default', 'quit', or 'error'. Got '"..tostring(mode).."'") end end --- used by Penlight functions to return errors. Its global behaviour is controlled -- by <code>utils.on_error</code> -- @param err the error string. -- @see utils.on_error function utils.raise (err) if err_mode == 'default' then return nil,err elseif err_mode == 'quit' then utils.quit(err) else error(err,2) end end --- is the object of the specified type?. -- If the type is a string, then use type, otherwise compare with metatable -- @param obj An object to check -- @param tp String of what type it should be function utils.is_type (obj,tp) if type(tp) == 'string' then return type(obj) == tp end local mt = getmetatable(obj) return tp == mt end raise = utils.raise --- load a code string or bytecode chunk. -- @param code Lua code as a string or bytecode -- @param name for source errors -- @param mode kind of chunk, 't' for text, 'b' for bytecode, 'bt' for all (default) -- @param env the environment for the new chunk (default nil) -- @return compiled chunk -- @return error message (chunk is nil) -- @function utils.load --------------- -- Get environment of a function. -- With Lua 5.2, may return nil for a function with no global references! -- Based on code by [Sergey Rozhenko](http://lua-users.org/lists/lua-l/2010-06/msg00313.html) -- @param f a function or a call stack reference -- @function utils.setfenv --------------- -- Set environment of a function -- @param f a function or a call stack reference -- @param env a table that becomes the new environment of `f` -- @function utils.setfenv --- execute a shell command. -- This is a compatibility function that returns the same for Lua 5.1 and Lua 5.2 -- @param cmd a shell command -- @return true if successful -- @return actual return code -- @function utils.execute return utils
agpl-3.0
sami2448/set
plugins/wikipn.lua
14
4516
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "جست و جویی برای گزینه پیدا نشد "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "ببخشید مشکلی رخ داده" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "هیچ جوابی پیدا نشد" return titles else return "متاسفم مشکلی رخ داده است" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "بگرد" then search = true term = matches[2] lang = nil elseif matches[2] == "بگرد" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^(در دانشنامه)(%w+) (بگرد) (.+)$", "^(در دانشنامه) (بگرد) ?(.*)$", "^(در دانشنامه)(%w+) (.+)$", "^(در دانشنامه) ?(.*)$" }, run = run }
gpl-2.0
CodingKitsune/Riritools
riritools/lua/base64.lua
1
1436
-- Lua 5.1+ base64 X v1.0 forked from base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de> -- modified by Coding Kitsune for Riritools -- licensed under the terms of the LGPL2 local table_utils = require("riritools.lua.table_utils") -- character table string local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' local function encode(data) return ((data:gsub('.', function(x) local r,s='',x:byte() for i=8,1,-1 do r=r..(s%2^i-s%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return b:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- decoding local function decode(data) data = string.gsub(data, '[^'..b..'=]', '') return (data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(b:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string.char(c) end)) end local base64 = table_utils.make_read_only_table { encode=encode, decode=decode, } return base64
mit
pprindeville/packages
lang/luaexpat/files/compat-5.1r5/compat-5.1.lua
251
6391
-- -- Compat-5.1 -- Copyright Kepler Project 2004-2006 (http://www.keplerproject.org/compat) -- According to Lua 5.1 -- $Id: compat-5.1.lua,v 1.22 2006/02/20 21:12:47 carregal Exp $ -- _COMPAT51 = "Compat-5.1 R5" local LUA_DIRSEP = '/' local LUA_OFSEP = '_' local OLD_LUA_OFSEP = '' local POF = 'luaopen_' local LUA_PATH_MARK = '?' local LUA_IGMARK = ':' local assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type = assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type local find, format, gfind, gsub, sub = string.find, string.format, string.gfind, string.gsub, string.sub -- -- avoid overwriting the package table if it's already there -- package = package or {} local _PACKAGE = package package.path = LUA_PATH or os.getenv("LUA_PATH") or ("./?.lua;" .. "/usr/local/share/lua/5.0/?.lua;" .. "/usr/local/share/lua/5.0/?/?.lua;" .. "/usr/local/share/lua/5.0/?/init.lua" ) package.cpath = LUA_CPATH or os.getenv("LUA_CPATH") or "./?.so;" .. "./l?.so;" .. "/usr/local/lib/lua/5.0/?.so;" .. "/usr/local/lib/lua/5.0/l?.so" -- -- make sure require works with standard libraries -- package.loaded = package.loaded or {} package.loaded.debug = debug package.loaded.string = string package.loaded.math = math package.loaded.io = io package.loaded.os = os package.loaded.table = table package.loaded.base = _G package.loaded.coroutine = coroutine local _LOADED = package.loaded -- -- avoid overwriting the package.preload table if it's already there -- package.preload = package.preload or {} local _PRELOAD = package.preload -- -- looks for a file `name' in given path -- local function findfile (name, pname) name = gsub (name, "%.", LUA_DIRSEP) local path = _PACKAGE[pname] assert (type(path) == "string", format ("package.%s must be a string", pname)) for c in gfind (path, "[^;]+") do c = gsub (c, "%"..LUA_PATH_MARK, name) local f = io.open (c) if f then f:close () return c end end return nil -- not found end -- -- check whether library is already loaded -- local function loader_preload (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) assert (type(_PRELOAD) == "table", "`package.preload' must be a table") return _PRELOAD[name] end -- -- Lua library loader -- local function loader_Lua (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local filename = findfile (name, "path") if not filename then return false end local f, err = loadfile (filename) if not f then error (format ("error loading module `%s' (%s)", name, err)) end return f end local function mkfuncname (name) name = gsub (name, "^.*%"..LUA_IGMARK, "") name = gsub (name, "%.", LUA_OFSEP) return POF..name end local function old_mkfuncname (name) --name = gsub (name, "^.*%"..LUA_IGMARK, "") name = gsub (name, "%.", OLD_LUA_OFSEP) return POF..name end -- -- C library loader -- local function loader_C (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local filename = findfile (name, "cpath") if not filename then return false end local funcname = mkfuncname (name) local f, err = loadlib (filename, funcname) if not f then funcname = old_mkfuncname (name) f, err = loadlib (filename, funcname) if not f then error (format ("error loading module `%s' (%s)", name, err)) end end return f end local function loader_Croot (name) local p = gsub (name, "^([^.]*).-$", "%1") if p == "" then return end local filename = findfile (p, "cpath") if not filename then return end local funcname = mkfuncname (name) local f, err, where = loadlib (filename, funcname) if f then return f elseif where ~= "init" then error (format ("error loading module `%s' (%s)", name, err)) end end -- create `loaders' table package.loaders = package.loaders or { loader_preload, loader_Lua, loader_C, loader_Croot, } local _LOADERS = package.loaders -- -- iterate over available loaders -- local function load (name, loaders) -- iterate over available loaders assert (type (loaders) == "table", "`package.loaders' must be a table") for i, loader in ipairs (loaders) do local f = loader (name) if f then return f end end error (format ("module `%s' not found", name)) end -- sentinel local sentinel = function () end -- -- new require -- function _G.require (modname) assert (type(modname) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local p = _LOADED[modname] if p then -- is it there? if p == sentinel then error (format ("loop or previous error loading module '%s'", modname)) end return p -- package is already loaded end local init = load (modname, _LOADERS) _LOADED[modname] = sentinel local actual_arg = _G.arg _G.arg = { modname } local res = init (modname) if res then _LOADED[modname] = res end _G.arg = actual_arg if _LOADED[modname] == sentinel then _LOADED[modname] = true end return _LOADED[modname] end -- findtable local function findtable (t, f) assert (type(f)=="string", "not a valid field name ("..tostring(f)..")") local ff = f.."." local ok, e, w = find (ff, '(.-)%.', 1) while ok do local nt = rawget (t, w) if not nt then nt = {} t[w] = nt elseif type(t) ~= "table" then return sub (f, e+1) end t = nt ok, e, w = find (ff, '(.-)%.', e+1) end return t end -- -- new package.seeall function -- function _PACKAGE.seeall (module) local t = type(module) assert (t == "table", "bad argument #1 to package.seeall (table expected, got "..t..")") local meta = getmetatable (module) if not meta then meta = {} setmetatable (module, meta) end meta.__index = _G end -- -- new module function -- function _G.module (modname, ...) local ns = _LOADED[modname] if type(ns) ~= "table" then ns = findtable (_G, modname) if not ns then error (string.format ("name conflict for module '%s'", modname)) end _LOADED[modname] = ns end if not ns._NAME then ns._NAME = modname ns._M = ns ns._PACKAGE = gsub (modname, "[^.]*$", "") end setfenv (2, ns) for i, f in ipairs (arg) do f (ns) end end
gpl-2.0
Maxsteam/MMMNNN
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
APCVSRepo/sdl_core
tools/intergen/third_party/pugixml/scripts/premake4.lua
128
2376
-- Reset RNG seed to get consistent results across runs (i.e. XCode) math.randomseed(12345) local static = _ARGS[1] == 'static' local action = premake.action.current() if string.startswith(_ACTION, "vs") then if action then -- Disable solution generation function action.onsolution(sln) sln.vstudio_configs = premake.vstudio_buildconfigs(sln) end -- Rename output file function action.onproject(prj) local name = "%%_" .. _ACTION .. (static and "_static" or "") if static then for k, v in pairs(prj.project.__configs) do v.objectsdir = v.objectsdir .. "Static" end end if _ACTION == "vs2010" then premake.generate(prj, name .. ".vcxproj", premake.vs2010_vcxproj) else premake.generate(prj, name .. ".vcproj", premake.vs200x_vcproj) end end end elseif _ACTION == "codeblocks" then action.onsolution = nil function action.onproject(prj) premake.generate(prj, "%%_" .. _ACTION .. ".cbp", premake.codeblocks_cbp) end elseif _ACTION == "codelite" then action.onsolution = nil function action.onproject(prj) premake.generate(prj, "%%_" .. _ACTION .. ".project", premake.codelite_project) end end solution "pugixml" objdir(_ACTION) targetdir(_ACTION) if string.startswith(_ACTION, "vs") then if _ACTION ~= "vs2002" and _ACTION ~= "vs2003" then platforms { "x32", "x64" } configuration "x32" targetdir(_ACTION .. "/x32") configuration "x64" targetdir(_ACTION .. "/x64") end configurations { "Debug", "Release" } if static then configuration "Debug" targetsuffix "sd" configuration "Release" targetsuffix "s" else configuration "Debug" targetsuffix "d" end else if _ACTION == "xcode3" then platforms "universal" end configurations { "Debug", "Release" } configuration "Debug" targetsuffix "d" end project "pugixml" kind "StaticLib" language "C++" files { "../src/pugixml.hpp", "../src/pugiconfig.hpp", "../src/pugixml.cpp" } flags { "NoPCH", "NoMinimalRebuild", "NoEditAndContinue", "Symbols" } uuid "89A1E353-E2DC-495C-B403-742BE206ACED" configuration "Debug" defines { "_DEBUG" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } if static then configuration "*" flags { "StaticRuntime" } end
bsd-3-clause
dloeng/guetzli
premake5.lua
3
1475
workspace "guetzli" configurations { "Release", "Debug" } language "C++" flags { "C++11" } includedirs { ".", "third_party/butteraugli" } filter "action:vs*" platforms { "x86_64", "x86" } filter "platforms:x86" architecture "x86" filter "platforms:x86_64" architecture "x86_64" -- workaround for #41 filter "action:gmake" symbols "On" filter "configurations:Debug" symbols "On" filter "configurations:Release" optimize "Full" filter {} project "guetzli_static" kind "StaticLib" files { "guetzli/*.cc", "guetzli/*.h", "third_party/butteraugli/butteraugli/butteraugli.cc", "third_party/butteraugli/butteraugli/butteraugli.h" } removefiles "guetzli/guetzli.cc" filter "action:gmake" linkoptions { "`pkg-config --static --libs libpng || libpng-config --static --ldflags`" } buildoptions { "`pkg-config --static --cflags libpng || libpng-config --static --cflags`" } project "guetzli" kind "ConsoleApp" filter "action:gmake" linkoptions { "`pkg-config --libs libpng || libpng-config --ldflags`" } buildoptions { "`pkg-config --cflags libpng || libpng-config --cflags`" } filter "action:vs*" links { "shlwapi" } filter {} files { "guetzli/*.cc", "guetzli/*.h", "third_party/butteraugli/butteraugli/butteraugli.cc", "third_party/butteraugli/butteraugli/butteraugli.h" }
apache-2.0
viticm/pf_win
applications/bin/public/data/script/functions/timer.lua
2
2072
--[[ - PAP Engine ( https://github.com/viticm/plainframework1 ) - $Id timer.lua - @link https://github.com/viticm/plainframework1 for the canonical source repository - @copyright Copyright (c) 2014- viticm( viticm@126.com/viticm.ti@gmail.com ) - @license - @user viticm<viticm@126.com/viticm.ti@gmail.com> - @date 2015/04/28 14:23 - @uses timer table - cn: 需要自己的监听方法来调用定时方法 --]] module("timer_t", package.seeall) local table_insert = table.insert -- 新建 function new() local timer = {} setmetatable(timer, {__index = timer_t}) timer:init() return timer end -- 初始化 function init(self) self.onesecond_eventlist_ = {} -- 一秒钟定时器事件列表 self.oneminute_eventlist_ = {} -- 一分钟定时器事件列表 self.fiveminute_eventlist_ = {} -- 五分钟定时器事件列表 end -- 注册一秒钟定时器事件 function register_onesecond_timer(self, func, param) if not func then return end local event = {func, param} table_insert(self.onesecond_eventlist_, event) end -- 注册一分钟定时器事件 function register_onminute_timer(self, func, param) if not func then return end local event = {func, param} table_insert(self.oneminute_eventlist_, event) end -- 注册五分钟定时器事件 function register_fiveminute_timer(self, func, param) if not func then return end local event = {func, param} table_insert(self.fiveminute_eventlist_, event) end -- 执行一秒钟定时器事件 function on_onesecond_timer(self) for _, event in ipairs(self.onesecond_eventlist_) do local func = event[1] local param = event[2] func(param) end end -- 执行一分钟定时器事件 function on_oneminute_timer(self) for _, event in ipairs(self.oneminute_eventlist_) do local func = event[1] local param = event[2] func(param) end end -- 执行五分钟定时器事件 function on_fiveminute_timer(self) for _, event in ipairs(self.fiveminute_eventlist_) do local func = event[1] local param = event[2] func(param) end end
mit
codemon66/Urho3D
bin/Data/LuaScripts/47_Typography.lua
8
6616
-- Text rendering example. -- Displays text at various sizes, with checkboxes to change the rendering parameters. require "LuaScripts/Utilities/Sample" -- Tag used to find all Text elements local TEXT_TAG = "Typography_text_tag" -- Top-level container for this sample's UI local uielement = nil function Start() -- Execute the common startup for samples SampleStart() -- Enable OS cursor input.mouseVisible = true -- Load XML file containing default UI style sheet local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") -- Set the loaded style as default style ui.root.defaultStyle = style -- Create a UIElement to hold all our content -- (Don't modify the root directly, as the base Sample class uses it) uielement = UIElement:new() uielement:SetAlignment(HA_CENTER, VA_CENTER) uielement:SetLayout(LM_VERTICAL, 10, IntRect(20, 40, 20, 40)) ui.root:AddChild(uielement) -- Add some sample text CreateText() -- Add a checkbox to toggle the background color. CreateCheckbox("White background", "HandleWhiteBackground") :SetChecked(false) -- Add a checkbox to toggle SRGB output conversion (if available). -- This will give more correct text output for FreeType fonts, as the FreeType rasterizer -- outputs linear coverage values rather than SRGB values. However, this feature isn't -- available on all platforms. CreateCheckbox("Graphics::SetSRGB", "HandleSRGB") :SetChecked(graphics:GetSRGB()) -- Add a checkbox for the global ForceAutoHint setting. This affects character spacing. CreateCheckbox("UI::SetForceAutoHint", "HandleForceAutoHint") :SetChecked(ui:GetForceAutoHint()) -- Add a drop-down menu to control the font hinting level. local levels = { "FONT_HINT_LEVEL_NONE", "FONT_HINT_LEVEL_LIGHT", "FONT_HINT_LEVEL_NORMAL" } CreateMenu("UI::SetFontHintLevel", levels, "HandleFontHintLevel") :SetSelection(ui:GetFontHintLevel()) -- Add a drop-down menu to control the subpixel threshold. local thresholds = { "0", "3", "6", "9", "12", "15", "18", "21" } CreateMenu("UI::SetFontSubpixelThreshold", thresholds, "HandleFontSubpixel") :SetSelection(ui:GetFontSubpixelThreshold() / 3) -- Add a drop-down menu to control oversampling. local limits = { "1", "2", "3", "4", "5", "6", "7", "8" } CreateMenu("UI::SetFontOversampling", limits, "HandleFontOversampling") :SetSelection(ui:GetFontOversampling() - 1) -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_FREE) end function CreateText() local container = UIElement:new() container:SetAlignment(HA_LEFT, VA_TOP) container:SetLayout(LM_VERTICAL) uielement:AddChild(container) local font = cache:GetResource("Font", "Fonts/BlueHighway.ttf") for size = 1, 18, 0.5 do local text = Text:new() text.text = "The quick brown fox jumps over the lazy dog (" .. size .. "pt)" text:SetFont(font, size) text:AddTag(TEXT_TAG) container:AddChild(text) end end function CreateCheckbox(label, handler) local container = UIElement:new() container:SetAlignment(HA_LEFT, VA_TOP) container:SetLayout(LM_HORIZONTAL, 8) uielement:AddChild(container) local box = CheckBox:new() container:AddChild(box) box:SetStyleAuto() local text = Text:new() container:AddChild(text) text.text = label text:SetStyleAuto() text:AddTag(TEXT_TAG) SubscribeToEvent(box, "Toggled", handler) return box end function CreateMenu(label, items, handler) local container = UIElement:new() container:SetAlignment(HA_LEFT, VA_TOP) container:SetLayout(LM_HORIZONTAL, 8) uielement:AddChild(container) local text = Text:new() container:AddChild(text) text.text = label text:SetStyleAuto() text:AddTag(TEXT_TAG) local list = DropDownList:new() container:AddChild(list) list:SetStyleAuto() for i, item in ipairs(items) do local t = Text:new() list:AddItem(t) t.text = item t:SetStyleAuto() t:SetMinWidth(t:GetRowWidth(0) + 10); t:AddTag(TEXT_TAG) end text:SetMaxWidth(text:GetRowWidth(0)) SubscribeToEvent(list, "ItemSelected", handler) return list end function HandleWhiteBackground(eventType, eventData) local box = eventData["Element"]:GetPtr("CheckBox") local checked = box:IsChecked() local fg = checked and Color.BLACK or Color.WHITE local bg = checked and Color.WHITE or Color.BLACK renderer.defaultZone.fogColor = bg local elements = uielement:GetChildrenWithTag(TEXT_TAG, true) for i, element in ipairs(elements) do element.color = fg end end function HandleForceAutoHint(eventType, eventData) local box = eventData["Element"]:GetPtr("CheckBox") local checked = box:IsChecked() ui:SetForceAutoHint(checked) end function HandleSRGB(eventType, eventData) local box = eventData["Element"]:GetPtr("CheckBox") local checked = box:IsChecked() if graphics:GetSRGBWriteSupport() then graphics:SetSRGB(checked) else log:Write(LOG_WARNING, "graphics:GetSRGBWriteSupport returned false") end end function HandleFontHintLevel(eventType, eventData) local list = eventData["Element"]:GetPtr("DropDownList") local i = list:GetSelection() ui:SetFontHintLevel(i) end function HandleFontSubpixel(eventType, eventData) local list = eventData["Element"]:GetPtr("DropDownList") local i = list:GetSelection() ui:SetFontSubpixelThreshold(i * 3) end function HandleFontOversampling(eventType, eventData) local list = eventData["Element"]:GetPtr("DropDownList") local i = list:GetSelection() ui:SetFontOversampling(i + 1) end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" .. " <attribute name=\"Is Visible\" value=\"false\" />" .. " </add>" .. "</patch>" end
mit
sBaildon/sInterface
embeds/rActionBar/blizzard.lua
1
1837
-- rActionBar: blizzard -- zork, 2016 ----------------------------- -- Config ----------------------------- local cfg = {} ----------------------------- -- Variables ----------------------------- local A, L = ... local hiddenFrame = CreateFrame("Frame") hiddenFrame:Hide() local scripts = { "OnShow", "OnHide", "OnEvent", "OnEnter", "OnLeave", "OnUpdate", "OnValueChanged", "OnClick", "OnMouseDown", "OnMouseUp", } local framesToHide = { MainMenuBar, OverrideActionBar, } local framesToDisable = { MainMenuBar, MicroButtonAndBagsBar, MainMenuBarArtFrame, StatusTrackingBarManager, ActionBarDownButton, ActionBarUpButton, MainMenuBarVehicleLeaveButton, OverrideActionBar, OverrideActionBarExpBar, OverrideActionBarHealthBar, OverrideActionBarPowerBar, OverrideActionBarPitchFrame, } ----------------------------- -- Functions ----------------------------- --DisableAllScripts local function DisableAllScripts(frame) for i, script in next, scripts do if frame:HasScript(script) then frame:SetScript(script,nil) end end end --L:HideMainMenuBar function L:HideMainMenuBar() --bring back the currency local function OnEvent(self,event) TokenFrame_LoadUI() TokenFrame_Update() BackpackTokenFrame_Update() end hiddenFrame:SetScript("OnEvent",OnEvent) hiddenFrame:RegisterEvent("CURRENCY_DISPLAY_UPDATE") for i, frame in next, framesToHide do frame:SetParent(hiddenFrame) end for i, frame in next, framesToDisable do frame:UnregisterAllEvents() DisableAllScripts(frame) end end --fix blizzard cooldown flash local function FixCooldownFlash(self) if not self then return end if self:GetEffectiveAlpha() > 0 then self:Show() else self:Hide() end end hooksecurefunc(getmetatable(ActionButton1Cooldown).__index, "SetCooldown", FixCooldownFlash)
mit
erfan1292/sezar3
plugins/welcome.lua
27
5188
------------------------------------------ -- DBTeam DBTeam DBTeam DBTeam DBTeam --- -- Welcome by @xxdamage --- -- multilanguage and fix by@Jarriz --- ------------------------------------------ function chat_new_user(msg) local name = msg.action.user.first_name:gsub('_', ' ') local id = msg.action.user.id if msg.action.user.username then name = name end local chat = msg.to.print_name:gsub('_', ' ') local receiver = get_receiver(msg) local message = redis:get('welcome:'..msg.to.id) if not message then return '😀 ' ..lang_text(msg.to.id, 'welcome1') ..name.. '! ' ..lang_text(msg.to.id, 'welcome2') ..chat..'!\n🆔 ' ..id end send_msg(receiver, message, ok_cb, false) end local function wlc_enabled(msg) local var = true local hash = 'wlcstatus:'..msg.to.id local cstatus = redis:get(hash) if cstatus == 'off' then var = false end return var end local function bye_enabled(msg) local var = true local hash = 'byestatus:'..msg.to.id local cstatus = redis:get(hash) if cstatus == 'off' then var = false end return var end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "chat_add_user" then if not wlc_enabled(msg) then return end return chat_new_user(msg) elseif matches[1] == "chat_add_user_link" then if not wlc_enabled(msg) then return end local name = msg.from.first_name:gsub('_', ' ') local chat = msg.to.print_name:gsub('_', ' ') local message if msg.from.username then name = name end message = redis:get('welcome:'..msg.to.id) if not message then return '😀' ..lang_text(msg.to.id, 'welcome1') ..name.. '!' ..lang_text(msg.to.id, 'welcome2') ..chat..'!\n🆔 ' ..id end send_msg(receiver, message, ok_cb, false) elseif matches[1] == "chat_del_user" then if not bye_enabled(msg) then return end local name = msg.action.user.first_name:gsub('_', ' ') if msg.action.user.username then name = name end local message = redis:get('bye:'..msg.to.id) if not message then return '😀 ' ..lang_text(msg.to.id, 'bye1') ..name.. '!' ..lang_text(msg.to.id, 'bye2') end send_msg(receiver, message, ok_cb, false) elseif matches[1] == 'setwelcome' then if not permissions(msg.from.id, msg.to.id, "welcome") then return '🚫 '..lang_text(msg.to.id, 'require_mod') end print(msg.to.id) local hash = 'welcome:'..msg.to.id redis:set(hash, matches[2]) return '✅ ' ..lang_text(msg.to.id, 'welnew') .. ': \n' ..matches[2] elseif matches[1] == 'getwelcome' then print(msg.to.id) local hash = 'welcome:'..msg.to.id local wel = redis:get(hash) if not wel then return 'ℹ️ ' ..lang_text(msg.to.id, 'weldefault') end return wel elseif matches[1] == 'setbye' then if not permissions(msg.from.id, msg.to.id, "welcome") then return ' 🚫'..lang_text(msg.to.id, 'require_mod') end print(msg.to.id) local hash = 'bye:'..msg.to.id redis:set(hash, matches[2]) return '✅ ' ..lang_text(msg.to.id, 'newbye') .. ':\n'..matches[2] elseif matches[1] == 'getbye' then if not permissions(msg.from.id, msg.to.id, "welcome") then return ' 🚫'..lang_text(msg.to.id, 'require_mod') end print(msg.to.id) local hash = 'bye:'..msg.to.id local wel = redis:get(hash) if not wel then return 'ℹ️ ' ..lang_text(msg.to.id, 'byedefault') end return wel elseif matches[1] == 'welcome on' then if not permissions(msg.from.id, msg.to.id, "welcome") then return ' 🚫'..lang_text(msg.to.id, 'require_mod') end local hash = 'wlcstatus:'..msg.to.id redis:set(hash, 'on') return 'ℹ️ '..lang_text(msg.to.id, 'welon') elseif matches[1] == 'welcome off' then if not permissions(msg.from.id, msg.to.id, "welcome") then return '🚫 '..lang_text(msg.to.id, 'require_mod') end local hash = 'wlcstatus:'..msg.to.id redis:set(hash, 'off') return 'ℹ️ '..lang_text(msg.to.id, 'weloff') elseif matches[1] == 'bye on' then if not permissions(msg.from.id, msg.to.id, "welcome") then return ' 🚫'..lang_text(msg.to.id, 'require_mod') end local hash = 'byestatus:'..msg.to.id redis:set(hash, 'on') return 'ℹ️ '..lang_text(msg.to.id, 'byeon') elseif matches[1] == 'bye off' then if not permissions(msg.from.id, msg.to.id, "welcome") then return ' 🚫'..lang_text(msg.to.id, 'require_mod') end local hash = 'byestatus:'..msg.to.id redis:set(hash, 'off') return 'ℹ️ '..lang_text(msg.to.id, 'byeoff') end end return { description = "Service plugin that sends a custom message when an user enters a chat.", usage = "", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_del_user)$", "^!!tgservice (chat_add_user_link)$", "^[!/#](setwelcome) (.*)", "^[!/#](getwelcome)", "^[!/#](setbye) (.*)", "^[!/#](getbye)", "^[!/#](welcome on)", "^[!/#](welcome off)", "^[!/#](bye on)", "^[!/#](bye off)" }, run = run }
gpl-2.0
EvPowerTeam/EV_OP
feeds/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/unixsock.lua
80
1455
--[[ Luci configuration model for statistics - collectd unixsock plugin configuration (c) 2008 Freifunk Leipzig / 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$ ]]-- m = Map("luci_statistics", translate("Unixsock Plugin Configuration"), translate( "The unixsock plugin creates a unix socket which can be used " .. "to read collected data from a running collectd instance." )) -- collectd_unixsock config section s = m:section( NamedSection, "collectd_unixsock", "luci_statistics" ) -- collectd_unixsock.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_unixsock.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile" ) socketfile.default = "/var/run/collect-query.socket" socketfile:depends( "enable", 1 ) -- collectd_unixsock.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup" ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_unixsock.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms" ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) return m
gpl-2.0
facebokiii/facebookplug
plugins/torrent_search.lua
411
1622
--[[ NOT USED DUE TO SSL ERROR -- See https://getstrike.net/api/ local function strike_search(query) local strike_base = 'http://getstrike.net/api/v2/torrents/' local url = strike_base..'search/?phrase='..URL.escape(query) print(url) local b,c = http.request(url) print(b,c) local search = json:decode(b) vardump(search) if c ~= 200 then return search.message end vardump(search) local results = search.results local text = 'Results: '..results local results = math.min(results, 3) for i=1,results do local torrent = search.torrents[i] text = text..torrent.torrent_title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.seeds ..'\n'..torrent.magnet_uri..'\n\n' end return text end]]-- local function search_kickass(query) local url = 'http://kat.cr/json.php?q='..URL.escape(query) local b,c = http.request(url) local data = json:decode(b) local text = 'Results: '..data.total_results..'\n\n' local results = math.min(#data.list, 5) for i=1,results do local torrent = data.list[i] local link = torrent.torrentLink link = link:gsub('%?title=.+','') text = text..torrent.title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.leechs ..'\n'..link --..'\n magnet:?xt=urn:btih:'..torrent.hash ..'\n\n' end return text end local function run(msg, matches) local query = matches[1] return search_kickass(query) end return { description = "Search Torrents", usage = "!torrent <search term>: Search for torrent", patterns = { "^!torrent (.+)$" }, run = run }
gpl-2.0
ominux/skia
resources/slides.lua
68
9898
gShowBounds = false gUseBlurInTransitions = false gPath = "/skia/trunk/resources/" function load_file(file) local prev_path = package.path package.path = package.path .. ";" .. gPath .. file .. ".lua" require(file) package.path = prev_path end load_file("slides_utils") gSlides = parse_file(io.open("/skia/trunk/resources/slides_content2.lua", "r")) function make_rect(l, t, r, b) return { left = l, top = t, right = r, bottom = b } end function make_paint(typefacename, stylebits, size, color) local paint = Sk.newPaint(); paint:setAntiAlias(true) paint:setSubpixelText(true) paint:setTypeface(Sk.newTypeface(typefacename, stylebits)) paint:setTextSize(size) paint:setColor(color) return paint end function draw_bullet(canvas, x, y, paint, indent) if 0 == indent then return end local ps = paint:getTextSize() local cx = x - ps * .8 local cy = y - ps * .4 local radius = ps * .2 canvas:drawCircle(cx, cy, radius, paint) end function stroke_rect(canvas, rect, color) local paint = Sk.newPaint() paint:setStroke(true); paint:setColor(color) canvas:drawRect(rect, paint) end function drawSlide(canvas, slide, master_template) if #slide == 1 then template = master_template.title canvas:drawText(slide[1].text, 320, 240, template[1]) return end template = master_template.slide local x = template.margin_x local y = template.margin_y local scale = 1.25 if slide.blockstyle == "code" then local paint = master_template.codePaint local fm = paint:getFontMetrics() local height = #slide * (fm.descent - fm.ascent) y = (480 - height) / 2 for i = 1, #slide do local node = slide[i] y = y - fm.ascent * scale canvas:drawText(node.text, x, y, paint) y = y + fm.descent * scale end return end for i = 1, #slide do local node = slide[i] local paint = template[node.indent + 1].paint local extra_dy = template[node.indent + 1].extra_dy local fm = paint:getFontMetrics() local x_offset = -fm.ascent * node.indent * 1.25 local bounds = make_rect(x + x_offset, y, 620, 640) local blob, newBottom = Sk.newTextBlob(node.text, bounds, paint) draw_bullet(canvas, x + x_offset, y - fm.ascent, paint, node.indent) canvas:drawTextBlob(blob, 0, 0, paint) y = newBottom + paint:getTextSize() * .5 + extra_dy if gShowBounds then bounds.bottom = newBottom stroke_rect(canvas, bounds, {a=1,r=0,g=1,b=0}) stroke_rect(canvas, blob:bounds(), {a=1,r=1,g=0,b=0}) end end end -------------------------------------------------------------------------------------- function make_tmpl(paint, extra_dy) return { paint = paint, extra_dy = extra_dy } end function SkiaPoint_make_template() local title = { margin_x = 30, margin_y = 100, } title[1] = make_paint("Arial", 1, 45, { a=1, r=1, g=1, b=1 }) title[1]:setTextAlign("center") title[2] = make_paint("Arial", 1, 25, { a=1, r=.75, g=.75, b=.75 }) title[2]:setTextAlign("center") local slide = { margin_x = 20, margin_y = 25, } slide[1] = make_tmpl(make_paint("Arial", 1, 35, { a=1, r=1, g=1, b=1 }), 18) slide[2] = make_tmpl(make_paint("Arial", 0, 25, { a=1, r=1, g=1, b=1 }), 10) slide[3] = make_tmpl(make_paint("Arial", 0, 20, { a=1, r=.9, g=.9, b=.9 }), 5) return { title = title, slide = slide, codePaint = make_paint("Courier", 0, 20, { a=1, r=.9, g=.9, b=.9 }), } end gTemplate = SkiaPoint_make_template() gRedPaint = Sk.newPaint() gRedPaint:setAntiAlias(true) gRedPaint:setColor{a=1, r=1, g=0, b=0 } -- animation.proc is passed the canvas before drawing. -- The animation.proc returns itself or another animation (which means keep animating) -- or it returns nil, which stops the animation. -- local gCurrAnimation gSlideIndex = 1 ----------------------------------------------------------------------------- function new_drawable_picture(pic) return { picture = pic, width = pic:width(), height = pic:height(), draw = function (self, canvas, x, y, paint) canvas:drawPicture(self.picture, x, y, paint) end } end function new_drawable_image(img) return { image = img, width = img:width(), height = img:height(), draw = function (self, canvas, x, y, paint) canvas:drawImage(self.image, x, y, paint) end } end function convert_to_picture_drawable(slide) local rec = Sk.newPictureRecorder() drawSlide(rec:beginRecording(640, 480), slide, gTemplate) return new_drawable_picture(rec:endRecording()) end function convert_to_image_drawable(slide) local surf = Sk.newRasterSurface(640, 480) drawSlide(surf:getCanvas(), slide, gTemplate) return new_drawable_image(surf:newImageSnapshot()) end function new_drawable_slide(slide) return { slide = slide, draw = function (self, canvas, x, y, paint) if (nil == paint or ("number" == type(paint) and (1 == paint))) then canvas:save() else canvas:saveLayer(paint) end canvas:translate(x, y) drawSlide(canvas, self.slide, gTemplate) canvas:restore() end } end gNewDrawableFactory = { default = new_drawable_slide, picture = convert_to_picture_drawable, image = convert_to_image_drawable, } ----------------------------------------------------------------------------- function next_slide() local prev = gSlides[gSlideIndex] if gSlideIndex < #gSlides then gSlideIndex = gSlideIndex + 1 spawn_transition(prev, gSlides[gSlideIndex], true) end end function prev_slide() local prev = gSlides[gSlideIndex] if gSlideIndex > 1 then gSlideIndex = gSlideIndex - 1 spawn_transition(prev, gSlides[gSlideIndex], false) end end gDrawableType = "default" load_file("slides_transitions") function spawn_transition(prevSlide, nextSlide, is_forward) local transition if is_forward then transition = gTransitionTable[nextSlide.transition] else transition = gTransitionTable[prevSlide.transition] end if not transition then transition = fade_slide_transition end local prevDrawable = gNewDrawableFactory[gDrawableType](prevSlide) local nextDrawable = gNewDrawableFactory[gDrawableType](nextSlide) gCurrAnimation = transition(prevDrawable, nextDrawable, is_forward) end -------------------------------------------------------------------------------------- function spawn_rotate_animation() gCurrAnimation = { angle = 0, angle_delta = 5, pivot_x = 320, pivot_y = 240, proc = function (self, canvas, drawSlideProc) if self.angle >= 360 then drawSlideProc(canvas) return nil end canvas:translate(self.pivot_x, self.pivot_y) canvas:rotate(self.angle) canvas:translate(-self.pivot_x, -self.pivot_y) drawSlideProc(canvas) self.angle = self.angle + self.angle_delta return self end } end function spawn_scale_animation() gCurrAnimation = { scale = 1, scale_delta = .95, scale_limit = 0.2, pivot_x = 320, pivot_y = 240, proc = function (self, canvas, drawSlideProc) if self.scale < self.scale_limit then self.scale = self.scale_limit self.scale_delta = 1 / self.scale_delta end if self.scale > 1 then drawSlideProc(canvas) return nil end canvas:translate(self.pivot_x, self.pivot_y) canvas:scale(self.scale, self.scale) canvas:translate(-self.pivot_x, -self.pivot_y) drawSlideProc(canvas) self.scale = self.scale * self.scale_delta return self end } end local bgPaint = nil function draw_bg(canvas) if not bgPaint then bgPaint = Sk.newPaint() local grad = Sk.newLinearGradient( 0, 0, { a=1, r=0, g=0, b=.3 }, 640, 480, { a=1, r=0, g=0, b=.8 }) bgPaint:setShader(grad) bgPaint:setDither(true) end canvas:drawPaint(bgPaint) end function onDrawContent(canvas, width, height) local matrix = Sk.newMatrix() matrix:setRectToRect(make_rect(0, 0, 640, 480), make_rect(0, 0, width, height), "center") canvas:concat(matrix) draw_bg(canvas) local drawSlideProc = function(canvas) drawSlide(canvas, gSlides[gSlideIndex], gTemplate) end if gCurrAnimation then gCurrAnimation = gCurrAnimation:proc(canvas, drawSlideProc) return true else drawSlideProc(canvas) return false end end function onClickHandler(x, y) return false end local keyProcs = { n = next_slide, p = prev_slide, r = spawn_rotate_animation, s = spawn_scale_animation, ["="] = function () scale_text_delta(gTemplate, 1) end, ["-"] = function () scale_text_delta(gTemplate, -1) end, b = function () gShowBounds = not gShowBounds end, B = function () gUseBlurInTransitions = not gUseBlurInTransitions end, ["1"] = function () gDrawableType = "default" end, ["2"] = function () gDrawableType = "picture" end, ["3"] = function () gDrawableType = "image" end, } function onCharHandler(uni) local proc = keyProcs[uni] if proc then proc() return true end return false end
apache-2.0
ashfinal/awesome-hammerspoon
Spoons/HSearch.spoon/hs_datamuse.lua
4
3260
local obj={} obj.__index = obj obj.name = "thesaurusDM" obj.version = "1.0" obj.author = "ashfinal <ashfinal@gmail.com>" -- Internal function used to find our location, so we know where to load files from local function script_path() local str = debug.getinfo(2, "S").source:sub(2) return str:match("(.*/)") end obj.spoonPath = script_path() -- Define the source's overview. A unique `keyword` key should exist, so this source can be found. obj.overview = {text="Type s ⇥ to request English Thesaurus.", image=hs.image.imageFromPath(obj.spoonPath .. "/resources/thesaurus.png"), keyword="s"} -- Define the notice when a long-time request is being executed. It could be `nil`. obj.notice = nil local function dmTips() local chooser_data = { {text="Datamuse Thesaurus", subText="Type something to get more words like it …", image=hs.image.imageFromPath(obj.spoonPath .. "/resources/thesaurus.png")} } return chooser_data end -- Define the function which will be called when the `keyword` triggers a new source. The returned value is a table. Read more: http://www.hammerspoon.org/docs/hs.chooser.html#choices obj.init_func = dmTips -- Insert a friendly tip at the head so users know what to do next. -- As this source highly relys on queryChangedCallback, we'd better tip users in callback instead of here obj.description = nil -- As the user is typing, the callback function will be called for every keypress. The returned value is a table. local function thesaurusRequest(querystr) local datamuse_baseurl = 'http://api.datamuse.com' if string.len(querystr) > 0 then local encoded_query = hs.http.encodeForQuery(querystr) local query_url = datamuse_baseurl .. '/words?ml=' .. encoded_query .. '&max=20' hs.http.asyncGet(query_url, nil, function(status, data) if status == 200 then if pcall(function() hs.json.decode(data) end) then local decoded_data = hs.json.decode(data) if #decoded_data > 0 then local chooser_data = hs.fnutils.imap(decoded_data, function(item) return {text = item.word, image=hs.image.imageFromPath(obj.spoonPath .. "/resources/thesaurus.png"), output="keystrokes", arg=item.word} end) -- Because we don't know when asyncGet will return data, we have to refresh hs.chooser choices in this callback. if spoon.HSearch then -- Make sure HSearch spoon is running now spoon.HSearch.chooser:choices(chooser_data) spoon.HSearch.chooser:refreshChoicesCallback() end end end end end) else local chooser_data = { {text="Datamuse Thesaurus", subText="Type something to get more words like it …", image=hs.image.imageFromPath(obj.spoonPath .. "/resources/thesaurus.png")} } if spoon.HSearch then spoon.HSearch.chooser:choices(chooser_data) spoon.HSearch.chooser:refreshChoicesCallback() end end end obj.callback = thesaurusRequest return obj
mit
dmccuskey/dmc-websockets
examples/dmc-websockets-pusher/dmc_corona/lib/dmc_lua/lua_class.lua
34
14185
--====================================================================-- -- dmc_lua/lua_class.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2015 David McCuskey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Lua Library : Lua Objects --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== Imports -- none --====================================================================-- --== Setup, Constants -- cache globals local assert, type, rawget, rawset = assert, type, rawget, rawset local getmetatable, setmetatable = getmetatable, setmetatable local sformat = string.format local tinsert = table.insert local tremove = table.remove -- table for copies from lua_utils local Utils = {} -- forward declare local ClassBase --====================================================================-- --== Class Support Functions --== Start: copy from lua_utils ==-- -- extend() -- Copy key/values from one table to another -- Will deep copy any value from first table which is itself a table. -- -- @param fromTable the table (object) from which to take key/value pairs -- @param toTable the table (object) in which to copy key/value pairs -- @return table the table (object) that received the copied items -- function Utils.extend( fromTable, toTable ) if not fromTable or not toTable then error( "table can't be nil" ) end function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end --== End: copy from lua_utils ==-- -- registerCtorName -- add names for the constructor -- local function registerCtorName( name, class ) class = class or ClassBase --==-- assert( type( name ) == 'string', "ctor name should be string" ) assert( class.is_class, "Class is not is_class" ) class[ name ] = class.__ctor__ return class[ name ] end -- registerDtorName -- add names for the destructor -- local function registerDtorName( name, class ) class = class or ClassBase --==-- assert( type( name ) == 'string', "dtor name should be string" ) assert( class.is_class, "Class is not is_class" ) class[ name ] = class.__dtor__ return class[ name ] end --[[ obj:superCall( 'string', ... ) obj:superCall( Class, 'string', ... ) --]] -- superCall() -- function to intelligently find methods in object hierarchy -- local function superCall( self, ... ) local args = {...} local arg1 = args[1] assert( type(arg1)=='table' or type(arg1)=='string', "superCall arg not table or string" ) --==-- -- pick off arguments local parent_lock, method, params if type(arg1) == 'table' then parent_lock = tremove( args, 1 ) method = tremove( args, 1 ) else method = tremove( args, 1 ) end params = args local self_dmc_super = self.__dmc_super local super_flag = ( self_dmc_super ~= nil ) local result = nil -- finds method name in class hierarchy -- returns found class or nil -- @params classes list of Classes on which to look, table/list -- @params name name of method to look for, string -- @params lock Class object with which to constrain searching -- local function findMethod( classes, name, lock ) if not classes then return end -- when using mixins, etc local cls = nil for _, class in ipairs( classes ) do if not lock or class == lock then if rawget( class, name ) then cls = class break else -- check parents for method cls = findMethod( class.__parents, name ) if cls then break end end end end return cls end local c, s -- class, super -- structure in which to save our place -- in case superCall() is invoked again -- if self_dmc_super == nil then self.__dmc_super = {} -- a stack self_dmc_super = self.__dmc_super -- find out where we are in hierarchy s = findMethod( { self.__class }, method ) tinsert( self_dmc_super, s ) end -- pull Class from stack and search for method on Supers -- look for method on supers -- call method if found -- c = self_dmc_super[ # self_dmc_super ] -- TODO: when c==nil -- if c==nil or type(c)~='table' then return end s = findMethod( c.__parents, method, parent_lock ) if s then tinsert( self_dmc_super, s ) result = s[method]( self, unpack( args ) ) tremove( self_dmc_super, # self_dmc_super ) end -- this is the first iteration and last -- so clean up callstack, etc -- if super_flag == false then parent_lock = nil tremove( self_dmc_super, # self_dmc_super ) self.__dmc_super = nil end return result end -- initializeObject -- this is the beginning of object initialization -- either Class or Instance -- this is what calls the parent constructors, eg new() -- called from newClass(), __create__(), __call() -- -- @params obj the object context -- @params params table with : -- set_isClass = true/false -- data contains {...} -- local function initializeObject( obj, params ) params = params or {} --==-- assert( params.set_isClass ~= nil, "initializeObject requires paramter 'set_isClass'" ) local is_class = params.set_isClass local args = params.data or {} -- set Class/Instance flag obj.__is_class = params.set_isClass -- call Parent constructors, if any -- do in reverse -- local parents = obj.__parents for i = #parents, 1, -1 do local parent = parents[i] assert( parent, "Lua Objects: parent is nil, check parent list" ) rawset( obj, '__parent_lock', parent ) if parent.__new__ then parent.__new__( obj, unpack( args ) ) end end rawset( obj, '__parent_lock', nil ) return obj end -- newindexFunc() -- override the normal Lua lookup functionality to allow -- property setter functions -- -- @param t object table -- @param k key -- @param v value -- local function newindexFunc( t, k, v ) local o, f -- check for key in setters table o = rawget( t, '__setters' ) or {} f = o[k] if f then -- found setter, so call it f(t,v) else -- place key/value directly on object rawset( t, k, v ) end end -- multiindexFunc() -- override the normal Lua lookup functionality to allow -- property getter functions -- -- @param t object table -- @param k key -- local function multiindexFunc( t, k ) local o, val --== do key lookup in different places on object -- check for key in getters table o = rawget( t, '__getters' ) or {} if o[k] then return o[k](t) end -- check for key directly on object val = rawget( t, k ) if val ~= nil then return val end -- check OO hierarchy -- check Parent Lock else all of Parents -- o = rawget( t, '__parent_lock' ) if o then if o then val = o[k] end if val ~= nil then return val end else local par = rawget( t, '__parents' ) for _, o in ipairs( par ) do if o[k] ~= nil then val = o[k] break end end if val ~= nil then return val end end return nil end -- blessObject() -- create new object, setup with Lua OO aspects, dmc-style aspects -- @params inheritance table of supers/parents (dmc-style objects) -- @params params -- params.object -- params.set_isClass -- local function blessObject( inheritance, params ) params = params or {} params.object = params.object or {} params.set_isClass = params.set_isClass == true and true or false --==-- local o = params.object local o_id = tostring(o) local mt = { __index = multiindexFunc, __newindex = newindexFunc, __tostring = function(obj) return obj:__tostring__(o_id) end, __call = function( cls, ... ) return cls:__ctor__( ... ) end } setmetatable( o, mt ) -- add Class property, access via getters:supers() o.__parents = inheritance o.__is_dmc = true -- create lookup tables - setters, getters o.__setters = {} o.__getters = {} -- copy down all getters/setters of parents -- do in reverse order, to match order of property lookup for i = #inheritance, 1, -1 do local cls = inheritance[i] if cls.__getters then o.__getters = Utils.extend( cls.__getters, o.__getters ) end if cls.__setters then o.__setters = Utils.extend( cls.__setters, o.__setters ) end end return o end local function unblessObject( o ) setmetatable( o, nil ) o.__parents=nil o.__is_dmc = nil o.__setters = nil o.__getters=nil end local function newClass( inheritance, params ) inheritance = inheritance or {} params = params or {} params.set_isClass = true params.name = params.name or "<unnamed class>" --==-- assert( type( inheritance ) == 'table', "first parameter should be nil, a Class, or a list of Classes" ) -- wrap single-class into table list -- testing for DMC-Style objects -- TODO: see if we can test for other Class libs -- if inheritance.is_class == true then inheritance = { inheritance } elseif ClassBase and #inheritance == 0 then -- add default base Class tinsert( inheritance, ClassBase ) end local o = blessObject( inheritance, {} ) initializeObject( o, params ) -- add Class property, access via getters:class() o.__class = o -- add Class property, access via getters:NAME() o.__name = params.name return o end -- backward compatibility -- local function inheritsFrom( baseClass, options, constructor ) baseClass = baseClass == nil and baseClass or { baseClass } return newClass( baseClass, options ) end --====================================================================-- --== Base Class --====================================================================-- ClassBase = newClass( nil, { name="Class Class" } ) -- __ctor__ method -- called by 'new()' and other registrations -- function ClassBase:__ctor__( ... ) local params = { data = {...}, set_isClass = false } --==-- local o = blessObject( { self.__class }, params ) initializeObject( o, params ) return o end -- __dtor__ method -- called by 'destroy()' and other registrations -- function ClassBase:__dtor__() self:__destroy__() -- unblessObject( self ) end function ClassBase:__new__( ... ) return self end function ClassBase:__tostring__( id ) return sformat( "%s (%s)", self.NAME, id ) end function ClassBase:__destroy__() end function ClassBase.__getters:NAME() return self.__name end function ClassBase.__getters:class() return self.__class end function ClassBase.__getters:supers() return self.__parents end function ClassBase.__getters:is_class() return self.__is_class end -- deprecated function ClassBase.__getters:is_intermediate() return self.__is_class end function ClassBase.__getters:is_instance() return not self.__is_class end function ClassBase.__getters:version() return self.__version end function ClassBase:isa( the_class ) local isa = false local cur_class = self.class -- test self if cur_class == the_class then isa = true -- test parents else local parents = self.__parents for i=1, #parents do local parent = parents[i] if parent.isa then isa = parent:isa( the_class ) end if isa == true then break end end end return isa end -- optimize() -- move super class methods to object -- function ClassBase:optimize() function _optimize( obj, inheritance ) if not inheritance or #inheritance == 0 then return end for i=#inheritance,1,-1 do local parent = inheritance[i] -- climb up the hierarchy _optimize( obj, parent.__parents ) -- make local references to all functions for k,v in pairs( parent ) do if type( v ) == 'function' then obj[ k ] = v end end end end _optimize( self, { self.__class } ) end -- deoptimize() -- remove super class (optimized) methods from object -- function ClassBase:deoptimize() for k,v in pairs( self ) do if type( v ) == 'function' then self[ k ] = nil end end end -- Setup Class Properties (function references) registerCtorName( 'new', ClassBase ) registerDtorName( 'destroy', ClassBase ) ClassBase.superCall = superCall --====================================================================-- --== Lua Objects Exports --====================================================================-- -- makeNewClassGlobal -- modifies the global namespace with newClass() -- add or remove -- local function makeNewClassGlobal( is_global ) is_global = is_global~=nil and is_global or true if _G.newClass ~= nil then print( "WARNING: newClass exists in global namespace" ) elseif is_global == true then _G.newClass = newClass else _G.newClass = nil end end makeNewClassGlobal() -- start it off return { __version=VERSION, __superCall=superCall, -- for testing setNewClassGlobal=makeNewClassGlobal, registerCtorName=registerCtorName, registerDtorName=registerDtorName, inheritsFrom=inheritsFrom, -- backwards compatibility newClass=newClass, Class=ClassBase }
mit
sami2448/set
plugins/vote.lua
83
2129
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
sigurdfdragon/wesnoth-fork
data/ai/micro_ais/micro_ai_self_data.lua
15
3878
-- This set of functions provides a consistent way of storing Micro AI variables -- in the AI's persistent data variable. These need to be stored inside -- a [micro_ai] tag, so that they are bundled together for a given Micro AI -- together with an ai_id= key. Their existence can then be checked when setting -- up another MAI. Otherwise other Micro AIs used in the same scenario might -- work incorrectly or not at all. -- Note that, ideally, we would delete these [micro_ai] tags when a Micro AI is -- deleted, but that that is not always possible as deletion can happen on -- another side's turn, while the data variable is only accessible during -- the AI turn. -- Note that, with this method, there can only ever be one of these tags for each -- Micro AI (but of course several when there are several Micro AIs for the -- same side). -- For the time being, we only allow key=value style variables. local micro_ai_self_data = {} function micro_ai_self_data.modify_mai_self_data(self_data, ai_id, action, vars_table) -- Modify data [micro_ai] tags -- @ai_id (string): the id of the Micro AI -- @action (string): "delete", "set" or "insert" -- @vars_table: table of key=value pairs with the variables to be set or inserted -- if this is set for @action="delete", then only the keys in @vars_table are deleted, -- otherwise the entire [micro_ai] tag is deleted -- Always delete the respective [micro_ai] tag, if it exists local existing_table for i,mai in ipairs(self_data, "micro_ai") do if (mai[1] == "micro_ai") and (mai[2].ai_id == ai_id) then if (action == "delete") and vars_table then for k,_ in pairs(vars_table) do mai[2][k] = nil end return end existing_table = mai[2] table.remove(self_data, i) break end end -- Then replace it, if the "set" action is selected -- or add the new keys to it, overwriting old ones with the same name, if action == "insert" if (action == "set") or (action == "insert") then local tag = { "micro_ai" } if (not existing_table) or (action == "set") then -- Important: we need to make a copy of the input table, not use it! tag[2] = {} for k,v in pairs(vars_table) do tag[2][k] = v end tag[2].ai_id = ai_id else for k,v in pairs(vars_table) do existing_table[k] = v end tag[2] = existing_table end table.insert(self_data, tag) end end function micro_ai_self_data.delete_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "delete", vars_table) end function micro_ai_self_data.insert_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "insert", vars_table) end function micro_ai_self_data.set_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "set", vars_table) end function micro_ai_self_data.get_mai_self_data(self_data, ai_id, key) -- Get the content of the data [micro_ai] tag for the given @ai_id -- Return value: -- - If tag is found: value of key if @key parameter is given, otherwise -- table of key=value pairs (including the ai_id key) -- - If no such tag is found: nil (if @key is set), otherwise empty table for mai in wml.child_range(self_data, "micro_ai") do if (mai.ai_id == ai_id) then if key then return mai[key] else return mai end end end -- If we got here, no corresponding tag was found -- Return empty table; or nil if @key was set if (not key) then return {} end end return micro_ai_self_data
gpl-2.0
dvr333/Zero-K
scripts/striderdetriment.lua
6
16843
include 'constants.lua' local AngleAverageShortest = Spring.Utilities.Vector.AngleAverageShortest local AngleSubtractShortest = Spring.Utilities.Vector.AngleSubtractShortest -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- pieces local pelvis, torso, head, shouldercannon, shoulderflare = piece('pelvis', 'torso', 'head', 'shouldercannon', 'shoulderflare') local aaturret, aagun, aaflare1, aaflare2, headlaser1, headlaser2, headlaser3 = piece('AAturret', 'AAguns', 'AAflare1', 'AAflare2', 'headlaser1', 'headlaser2', 'headlaser3') local larm, larmcannon, larmbarrel1, larmflare1, larmbarrel2, larmflare2, larmbarrel3, larmflare3 = piece('larm', 'larmcannon', 'larmbarrel1', 'larmflare1', 'larmbarrel2', 'larmflare2', 'larmbarrel3', 'larmflare3') local rarm, rarmcannon, rarmbarrel1, rarmflare1, rarmbarrel2, rarmflare2, rarmbarrel3, rarmflare3 = piece('rarm', 'rarmcannon', 'rarmbarrel1', 'rarmflare1', 'rarmbarrel2', 'rarmflare2', 'rarmbarrel3', 'rarmflare3') local lupleg, lmidleg, lleg, lfoot, lftoe, lbtoe = piece('lupleg', 'lmidleg', 'lleg', 'lfoot', 'lftoe', 'lbtoe') local rupleg, rmidleg, rleg, rfoot, rftoe, rbtoe = piece('rupleg', 'rmidleg', 'rleg', 'rfoot', 'rftoe', 'rbtoe') local leftLeg = { thigh=piece'lupleg', knee=piece'lmidleg', shin=piece'lleg', foot=piece'lfoot', toef=piece'lftoe', toeb=piece'lbtoe' } local rightLeg = { thigh=piece'rupleg', knee=piece'rmidleg', shin=piece'rleg', foot=piece'rfoot', toef=piece'rftoe', toeb=piece'rbtoe' } local mainLeg, offLeg = leftLeg, rightLeg local smokePiece = { torso, head, shouldercannon } local gunFlares = { {larmflare1, larmflare2, larmflare3}, {rarmflare1, rarmflare2, rarmflare3}, {shoulderflare}, {aaflare1, aaflare2}, {headlaser1, headlaser2, headlaser3}, {lfoot}, {lfoot}, {lfoot} } local barrels = { {larmbarrel1, larmbarrel2, larmbarrel3}, {rarmbarrel1, rarmbarrel2, rarmbarrel3}, } local aimpoints = {larmcannon, rarmcannon, aaturret, headlaser2, shouldercannon, lfoot, lfoot, lfoot} local gunIndex = {1,1,1,1,1,1,1,1} local blockGauss = {false, false} local gunFlareCount = {} for i = 1, #gunFlares do gunFlareCount[i] = #gunFlares[i] end local lastTorsoHeading = 0 local manualfireAimOverride = false local weaponBlocked = false -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --signals local SIG_Restore = 1 local SIG_Walk = 2 local PACE = 0.8 -- four leg positions - front to straight, then to back, then to bent (then front again) local LEG_FRONT_ANGLES = { thigh=math.rad(-40), knee=math.rad(-10), shin=math.rad(50), foot=math.rad(0), toef=math.rad(0), toeb=math.rad(15) } local LEG_FRONT_SPEEDS = { thigh=math.rad(60)*PACE, knee=math.rad(60)*PACE, shin=math.rad(110)*PACE, foot=math.rad(90)*PACE, toef=math.rad(90)*PACE, toeb=math.rad(30)*PACE } local LEG_STRAIGHT_ANGLES = { thigh=math.rad(-10), knee=math.rad(-20), shin=math.rad(30), foot=math.rad(0), toef=math.rad(0), toeb=math.rad(0) } local LEG_STRAIGHT_SPEEDS = { thigh=math.rad(60)*PACE, knee=math.rad(30)*PACE, shin=math.rad(40)*PACE, foot=math.rad(90)*PACE, toef=math.rad(90)*PACE, toeb=math.rad(30)*PACE } local LEG_BACK_ANGLES = { thigh=math.rad(10), knee=math.rad(-5), shin=math.rad(15), foot=math.rad(0), toef=math.rad(-20), toeb=math.rad(-10) } local LEG_BACK_SPEEDS = { thigh=math.rad(30)*PACE, knee=math.rad(60)*PACE, shin=math.rad(90)*PACE, foot=math.rad(90)*PACE, toef=math.rad(40)*PACE, toeb=math.rad(60)*PACE } local LEG_BENT_ANGLES = { thigh=math.rad(-15), knee=math.rad(20), shin=math.rad(-20), foot=math.rad(0), toef=math.rad(0), toeb=math.rad(0) } local LEG_BENT_SPEEDS = { thigh=math.rad(60)*PACE, knee=math.rad(90)*PACE, shin=math.rad(90)*PACE, foot=math.rad(90)*PACE, toef=math.rad(90)*PACE, toeb=math.rad(90)*PACE } local LEG_STEP_ANGLES = { thigh=math.rad(-9), knee=math.rad(30), shin=math.rad(-22), foot=math.rad(0), toef=math.rad(8), toeb=math.rad(0) } local LEG_STEP_SPEEDS = { thigh=math.rad(15)*PACE, knee=math.rad(50)*PACE, shin=math.rad(36.6)*PACE, foot=math.rad(50)*PACE, toef=math.rad(13.3)*PACE, toeb=math.rad(50)*PACE } local TORSO_ANGLE_MOTION = math.rad(8) local TORSO_SPEED_MOTION = math.rad(15)*PACE local TORSO_TILT_ANGLE = math.rad(15) local TORSO_TILT_SPEED = math.rad(15)*PACE local PELVIS_LIFT_HEIGHT = 11.5 local PELVIS_LIFT_SPEED = 14 local PELVIS_LOWER_HEIGHT = 6.5 local PELVIS_LOWER_SPEED = 15 local ARM_FRONT_ANGLE = math.rad(-15) local ARM_FRONT_SPEED = math.rad(35) * PACE local ARM_BACK_ANGLE = math.rad(5) local ARM_BACK_SPEED = math.rad(30) * PACE local leftTorsoHeading = false local rightTorsoHeading = false local lastGunAverageHeading = false local JUMP_TURN_SPEED = math.pi/80 -- matches jump_delay_turn_scale in unitdef local isFiring = false -- Effects local dirtfling = 1024 local muzzle_flash = 1025 local shells = 1026 local muzzle_flash_large = 1027 local muzzle_smoke_large = 1028 local jetfeet = 1029 local jetfeet_fire = 1030 -- Weapons local landing_explosion = 4101 --Weapon 6 local footcrater = 4102 --Weapon 7 local takeoff_explosion = 4103 --Weapon 8 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function DoRestore() Turn(head, y_axis, 0, 2) Move(head, y_axis, -6, 10) Move(head, z_axis, -4, 10) Turn(torso, y_axis, 0, math.rad(70)) Turn(larm, x_axis, 0, math.rad(30)) Turn(larmcannon, y_axis, 0, math.rad(10)) Turn(rarm, x_axis, 0, math.rad(30)) Turn(rarmcannon, y_axis, 0, math.rad(10)) Turn(shouldercannon, x_axis, 0, math.rad(90)) isFiring = false lastTorsoHeading = 0 end local function Step(frontLeg, backLeg, impactFoot, pelvisMult) mainLeg, offLeg = offLeg, mainLeg -- contact: legs fully extended in stride for i,p in pairs(frontLeg) do Turn(frontLeg[i], x_axis, LEG_FRONT_ANGLES[i], LEG_FRONT_SPEEDS[i]) Turn(backLeg[i], x_axis, LEG_BACK_ANGLES[i], LEG_BACK_SPEEDS[i]) end -- swing arms and body if not(isFiring) then if (frontLeg == leftLeg) then Turn(torso, y_axis, TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION) Turn(larm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED) Turn(larmcannon, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED) Turn(rarm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED) else Turn(torso, y_axis, -TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION) Turn(larm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED) Turn(rarmcannon, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED) Turn(rarm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED) end end Move(pelvis, y_axis, PELVIS_LOWER_HEIGHT, PELVIS_LOWER_SPEED*pelvisMult) Turn(torso, x_axis, TORSO_TILT_ANGLE, TORSO_TILT_SPEED) for i, p in pairs(frontLeg) do WaitForTurn(frontLeg[i], x_axis) WaitForTurn(backLeg[i], x_axis) end -- passing (front foot flat under body, back foot passing with bent knee) for i, p in pairs(frontLeg) do Turn(frontLeg[i], x_axis, LEG_STRAIGHT_ANGLES[i], LEG_STRAIGHT_SPEEDS[i]) Turn(backLeg[i], x_axis, LEG_BENT_ANGLES[i], LEG_BENT_SPEEDS[i]) end --EmitSfx(impactFoot, dirtfling) --EmitSfx(impactFoot, footcrater) Move(pelvis, y_axis, PELVIS_LIFT_HEIGHT, PELVIS_LIFT_SPEED*pelvisMult) Turn(torso, x_axis, 0, TORSO_TILT_SPEED) for i, p in pairs(frontLeg) do WaitForTurn(frontLeg[i], x_axis) WaitForTurn(backLeg[i], x_axis) end Sleep(0) end local function StepInPlace(frontLeg, backLeg) Move(pelvis, y_axis, 2, 6) for i, p in pairs(frontLeg) do Turn(frontLeg[i], x_axis, 0.8*LEG_STEP_ANGLES[i], LEG_STEP_SPEEDS[i]*1.4) Turn( backLeg[i], x_axis, -0.5*LEG_STEP_ANGLES[i], LEG_STEP_SPEEDS[i]) end Sleep(400) end local function Walk() Signal(SIG_Walk) SetSignalMask(SIG_Walk) local first = true while (true) do Step(mainLeg, offLeg, lfoot, (first and 2) or 1) Step(mainLeg, offLeg, rfoot, (first and 1.2) or 1) first = false end end local function StopWalk() Signal(SIG_Walk) SetSignalMask(SIG_Walk) Move(torso, y_axis, 0, 1) for i,p in pairs(leftLeg) do Turn(leftLeg[i], x_axis, 0, LEG_STRAIGHT_SPEEDS[i]) Turn(rightLeg[i], x_axis, 0, LEG_STRAIGHT_SPEEDS[i]) end Turn(pelvis, z_axis, 0, math.rad(30)) Turn(torso, x_axis, 0, math.rad(30)) if not(isFiring) then Turn(torso, y_axis, 0, math.rad(30)) end Move(pelvis, y_axis, 0, 20) Turn(rarm, x_axis, 0, math.rad(30)) Turn(larm, x_axis, 0, math.rad(10)) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(StopWalk) end -- Jumping local function PreJumpThread(turn, lineDist, flightDist, duration) Signal(SIG_Walk) SetSignalMask(SIG_Walk) DoRestore() weaponBlocked = true local heading = -Spring.GetUnitHeading(unitID)*GG.Script.headingToRad Spring.MoveCtrl.SetRotation(unitID, 0, heading, 0) -- keep current heading local rotationRequired = -turn*GG.Script.headingToRad local rotationFrames = math.ceil(math.abs(rotationRequired/JUMP_TURN_SPEED)/12)*12 --Spring.MoveCtrl.SetRotation(unitID, 0, heading + rotationRequired, 0) -- keep current heading --Sleep(2000) if rotationFrames > 0 then Spring.MoveCtrl.SetRotationVelocity(unitID, 0, rotationRequired/rotationFrames, 0) while true do StepInPlace(leftLeg, rightLeg) rotationFrames = rotationFrames - 12 if rotationFrames <= 0 then break end Move(pelvis, y_axis, 4, 7) Sleep(400) rotationFrames = rotationFrames - 12 if rotationFrames <= 0 then break end StepInPlace(rightLeg, leftLeg) rotationFrames = rotationFrames - 12 if rotationFrames <= 0 then break end Move(pelvis, y_axis, 4, 7) Sleep(400) rotationFrames = rotationFrames - 12 if rotationFrames <= 0 then break end end end Spring.MoveCtrl.SetRotationVelocity(unitID, 0, 0, 0) for i,p in pairs(leftLeg) do Turn(leftLeg[i], x_axis, 0, LEG_STEP_SPEEDS[i]) Turn(rightLeg[i], x_axis, 0, LEG_STEP_SPEEDS[i]) end Move(pelvis, y_axis, 0, 8) Sleep(600) for i,p in pairs(leftLeg) do Turn(leftLeg[i], x_axis, 1.66*LEG_STEP_ANGLES[i], LEG_STEP_SPEEDS[i]) Turn(rightLeg[i], x_axis, 1.66*LEG_STEP_ANGLES[i], LEG_STEP_SPEEDS[i]) end Move(torso, y_axis, 0, 1) Move(pelvis, y_axis, -20, 16) Move(pelvis, z_axis, -10, 8) Turn(torso, x_axis, math.rad(20), math.rad(30)) Turn(pelvis, z_axis, 0, math.rad(30)) --EmitSfx(lfoot, jetfeet) --EmitSfx(rfoot, jetfeet) end local function EndJumpThread() EmitSfx(lfoot, landing_explosion) EmitSfx(lfoot, dirtfling) Turn(torso, x_axis, math.rad(45)) Turn(larm, x_axis, math.rad(-40)) Turn(rarm, x_axis, math.rad(-40)) Sleep(50) Turn(torso, x_axis, 0, math.rad(35)) Turn(larm, x_axis, 0, math.rad(35)) Turn(rarm, x_axis, 0, math.rad(35)) end function preJump(turn,lineDist,flightDist,duration) StartThread(PreJumpThread, turn,lineDist,flightDist,duration) end function beginJump() for i,p in pairs(leftLeg) do Turn(leftLeg[i], x_axis, 0, LEG_STEP_SPEEDS[i]) Turn(rightLeg[i], x_axis, 0, LEG_STEP_SPEEDS[i]) end local x,y,z = Spring.GetUnitPosition(unitID, true) GG.PlayFogHiddenSound("DetrimentJump", 15, x, y, z) end function jumping(jumpPercent) if jumpPercent < 30 then GG.PokeDecloakUnit(unitID, unitDefID) EmitSfx(lfoot, jetfeet_fire) EmitSfx(rfoot, jetfeet_fire) end if weaponBlocked and jumpPercent >= 25 then Move(pelvis, y_axis, 0, 5) Move(pelvis, z_axis, 0, 3) Turn(torso, x_axis, 0, math.rad(10)) weaponBlocked = false end end function endJump() StartThread(EndJumpThread) end function script.Create() Turn(larm, z_axis, -0.1) Turn(rarm, z_axis, 0.1) Turn(shoulderflare, x_axis, math.rad(-90)) StartThread(GG.Script.SmokeUnit, unitID, smokePiece) Spring.SetUnitMaxRange(unitID, 510) end local function RestoreAfterDelay() Signal(SIG_Restore) SetSignalMask(SIG_Restore) Sleep(2000) DoRestore() end function script.AimFromWeapon(num) return aimpoints[num] end function script.QueryWeapon(num) return gunFlares[num][ gunIndex[num] ] end function script.AimWeapon(num, heading, pitch) local SIG_AIM = 2^(num+1) isFiring = true Signal(SIG_AIM) SetSignalMask(SIG_AIM) if manualfireAimOverride and (num == 1 or num == 2 or num == 5) then manualfireAimOverride = manualfireAimOverride - 1 if manualfireAimOverride <= 0 then manualfireAimOverride = false Turn(shouldercannon, x_axis, 0, math.rad(90)) end Sleep(500) return false end if weaponBlocked and (num == 1 or num == 2 or num == 3 or num == 5) then return false end StartThread(RestoreAfterDelay) if num == 1 then -- Left gunpod leftTorsoHeading = heading if rightTorsoHeading then heading = AngleAverageShortest(rightTorsoHeading, leftTorsoHeading) rightTorsoHeading = false end lastGunAverageHeading = heading local armAngle = leftTorsoHeading - heading if armAngle > 3 then armAngle = armAngle - 2*math.pi end armAngle = math.min(0.2, math.max(-0.2, armAngle)) Turn(torso, y_axis, heading, math.rad(140)) Turn(larmcannon, y_axis, armAngle, math.rad(20)) Turn(larm, x_axis, -pitch, math.rad(40)) WaitForTurn(torso, y_axis) WaitForTurn(larm, x_axis) elseif num == 2 then -- Right gunpod rightTorsoHeading = heading if leftTorsoHeading then heading = AngleAverageShortest(rightTorsoHeading, leftTorsoHeading) leftTorsoHeading = false end lastGunAverageHeading = heading local armAngle = rightTorsoHeading - heading if armAngle > 3 then armAngle = armAngle - 2*math.pi end -- The right arm avoids aiming if there is too much conflict between the arms. if math.abs(armAngle) > 0.7 then lastGunAverageHeading = false rightTorsoHeading = false return false end armAngle = math.min(0.2, math.max(-0.2, armAngle)) Turn(torso, y_axis, heading, math.rad(140)) Turn(rarmcannon, y_axis, armAngle, math.rad(20)) Turn(rarm, x_axis, -pitch, math.rad(40)) WaitForTurn(torso, y_axis) WaitForTurn(rarm, x_axis) elseif num == 3 then -- Shoulder Cannon manualfireAimOverride = 60 Turn(torso, y_axis, heading, math.rad(90)) WaitForTurn(torso, y_axis) Turn(shouldercannon, x_axis, -pitch+math.rad(90), math.rad(90)) Move(shouldercannon, y_axis, -2, 0.7) WaitForTurn(shouldercannon, x_axis) elseif num == 4 then Turn(aaturret, y_axis, heading - lastTorsoHeading, math.rad(360)) Turn(aagun, x_axis, -pitch, math.rad(240)) WaitForTurn(aaturret, y_axis) WaitForTurn(aagun, x_axis) return true elseif num == 5 then -- Face laser local wantedHeading = heading if lastGunAverageHeading then heading = lastGunAverageHeading lastGunAverageHeading = false end local diffAngle = wantedHeading - heading if diffAngle > 3 then diffAngle = diffAngle - 2*math.pi end if math.abs(diffAngle) > 0.7 then return false end Turn(torso, y_axis, heading, math.rad(90)) Move(head, y_axis, 0, 10) Move(head, z_axis, 0, 10) WaitForTurn(torso, y_axis) end lastTorsoHeading = heading return true end local function BumpGunNum(num) gunIndex[num] = gunIndex[num] + 1 if gunIndex[num] > gunFlareCount[num] then gunIndex[num] = 1 end end local function Recoil(num) Sleep(33) EmitSfx(gunFlares[num][gunIndex[num]], muzzle_flash_large) Move(barrels[num][gunIndex[num]], z_axis, -40) Move(barrels[num][gunIndex[num]], z_axis, 0, 30) BumpGunNum(num) end function script.Shot(num) -- Left if num == 1 or num == 2 then StartThread(Recoil, num, true) end -- Shoulder cannon if num == 3 then manualfireAimOverride = 60 Move(shouldercannon, z_axis, -30) Turn(torso, x_axis, math.rad(-5)) EmitSfx(shoulderflare, muzzle_flash_large) Turn(torso, x_axis, 0, math.rad(10)) Move(shouldercannon, z_axis, 0, 50) Turn(shouldercannon, x_axis, 0, math.rad(10)) end end function script.BlockShot(num, targetID) if weaponBlocked and (num == 1 or num == 2 or num == 3 or num == 5) then return true end if num > 2 then return false end local frame = Spring.GetGameFrame() if (blockGauss[num] or 0) > frame then return true end blockGauss[3 - num] = frame + 20 return false end -- EndBurst so that the projectile fires from the correct gun function script.EndBurst(num) if num == 4 then gunIndex[num] = 3 - gunIndex[num] end end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= .5) then Explode(torso, SFX.NONE) Explode(head, SFX.NONE) Explode(pelvis, SFX.NONE) Explode(rarmcannon, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE) Explode(larmcannon, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE) Explode(larm, SFX.SHATTER) return 1 -- corpsetype else Explode(torso, SFX.SHATTER) Explode(head, SFX.SMOKE + SFX.FIRE) Explode(pelvis, SFX.SHATTER) return 2 -- corpsetype end end
gpl-2.0
m241dan/darkstar
scripts/zones/Rabao/npcs/Porter_Moogle.lua
41
1509
----------------------------------- -- Area: Rabao -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 247 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Rabao/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 136, STORE_EVENT_ID = 137, RETRIEVE_EVENT_ID = 138, ALREADY_STORED_ID = 139, MAGIAN_TRIAL_ID = 140 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
santssoft/darkstar
scripts/zones/Lower_Jeuno/npcs/Hasim.lua
6
3566
----------------------------------- -- Area: Lower Jeuno -- NPC: Hasim -- Standard Merchant NPC ----------------------------------- local ID = require("scripts/zones/Lower_Jeuno/IDs") require("scripts/globals/shop") function onTrade(player,npc,trade) end function onTrigger(player,npc) local stock = { 4612, 23400, -- Scroll of Cure IV 4616, 11200, -- Scroll of Curaga II 4617, 19932, -- Scroll of Curaga III 4625, 2330, -- Scroll of Silena 4626, 19200, -- Scroll of Stona 4627, 13300, -- Scroll of Viruna 4628, 8586, -- Scroll of Cursna 4653, 32000, -- Scroll of Protect III 4734, 7074, -- Scroll of Protectra II 4735, 19200, -- Scroll of Protectra III 4658, 26244, -- Scroll of Shell III 4738, 1760, -- Scroll of Shellra 4739, 14080, -- Scroll of Shellra II 4740, 26244, -- Scroll of Shellra III 4668, 1760, -- Scroll of Barfire 4669, 3624, -- Scroll of Barblizzard 4670, 930, -- Scroll of Baraero 4671, 156, -- Scroll of Barstone 4672, 5754, -- Scroll of Barthunder 4673, 360, -- Scroll of Barwater 4674, 1760, -- Scroll of Barfira 4675, 3624, -- Scroll of Barblizzara 4676, 930, -- Scroll of Baraera 4677, 156, -- Scroll of Barstonra 4678, 5754, -- Scroll of Barthundra 4679, 360, -- Scroll of Barwatera 4680, 244, -- Scroll of Barsleep 4681, 400, -- Scroll of Barpoison 4682, 780, -- Scroll of Barparalyze 4683, 2030, -- Scroll of Barblind 4684, 4608, -- Scroll of Barsilence 4694, 244, -- Scroll of Barsleepra 4695, 400, -- Scroll of Barpoisonra 4696, 780, -- Scroll of Barparalyzra 4697, 2030, -- Scroll of Barblindra 4698, 4608, -- Scroll of Barsilencera 4685, 15120, -- Scroll of Barpetrify 4686, 9600, -- Scroll of Barvirus 4699, 15120, -- Scroll of Barpetra 4700, 9600, -- Scroll of Barvira 5089, 73740, -- Scroll of Gain-VIT 5092, 77500, -- Scroll of Gain-MND 5090, 85680, -- Scroll of Gain-AGI 5093, 81900, -- Scroll of Gain-CHR 5087, 89804, -- Scroll of Gain-STR 5091, 94461, -- Scroll of Gain-INT 5088, 99613, -- Scroll of Gain-DEX 5096, 73740, -- Scroll of Boost-VIT 5099, 77500, -- Scroll of Boost-MND 5097, 85680, -- Scroll of Boost-AGI 5100, 81900, -- Scroll of Boost-CHR 5094, 89804, -- Scroll of Boost-STR 5098, 94461, -- Scroll of Boost-INT 5095, 99613, -- Scroll of Boost-DEX 5106, 73500, -- Scroll of Inundation 4849, 130378, -- Scroll of Addle 4629, 35000, -- Scroll of Holy 4647, 20000, -- Scroll of Banishga II 4737, 119240, -- Scroll of Protecra V 4742, 124540, -- Scroll of Shellra V 4633, 139135, -- Scroll of Dia III 6569, 139135, -- Scroll of Slow II 6570, 139135, -- Scroll of Paralyze II 6571, 139135, -- Scroll of Phalanx II } player:showText(npc,ID.text.HASIM_SHOP_DIALOG) dsp.shop.general(player, stock) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
atitus5/FastLID-DNN
posteriors.lua
1
3694
require "torch" require "nn" local lre03DatasetReader = require "lre03DatasetReader" -- Parse command-line options local opt = lapp[[ -n,--network (string) reload pretrained network -g,--gpu evaluate on GPU -t,--threads (default 4) number of threads --languages (string) languages being used, delimited by "_" ]] if opt.gpu then require "cunn" end -- Fix seed torch.manualSeed(1) -- Threads torch.setnumthreads(opt.threads) print('Set nb of threads to ' .. torch.getnumthreads()) print("Setting up evaluation dataset...") local features_file="/pool001/atitus/FastLID-DNN/data_prep/feats/" .. opt.languages .. "_evaluate" local lang2label = {outofset = 1, english = 2, german = 1, mandarin = 3} -- Balance data --local total_frames = 26326 -- Amount in German, the minimum of this language set local total_frames = 47907 -- Amount in Mandarin, the minimum of this language set local label2maxframes = torch.zeros(4) label2maxframes[lang2label["outofset"]] = total_frames label2maxframes[lang2label["english"]] = total_frames label2maxframes[lang2label["german"]] = total_frames label2maxframes[lang2label["mandarin"]] = total_frames print("Loading neural network " .. opt.network .. "...") model = torch.load(opt.network) print("Loaded neural network " .. opt.network) -- Set up for evaluation (i.e. deactivate Dropout) model:evaluate() print("Using model:") print(model) if opt.gpu then -- Convert our network to CUDA-compatible version print("Convert network to CUDA") model = model:cuda() end -- Load the evaluation dataset local feature_dim = 39 -- 13 MFCCs, 13 delta MFCCS, 13 delta-delta MFCCs local context_frames = 20 local readCfg = { features_file = features_file, lang2label = lang2label, label2maxframes = label2maxframes, include_utts = true, gpu = opt.gpu } local dataset, label2framecount = lre03DatasetReader.read(readCfg) print("Testing neural network posteriors...") local input = torch.zeros(feature_dim * (context_frames + 1)) if opt.gpu then -- Convert our input tensor to CUDA-compatible version print("Convert input tensor to CUDA") input = input:cuda() end for i=1,dataset:size() do local data = dataset[i] local features_tensor = data[1] local label = data[2] local utt = data[3] -- Load current features input:zero() input[{ {1, feature_dim} }] = features_tensor -- Load context features, if any for context = 1, math.min(context_frames, i - 1) do local context_data = dataset[i - context] local context_features_tensor = context_data[1] local context_utt = context_data[3] -- Don't let another utterance spill over into this one! if context_utt == utt then local slice_begin = (context * feature_dim) + 1 local slice_end = (context+1)*feature_dim input[{ {slice_begin, slice_end} }] = context_features_tensor end end -- Evaluate this frame local output_probs = model:forward(input) -- Update utterance-level stats if utt ~= current_utterance then -- Create new entry current_utterance = utt print("UTTERANCE " .. current_utterance .. " WITH LABEL " .. label) end -- Print posteriors to our log --print("Frame " .. i .. " posteriors:" .. output_probs[lang2label["outofset"]] .. "," .. output_probs[lang2label["english"]] .. "," .. output_probs[lang2label["german"]] .. "," .. output_probs[lang2label["mandarin"]]) print("Frame " .. i .. " posteriors:" .. output_probs[1] .. "," .. output_probs[2] .. "," .. output_probs[3]) end
mit
m241dan/darkstar
scripts/zones/Meriphataud_Mountains/npcs/Mushosho.lua
13
1915
----------------------------------- -- Area: Meriphataud Mountains -- NPC: Mushosho -- Type: Outpost Vendor -- @pos -290 16 415 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Meriphataud_Mountains/TextIDs"); local region = ARAGONEU; local csid = 0x7ff4; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
santssoft/darkstar
scripts/zones/La_Theine_Plateau/npcs/Galaihaurat.lua
9
2205
----------------------------------- -- Area: La Theine Plateau -- NPC: Galaihaurat -- Involved in Mission: The Rescue Drill -- !pos -482 -7 222 102 ----------------------------------- require("scripts/globals/missions"); local ID = require("scripts/zones/La_Theine_Plateau/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.THE_RESCUE_DRILL) then local MissionStatus = player:getCharVar("MissionStatus"); if (MissionStatus == 0) then player:startEvent(110); elseif (MissionStatus == 2) then player:showText(npc, ID.text.RESCUE_DRILL + 16); elseif (MissionStatus == 8) then if (player:getCharVar("theRescueDrillRandomNPC") == 1) then player:startEvent(114); else player:showText(npc, ID.text.RESCUE_DRILL + 21); end elseif (MissionStatus == 9) then if (player:getCharVar("theRescueDrillRandomNPC") == 1) then player:showText(npc, ID.text.RESCUE_DRILL + 25); else player:showText(npc, ID.text.RESCUE_DRILL + 26); end elseif (MissionStatus >= 10) then player:showText(npc, ID.text.RESCUE_DRILL + 30); else player:showText(npc, ID.text.RESCUE_DRILL); end elseif (player:hasCompletedMission(SANDORIA,dsp.mission.id.sandoria.THE_RESCUE_DRILL)) then player:showText(npc, ID.text.RESCUE_DRILL + 30); else player:showText(npc, ID.text.RESCUE_DRILL); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 110) then player:setCharVar("MissionStatus",2); elseif (csid == 114) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,16535); -- Bronze Sword else player:addItem(16535); player:messageSpecial(ID.text.ITEM_OBTAINED, 16535); -- Bronze Sword player:setCharVar("MissionStatus",9); end end end;
gpl-3.0
videolan/vlc
share/lua/playlist/dailymotion.lua
1
4285
--[[ Translate Dailymotion video webpages URLs to corresponding video stream URLs. Copyright © 2007-2020 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return ( vlc.access == "http" or vlc.access == "https" ) and string.match( vlc.path, "^www%.dailymotion%.com/video/" ) end -- Parse function. function parse() while true do line = vlc.readline() if not line then break end if string.match( line, "<meta property=\"og:title\"" ) then _,_,name = string.find( line, "content=\"(.-)\"" ) name = vlc.strings.resolve_xml_special_chars( name ) name = string.gsub( name, " %- [^ ]+ [Dd]ailymotion$", "" ) end if string.match( line, "<meta name=\"description\"" ) then _,_,description = string.find( line, "content=\"(.-)\"" ) if (description ~= nil) then description = vlc.strings.resolve_xml_special_chars( description ) end end if string.match( line, "<meta property=\"og:image\"" ) then arturl = string.match( line, "content=\"(.-)\"" ) end end local video_id = string.match( vlc.path, "^www%.dailymotion%.com/video/([^/?#]+)" ) if video_id then local metadata = vlc.stream( vlc.access.."://www.dailymotion.com/player/metadata/video/"..video_id ) if metadata then local line = metadata:readline() -- data is on one line only -- TODO: fetch "title" and resolve \u escape sequences -- FIXME: use "screenname" instead and resolve \u escape sequences artist = string.match( line, '"username":"([^"]+)"' ) local poster = string.match( line, '"poster_url":"([^"]+)"' ) if poster then arturl = string.gsub( poster, "\\/", "/") end local streams = string.match( line, "\"qualities\":{(.-%])}" ) if streams then -- Most of this has become unused, as in practice Dailymotion -- has currently stopped offering progressive download and -- been offering only adaptive streaming for a while now. local prefres = vlc.var.inherit(nil, "preferred-resolution") local file = nil local live = nil for height,stream in string.gmatch( streams, "\"(%w+)\":%[(.-)%]" ) do -- Apparently formats are listed in increasing quality -- order, so we take the first, lowest quality as -- fallback, then pick the last one that matches. if string.match( height, "^(%d+)$" ) and ( ( not file ) or prefres < 0 or tonumber( height ) <= prefres ) then local f = string.match( stream, '"type":"video\\/[^"]+","url":"([^"]+)"' ) if f then file = f end end if not live then live = string.match( stream, '"type":"application\\/x%-mpegURL","url":"([^"]+)"' ) end end -- Pick live streaming only as a fallback path = file or live if path then path = string.gsub( path, "\\/", "/") end end end end if not path then vlc.msg.err("Couldn't extract dailymotion video URL, please check for updates to this script") return { } end return { { path = path; name = name; description = description; arturl = arturl; artist = artist } } end
gpl-2.0
PGower/google-diff-match-patch
lua/diff_match_patch.lua
265
73869
--[[ * Diff Match and Patch * * Copyright 2006 Google Inc. * http://code.google.com/p/google-diff-match-patch/ * * Based on the JavaScript implementation by Neil Fraser. * Ported to Lua by Duncan Cross. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. --]] --[[ -- Lua 5.1 and earlier requires the external BitOp library. -- This library is built-in from Lua 5.2 and later as 'bit32'. require 'bit' -- <http://bitop.luajit.org/> local band, bor, lshift = bit.band, bit.bor, bit.lshift --]] local band, bor, lshift = bit32.band, bit32.bor, bit32.lshift local type, setmetatable, ipairs, select = type, setmetatable, ipairs, select local unpack, tonumber, error = unpack, tonumber, error local strsub, strbyte, strchar, gmatch, gsub = string.sub, string.byte, string.char, string.gmatch, string.gsub local strmatch, strfind, strformat = string.match, string.find, string.format local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local max, min, floor, ceil, abs = math.max, math.min, math.floor, math.ceil, math.abs local clock = os.clock -- Utility functions. local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]' local function percentEncode_replace(v) return strformat('%%%02X', strbyte(v)) end local function tsplice(t, idx, deletions, ...) local insertions = select('#', ...) for i = 1, deletions do tremove(t, idx) end for i = insertions, 1, -1 do -- do not remove parentheses around select tinsert(t, idx, (select(i, ...))) end end local function strelement(str, i) return strsub(str, i, i) end local function indexOf(a, b, start) if (#b == 0) then return nil end return strfind(a, b, start, true) end local htmlEncode_pattern = '[&<>\n]' local htmlEncode_replace = { ['&'] = '&amp;', ['<'] = '&lt;', ['>'] = '&gt;', ['\n'] = '&para;<br>' } -- Public API Functions -- (Exported at the end of the script) local diff_main, diff_cleanupSemantic, diff_cleanupEfficiency, diff_levenshtein, diff_prettyHtml local match_main local patch_make, patch_toText, patch_fromText, patch_apply --[[ * The data structure representing a diff is an array of tuples: * {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}} * which means: delete 'Hello', add 'Goodbye' and keep ' world.' --]] local DIFF_DELETE = -1 local DIFF_INSERT = 1 local DIFF_EQUAL = 0 -- Number of seconds to map a diff before giving up (0 for infinity). local Diff_Timeout = 1.0 -- Cost of an empty edit operation in terms of edit characters. local Diff_EditCost = 4 -- At what point is no match declared (0.0 = perfection, 1.0 = very loose). local Match_Threshold = 0.5 -- How far to search for a match (0 = exact location, 1000+ = broad match). -- A match this many characters away from the expected location will add -- 1.0 to the score (0.0 is a perfect match). local Match_Distance = 1000 -- When deleting a large block of text (over ~64 characters), how close do -- the contents have to be to match the expected contents. (0.0 = perfection, -- 1.0 = very loose). Note that Match_Threshold controls how closely the -- end points of a delete need to match. local Patch_DeleteThreshold = 0.5 -- Chunk size for context length. local Patch_Margin = 4 -- The number of bits in an int. local Match_MaxBits = 32 function settings(new) if new then Diff_Timeout = new.Diff_Timeout or Diff_Timeout Diff_EditCost = new.Diff_EditCost or Diff_EditCost Match_Threshold = new.Match_Threshold or Match_Threshold Match_Distance = new.Match_Distance or Match_Distance Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold Patch_Margin = new.Patch_Margin or Patch_Margin Match_MaxBits = new.Match_MaxBits or Match_MaxBits else return { Diff_Timeout = Diff_Timeout; Diff_EditCost = Diff_EditCost; Match_Threshold = Match_Threshold; Match_Distance = Match_Distance; Patch_DeleteThreshold = Patch_DeleteThreshold; Patch_Margin = Patch_Margin; Match_MaxBits = Match_MaxBits; } end end -- --------------------------------------------------------------------------- -- DIFF API -- --------------------------------------------------------------------------- -- The private diff functions local _diff_compute, _diff_bisect, _diff_halfMatchI, _diff_halfMatch, _diff_cleanupSemanticScore, _diff_cleanupSemanticLossless, _diff_cleanupMerge, _diff_commonPrefix, _diff_commonSuffix, _diff_commonOverlap, _diff_xIndex, _diff_text1, _diff_text2, _diff_toDelta, _diff_fromDelta --[[ * Find the differences between two texts. Simplifies the problem by stripping * any common prefix or suffix off the texts before diffing. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} opt_checklines Has no effect in Lua. * @param {number} opt_deadline Optional time when the diff should be complete * by. Used internally for recursive calls. Users should set DiffTimeout * instead. * @return {Array.<Array.<number|string>>} Array of diff tuples. --]] function diff_main(text1, text2, opt_checklines, opt_deadline) -- Set a deadline by which time the diff must be complete. if opt_deadline == nil then if Diff_Timeout <= 0 then opt_deadline = 2 ^ 31 else opt_deadline = clock() + Diff_Timeout end end local deadline = opt_deadline -- Check for null inputs. if text1 == nil or text1 == nil then error('Null inputs. (diff_main)') end -- Check for equality (speedup). if text1 == text2 then if #text1 > 0 then return {{DIFF_EQUAL, text1}} end return {} end -- LUANOTE: Due to the lack of Unicode support, Lua is incapable of -- implementing the line-mode speedup. local checklines = false -- Trim off common prefix (speedup). local commonlength = _diff_commonPrefix(text1, text2) local commonprefix if commonlength > 0 then commonprefix = strsub(text1, 1, commonlength) text1 = strsub(text1, commonlength + 1) text2 = strsub(text2, commonlength + 1) end -- Trim off common suffix (speedup). commonlength = _diff_commonSuffix(text1, text2) local commonsuffix if commonlength > 0 then commonsuffix = strsub(text1, -commonlength) text1 = strsub(text1, 1, -commonlength - 1) text2 = strsub(text2, 1, -commonlength - 1) end -- Compute the diff on the middle block. local diffs = _diff_compute(text1, text2, checklines, deadline) -- Restore the prefix and suffix. if commonprefix then tinsert(diffs, 1, {DIFF_EQUAL, commonprefix}) end if commonsuffix then diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix} end _diff_cleanupMerge(diffs) return diffs end --[[ * Reduce the number of edits by eliminating semantically trivial equalities. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function diff_cleanupSemantic(diffs) local changes = false local equalities = {} -- Stack of indices where equalities are found. local equalitiesLength = 0 -- Keeping our own length var is faster. local lastequality = nil -- Always equal to diffs[equalities[equalitiesLength]][2] local pointer = 1 -- Index of current position. -- Number of characters that changed prior to the equality. local length_insertions1 = 0 local length_deletions1 = 0 -- Number of characters that changed after the equality. local length_insertions2 = 0 local length_deletions2 = 0 while diffs[pointer] do if diffs[pointer][1] == DIFF_EQUAL then -- Equality found. equalitiesLength = equalitiesLength + 1 equalities[equalitiesLength] = pointer length_insertions1 = length_insertions2 length_deletions1 = length_deletions2 length_insertions2 = 0 length_deletions2 = 0 lastequality = diffs[pointer][2] else -- An insertion or deletion. if diffs[pointer][1] == DIFF_INSERT then length_insertions2 = length_insertions2 + #(diffs[pointer][2]) else length_deletions2 = length_deletions2 + #(diffs[pointer][2]) end -- Eliminate an equality that is smaller or equal to the edits on both -- sides of it. if lastequality and (#lastequality <= max(length_insertions1, length_deletions1)) and (#lastequality <= max(length_insertions2, length_deletions2)) then -- Duplicate record. tinsert(diffs, equalities[equalitiesLength], {DIFF_DELETE, lastequality}) -- Change second copy to insert. diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT -- Throw away the equality we just deleted. equalitiesLength = equalitiesLength - 1 -- Throw away the previous equality (it needs to be reevaluated). equalitiesLength = equalitiesLength - 1 pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0 length_insertions1, length_deletions1 = 0, 0 -- Reset the counters. length_insertions2, length_deletions2 = 0, 0 lastequality = nil changes = true end end pointer = pointer + 1 end -- Normalize the diff. if changes then _diff_cleanupMerge(diffs) end _diff_cleanupSemanticLossless(diffs) -- Find any overlaps between deletions and insertions. -- e.g: <del>abcxxx</del><ins>xxxdef</ins> -- -> <del>abc</del>xxx<ins>def</ins> -- e.g: <del>xxxabc</del><ins>defxxx</ins> -- -> <ins>def</ins>xxx<del>abc</del> -- Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 2 while diffs[pointer] do if (diffs[pointer - 1][1] == DIFF_DELETE and diffs[pointer][1] == DIFF_INSERT) then local deletion = diffs[pointer - 1][2] local insertion = diffs[pointer][2] local overlap_length1 = _diff_commonOverlap(deletion, insertion) local overlap_length2 = _diff_commonOverlap(insertion, deletion) if (overlap_length1 >= overlap_length2) then if (overlap_length1 >= #deletion / 2 or overlap_length1 >= #insertion / 2) then -- Overlap found. Insert an equality and trim the surrounding edits. tinsert(diffs, pointer, {DIFF_EQUAL, strsub(insertion, 1, overlap_length1)}) diffs[pointer - 1][2] = strsub(deletion, 1, #deletion - overlap_length1) diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1) pointer = pointer + 1 end else if (overlap_length2 >= #deletion / 2 or overlap_length2 >= #insertion / 2) then -- Reverse overlap found. -- Insert an equality and swap and trim the surrounding edits. tinsert(diffs, pointer, {DIFF_EQUAL, strsub(deletion, 1, overlap_length2)}) diffs[pointer - 1] = {DIFF_INSERT, strsub(insertion, 1, #insertion - overlap_length2)} diffs[pointer + 1] = {DIFF_DELETE, strsub(deletion, overlap_length2 + 1)} pointer = pointer + 1 end end pointer = pointer + 1 end pointer = pointer + 1 end end --[[ * Reduce the number of edits by eliminating operationally trivial equalities. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function diff_cleanupEfficiency(diffs) local changes = false -- Stack of indices where equalities are found. local equalities = {} -- Keeping our own length var is faster. local equalitiesLength = 0 -- Always equal to diffs[equalities[equalitiesLength]][2] local lastequality = nil -- Index of current position. local pointer = 1 -- The following four are really booleans but are stored as numbers because -- they are used at one point like this: -- -- (pre_ins + pre_del + post_ins + post_del) == 3 -- -- ...i.e. checking that 3 of them are true and 1 of them is false. -- Is there an insertion operation before the last equality. local pre_ins = 0 -- Is there a deletion operation before the last equality. local pre_del = 0 -- Is there an insertion operation after the last equality. local post_ins = 0 -- Is there a deletion operation after the last equality. local post_del = 0 while diffs[pointer] do if diffs[pointer][1] == DIFF_EQUAL then -- Equality found. local diffText = diffs[pointer][2] if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then -- Candidate found. equalitiesLength = equalitiesLength + 1 equalities[equalitiesLength] = pointer pre_ins, pre_del = post_ins, post_del lastequality = diffText else -- Not a candidate, and can never become one. equalitiesLength = 0 lastequality = nil end post_ins, post_del = 0, 0 else -- An insertion or deletion. if diffs[pointer][1] == DIFF_DELETE then post_del = 1 else post_ins = 1 end --[[ * Five types to be split: * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> * <ins>A</ins>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<ins>C</ins> * <ins>A</del>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<del>C</del> --]] if lastequality and ( (pre_ins+pre_del+post_ins+post_del == 4) or ( (#lastequality < Diff_EditCost / 2) and (pre_ins+pre_del+post_ins+post_del == 3) )) then -- Duplicate record. tinsert(diffs, equalities[equalitiesLength], {DIFF_DELETE, lastequality}) -- Change second copy to insert. diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT -- Throw away the equality we just deleted. equalitiesLength = equalitiesLength - 1 lastequality = nil if (pre_ins == 1) and (pre_del == 1) then -- No changes made which could affect previous entry, keep going. post_ins, post_del = 1, 1 equalitiesLength = 0 else -- Throw away the previous equality. equalitiesLength = equalitiesLength - 1 pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0 post_ins, post_del = 0, 0 end changes = true end end pointer = pointer + 1 end if changes then _diff_cleanupMerge(diffs) end end --[[ * Compute the Levenshtein distance; the number of inserted, deleted or * substituted characters. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {number} Number of changes. --]] function diff_levenshtein(diffs) local levenshtein = 0 local insertions, deletions = 0, 0 for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if (op == DIFF_INSERT) then insertions = insertions + #data elseif (op == DIFF_DELETE) then deletions = deletions + #data elseif (op == DIFF_EQUAL) then -- A deletion and an insertion is one substitution. levenshtein = levenshtein + max(insertions, deletions) insertions = 0 deletions = 0 end end levenshtein = levenshtein + max(insertions, deletions) return levenshtein end --[[ * Convert a diff array into a pretty HTML report. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} HTML representation. --]] function diff_prettyHtml(diffs) local html = {} for x, diff in ipairs(diffs) do local op = diff[1] -- Operation (insert, delete, equal) local data = diff[2] -- Text of change. local text = gsub(data, htmlEncode_pattern, htmlEncode_replace) if op == DIFF_INSERT then html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>' elseif op == DIFF_DELETE then html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>' elseif op == DIFF_EQUAL then html[x] = '<span>' .. text .. '</span>' end end return tconcat(html) end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE DIFF FUNCTIONS -- --------------------------------------------------------------------------- --[[ * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} checklines Has no effect in Lua. * @param {number} deadline Time when the diff should be complete by. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_compute(text1, text2, checklines, deadline) if #text1 == 0 then -- Just add some text (speedup). return {{DIFF_INSERT, text2}} end if #text2 == 0 then -- Just delete some text (speedup). return {{DIFF_DELETE, text1}} end local diffs local longtext = (#text1 > #text2) and text1 or text2 local shorttext = (#text1 > #text2) and text2 or text1 local i = indexOf(longtext, shorttext) if i ~= nil then -- Shorter text is inside the longer text (speedup). diffs = { {DIFF_INSERT, strsub(longtext, 1, i - 1)}, {DIFF_EQUAL, shorttext}, {DIFF_INSERT, strsub(longtext, i + #shorttext)} } -- Swap insertions for deletions if diff is reversed. if #text1 > #text2 then diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE end return diffs end if #shorttext == 1 then -- Single character string. -- After the previous speedup, the character can't be an equality. return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}} end -- Check to see if the problem can be split in two. do local text1_a, text1_b, text2_a, text2_b, mid_common = _diff_halfMatch(text1, text2) if text1_a then -- A half-match was found, sort out the return data. -- Send both pairs off for separate processing. local diffs_a = diff_main(text1_a, text2_a, checklines, deadline) local diffs_b = diff_main(text1_b, text2_b, checklines, deadline) -- Merge the results. local diffs_a_len = #diffs_a diffs = diffs_a diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common} for i, b_diff in ipairs(diffs_b) do diffs[diffs_a_len + 1 + i] = b_diff end return diffs end end return _diff_bisect(text1, text2, deadline) end --[[ * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time at which to bail if not yet complete. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_bisect(text1, text2, deadline) -- Cache the text lengths to prevent multiple calls. local text1_length = #text1 local text2_length = #text2 local _sub, _element local max_d = ceil((text1_length + text2_length) / 2) local v_offset = max_d local v_length = 2 * max_d local v1 = {} local v2 = {} -- Setting all elements to -1 is faster in Lua than mixing integers and nil. for x = 0, v_length - 1 do v1[x] = -1 v2[x] = -1 end v1[v_offset + 1] = 0 v2[v_offset + 1] = 0 local delta = text1_length - text2_length -- If the total number of characters is odd, then -- the front path will collide with the reverse path. local front = (delta % 2 ~= 0) -- Offsets for start and end of k loop. -- Prevents mapping of space beyond the grid. local k1start = 0 local k1end = 0 local k2start = 0 local k2end = 0 for d = 0, max_d - 1 do -- Bail out if deadline is reached. if clock() > deadline then break end -- Walk the front path one step. for k1 = -d + k1start, d - k1end, 2 do local k1_offset = v_offset + k1 local x1 if (k1 == -d) or ((k1 ~= d) and (v1[k1_offset - 1] < v1[k1_offset + 1])) then x1 = v1[k1_offset + 1] else x1 = v1[k1_offset - 1] + 1 end local y1 = x1 - k1 while (x1 <= text1_length) and (y1 <= text2_length) and (strelement(text1, x1) == strelement(text2, y1)) do x1 = x1 + 1 y1 = y1 + 1 end v1[k1_offset] = x1 if x1 > text1_length + 1 then -- Ran off the right of the graph. k1end = k1end + 2 elseif y1 > text2_length + 1 then -- Ran off the bottom of the graph. k1start = k1start + 2 elseif front then local k2_offset = v_offset + delta - k1 if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then -- Mirror x2 onto top-left coordinate system. local x2 = text1_length - v2[k2_offset] + 1 if x1 > x2 then -- Overlap detected. return _diff_bisectSplit(text1, text2, x1, y1, deadline) end end end end -- Walk the reverse path one step. for k2 = -d + k2start, d - k2end, 2 do local k2_offset = v_offset + k2 local x2 if (k2 == -d) or ((k2 ~= d) and (v2[k2_offset - 1] < v2[k2_offset + 1])) then x2 = v2[k2_offset + 1] else x2 = v2[k2_offset - 1] + 1 end local y2 = x2 - k2 while (x2 <= text1_length) and (y2 <= text2_length) and (strelement(text1, -x2) == strelement(text2, -y2)) do x2 = x2 + 1 y2 = y2 + 1 end v2[k2_offset] = x2 if x2 > text1_length + 1 then -- Ran off the left of the graph. k2end = k2end + 2 elseif y2 > text2_length + 1 then -- Ran off the top of the graph. k2start = k2start + 2 elseif not front then local k1_offset = v_offset + delta - k2 if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then local x1 = v1[k1_offset] local y1 = v_offset + x1 - k1_offset -- Mirror x2 onto top-left coordinate system. x2 = text1_length - x2 + 1 if x1 > x2 then -- Overlap detected. return _diff_bisectSplit(text1, text2, x1, y1, deadline) end end end end end -- Diff took too long and hit the deadline or -- number of diffs equals number of characters, no commonality at all. return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}} end --[[ * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @param {number} deadline Time at which to bail if not yet complete. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @private --]] function _diff_bisectSplit(text1, text2, x, y, deadline) local text1a = strsub(text1, 1, x - 1) local text2a = strsub(text2, 1, y - 1) local text1b = strsub(text1, x) local text2b = strsub(text2, y) -- Compute both diffs serially. local diffs = diff_main(text1a, text2a, false, deadline) local diffsb = diff_main(text1b, text2b, false, deadline) local diffs_len = #diffs for i, v in ipairs(diffsb) do diffs[diffs_len + i] = v end return diffs end --[[ * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. --]] function _diff_commonPrefix(text1, text2) -- Quick check for common null cases. if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1)) then return 0 end -- Binary search. -- Performance analysis: http://neil.fraser.name/news/2007/10/09/ local pointermin = 1 local pointermax = min(#text1, #text2) local pointermid = pointermax local pointerstart = 1 while (pointermin < pointermid) do if (strsub(text1, pointerstart, pointermid) == strsub(text2, pointerstart, pointermid)) then pointermin = pointermid pointerstart = pointermin else pointermax = pointermid end pointermid = floor(pointermin + (pointermax - pointermin) / 2) end return pointermid end --[[ * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. --]] function _diff_commonSuffix(text1, text2) -- Quick check for common null cases. if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, -1) ~= strbyte(text2, -1)) then return 0 end -- Binary search. -- Performance analysis: http://neil.fraser.name/news/2007/10/09/ local pointermin = 1 local pointermax = min(#text1, #text2) local pointermid = pointermax local pointerend = 1 while (pointermin < pointermid) do if (strsub(text1, -pointermid, -pointerend) == strsub(text2, -pointermid, -pointerend)) then pointermin = pointermid pointerend = pointermin else pointermax = pointermid end pointermid = floor(pointermin + (pointermax - pointermin) / 2) end return pointermid end --[[ * Determine if the suffix of one string is the prefix of another. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of the first * string and the start of the second string. * @private --]] function _diff_commonOverlap(text1, text2) -- Cache the text lengths to prevent multiple calls. local text1_length = #text1 local text2_length = #text2 -- Eliminate the null case. if text1_length == 0 or text2_length == 0 then return 0 end -- Truncate the longer string. if text1_length > text2_length then text1 = strsub(text1, text1_length - text2_length + 1) elseif text1_length < text2_length then text2 = strsub(text2, 1, text1_length) end local text_length = min(text1_length, text2_length) -- Quick check for the worst case. if text1 == text2 then return text_length end -- Start by looking for a single character match -- and increase length until no match is found. -- Performance analysis: http://neil.fraser.name/news/2010/11/04/ local best = 0 local length = 1 while true do local pattern = strsub(text1, text_length - length + 1) local found = strfind(text2, pattern, 1, true) if found == nil then return best end length = length + found - 1 if found == 1 or strsub(text1, text_length - length + 1) == strsub(text2, 1, length) then best = length length = length + 1 end end end --[[ * Does a substring of shorttext exist within longtext such that the substring * is at least half the length of longtext? * This speedup can produce non-minimal diffs. * Closure, but does not reference any external variables. * @param {string} longtext Longer string. * @param {string} shorttext Shorter string. * @param {number} i Start index of quarter length substring within longtext. * @return {?Array.<string>} Five element Array, containing the prefix of * longtext, the suffix of longtext, the prefix of shorttext, the suffix * of shorttext and the common middle. Or nil if there was no match. * @private --]] function _diff_halfMatchI(longtext, shorttext, i) -- Start with a 1/4 length substring at position i as a seed. local seed = strsub(longtext, i, i + floor(#longtext / 4)) local j = 0 -- LUANOTE: do not change to 1, was originally -1 local best_common = '' local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b while true do j = indexOf(shorttext, seed, j + 1) if (j == nil) then break end local prefixLength = _diff_commonPrefix(strsub(longtext, i), strsub(shorttext, j)) local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1), strsub(shorttext, 1, j - 1)) if #best_common < suffixLength + prefixLength then best_common = strsub(shorttext, j - suffixLength, j - 1) .. strsub(shorttext, j, j + prefixLength - 1) best_longtext_a = strsub(longtext, 1, i - suffixLength - 1) best_longtext_b = strsub(longtext, i + prefixLength) best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1) best_shorttext_b = strsub(shorttext, j + prefixLength) end end if #best_common * 2 >= #longtext then return {best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common} else return nil end end --[[ * Do the two texts share a substring which is at least half the length of the * longer text? * @param {string} text1 First string. * @param {string} text2 Second string. * @return {?Array.<string>} Five element Array, containing the prefix of * text1, the suffix of text1, the prefix of text2, the suffix of * text2 and the common middle. Or nil if there was no match. * @private --]] function _diff_halfMatch(text1, text2) if Diff_Timeout <= 0 then -- Don't risk returning a non-optimal diff if we have unlimited time. return nil end local longtext = (#text1 > #text2) and text1 or text2 local shorttext = (#text1 > #text2) and text2 or text1 if (#longtext < 4) or (#shorttext * 2 < #longtext) then return nil -- Pointless. end -- First check if the second quarter is the seed for a half-match. local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4)) -- Check again based on the third quarter. local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2)) local hm if not hm1 and not hm2 then return nil elseif not hm2 then hm = hm1 elseif not hm1 then hm = hm2 else -- Both matched. Select the longest. hm = (#hm1[5] > #hm2[5]) and hm1 or hm2 end -- A half-match was found, sort out the return data. local text1_a, text1_b, text2_a, text2_b if (#text1 > #text2) then text1_a, text1_b = hm[1], hm[2] text2_a, text2_b = hm[3], hm[4] else text2_a, text2_b = hm[1], hm[2] text1_a, text1_b = hm[3], hm[4] end local mid_common = hm[5] return text1_a, text1_b, text2_a, text2_b, mid_common end --[[ * Given two strings, compute a score representing whether the internal * boundary falls on logical boundaries. * Scores range from 6 (best) to 0 (worst). * @param {string} one First string. * @param {string} two Second string. * @return {number} The score. * @private --]] function _diff_cleanupSemanticScore(one, two) if (#one == 0) or (#two == 0) then -- Edges are the best. return 6 end -- Each port of this function behaves slightly differently due to -- subtle differences in each language's definition of things like -- 'whitespace'. Since this function's purpose is largely cosmetic, -- the choice has been made to use each language's native features -- rather than force total conformity. local char1 = strsub(one, -1) local char2 = strsub(two, 1, 1) local nonAlphaNumeric1 = strmatch(char1, '%W') local nonAlphaNumeric2 = strmatch(char2, '%W') local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s') local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s') local lineBreak1 = whitespace1 and strmatch(char1, '%c') local lineBreak2 = whitespace2 and strmatch(char2, '%c') local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$') local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n') if blankLine1 or blankLine2 then -- Five points for blank lines. return 5 elseif lineBreak1 or lineBreak2 then -- Four points for line breaks. return 4 elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then -- Three points for end of sentences. return 3 elseif whitespace1 or whitespace2 then -- Two points for whitespace. return 2 elseif nonAlphaNumeric1 or nonAlphaNumeric2 then -- One point for non-alphanumeric. return 1 end return 0 end --[[ * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function _diff_cleanupSemanticLossless(diffs) local pointer = 2 -- Intentionally ignore the first and last element (don't need checking). while diffs[pointer + 1] do local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1] if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then -- This is a single edit surrounded by equalities. local diff = diffs[pointer] local equality1 = prevDiff[2] local edit = diff[2] local equality2 = nextDiff[2] -- First, shift the edit as far left as possible. local commonOffset = _diff_commonSuffix(equality1, edit) if commonOffset > 0 then local commonString = strsub(edit, -commonOffset) equality1 = strsub(equality1, 1, -commonOffset - 1) edit = commonString .. strsub(edit, 1, -commonOffset - 1) equality2 = commonString .. equality2 end -- Second, step character by character right, looking for the best fit. local bestEquality1 = equality1 local bestEdit = edit local bestEquality2 = equality2 local bestScore = _diff_cleanupSemanticScore(equality1, edit) + _diff_cleanupSemanticScore(edit, equality2) while strbyte(edit, 1) == strbyte(equality2, 1) do equality1 = equality1 .. strsub(edit, 1, 1) edit = strsub(edit, 2) .. strsub(equality2, 1, 1) equality2 = strsub(equality2, 2) local score = _diff_cleanupSemanticScore(equality1, edit) + _diff_cleanupSemanticScore(edit, equality2) -- The >= encourages trailing rather than leading whitespace on edits. if score >= bestScore then bestScore = score bestEquality1 = equality1 bestEdit = edit bestEquality2 = equality2 end end if prevDiff[2] ~= bestEquality1 then -- We have an improvement, save it back to the diff. if #bestEquality1 > 0 then diffs[pointer - 1][2] = bestEquality1 else tremove(diffs, pointer - 1) pointer = pointer - 1 end diffs[pointer][2] = bestEdit if #bestEquality2 > 0 then diffs[pointer + 1][2] = bestEquality2 else tremove(diffs, pointer + 1, 1) pointer = pointer - 1 end end end pointer = pointer + 1 end end --[[ * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. --]] function _diff_cleanupMerge(diffs) diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end. local pointer = 1 local count_delete, count_insert = 0, 0 local text_delete, text_insert = '', '' local commonlength while diffs[pointer] do local diff_type = diffs[pointer][1] if diff_type == DIFF_INSERT then count_insert = count_insert + 1 text_insert = text_insert .. diffs[pointer][2] pointer = pointer + 1 elseif diff_type == DIFF_DELETE then count_delete = count_delete + 1 text_delete = text_delete .. diffs[pointer][2] pointer = pointer + 1 elseif diff_type == DIFF_EQUAL then -- Upon reaching an equality, check for prior redundancies. if count_delete + count_insert > 1 then if (count_delete > 0) and (count_insert > 0) then -- Factor out any common prefixies. commonlength = _diff_commonPrefix(text_insert, text_delete) if commonlength > 0 then local back_pointer = pointer - count_delete - count_insert if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL) then diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2] .. strsub(text_insert, 1, commonlength) else tinsert(diffs, 1, {DIFF_EQUAL, strsub(text_insert, 1, commonlength)}) pointer = pointer + 1 end text_insert = strsub(text_insert, commonlength + 1) text_delete = strsub(text_delete, commonlength + 1) end -- Factor out any common suffixies. commonlength = _diff_commonSuffix(text_insert, text_delete) if commonlength ~= 0 then diffs[pointer][2] = strsub(text_insert, -commonlength) .. diffs[pointer][2] text_insert = strsub(text_insert, 1, -commonlength - 1) text_delete = strsub(text_delete, 1, -commonlength - 1) end end -- Delete the offending records and add the merged ones. if count_delete == 0 then tsplice(diffs, pointer - count_insert, count_insert, {DIFF_INSERT, text_insert}) elseif count_insert == 0 then tsplice(diffs, pointer - count_delete, count_delete, {DIFF_DELETE, text_delete}) else tsplice(diffs, pointer - count_delete - count_insert, count_delete + count_insert, {DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert}) end pointer = pointer - count_delete - count_insert + (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1 elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then -- Merge this equality with the previous one. diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2] tremove(diffs, pointer) else pointer = pointer + 1 end count_insert, count_delete = 0, 0 text_delete, text_insert = '', '' end end if diffs[#diffs][2] == '' then diffs[#diffs] = nil -- Remove the dummy entry at the end. end -- Second pass: look for single edits surrounded on both sides by equalities -- which can be shifted sideways to eliminate an equality. -- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC local changes = false pointer = 2 -- Intentionally ignore the first and last element (don't need checking). while pointer < #diffs do local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1] if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then -- This is a single edit surrounded by equalities. local diff = diffs[pointer] local currentText = diff[2] local prevText = prevDiff[2] local nextText = nextDiff[2] if strsub(currentText, -#prevText) == prevText then -- Shift the edit over the previous equality. diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1) nextDiff[2] = prevText .. nextDiff[2] tremove(diffs, pointer - 1) changes = true elseif strsub(currentText, 1, #nextText) == nextText then -- Shift the edit over the next equality. prevDiff[2] = prevText .. nextText diff[2] = strsub(currentText, #nextText + 1) .. nextText tremove(diffs, pointer + 1) changes = true end end pointer = pointer + 1 end -- If shifts were made, the diff needs reordering and another shift sweep. if changes then -- LUANOTE: no return value, but necessary to use 'return' to get -- tail calls. return _diff_cleanupMerge(diffs) end end --[[ * loc is a location in text1, compute and return the equivalent location in * text2. * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @param {number} loc Location within text1. * @return {number} Location within text2. --]] function _diff_xIndex(diffs, loc) local chars1 = 1 local chars2 = 1 local last_chars1 = 1 local last_chars2 = 1 local x for _x, diff in ipairs(diffs) do x = _x if diff[1] ~= DIFF_INSERT then -- Equality or deletion. chars1 = chars1 + #diff[2] end if diff[1] ~= DIFF_DELETE then -- Equality or insertion. chars2 = chars2 + #diff[2] end if chars1 > loc then -- Overshot the location. break end last_chars1 = chars1 last_chars2 = chars2 end -- Was the location deleted? if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then return last_chars2 end -- Add the remaining character length. return last_chars2 + (loc - last_chars1) end --[[ * Compute and return the source text (all equalities and deletions). * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Source text. --]] function _diff_text1(diffs) local text = {} for x, diff in ipairs(diffs) do if diff[1] ~= DIFF_INSERT then text[#text + 1] = diff[2] end end return tconcat(text) end --[[ * Compute and return the destination text (all equalities and insertions). * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Destination text. --]] function _diff_text2(diffs) local text = {} for x, diff in ipairs(diffs) do if diff[1] ~= DIFF_DELETE then text[#text + 1] = diff[2] end end return tconcat(text) end --[[ * Crush the diff into an encoded string which describes the operations * required to transform text1 into text2. * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. * Operations are tab-separated. Inserted text is escaped using %xx notation. * @param {Array.<Array.<number|string>>} diffs Array of diff tuples. * @return {string} Delta text. --]] function _diff_toDelta(diffs) local text = {} for x, diff in ipairs(diffs) do local op, data = diff[1], diff[2] if op == DIFF_INSERT then text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace) elseif op == DIFF_DELETE then text[x] = '-' .. #data elseif op == DIFF_EQUAL then text[x] = '=' .. #data end end return tconcat(text, '\t') end --[[ * Given the original text1, and an encoded string which describes the * operations required to transform text1 into text2, compute the full diff. * @param {string} text1 Source string for the diff. * @param {string} delta Delta text. * @return {Array.<Array.<number|string>>} Array of diff tuples. * @throws {Errorend If invalid input. --]] function _diff_fromDelta(text1, delta) local diffs = {} local diffsLength = 0 -- Keeping our own length var is faster local pointer = 1 -- Cursor in text1 for token in gmatch(delta, '[^\t]+') do -- Each token begins with a one character parameter which specifies the -- operation of this token (delete, insert, equality). local tokenchar, param = strsub(token, 1, 1), strsub(token, 2) if (tokenchar == '+') then local invalidDecode = false local decoded = gsub(param, '%%(.?.?)', function(c) local n = tonumber(c, 16) if (#c ~= 2) or (n == nil) then invalidDecode = true return '' end return strchar(n) end) if invalidDecode then -- Malformed URI sequence. error('Illegal escape in _diff_fromDelta: ' .. param) end diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_INSERT, decoded} elseif (tokenchar == '-') or (tokenchar == '=') then local n = tonumber(param) if (n == nil) or (n < 0) then error('Invalid number in _diff_fromDelta: ' .. param) end local text = strsub(text1, pointer, pointer + n - 1) pointer = pointer + n if (tokenchar == '=') then diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_EQUAL, text} else diffsLength = diffsLength + 1 diffs[diffsLength] = {DIFF_DELETE, text} end else error('Invalid diff operation in _diff_fromDelta: ' .. token) end end if (pointer ~= #text1 + 1) then error('Delta length (' .. (pointer - 1) .. ') does not equal source text length (' .. #text1 .. ').') end return diffs end -- --------------------------------------------------------------------------- -- MATCH API -- --------------------------------------------------------------------------- local _match_bitap, _match_alphabet --[[ * Locate the best instance of 'pattern' in 'text' near 'loc'. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. --]] function match_main(text, pattern, loc) -- Check for null inputs. if text == nil or pattern == nil or loc == nil then error('Null inputs. (match_main)') end if text == pattern then -- Shortcut (potentially not guaranteed by the algorithm) return 1 elseif #text == 0 then -- Nothing to match. return -1 end loc = max(1, min(loc, #text)) if strsub(text, loc, loc + #pattern - 1) == pattern then -- Perfect match at the perfect spot! (Includes case of null pattern) return loc else -- Do a fuzzy compare. return _match_bitap(text, pattern, loc) end end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE MATCH FUNCTIONS -- --------------------------------------------------------------------------- --[[ * Initialise the alphabet for the Bitap algorithm. * @param {string} pattern The text to encode. * @return {Object} Hash of character locations. * @private --]] function _match_alphabet(pattern) local s = {} local i = 0 for c in gmatch(pattern, '.') do s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1)) i = i + 1 end return s end --[[ * Locate the best instance of 'pattern' in 'text' near 'loc' using the * Bitap algorithm. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. * @private --]] function _match_bitap(text, pattern, loc) if #pattern > Match_MaxBits then error('Pattern too long.') end -- Initialise the alphabet. local s = _match_alphabet(pattern) --[[ * Compute and return the score for a match with e errors and x location. * Accesses loc and pattern through being a closure. * @param {number} e Number of errors in match. * @param {number} x Location of match. * @return {number} Overall score for match (0.0 = good, 1.0 = bad). * @private --]] local function _match_bitapScore(e, x) local accuracy = e / #pattern local proximity = abs(loc - x) if (Match_Distance == 0) then -- Dodge divide by zero error. return (proximity == 0) and 1 or accuracy end return accuracy + (proximity / Match_Distance) end -- Highest score beyond which we give up. local score_threshold = Match_Threshold -- Is there a nearby exact match? (speedup) local best_loc = indexOf(text, pattern, loc) if best_loc then score_threshold = min(_match_bitapScore(0, best_loc), score_threshold) -- LUANOTE: Ideally we'd also check from the other direction, but Lua -- doesn't have an efficent lastIndexOf function. end -- Initialise the bit arrays. local matchmask = lshift(1, #pattern - 1) best_loc = -1 local bin_min, bin_mid local bin_max = #pattern + #text local last_rd for d = 0, #pattern - 1, 1 do -- Scan for the best match; each iteration allows for one more error. -- Run a binary search to determine how far from 'loc' we can stray at this -- error level. bin_min = 0 bin_mid = bin_max while (bin_min < bin_mid) do if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then bin_min = bin_mid else bin_max = bin_mid end bin_mid = floor(bin_min + (bin_max - bin_min) / 2) end -- Use the result from this iteration as the maximum for the next. bin_max = bin_mid local start = max(1, loc - bin_mid + 1) local finish = min(loc + bin_mid, #text) + #pattern local rd = {} for j = start, finish do rd[j] = 0 end rd[finish + 1] = lshift(1, d) - 1 for j = finish, start, -1 do local charMatch = s[strsub(text, j - 1, j - 1)] or 0 if (d == 0) then -- First pass: exact match. rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch) else -- Subsequent passes: fuzzy match. -- Functions instead of operators make this hella messy. rd[j] = bor( band( bor( lshift(rd[j + 1], 1), 1 ), charMatch ), bor( bor( lshift(bor(last_rd[j + 1], last_rd[j]), 1), 1 ), last_rd[j + 1] ) ) end if (band(rd[j], matchmask) ~= 0) then local score = _match_bitapScore(d, j - 1) -- This match will almost certainly be better than any existing match. -- But check anyway. if (score <= score_threshold) then -- Told you so. score_threshold = score best_loc = j - 1 if (best_loc > loc) then -- When passing loc, don't exceed our current distance from loc. start = max(1, loc * 2 - best_loc) else -- Already passed loc, downhill from here on in. break end end end end -- No hope for a (better) match at greater error levels. if (_match_bitapScore(d + 1, loc) > score_threshold) then break end last_rd = rd end return best_loc end -- ----------------------------------------------------------------------------- -- PATCH API -- ----------------------------------------------------------------------------- local _patch_addContext, _patch_deepCopy, _patch_addPadding, _patch_splitMax, _patch_appendText, _new_patch_obj --[[ * Compute a list of patches to turn text1 into text2. * Use diffs if provided, otherwise compute it ourselves. * There are four ways to call this function, depending on what data is * available to the caller: * Method 1: * a = text1, b = text2 * Method 2: * a = diffs * Method 3 (optimal): * a = text1, b = diffs * Method 4 (deprecated, use method 3): * a = text1, b = text2, c = diffs * * @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or * Array of diff tuples for text1 to text2 (method 2). * @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). * @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for * text1 to text2 (method 4) or undefined (methods 1,2,3). * @return {Array.<_new_patch_obj>} Array of patch objects. --]] function patch_make(a, opt_b, opt_c) local text1, diffs local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c) if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then -- Method 1: text1, text2 -- Compute diffs from text1 and text2. text1 = a diffs = diff_main(text1, opt_b, true) if (#diffs > 2) then diff_cleanupSemantic(diffs) diff_cleanupEfficiency(diffs) end elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then -- Method 2: diffs -- Compute text1 from diffs. diffs = a text1 = _diff_text1(diffs) elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then -- Method 3: text1, diffs text1 = a diffs = opt_b elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table') then -- Method 4: text1, text2, diffs -- text2 is not used. text1 = a diffs = opt_c else error('Unknown call format to patch_make.') end if (diffs[1] == nil) then return {} -- Get rid of the null case. end local patches = {} local patch = _new_patch_obj() local patchDiffLength = 0 -- Keeping our own length var is faster. local char_count1 = 0 -- Number of characters into the text1 string. local char_count2 = 0 -- Number of characters into the text2 string. -- Start with text1 (prepatch_text) and apply the diffs until we arrive at -- text2 (postpatch_text). We recreate the patches one by one to determine -- context info. local prepatch_text, postpatch_text = text1, text1 for x, diff in ipairs(diffs) do local diff_type, diff_text = diff[1], diff[2] if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then -- A new patch starts here. patch.start1 = char_count1 + 1 patch.start2 = char_count2 + 1 end if (diff_type == DIFF_INSERT) then patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff patch.length2 = patch.length2 + #diff_text postpatch_text = strsub(postpatch_text, 1, char_count2) .. diff_text .. strsub(postpatch_text, char_count2 + 1) elseif (diff_type == DIFF_DELETE) then patch.length1 = patch.length1 + #diff_text patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff postpatch_text = strsub(postpatch_text, 1, char_count2) .. strsub(postpatch_text, char_count2 + #diff_text + 1) elseif (diff_type == DIFF_EQUAL) then if (#diff_text <= Patch_Margin * 2) and (patchDiffLength ~= 0) and (#diffs ~= x) then -- Small equality inside a patch. patchDiffLength = patchDiffLength + 1 patch.diffs[patchDiffLength] = diff patch.length1 = patch.length1 + #diff_text patch.length2 = patch.length2 + #diff_text elseif (#diff_text >= Patch_Margin * 2) then -- Time for a new patch. if (patchDiffLength ~= 0) then _patch_addContext(patch, prepatch_text) patches[#patches + 1] = patch patch = _new_patch_obj() patchDiffLength = 0 -- Unlike Unidiff, our patch lists have a rolling context. -- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff -- Update prepatch text & pos to reflect the application of the -- just completed patch. prepatch_text = postpatch_text char_count1 = char_count2 end end end -- Update the current character count. if (diff_type ~= DIFF_INSERT) then char_count1 = char_count1 + #diff_text end if (diff_type ~= DIFF_DELETE) then char_count2 = char_count2 + #diff_text end end -- Pick up the leftover patch if not empty. if (patchDiffLength > 0) then _patch_addContext(patch, prepatch_text) patches[#patches + 1] = patch end return patches end --[[ * Merge a set of patches onto the text. Return a patched text, as well * as a list of true/false values indicating which patches were applied. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @param {string} text Old text. * @return {Array.<string|Array.<boolean>>} Two return values, the * new text and an array of boolean values. --]] function patch_apply(patches, text) if patches[1] == nil then return text, {} end -- Deep copy the patches so that no changes are made to originals. patches = _patch_deepCopy(patches) local nullPadding = _patch_addPadding(patches) text = nullPadding .. text .. nullPadding _patch_splitMax(patches) -- delta keeps track of the offset between the expected and actual location -- of the previous patch. If there are patches expected at positions 10 and -- 20, but the first patch was found at 12, delta is 2 and the second patch -- has an effective expected position of 22. local delta = 0 local results = {} for x, patch in ipairs(patches) do local expected_loc = patch.start2 + delta local text1 = _diff_text1(patch.diffs) local start_loc local end_loc = -1 if #text1 > Match_MaxBits then -- _patch_splitMax will only provide an oversized pattern in -- the case of a monster delete. start_loc = match_main(text, strsub(text1, 1, Match_MaxBits), expected_loc) if start_loc ~= -1 then end_loc = match_main(text, strsub(text1, -Match_MaxBits), expected_loc + #text1 - Match_MaxBits) if end_loc == -1 or start_loc >= end_loc then -- Can't find valid trailing context. Drop this patch. start_loc = -1 end end else start_loc = match_main(text, text1, expected_loc) end if start_loc == -1 then -- No match found. :( results[x] = false -- Subtract the delta for this failed patch from subsequent patches. delta = delta - patch.length2 - patch.length1 else -- Found a match. :) results[x] = true delta = start_loc - expected_loc local text2 if end_loc == -1 then text2 = strsub(text, start_loc, start_loc + #text1 - 1) else text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1) end if text1 == text2 then -- Perfect match, just shove the replacement text in. text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs) .. strsub(text, start_loc + #text1) else -- Imperfect match. Run a diff to get a framework of equivalent -- indices. local diffs = diff_main(text1, text2, false) if (#text1 > Match_MaxBits) and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then -- The end points match, but the content is unacceptably bad. results[x] = false else _diff_cleanupSemanticLossless(diffs) local index1 = 1 local index2 for y, mod in ipairs(patch.diffs) do if mod[1] ~= DIFF_EQUAL then index2 = _diff_xIndex(diffs, index1) end if mod[1] == DIFF_INSERT then text = strsub(text, 1, start_loc + index2 - 2) .. mod[2] .. strsub(text, start_loc + index2 - 1) elseif mod[1] == DIFF_DELETE then text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text, start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1)) end if mod[1] ~= DIFF_DELETE then index1 = index1 + #mod[2] end end end end end end -- Strip the padding off. text = strsub(text, #nullPadding + 1, -#nullPadding - 1) return text, results end --[[ * Take a list of patches and return a textual representation. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {string} Text representation of patches. --]] function patch_toText(patches) local text = {} for x, patch in ipairs(patches) do _patch_appendText(patch, text) end return tconcat(text) end --[[ * Parse a textual representation of patches and return a list of patch objects. * @param {string} textline Text representation of patches. * @return {Array.<_new_patch_obj>} Array of patch objects. * @throws {Error} If invalid input. --]] function patch_fromText(textline) local patches = {} if (#textline == 0) then return patches end local text = {} for line in gmatch(textline, '([^\n]*)') do text[#text + 1] = line end local textPointer = 1 while (textPointer <= #text) do local start1, length1, start2, length2 = strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$') if (start1 == nil) then error('Invalid patch string: "' .. text[textPointer] .. '"') end local patch = _new_patch_obj() patches[#patches + 1] = patch start1 = tonumber(start1) length1 = tonumber(length1) or 1 if (length1 == 0) then start1 = start1 + 1 end patch.start1 = start1 patch.length1 = length1 start2 = tonumber(start2) length2 = tonumber(length2) or 1 if (length2 == 0) then start2 = start2 + 1 end patch.start2 = start2 patch.length2 = length2 textPointer = textPointer + 1 while true do local line = text[textPointer] if (line == nil) then break end local sign; sign, line = strsub(line, 1, 1), strsub(line, 2) local invalidDecode = false local decoded = gsub(line, '%%(.?.?)', function(c) local n = tonumber(c, 16) if (#c ~= 2) or (n == nil) then invalidDecode = true return '' end return strchar(n) end) if invalidDecode then -- Malformed URI sequence. error('Illegal escape in patch_fromText: ' .. line) end line = decoded if (sign == '-') then -- Deletion. patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line} elseif (sign == '+') then -- Insertion. patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line} elseif (sign == ' ') then -- Minor equality. patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line} elseif (sign == '@') then -- Start of next patch. break elseif (sign == '') then -- Blank line? Whatever. else -- WTF? error('Invalid patch mode "' .. sign .. '" in: ' .. line) end textPointer = textPointer + 1 end end return patches end -- --------------------------------------------------------------------------- -- UNOFFICIAL/PRIVATE PATCH FUNCTIONS -- --------------------------------------------------------------------------- local patch_meta = { __tostring = function(patch) local buf = {} _patch_appendText(patch, buf) return tconcat(buf) end } --[[ * Class representing one patch operation. * @constructor --]] function _new_patch_obj() return setmetatable({ --[[ @type {Array.<Array.<number|string>>} ]] diffs = {}; --[[ @type {?number} ]] start1 = 1; -- nil; --[[ @type {?number} ]] start2 = 1; -- nil; --[[ @type {number} ]] length1 = 0; --[[ @type {number} ]] length2 = 0; }, patch_meta) end --[[ * Increase the context until it is unique, * but don't let the pattern expand beyond Match_MaxBits. * @param {_new_patch_obj} patch The patch to grow. * @param {string} text Source text. * @private --]] function _patch_addContext(patch, text) if (#text == 0) then return end local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1) local padding = 0 -- LUANOTE: Lua's lack of a lastIndexOf function results in slightly -- different logic here than in other language ports. -- Look for the first two matches of pattern in text. If two are found, -- increase the pattern length. local firstMatch = indexOf(text, pattern) local secondMatch = nil if (firstMatch ~= nil) then secondMatch = indexOf(text, pattern, firstMatch + 1) end while (#pattern == 0 or secondMatch ~= nil) and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do padding = padding + Patch_Margin pattern = strsub(text, max(1, patch.start2 - padding), patch.start2 + patch.length1 - 1 + padding) firstMatch = indexOf(text, pattern) if (firstMatch ~= nil) then secondMatch = indexOf(text, pattern, firstMatch + 1) else secondMatch = nil end end -- Add one chunk for good luck. padding = padding + Patch_Margin -- Add the prefix. local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1) if (#prefix > 0) then tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix}) end -- Add the suffix. local suffix = strsub(text, patch.start2 + patch.length1, patch.start2 + patch.length1 - 1 + padding) if (#suffix > 0) then patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix} end -- Roll back the start points. patch.start1 = patch.start1 - #prefix patch.start2 = patch.start2 - #prefix -- Extend the lengths. patch.length1 = patch.length1 + #prefix + #suffix patch.length2 = patch.length2 + #prefix + #suffix end --[[ * Given an array of patches, return another array that is identical. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {Array.<_new_patch_obj>} Array of patch objects. --]] function _patch_deepCopy(patches) local patchesCopy = {} for x, patch in ipairs(patches) do local patchCopy = _new_patch_obj() local diffsCopy = {} for i, diff in ipairs(patch.diffs) do diffsCopy[i] = {diff[1], diff[2]} end patchCopy.diffs = diffsCopy patchCopy.start1 = patch.start1 patchCopy.start2 = patch.start2 patchCopy.length1 = patch.length1 patchCopy.length2 = patch.length2 patchesCopy[x] = patchCopy end return patchesCopy end --[[ * Add some padding on text start and end so that edges can match something. * Intended to be called only from within patch_apply. * @param {Array.<_new_patch_obj>} patches Array of patch objects. * @return {string} The padding string added to each side. --]] function _patch_addPadding(patches) local paddingLength = Patch_Margin local nullPadding = '' for x = 1, paddingLength do nullPadding = nullPadding .. strchar(x) end -- Bump all the patches forward. for x, patch in ipairs(patches) do patch.start1 = patch.start1 + paddingLength patch.start2 = patch.start2 + paddingLength end -- Add some padding on start of first diff. local patch = patches[1] local diffs = patch.diffs local firstDiff = diffs[1] if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then -- Add nullPadding equality. tinsert(diffs, 1, {DIFF_EQUAL, nullPadding}) patch.start1 = patch.start1 - paddingLength -- Should be 0. patch.start2 = patch.start2 - paddingLength -- Should be 0. patch.length1 = patch.length1 + paddingLength patch.length2 = patch.length2 + paddingLength elseif (paddingLength > #firstDiff[2]) then -- Grow first equality. local extraLength = paddingLength - #firstDiff[2] firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2] patch.start1 = patch.start1 - extraLength patch.start2 = patch.start2 - extraLength patch.length1 = patch.length1 + extraLength patch.length2 = patch.length2 + extraLength end -- Add some padding on end of last diff. patch = patches[#patches] diffs = patch.diffs local lastDiff = diffs[#diffs] if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then -- Add nullPadding equality. diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding} patch.length1 = patch.length1 + paddingLength patch.length2 = patch.length2 + paddingLength elseif (paddingLength > #lastDiff[2]) then -- Grow last equality. local extraLength = paddingLength - #lastDiff[2] lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength) patch.length1 = patch.length1 + extraLength patch.length2 = patch.length2 + extraLength end return nullPadding end --[[ * Look through the patches and break up any which are longer than the maximum * limit of the match algorithm. * Intended to be called only from within patch_apply. * @param {Array.<_new_patch_obj>} patches Array of patch objects. --]] function _patch_splitMax(patches) local patch_size = Match_MaxBits local x = 1 while true do local patch = patches[x] if patch == nil then return end if patch.length1 > patch_size then local bigpatch = patch -- Remove the big old patch. tremove(patches, x) x = x - 1 local start1 = bigpatch.start1 local start2 = bigpatch.start2 local precontext = '' while bigpatch.diffs[1] do -- Create one of several smaller patches. local patch = _new_patch_obj() local empty = true patch.start1 = start1 - #precontext patch.start2 = start2 - #precontext if precontext ~= '' then patch.length1, patch.length2 = #precontext, #precontext patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext} end while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do local diff_type = bigpatch.diffs[1][1] local diff_text = bigpatch.diffs[1][2] if (diff_type == DIFF_INSERT) then -- Insertions are harmless. patch.length2 = patch.length2 + #diff_text start2 = start2 + #diff_text patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1] tremove(bigpatch.diffs, 1) empty = false elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1) and (patch.diffs[1][1] == DIFF_EQUAL) and (#diff_text > 2 * patch_size) then -- This is a large deletion. Let it pass in one chunk. patch.length1 = patch.length1 + #diff_text start1 = start1 + #diff_text empty = false patch.diffs[#patch.diffs + 1] = {diff_type, diff_text} tremove(bigpatch.diffs, 1) else -- Deletion or equality. -- Only take as much as we can stomach. diff_text = strsub(diff_text, 1, patch_size - patch.length1 - Patch_Margin) patch.length1 = patch.length1 + #diff_text start1 = start1 + #diff_text if (diff_type == DIFF_EQUAL) then patch.length2 = patch.length2 + #diff_text start2 = start2 + #diff_text else empty = false end patch.diffs[#patch.diffs + 1] = {diff_type, diff_text} if (diff_text == bigpatch.diffs[1][2]) then tremove(bigpatch.diffs, 1) else bigpatch.diffs[1][2] = strsub(bigpatch.diffs[1][2], #diff_text + 1) end end end -- Compute the head context for the next patch. precontext = _diff_text2(patch.diffs) precontext = strsub(precontext, -Patch_Margin) -- Append the end context for this patch. local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin) if postcontext ~= '' then patch.length1 = patch.length1 + #postcontext patch.length2 = patch.length2 + #postcontext if patch.diffs[1] and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2] .. postcontext else patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext} end end if not empty then x = x + 1 tinsert(patches, x, patch) end end end x = x + 1 end end --[[ * Emulate GNU diff's format. * Header: @@ -382,8 +481,9 @@ * @return {string} The GNU diff string. --]] function _patch_appendText(patch, text) local coords1, coords2 local length1, length2 = patch.length1, patch.length2 local start1, start2 = patch.start1, patch.start2 local diffs = patch.diffs if length1 == 1 then coords1 = start1 else coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1 end if length2 == 1 then coords2 = start2 else coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2 end text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n' local op -- Escape the body of the patch with %xx notation. for x, diff in ipairs(patch.diffs) do local diff_type = diff[1] if diff_type == DIFF_INSERT then op = '+' elseif diff_type == DIFF_DELETE then op = '-' elseif diff_type == DIFF_EQUAL then op = ' ' end text[#text + 1] = op .. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace) .. '\n' end return text end -- Expose the API local _M = {} _M.DIFF_DELETE = DIFF_DELETE _M.DIFF_INSERT = DIFF_INSERT _M.DIFF_EQUAL = DIFF_EQUAL _M.diff_main = diff_main _M.diff_cleanupSemantic = diff_cleanupSemantic _M.diff_cleanupEfficiency = diff_cleanupEfficiency _M.diff_levenshtein = diff_levenshtein _M.diff_prettyHtml = diff_prettyHtml _M.match_main = match_main _M.patch_make = patch_make _M.patch_toText = patch_toText _M.patch_fromText = patch_fromText _M.patch_apply = patch_apply -- Expose some non-API functions as well, for testing purposes etc. _M.diff_commonPrefix = _diff_commonPrefix _M.diff_commonSuffix = _diff_commonSuffix _M.diff_commonOverlap = _diff_commonOverlap _M.diff_halfMatch = _diff_halfMatch _M.diff_bisect = _diff_bisect _M.diff_cleanupMerge = _diff_cleanupMerge _M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless _M.diff_text1 = _diff_text1 _M.diff_text2 = _diff_text2 _M.diff_toDelta = _diff_toDelta _M.diff_fromDelta = _diff_fromDelta _M.diff_xIndex = _diff_xIndex _M.match_alphabet = _match_alphabet _M.match_bitap = _match_bitap _M.new_patch_obj = _new_patch_obj _M.patch_addContext = _patch_addContext _M.patch_splitMax = _patch_splitMax _M.patch_addPadding = _patch_addPadding _M.settings = settings return _M
apache-2.0
TeamDSN/TaxiCall
xml.lua
2
3667
module(..., package.seeall) --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- -- -- xml.lua - XML parser for use with the Corona SDK. -- -- version: 1.1 -- -- CHANGELOG: -- -- 1.1 - Fixed base directory issue with the loadFile() function. -- -- NOTE: This is a modified version of Alexander Makeev's Lua-only XML parser -- found here: http://lua-users.org/wiki/LuaXml -- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- function newParser() XmlParser = {}; function XmlParser:ToXmlString(value) value = string.gsub (value, "&", "&amp;"); -- '&' -> "&amp;" value = string.gsub (value, "<", "&lt;"); -- '<' -> "&lt;" value = string.gsub (value, ">", "&gt;"); -- '>' -> "&gt;" value = string.gsub (value, "\"", "&quot;"); -- '"' -> "&quot;" value = string.gsub(value, "([^%w%&%;%p%\t% ])", function (c) return string.format("&#x%X;", string.byte(c)) end); return value; end function XmlParser:FromXmlString(value) value = string.gsub(value, "&#x([%x]+)%;", function(h) return string.char(tonumber(h,16)) end); value = string.gsub(value, "&#([0-9]+)%;", function(h) return string.char(tonumber(h,10)) end); value = string.gsub (value, "&quot;", "\""); value = string.gsub (value, "&apos;", "'"); value = string.gsub (value, "&gt;", ">"); value = string.gsub (value, "&lt;", "<"); value = string.gsub (value, "&amp;", "&"); return value; end function XmlParser:ParseArgs(s) local arg = {} string.gsub(s, "(%w+)=([\"'])(.-)%2", function (w, _, a) arg[w] = self:FromXmlString(a); end) return arg end function XmlParser:ParseXmlText(xmlText) local stack = {} local top = {name=nil,value=nil,properties={},child={}} table.insert(stack, top) local ni,c,label,xarg, empty local i, j = 1, 1 while true do ni,j,c,label,xarg, empty = string.find(xmlText, "<(%/?)([%w:]+)(.-)(%/?)>", i) if not ni then break end local text = string.sub(xmlText, i, ni-1); if not string.find(text, "^%s*$") then top.value=(top.value or "")..self:FromXmlString(text); end if empty == "/" then -- empty element tag table.insert(top.child, {name=label,value=nil,properties=self:ParseArgs(xarg),child={}}) elseif c == "" then -- start tag top = {name=label, value=nil, properties=self:ParseArgs(xarg), child={}} table.insert(stack, top) -- new level else -- end tag local toclose = table.remove(stack) -- remove top top = stack[#stack] if #stack < 1 then error("XmlParser: nothing to close with "..label) end if toclose.name ~= label then error("XmlParser: trying to close "..toclose.name.." with "..label) end table.insert(top.child, toclose) end i = j+1 end local text = string.sub(xmlText, i); if not string.find(text, "^%s*$") then stack[#stack].value=(stack[#stack].value or "")..self:FromXmlString(text); end if #stack > 1 then error("XmlParser: unclosed "..stack[stack.n].name) end return stack[1].child[1]; end function XmlParser:loadFile(xmlFilename, base) if not base then base = system.ResourceDirectory end local path = system.pathForFile( xmlFilename, base ) local hFile, err = io.open(path,"r"); if hFile and not err then local xmlText=hFile:read("*a"); -- read file content io.close(hFile); return self:ParseXmlText(xmlText),nil; else print( err ) return nil end end return XmlParser end
gpl-2.0
dvr333/Zero-K
scripts/dynrecon.lua
4
18554
include "constants.lua" include "JumpRetreat.lua" local dyncomm = include('dynamicCommander.lua') _G.dyncomm = dyncomm -------------------------------------------------------------------------------- -- pieces -------------------------------------------------------------------------------- local base = piece 'base' local shield = piece 'shield' local pelvis = piece 'pelvis' local turret = piece 'turret' local torso = piece 'torso' local head = piece 'head' local armhold = piece 'armhold' local ruparm = piece 'ruparm' local rarm = piece 'rarm' local rloarm = piece 'rloarm' local luparm = piece 'luparm' local larm = piece 'larm' local lloarm = piece 'lloarm' local rupleg = piece 'rupleg' local lupleg = piece 'lupleg' local lloleg = piece 'lloleg' local rloleg = piece 'rloleg' local rfoot = piece 'rfoot' local lfoot = piece 'lfoot' local gun = piece 'gun' local flare = piece 'flare' local rsword = piece 'rsword' local lsword = piece 'lsword' local jet1 = piece 'jet1' local jet2 = piece 'jet2' local jx1 = piece 'jx1' local jx2 = piece 'jx2' local stab = piece 'stab' local nanospray = piece 'nanospray' local grenade = piece 'grenade' local smokePiece = {torso} local nanoPieces = {nanospray} local SPEED_MULT = 1 local sizeSpeedMult = 1 -------------------------------------------------------------------------------- -- constants -------------------------------------------------------------------------------- local SIG_RESTORE = 1 local SIG_AIM = 2 local SIG_AIM_2 = 4 --local SIG_AIM_3 = 8 --step on -------------------------------------------------------------------------------- -- vars -------------------------------------------------------------------------------- local restoreHeading, restorePitch = 0, 0 wepTable = nil local canDgun = UnitDefs[unitDefID].canDgun local dead = false local bMoving = false local bAiming = false local shieldOn = true local inJumpMode = false -------------------------------------------------------------------------------- -- funcs -------------------------------------------------------------------------------- local function BuildPose(heading, pitch) Turn(luparm, x_axis, math.rad(-60), math.rad(250)) Turn(luparm, y_axis, math.rad(-15), math.rad(250)) Turn(luparm, z_axis, math.rad(-10), math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) Turn(larm, y_axis, math.rad(-30), math.rad(250)) Turn(larm, z_axis, math.rad(26), math.rad(250)) Turn(lloarm, y_axis, math.rad(-37), math.rad(250)) Turn(lloarm, z_axis, math.rad(-152), math.rad(450)) Turn(turret, y_axis, heading, math.rad(350)) Turn(lloarm, x_axis, -pitch, math.rad(250)) end local function RestoreAfterDelay() Signal(SIG_RESTORE) SetSignalMask(SIG_RESTORE) Sleep(6000) if not dead then if GetUnitValue(COB.INBUILDSTANCE) == 1 then BuildPose(restoreHeading, restorePitch) else Turn(turret, x_axis, 0, math.rad(150)) Turn(turret, y_axis, 0, math.rad(150)) --torso Turn(torso, x_axis, 0, math.rad(250)) Turn(torso, y_axis, 0, math.rad(250)) Turn(torso, z_axis, 0, math.rad(250)) --head Turn(head, x_axis, 0, math.rad(250)) Turn(head, y_axis, 0, math.rad(250)) Turn(head, z_axis, 0, math.rad(250)) -- at ease pose Turn(armhold, x_axis, math.rad(-45), math.rad(250)) --upspring at -45 Turn(ruparm, x_axis, 0, math.rad(250)) Turn(ruparm, y_axis, 0, math.rad(250)) Turn(ruparm, z_axis, 0, math.rad(250)) Turn(rarm, x_axis, math.rad(2), math.rad(250)) --up 2 Turn(rarm, y_axis, 0, math.rad(250)) Turn(rarm, z_axis, math.rad(-(-12)), math.rad(250)) --up -12 Turn(rloarm, x_axis, math.rad(47), math.rad(250)) --up 47 Turn(rloarm, y_axis, math.rad(76), math.rad(250)) --up 76 Turn(rloarm, z_axis, math.rad(-(-47)), math.rad(250)) --up -47 Turn(luparm, x_axis, math.rad(-9), math.rad(250)) --up -9 Turn(luparm, y_axis, 0, math.rad(250)) Turn(luparm, z_axis, 0, math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) --up 5 Turn(larm, y_axis, math.rad(-3), math.rad(250)) --up -3 Turn(larm, z_axis, math.rad(-(22)), math.rad(250)) --up 22 Turn(lloarm, x_axis, math.rad(92), math.rad(250)) -- up 82 Turn(lloarm, y_axis, 0, math.rad(250)) Turn(lloarm, z_axis, math.rad(-(94)), math.rad(250)) --upspring 94 -- done at ease Sleep(100) end bAiming = false end end local function Walk() if not bAiming then Turn(torso, x_axis, math.rad(12) * sizeSpeedMult) --tilt forward Turn(torso, y_axis, math.rad(3.335165) * sizeSpeedMult) end Move(pelvis, y_axis, 0) Turn(rupleg, x_axis, math.rad(5.670330) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(-26.467033) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(26.967033) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(26.967033) * sizeSpeedMult) Turn(rfoot, x_axis, math.rad(-19.824176) * sizeSpeedMult) Sleep(90/sizeSpeedMult) --had to + 20 to all sleeps in walk if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(1.681319) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(-5.269231) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(-20.989011) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(20.945055) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(41.368132 * sizeSpeedMult)) Turn(rfoot, x_axis, math.rad(-15.747253) * sizeSpeedMult) Sleep(70/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, 0 * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(-9.071429) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(-12.670330) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(12.670330) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(43.571429) * sizeSpeedMult) Turn(rfoot, x_axis, math.rad(-12.016484) * sizeSpeedMult) Sleep(50/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(-1.77) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(-21.357143) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(2.824176) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(3.560440) * sizeSpeedMult) Turn(lfoot, x_axis, math.rad(-4.527473) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(52.505495) * sizeSpeedMult) Turn(rfoot, x_axis, 0) Sleep(40/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(-3.15) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(-35.923077) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(7.780220) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(8.203297) * sizeSpeedMult) Turn(lfoot, x_axis, math.rad(-12.571429) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(54.390110) * sizeSpeedMult) Sleep(50/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(-4.2) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(-37.780220) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(10.137363) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(13.302198) * sizeSpeedMult) Turn(lfoot, x_axis, math.rad(-16.714286) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(32.582418) * sizeSpeedMult) Sleep(50/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(-3.15) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(-28.758242) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(12.247253) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(19.659341) * sizeSpeedMult) Turn(lfoot, x_axis, math.rad(-19.659341) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(28.758242) * sizeSpeedMult) Sleep(90/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(-1.88) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(-22.824176) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(2.824176) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(34.060440) * sizeSpeedMult) Turn(rfoot, x_axis, math.rad(-6.313187) * sizeSpeedMult) Sleep(70/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, 0 * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(-11.604396) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(-6.725275) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(39.401099) * sizeSpeedMult) Turn(lfoot, x_axis, math.rad(-13.956044) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(19.005495) * sizeSpeedMult) Turn(rfoot, x_axis, math.rad(-7.615385) * sizeSpeedMult) Sleep(50/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(1.88) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(1.857143) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(-24.357143) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(45.093407) * sizeSpeedMult) Turn(lfoot, x_axis, math.rad(-7.703297) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(3.560440) * sizeSpeedMult) Turn(rfoot, x_axis, math.rad(-4.934066) * sizeSpeedMult) Sleep(40/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(3.15) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(7.148352) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(-28.181319) * sizeSpeedMult) Turn(rfoot, x_axis, math.rad(-9.813187) * sizeSpeedMult) Sleep(50/sizeSpeedMult) if not bMoving then return end if not bAiming then Turn(torso, y_axis, math.rad(4.2) * sizeSpeedMult) end Turn(rupleg, x_axis, math.rad(8.423077) * sizeSpeedMult) Turn(lupleg, x_axis, math.rad(-32.060440) * sizeSpeedMult) Turn(lloleg, x_axis, math.rad(27.527473) * sizeSpeedMult) Turn(lfoot, x_axis, math.rad(-2.857143) * sizeSpeedMult) Turn(rloleg, x_axis, math.rad(24.670330) * sizeSpeedMult) Turn(rfoot, x_axis, math.rad(-33.313187) * sizeSpeedMult) Sleep(70/sizeSpeedMult) end local function MotionControl() --for i = 1024, 1050 do -- Spring.Echo("Weapon", i) -- for j = 1, 12 do -- EmitSfx(flare, i) -- Sleep (100) -- end --end --for i = 1, 20 do -- local reloadTime = Spring.GetUnitWeaponState(unitID, i, "reloadTime") -- Spring.Echo("Weapon reload time", i, reloadTime) --end local moving, aiming local justmoved = true while true do moving = bMoving aiming = bAiming if moving then Walk() justmoved = true else if justmoved then Turn(rupleg, x_axis, 0, math.rad(200.071429) * sizeSpeedMult) Turn(rloleg, x_axis, 0, math.rad(200.071429) * sizeSpeedMult) Turn(rfoot, x_axis, 0, math.rad(200.071429) * sizeSpeedMult) Turn(lupleg, x_axis, 0, math.rad(200.071429) * sizeSpeedMult) Turn(lloleg, x_axis, 0, math.rad(200.071429) * sizeSpeedMult) Turn(lfoot, x_axis, 0, math.rad(200.071429) * sizeSpeedMult) if not aiming then Turn(torso, x_axis, 0) --untilt forward Turn(torso, y_axis, 0, math.rad(90.027473) * sizeSpeedMult) Turn(ruparm, x_axis, 0, math.rad(200.071429) * sizeSpeedMult) -- Turn(luparm, x_axis, 0, math.rad(200.071429)) end justmoved = false end Sleep(100) end end end function script.Create() dyncomm.Create() sizeSpeedMult = (1 - (1 - dyncomm.GetPace())/2.5) *SPEED_MULT --alert to dirt Turn(armhold, x_axis, math.rad(-45), math.rad(250)) --upspring at -45 Turn(ruparm, x_axis, 0, math.rad(250)) Turn(ruparm, y_axis, 0, math.rad(250)) Turn(ruparm, z_axis, 0, math.rad(250)) Turn(rarm, x_axis, math.rad(2), math.rad(250)) --up 2 Turn(rarm, y_axis, 0, math.rad(250)) Turn(rarm, z_axis, math.rad(-(-12)), math.rad(250)) --up -12 Turn(rloarm, x_axis, math.rad(47), math.rad(250)) --up 47 Turn(rloarm, y_axis, math.rad(76), math.rad(250)) --up 76 Turn(rloarm, z_axis, math.rad(-(-47)), math.rad(250)) --up -47 Turn(luparm, x_axis, math.rad(-9), math.rad(250)) --up -9 Turn(luparm, y_axis, 0, math.rad(250)) Turn(luparm, z_axis, 0, math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) --up 5 Turn(larm, y_axis, math.rad(-3), math.rad(250)) --up -3 Turn(larm, z_axis, math.rad(-(22)), math.rad(250)) --up 22 Turn(lloarm, x_axis, math.rad(92), math.rad(250)) -- up 82 Turn(lloarm, y_axis, 0, math.rad(250)) Turn(lloarm, z_axis, math.rad(-(94)), math.rad(250)) --upspring 94 Hide(flare) Hide(jx1) Hide(jx2) Hide(grenade) StartThread(MotionControl) StartThread(RestoreAfterDelay) StartThread(GG.Script.SmokeUnit, unitID, smokePiece) Spring.SetUnitNanoPieces(unitID, nanoPieces) end function script.StartMoving() bMoving = true end function script.StopMoving() bMoving = false end function script.AimFromWeapon(num) return pelvis end local function AimRifle(heading, pitch, isDgun) --torso Turn(torso, x_axis, math.rad(15), math.rad(250)) Turn(torso, y_axis, math.rad(-25), math.rad(250)) Turn(torso, z_axis, 0, math.rad(250)) --head Turn(head, x_axis, math.rad(-15), math.rad(250)) Turn(head, y_axis, math.rad(25), math.rad(250)) Turn(head, z_axis, 0, math.rad(250)) --rarm Turn(ruparm, x_axis, math.rad(-83), math.rad(250)) Turn(ruparm, y_axis, math.rad(30), math.rad(250)) Turn(ruparm, z_axis, math.rad(-(10)), math.rad(250)) Turn(rarm, x_axis, math.rad(41), math.rad(250)) Turn(rarm, y_axis, math.rad(19), math.rad(250)) Turn(rarm, z_axis, math.rad(-(-3)), math.rad(250)) Turn(rloarm, x_axis, math.rad(18), math.rad(250)) Turn(rloarm, y_axis, math.rad(19), math.rad(250)) Turn(rloarm, z_axis, math.rad(-(14)), math.rad(250)) Turn(gun, x_axis, math.rad(15.0), math.rad(250)) Turn(gun, y_axis, math.rad(-15.0), math.rad(250)) Turn(gun, z_axis, math.rad(31), math.rad(250)) --larm Turn(luparm, x_axis, math.rad(-80), math.rad(250)) Turn(luparm, y_axis, math.rad(-15), math.rad(250)) Turn(luparm, z_axis, math.rad(-10), math.rad(250)) Turn(larm, x_axis, math.rad(5), math.rad(250)) Turn(larm, y_axis, math.rad(-77), math.rad(250)) Turn(larm, z_axis, math.rad(-(-26)), math.rad(250)) Turn(lloarm, x_axis, math.rad(65), math.rad(250)) Turn(lloarm, y_axis, math.rad(-37), math.rad(250)) Turn(lloarm, z_axis, math.rad(-152), math.rad(450)) WaitForTurn(ruparm, x_axis) Turn(turret, y_axis, heading, math.rad(350)) Turn(armhold, x_axis, - pitch, math.rad(250)) WaitForTurn(turret, y_axis) WaitForTurn(armhold, x_axis) WaitForTurn(lloarm, z_axis) StartThread(RestoreAfterDelay) return true end function script.AimWeapon(num, heading, pitch) local weaponNum = dyncomm.GetWeapon(num) if weaponNum == 3 then -- shield return true end if weaponNum == 1 then Signal(SIG_AIM) SetSignalMask(SIG_AIM) elseif weaponNum == 2 then Signal(SIG_AIM_2) SetSignalMask(SIG_AIM_2) else return false end return AimRifle(heading, pitch, dyncomm.IsManualFire(num)) end function script.Activate() --spSetUnitShieldState(unitID, true) end function script.Deactivate() --spSetUnitShieldState(unitID, false) end local weaponFlares = { [1] = flare, [2] = flare, [3] = shield, } function script.QueryWeapon(num) return weaponFlares[dyncomm.GetWeapon(num) or 3] end function script.FireWeapon(num) dyncomm.EmitWeaponFireSfx(flare, num) end function script.Shot(num) dyncomm.EmitWeaponShotSfx(flare, num) end local function JumpExhaust() while inJumpMode do EmitSfx(jx1, 1028) EmitSfx(jx2, 1028) Sleep(33) end end function beginJump() script.StopMoving() GG.PokeDecloakUnit(unitID, unitDefID) inJumpMode = true --[[ StartThread(JumpExhaust) --]] end function jumping() GG.PokeDecloakUnit(unitID, unitDefID) EmitSfx(jx1, 1028) EmitSfx(jx2, 1028) end function endJump() script.StopMoving() inJumpMode = false EmitSfx(base, 1029) end function script.StopBuilding() SetUnitValue(COB.INBUILDSTANCE, 0) restoreHeading, restorePitch = 0, 0 if not bAiming then StartThread(RestoreAfterDelay) end end function script.StartBuilding(heading, pitch) --larm restoreHeading, restorePitch = heading, pitch BuildPose(heading, pitch) SetUnitValue(COB.INBUILDSTANCE, 1) restoreHeading, restorePitch = heading, pitch end function script.QueryNanoPiece() GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),nanospray) return nanospray end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth dead = true -- Turn(turret, y_axis, 0, math.rad(500)) if severity <= 0.5 and not inJumpMode then dyncomm.SpawnModuleWrecks(1) Turn(base, x_axis, math.rad(80), math.rad(80)) Turn(turret, x_axis, math.rad(-16), math.rad(50)) Turn(turret, y_axis, 0, math.rad(90)) Turn(rloleg, x_axis, math.rad(9), math.rad(250)) Turn(rloleg, y_axis, math.rad(-73), math.rad(250)) Turn(rloleg, z_axis, math.rad(-(3)), math.rad(250)) Turn(lupleg, x_axis, math.rad(7), math.rad(250)) Turn(lloleg, y_axis, math.rad(21), math.rad(250)) Turn(lfoot, x_axis, math.rad(24), math.rad(250)) GG.Script.InitializeDeathAnimation(unitID) Sleep(200) --give time to fall Turn(ruparm, x_axis, math.rad(-48), math.rad(350)) Turn(ruparm, y_axis, math.rad(32), math.rad(350)) --was -32 Turn(luparm, x_axis, math.rad(-50), math.rad(350)) Turn(luparm, y_axis, math.rad(47), math.rad(350)) Turn(luparm, z_axis, math.rad(-(50)), math.rad(350)) Sleep(600) EmitSfx(turret, 1027) --impact --StartThread(burn) --Sleep((1000 * rand (2, 5))) Sleep(100) dyncomm.SpawnWreck(1) elseif severity <= 0.5 then dyncomm.SpawnModuleWrecks(1) Explode(gun, SFX.FALL + SFX.SMOKE + SFX.EXPLODE) Explode(head, SFX.FIRE + SFX.EXPLODE) Explode(pelvis, SFX.FIRE + SFX.EXPLODE) Explode(lloarm, SFX.FIRE + SFX.EXPLODE) Explode(luparm, SFX.FIRE + SFX.EXPLODE) Explode(lloleg, SFX.FIRE + SFX.EXPLODE) Explode(lupleg, SFX.FIRE + SFX.EXPLODE) Explode(rloarm, SFX.FIRE + SFX.EXPLODE) Explode(rloleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(ruparm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(rupleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(torso, SFX.SHATTER + SFX.EXPLODE) dyncomm.SpawnWreck(1) else dyncomm.SpawnModuleWrecks(2) Explode(gun, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(head, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(pelvis, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(lloarm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(luparm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(lloleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(lupleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(rloarm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(rloleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(ruparm, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(rupleg, SFX.FALL + SFX.FIRE + SFX.SMOKE + SFX.EXPLODE) Explode(torso, SFX.SHATTER + SFX.EXPLODE) dyncomm.SpawnWreck(2) end end
gpl-2.0
m241dan/darkstar
scripts/zones/RuAun_Gardens/npcs/HomePoint#3.lua
27
1266
----------------------------------- -- Area: RuAun_Gardens -- NPC: HomePoint#3 -- @pos -312 -42 -422 130 ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/RuAun_Gardens/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 61); 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 == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
m241dan/darkstar
scripts/zones/Bastok_Mines/npcs/Explorer_Moogle.lua
13
1711
----------------------------------- -- Area: Bastok Mines -- NPC: Explorer Moogle -- ----------------------------------- 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 = 0x0249; 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 == 0x0249) 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
rekotc/game-engine-experimental-3
Source/GCC4/3rdParty/luaplus51-all/Src/Modules/wxLua/bindings/wxluasocket/wxluasocket_rules.lua
3
7859
-- ---------------------------------------------------------------------------- -- Rules to build wxWidgets' wxStyledTextCtrl binding for wxLua -- load using : $lua -e"rulesFilename=\"rules.lua\"" genwxbind.lua -- ---------------------------------------------------------------------------- -- ---------------------------------------------------------------------------- -- Set the root directory of the wxLua distribution, used only in this file wxlua_dir = "../" -- ============================================================================ -- Set the Lua namespace (Lua table) that the bindings will be placed into. -- See wxLuaBinding::GetLuaNamespace(); eg. wx.wxWindow(...) hook_lua_namespace = "wxlua" -- Set the unique C++ "namespace" for the bindings, not a real namespace, but -- a string used in declared C++ objects to prevent duplicate names. -- See wxLuaBinding::GetBindingName(). hook_cpp_namespace = "wxluasocket" -- ============================================================================ -- Set the directory to output the bindings to, both C++ header and source files output_cpp_header_filepath = wxlua_dir.."modules/wxluasocket/include" output_cpp_filepath = wxlua_dir.."modules/wxluasocket/src" -- ============================================================================ -- Set the DLLIMPEXP macros for compiling these bindings into a DLL -- Use "WXLUA_NO_DLLIMPEXP" and "WXLUA_NO_DLLIMPEXP_DATA" for no IMPEXP macros output_cpp_impexpsymbol = "WXDLLIMPEXP_WXLUASOCKET" output_cpp_impexpdatasymbol = "WXDLLIMPEXP_DATA_WXLUASOCKET" -- ---------------------------------------------------------------------------- -- Set the name of the header file that will have the #includes from the -- bindings in it. This will be used as #include "hook_cpp_header_filename" in -- the C++ wrapper files, so it must include the proper #include path. hook_cpp_header_filename = "wxluasocket/include/"..hook_cpp_namespace.."_bind.h" -- ---------------------------------------------------------------------------- -- Set the name of the main binding file that will have the glue code for the -- bindings in it. This file along with the output from the *.i files will be -- placed in the "output_cpp_filepath". hook_cpp_binding_filename = hook_cpp_namespace.."_bind.cpp" -- ---------------------------------------------------------------------------- -- Generate only a single output C++ binding source file with the name of -- hook_cpp_binding_filename, as opposed to generating a single cpp file -- for each *.i file plus the hook_cpp_binding_filename file. output_single_cpp_binding_file = true -- ---------------------------------------------------------------------------- -- Set the name of the subclassed wxLuaBinding class hook_cpp_binding_classname = "wxLuaBinding_"..hook_cpp_namespace -- ---------------------------------------------------------------------------- -- Set the function names that wrap the output structs of defined values, -- objects, events, functions, and classes. hook_cpp_define_funcname = "wxLuaGetDefineList_"..hook_cpp_namespace hook_cpp_string_funcname = "wxLuaGetStringList_"..hook_cpp_namespace hook_cpp_object_funcname = "wxLuaGetObjectList_"..hook_cpp_namespace hook_cpp_event_funcname = "wxLuaGetEventList_"..hook_cpp_namespace hook_cpp_function_funcname = "wxLuaGetFunctionList_"..hook_cpp_namespace hook_cpp_class_funcname = "wxLuaGetClassList_"..hook_cpp_namespace -- ---------------------------------------------------------------------------- -- Set any #includes or other C++ code to be placed verbatim at the top of -- every generated cpp file or "" for none hook_cpp_binding_includes = "" -- ---------------------------------------------------------------------------- -- Set any #includes or other C++ code to be placed verbatim below the -- #includes of every generated cpp file or "" for none hook_cpp_binding_post_includes = "" -- ---------------------------------------------------------------------------- -- Add additional include information or C++ code for the binding header file. -- This code will be place directly after any #includes at the top of the file hook_cpp_binding_header_includes = "#include \"wx/defs.h\"\n".. "#include \"wxluasocket/include/wxluasocketdefs.h\"\n".. "#include \"wxbind/include/wxcore_bind.h\"\n" -- ---------------------------------------------------------------------------- -- Set any #includes or other C++ code to be placed verbatim at the top of -- the single hook_cpp_binding_filename generated cpp file or "" for none hook_cpp_binding_source_includes = "" -- ============================================================================ -- Set the bindings directory that contains the *.i interface files interface_filepath = wxlua_dir.."bindings/wxluasocket" -- ---------------------------------------------------------------------------- -- A list of interface files to use to make the bindings. These files will be -- converted into *.cpp and placed in the output_cpp_filepath directory. -- The files are loaded from the interface_filepath. interface_fileTable = { "wxluasocket.i" } -- ---------------------------------------------------------------------------- -- A list of files that contain bindings that need to be overridden or empty -- table {} for none. -- The files are loaded from the interface_filepath. override_fileTable = { "override.hpp" } -- ============================================================================ -- A table containing filenames of XXX_datatype.lua from other wrappers to -- to define classes and data types used in this wrapper -- NOTE: for the base wxWidgets wrappers we don't load the cache since they -- don't depend on other wrappers and can cause problems when interface -- files are updated. Make sure you delete or have updated any cache file -- that changes any data types used by this binding. datatype_cache_input_fileTable = { wxlua_dir.."bindings/wxwidgets/wxcore_datatypes.lua" } -- ---------------------------------------------------------------------------- -- The file to output the data type cache for later use with a binding that -- makes use of data types (classes, enums, etc) that are declared in this -- binding. The file will be generated in the interface_filepath. datatypes_cache_output_filename = hook_cpp_namespace.."_datatypes.lua" -- ============================================================================ -- Declare functions or member variables for the derived wxLuaBinding class -- that will be generated for this binding. The string will be copied verbatim -- into the body of the hook_cpp_binding_classname class declaration in the -- hook_cpp_header_filename header file. May be remmed out to ignore it. -- See usage in the wxWidgets wxbase_rules.lua file. --wxLuaBinding_class_declaration = nothing to do here -- ---------------------------------------------------------------------------- -- Implement the functions or member variables for the derived wxLuaBinding -- class that you have declared. The string will be copied into the -- hook_cpp_binding_filename source file. May be remmed out to ignore it. -- See usage in the wxWidgets wxbase_rules.lua file. --wxLuaBinding_class_implementation = nothing to do here -- ============================================================================ -- Add additional conditions here -- example: conditions["DOXYGEN_INCLUDE"] = "defined(DOXYGEN_INCLUDE)" -- ---------------------------------------------------------------------------- -- Add additional data types here -- example: AllocDataType("wxArrayInt", "class",false) -- ============================================================================ -- Generate comments into binding C++ code comment_cpp_binding_code = true
lgpl-3.0
hylthink/Sample_Lua
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ClippingRectangleNode.lua
10
1311
-------------------------------- -- @module ClippingRectangleNode -- @extend Node -- @parent_module cc -------------------------------- -- -- @function [parent=#ClippingRectangleNode] isClippingEnabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ClippingRectangleNode] setClippingEnabled -- @param self -- @param #bool enabled -------------------------------- -- -- @function [parent=#ClippingRectangleNode] getClippingRegion -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- -- @function [parent=#ClippingRectangleNode] setClippingRegion -- @param self -- @param #rect_table clippingRegion -------------------------------- -- @overload self -- @overload self, rect_table -- @function [parent=#ClippingRectangleNode] create -- @param self -- @param #rect_table clippingRegion -- @return ClippingRectangleNode#ClippingRectangleNode ret (return value: cc.ClippingRectangleNode) -------------------------------- -- -- @function [parent=#ClippingRectangleNode] visit -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table parentTransform -- @param #unsigned int parentFlags return nil
mit
santssoft/darkstar
scripts/zones/Sacrificial_Chamber/bcnms/temple_of_uggalepih.lua
9
1885
----------------------------------- -- Temple of Uggalepih -- Balga's Dais Mission Battlefield ----------------------------------- local ID = require("scripts/zones/Sacrificial_Chamber/IDs") require("scripts/globals/battlefield") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/titles") ----------------------------------- 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) if csid == 32001 then player:addTitle(dsp.title.BEARER_OF_THE_WISEWOMANS_HOPE) if player:getCurrentMission(ZILART) == dsp.mission.id.zilart.THE_TEMPLE_OF_UGGALEPIH then player:startEvent(7) end elseif csid == 7 then player:startEvent(8) elseif csid == 8 and player:getCurrentMission(ZILART) == dsp.mission.id.zilart.THE_TEMPLE_OF_UGGALEPIH then player:delKeyItem(dsp.ki.SACRIFICIAL_CHAMBER_KEY) player:addKeyItem(dsp.ki.DARK_FRAGMENT) player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.DARK_FRAGMENT) player:completeMission(ZILART, dsp.mission.id.zilart.THE_TEMPLE_OF_UGGALEPIH) player:addMission(ZILART, dsp.mission.id.zilart.HEADSTONE_PILGRIMAGE) end end
gpl-3.0
palmettos/test
applications/luci-ahcp/luasrc/model/cbi/ahcp.lua
36
3895
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: init.lua 5764 2010-03-08 19:05:34Z jow $ ]]-- m = Map("ahcpd", translate("AHCP Server"), translate("AHCP is an autoconfiguration protocol " .. "for IPv6 and dual-stack IPv6/IPv4 networks designed to be used in place of router " .. "discovery or DHCP on networks where it is difficult or impossible to configure a " .. "server within every link-layer broadcast domain, for example mobile ad-hoc networks.")) m:section(SimpleSection).template = "ahcp_status" s = m:section(TypedSection, "ahcpd") s:tab("general", translate("General Setup")) s:tab("advanced", translate("Advanced Settings")) s.addremove = false s.anonymous = true mode = s:taboption("general", ListValue, "mode", translate("Operation mode")) mode:value("server", translate("Server")) mode:value("forwarder", translate("Forwarder")) net = s:taboption("general", Value, "interface", translate("Served interfaces")) net.template = "cbi/network_netlist" net.widget = "checkbox" net.nocreate = true function net.cfgvalue(self, section) return m.uci:get("ahcpd", section, "interface") end pfx = s:taboption("general", DynamicList, "prefix", translate("Announced prefixes"), translate("Specifies the announced IPv4 and IPv6 network prefixes in CIDR notation")) pfx.optional = true pfx.datatype = "ipaddr" pfx:depends("mode", "server") nss = s:taboption("general", DynamicList, "name_server", translate("Announced DNS servers"), translate("Specifies the announced IPv4 and IPv6 name servers")) nss.optional = true nss.datatype = "ipaddr" nss:depends("mode", "server") ntp = s:taboption("general", DynamicList, "ntp_server", translate("Announced NTP servers"), translate("Specifies the announced IPv4 and IPv6 NTP servers")) ntp.optional = true ntp.datatype = "ipaddr" ntp:depends("mode", "server") mca = s:taboption("general", Value, "multicast_address", translate("Multicast address")) mca.optional = true mca.placeholder = "ff02::cca6:c0f9:e182:5359" mca.datatype = "ip6addr" port = s:taboption("general", Value, "port", translate("Port")) port.optional = true port.placeholder = 5359 port.datatype = "port" fam = s:taboption("general", ListValue, "_family", translate("Protocol family")) fam:value("", translate("IPv4 and IPv6")) fam:value("ipv4", translate("IPv4 only")) fam:value("ipv6", translate("IPv6 only")) function fam.cfgvalue(self, section) local v4 = m.uci:get_bool("ahcpd", section, "ipv4_only") local v6 = m.uci:get_bool("ahcpd", section, "ipv6_only") if v4 then return "ipv4" elseif v6 then return "ipv6" end return "" end function fam.write(self, section, value) if value == "ipv4" then m.uci:set("ahcpd", section, "ipv4_only", "true") m.uci:delete("ahcpd", section, "ipv6_only") elseif value == "ipv6" then m.uci:set("ahcpd", section, "ipv6_only", "true") m.uci:delete("ahcpd", section, "ipv4_only") end end function fam.remove(self, section) m.uci:delete("ahcpd", section, "ipv4_only") m.uci:delete("ahcpd", section, "ipv6_only") end ltime = s:taboption("general", Value, "lease_time", translate("Lease validity time")) ltime.optional = true ltime.placeholder = 3666 ltime.datatype = "uinteger" ld = s:taboption("advanced", Value, "lease_dir", translate("Lease directory")) ld.datatype = "directory" ld.placeholder = "/var/lib/leases" id = s:taboption("advanced", Value, "id_file", translate("Unique ID file")) --id.datatype = "file" id.placeholder = "/var/lib/ahcpd-unique-id" log = s:taboption("advanced", Value, "log_file", translate("Log file")) --log.datatype = "file" log.placeholder = "/var/log/ahcpd.log" return m
apache-2.0
m241dan/darkstar
scripts/zones/Open_sea_route_to_Al_Zahbi/Zone.lua
13
1615
----------------------------------- -- -- Zone: Open_sea_route_to_Al_Zahbi (46) -- ----------------------------------- package.loaded["scripts/zones/Open_sea_route_to_Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Open_sea_route_to_Al_Zahbi/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then local position = math.random(-2,2) + 0.150; player:setPos(position,-2.100,3.250,64); end return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x0404); player:messageSpecial(DOCKING_IN_AL_ZAHBI); end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x0404) then player:setPos(0,0,0,0,50); end end;
gpl-3.0