repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
pazos/koreader
plugins/autosuspend.koplugin/main.lua
2
8480
local Device = require("device") if not Device:isCervantes() and not Device:isKobo() and not Device:isRemarkable() and not Device:isSDL() and not Device:isSonyPRSTUX() and not Device:isPocketBook() then return { disabled = true, } end local DataStorage = require("datastorage") local LuaSettings = require("luasettings") local PluginShare = require("pluginshare") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local logger = require("logger") local _ = require("gettext") local T = require("ffi/util").template local default_autoshutdown_timeout_seconds = 3*24*60*60 local AutoSuspend = WidgetContainer:new{ name = "autosuspend", is_doc_only = false, autoshutdown_timeout_seconds = G_reader_settings:readSetting("autoshutdown_timeout_seconds") or default_autoshutdown_timeout_seconds, settings = LuaSettings:open(DataStorage:getSettingsDir() .. "/koboautosuspend.lua"), last_action_sec = os.time(), standby_prevented = false, } function AutoSuspend:_readTimeoutSecFrom(settings) local sec = settings:readSetting("auto_suspend_timeout_seconds") if type(sec) == "number" then return sec end return -1 end function AutoSuspend:_readTimeoutSec() local candidates = { self.settings, G_reader_settings } for _, candidate in ipairs(candidates) do local sec = self:_readTimeoutSecFrom(candidate) if sec ~= -1 then return sec end end -- default setting is 60 minutes return 60 * 60 end function AutoSuspend:_enabled() return self.auto_suspend_sec > 0 end function AutoSuspend:_enabledShutdown() return Device:canPowerOff() and self.autoshutdown_timeout_seconds > 0 end function AutoSuspend:_schedule() if not self:_enabled() then logger.dbg("AutoSuspend:_schedule is disabled") return end local delay_suspend, delay_shutdown if PluginShare.pause_auto_suspend or Device.standby_prevented or Device.powerd:isCharging() then delay_suspend = self.auto_suspend_sec delay_shutdown = self.autoshutdown_timeout_seconds else local now_ts = os.time() delay_suspend = self.last_action_sec + self.auto_suspend_sec - now_ts delay_shutdown = self.last_action_sec + self.autoshutdown_timeout_seconds - now_ts end -- Try to shutdown first, as we may have been woken up from suspend just for the sole purpose of doing that. if delay_shutdown <= 0 then logger.dbg("AutoSuspend: initiating shutdown") UIManager:poweroff_action() elseif delay_suspend <= 0 then logger.dbg("AutoSuspend: will suspend the device") UIManager:suspend() else if self:_enabled() then logger.dbg("AutoSuspend: schedule suspend in", delay_suspend) UIManager:scheduleIn(delay_suspend, self._schedule, self) end if self:_enabledShutdown() then logger.dbg("AutoSuspend: schedule shutdown in", delay_shutdown) UIManager:scheduleIn(delay_shutdown, self._schedule, self) end end end function AutoSuspend:_unschedule() logger.dbg("AutoSuspend: unschedule") UIManager:unschedule(self._schedule) end function AutoSuspend:_start() if self:_enabled() or self:_enabledShutdown() then local now_ts = os.time() logger.dbg("AutoSuspend: start at", now_ts) self.last_action_sec = now_ts self:_schedule() end end function AutoSuspend:init() if Device:isPocketBook() and not Device:canSuspend() then return end UIManager.event_hook:registerWidget("InputEvent", self) self.auto_suspend_sec = self:_readTimeoutSec() self:_unschedule() self:_start() -- self.ui is nil in the testsuite if not self.ui or not self.ui.menu then return end self.ui.menu:registerToMainMenu(self) end function AutoSuspend:onInputEvent() logger.dbg("AutoSuspend: onInputEvent") self.last_action_sec = os.time() end function AutoSuspend:onSuspend() logger.dbg("AutoSuspend: onSuspend") -- We do not want auto suspend procedure to waste battery during suspend. So let's unschedule it -- when suspending and restart it after resume. self:_unschedule() if self:_enabledShutdown() and Device.wakeup_mgr then Device.wakeup_mgr:addTask(self.autoshutdown_timeout_seconds, UIManager.poweroff_action) end end function AutoSuspend:onResume() logger.dbg("AutoSuspend: onResume") if self:_enabledShutdown() and Device.wakeup_mgr then Device.wakeup_mgr:removeTask(nil, nil, UIManager.poweroff_action) end self:_start() end function AutoSuspend:onAllowStandby() self.standby_prevented = false end function AutoSuspend:onPreventStandby() self.standby_prevented = true end function AutoSuspend:addToMainMenu(menu_items) menu_items.autosuspend = { sorting_hint = "device", text = _("Autosuspend timeout"), callback = function() local InfoMessage = require("ui/widget/infomessage") local Screen = Device.screen local SpinWidget = require("ui/widget/spinwidget") local curr_items = G_reader_settings:readSetting("auto_suspend_timeout_seconds") or 60*60 local autosuspend_spin = SpinWidget:new { width = math.floor(Screen:getWidth() * 0.6), value = curr_items / 60, value_min = 5, value_max = 240, value_hold_step = 15, ok_text = _("Set timeout"), title_text = _("Timeout in minutes"), callback = function(autosuspend_spin) local autosuspend_timeout_seconds = autosuspend_spin.value * 60 self.auto_suspend_sec = autosuspend_timeout_seconds G_reader_settings:saveSetting("auto_suspend_timeout_seconds", autosuspend_timeout_seconds) UIManager:show(InfoMessage:new{ text = T(_("The system will automatically suspend after %1 minutes of inactivity."), string.format("%.2f", autosuspend_timeout_seconds/60)), timeout = 3, }) self:_unschedule() self:_start() end } UIManager:show(autosuspend_spin) end, } if not (Device:canPowerOff() or Device:isEmulator()) then return end menu_items.autoshutdown = { sorting_hint = "device", text = _("Autoshutdown timeout"), callback = function() local InfoMessage = require("ui/widget/infomessage") local Screen = Device.screen local SpinWidget = require("ui/widget/spinwidget") local curr_items = self.autoshutdown_timeout_seconds local autosuspend_spin = SpinWidget:new { width = math.floor(Screen:getWidth() * 0.6), value = curr_items / 60 / 60, -- About a minute, good for testing and battery life fanatics. -- Just high enough to avoid an instant shutdown death scenario. value_min = 0.017, -- More than three weeks seems a bit excessive if you want to enable authoshutdown, -- even if the battery can last up to three months. value_max = 28*24, value_hold_step = 24, precision = "%.2f", ok_text = _("Set timeout"), title_text = _("Timeout in hours"), callback = function(autosuspend_spin) local autoshutdown_timeout_seconds = math.floor(autosuspend_spin.value * 60*60) self.autoshutdown_timeout_seconds = autoshutdown_timeout_seconds G_reader_settings:saveSetting("autoshutdown_timeout_seconds", autoshutdown_timeout_seconds) UIManager:show(InfoMessage:new{ text = T(_("The system will automatically shut down after %1 hours of inactivity."), string.format("%.2f", autoshutdown_timeout_seconds/60/60)), timeout = 3, }) self:_unschedule() self:_start() end } UIManager:show(autosuspend_spin) end, } end return AutoSuspend
agpl-3.0
pecio/RBP-Broker
Common/AceDB-3.0/AceDB-3.0.lua
2
25843
--- **AceDB-3.0** manages the SavedVariables of your addon. -- It offers profile management, smart defaults and namespaces for modules.\\ -- Data can be saved in different data-types, depending on its intended usage. -- The most common data-type is the `profile` type, which allows the user to choose -- the active profile, and manage the profiles of all of his characters.\\ -- The following data types are available: -- * **char** Character-specific data. Every character has its own database. -- * **realm** Realm-specific data. All of the players characters on the same realm share this database. -- * **class** Class-specific data. All of the players characters of the same class share this database. -- * **race** Race-specific data. All of the players characters of the same race share this database. -- * **faction** Faction-specific data. All of the players characters of the same faction share this database. -- * **factionrealm** Faction and realm specific data. All of the players characters on the same realm and of the same faction share this database. -- * **locale** Locale specific data, based on the locale of the players game client. -- * **global** Global Data. All characters on the same account share this database. -- * **profile** Profile-specific data. All characters using the same profile share this database. The user can control which profile should be used. -- -- Creating a new Database using the `:New` function will return a new DBObject. A database will inherit all functions -- of the DBObjectLib listed here. \\ -- If you create a new namespaced child-database (`:RegisterNamespace`), you'll get a DBObject as well, but note -- that the child-databases cannot individually change their profile, and are linked to their parents profile - and because of that, -- the profile related APIs are not available. Only `:RegisterDefaults` and `:ResetProfile` are available on child-databases. -- -- For more details on how to use AceDB-3.0, see the [[AceDB-3.0 Tutorial]]. -- -- You may also be interested in [[libdualspec-1-0|LibDualSpec-1.0]] to do profile switching automatically when switching specs. -- -- @usage -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("DBExample") -- -- -- declare defaults to be used in the DB -- local defaults = { -- profile = { -- setting = true, -- } -- } -- -- function MyAddon:OnInitialize() -- -- Assuming the .toc says ## SavedVariables: MyAddonDB -- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true) -- end -- @class file -- @name AceDB-3.0.lua -- @release $Id: AceDB-3.0.lua 1217 2019-07-11 03:06:18Z funkydude $ local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 27 local AceDB = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR) if not AceDB then return end -- No upgrade needed -- Lua APIs local type, pairs, next, error = type, pairs, next, error local setmetatable, rawset, rawget = setmetatable, rawset, rawget -- WoW APIs local _G = _G -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: LibStub AceDB.db_registry = AceDB.db_registry or {} AceDB.frame = AceDB.frame or CreateFrame("Frame") local CallbackHandler local CallbackDummy = { Fire = function() end } local DBObjectLib = {} --[[------------------------------------------------------------------------- AceDB Utility Functions ---------------------------------------------------------------------------]] -- Simple shallow copy for copying defaults local function copyTable(src, dest) if type(dest) ~= "table" then dest = {} end if type(src) == "table" then for k,v in pairs(src) do if type(v) == "table" then -- try to index the key first so that the metatable creates the defaults, if set, and use that table v = copyTable(v, dest[k]) end dest[k] = v end end return dest end -- Called to add defaults to a section of the database -- -- When a ["*"] default section is indexed with a new key, a table is returned -- and set in the host table. These tables must be cleaned up by removeDefaults -- in order to ensure we don't write empty default tables. local function copyDefaults(dest, src) -- this happens if some value in the SV overwrites our default value with a non-table --if type(dest) ~= "table" then return end for k, v in pairs(src) do if k == "*" or k == "**" then if type(v) == "table" then -- This is a metatable used for table defaults local mt = { -- This handles the lookup and creation of new subtables __index = function(t,k) if k == nil then return nil end local tbl = {} copyDefaults(tbl, v) rawset(t, k, tbl) return tbl end, } setmetatable(dest, mt) -- handle already existing tables in the SV for dk, dv in pairs(dest) do if not rawget(src, dk) and type(dv) == "table" then copyDefaults(dv, v) end end else -- Values are not tables, so this is just a simple return local mt = {__index = function(t,k) return k~=nil and v or nil end} setmetatable(dest, mt) end elseif type(v) == "table" then if not rawget(dest, k) then rawset(dest, k, {}) end if type(dest[k]) == "table" then copyDefaults(dest[k], v) if src['**'] then copyDefaults(dest[k], src['**']) end end else if rawget(dest, k) == nil then rawset(dest, k, v) end end end end -- Called to remove all defaults in the default table from the database local function removeDefaults(db, defaults, blocker) -- remove all metatables from the db, so we don't accidentally create new sub-tables through them setmetatable(db, nil) -- loop through the defaults and remove their content for k,v in pairs(defaults) do if k == "*" or k == "**" then if type(v) == "table" then -- Loop through all the actual k,v pairs and remove for key, value in pairs(db) do if type(value) == "table" then -- if the key was not explicitly specified in the defaults table, just strip everything from * and ** tables if defaults[key] == nil and (not blocker or blocker[key] == nil) then removeDefaults(value, v) -- if the table is empty afterwards, remove it if next(value) == nil then db[key] = nil end -- if it was specified, only strip ** content, but block values which were set in the key table elseif k == "**" then removeDefaults(value, v, defaults[key]) end end end elseif k == "*" then -- check for non-table default for key, value in pairs(db) do if defaults[key] == nil and v == value then db[key] = nil end end end elseif type(v) == "table" and type(db[k]) == "table" then -- if a blocker was set, dive into it, to allow multi-level defaults removeDefaults(db[k], v, blocker and blocker[k]) if next(db[k]) == nil then db[k] = nil end else -- check if the current value matches the default, and that its not blocked by another defaults table if db[k] == defaults[k] and (not blocker or blocker[k] == nil) then db[k] = nil end end end end -- This is called when a table section is first accessed, to set up the defaults local function initSection(db, section, svstore, key, defaults) local sv = rawget(db, "sv") local tableCreated if not sv[svstore] then sv[svstore] = {} end if not sv[svstore][key] then sv[svstore][key] = {} tableCreated = true end local tbl = sv[svstore][key] if defaults then copyDefaults(tbl, defaults) end rawset(db, section, tbl) return tableCreated, tbl end -- Metatable to handle the dynamic creation of sections and copying of sections. local dbmt = { __index = function(t, section) local keys = rawget(t, "keys") local key = keys[section] if key then local defaultTbl = rawget(t, "defaults") local defaults = defaultTbl and defaultTbl[section] if section == "profile" then local new = initSection(t, section, "profiles", key, defaults) if new then -- Callback: OnNewProfile, database, newProfileKey t.callbacks:Fire("OnNewProfile", t, key) end elseif section == "profiles" then local sv = rawget(t, "sv") if not sv.profiles then sv.profiles = {} end rawset(t, "profiles", sv.profiles) elseif section == "global" then local sv = rawget(t, "sv") if not sv.global then sv.global = {} end if defaults then copyDefaults(sv.global, defaults) end rawset(t, section, sv.global) else initSection(t, section, section, key, defaults) end end return rawget(t, section) end } local function validateDefaults(defaults, keyTbl, offset) if not defaults then return end offset = offset or 0 for k in pairs(defaults) do if not keyTbl[k] or k == "profiles" then error(("Usage: AceDBObject:RegisterDefaults(defaults): '%s' is not a valid datatype."):format(k), 3 + offset) end end end local preserve_keys = { ["callbacks"] = true, ["RegisterCallback"] = true, ["UnregisterCallback"] = true, ["UnregisterAllCallbacks"] = true, ["children"] = true, } local realmKey = GetRealmName() local charKey = UnitName("player") .. " - " .. realmKey local _, classKey = UnitClass("player") local _, raceKey = UnitRace("player") local factionKey = UnitFactionGroup("player") local factionrealmKey = factionKey .. " - " .. realmKey local localeKey = GetLocale():lower() local regionTable = { "US", "KR", "EU", "TW", "CN" } local regionKey = regionTable[GetCurrentRegion()] local factionrealmregionKey = factionrealmKey .. " - " .. regionKey -- Actual database initialization function local function initdb(sv, defaults, defaultProfile, olddb, parent) -- Generate the database keys for each section -- map "true" to our "Default" profile if defaultProfile == true then defaultProfile = "Default" end local profileKey if not parent then -- Make a container for profile keys if not sv.profileKeys then sv.profileKeys = {} end -- Try to get the profile selected from the char db profileKey = sv.profileKeys[charKey] or defaultProfile or charKey -- save the selected profile for later sv.profileKeys[charKey] = profileKey else -- Use the profile of the parents DB profileKey = parent.keys.profile or defaultProfile or charKey -- clear the profileKeys in the DB, namespaces don't need to store them sv.profileKeys = nil end -- This table contains keys that enable the dynamic creation -- of each section of the table. The 'global' and 'profiles' -- have a key of true, since they are handled in a special case local keyTbl= { ["char"] = charKey, ["realm"] = realmKey, ["class"] = classKey, ["race"] = raceKey, ["faction"] = factionKey, ["factionrealm"] = factionrealmKey, ["factionrealmregion"] = factionrealmregionKey, ["profile"] = profileKey, ["locale"] = localeKey, ["global"] = true, ["profiles"] = true, } validateDefaults(defaults, keyTbl, 1) -- This allows us to use this function to reset an entire database -- Clear out the old database if olddb then for k,v in pairs(olddb) do if not preserve_keys[k] then olddb[k] = nil end end end -- Give this database the metatable so it initializes dynamically local db = setmetatable(olddb or {}, dbmt) if not rawget(db, "callbacks") then -- try to load CallbackHandler-1.0 if it loaded after our library if not CallbackHandler then CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0", true) end db.callbacks = CallbackHandler and CallbackHandler:New(db) or CallbackDummy end -- Copy methods locally into the database object, to avoid hitting -- the metatable when calling methods if not parent then for name, func in pairs(DBObjectLib) do db[name] = func end else -- hack this one in db.RegisterDefaults = DBObjectLib.RegisterDefaults db.ResetProfile = DBObjectLib.ResetProfile end -- Set some properties in the database object db.profiles = sv.profiles db.keys = keyTbl db.sv = sv --db.sv_name = name db.defaults = defaults db.parent = parent -- store the DB in the registry AceDB.db_registry[db] = true return db end -- handle PLAYER_LOGOUT -- strip all defaults from all databases -- and cleans up empty sections local function logoutHandler(frame, event) if event == "PLAYER_LOGOUT" then for db in pairs(AceDB.db_registry) do db.callbacks:Fire("OnDatabaseShutdown", db) db:RegisterDefaults(nil) -- cleanup sections that are empty without defaults local sv = rawget(db, "sv") for section in pairs(db.keys) do if rawget(sv, section) then -- global is special, all other sections have sub-entrys -- also don't delete empty profiles on main dbs, only on namespaces if section ~= "global" and (section ~= "profiles" or rawget(db, "parent")) then for key in pairs(sv[section]) do if not next(sv[section][key]) then sv[section][key] = nil end end end if not next(sv[section]) then sv[section] = nil end end end end end end AceDB.frame:RegisterEvent("PLAYER_LOGOUT") AceDB.frame:SetScript("OnEvent", logoutHandler) --[[------------------------------------------------------------------------- AceDB Object Method Definitions ---------------------------------------------------------------------------]] --- Sets the defaults table for the given database object by clearing any -- that are currently set, and then setting the new defaults. -- @param defaults A table of defaults for this database function DBObjectLib:RegisterDefaults(defaults) if defaults and type(defaults) ~= "table" then error(("Usage: AceDBObject:RegisterDefaults(defaults): 'defaults' - table or nil expected, got %q."):format(type(defaults)), 2) end validateDefaults(defaults, self.keys) -- Remove any currently set defaults if self.defaults then for section,key in pairs(self.keys) do if self.defaults[section] and rawget(self, section) then removeDefaults(self[section], self.defaults[section]) end end end -- Set the DBObject.defaults table self.defaults = defaults -- Copy in any defaults, only touching those sections already created if defaults then for section,key in pairs(self.keys) do if defaults[section] and rawget(self, section) then copyDefaults(self[section], defaults[section]) end end end end --- Changes the profile of the database and all of it's namespaces to the -- supplied named profile -- @param name The name of the profile to set as the current profile function DBObjectLib:SetProfile(name) if type(name) ~= "string" then error(("Usage: AceDBObject:SetProfile(name): 'name' - string expected, got %q."):format(type(name)), 2) end -- changing to the same profile, dont do anything if name == self.keys.profile then return end local oldProfile = self.profile local defaults = self.defaults and self.defaults.profile -- Callback: OnProfileShutdown, database self.callbacks:Fire("OnProfileShutdown", self) if oldProfile and defaults then -- Remove the defaults from the old profile removeDefaults(oldProfile, defaults) end self.profile = nil self.keys["profile"] = name -- if the storage exists, save the new profile -- this won't exist on namespaces. if self.sv.profileKeys then self.sv.profileKeys[charKey] = name end -- populate to child namespaces if self.children then for _, db in pairs(self.children) do DBObjectLib.SetProfile(db, name) end end -- Callback: OnProfileChanged, database, newProfileKey self.callbacks:Fire("OnProfileChanged", self, name) end --- Returns a table with the names of the existing profiles in the database. -- You can optionally supply a table to re-use for this purpose. -- @param tbl A table to store the profile names in (optional) function DBObjectLib:GetProfiles(tbl) if tbl and type(tbl) ~= "table" then error(("Usage: AceDBObject:GetProfiles(tbl): 'tbl' - table or nil expected, got %q."):format(type(tbl)), 2) end -- Clear the container table if tbl then for k,v in pairs(tbl) do tbl[k] = nil end else tbl = {} end local curProfile = self.keys.profile local i = 0 for profileKey in pairs(self.profiles) do i = i + 1 tbl[i] = profileKey if curProfile and profileKey == curProfile then curProfile = nil end end -- Add the current profile, if it hasn't been created yet if curProfile then i = i + 1 tbl[i] = curProfile end return tbl, i end --- Returns the current profile name used by the database function DBObjectLib:GetCurrentProfile() return self.keys.profile end --- Deletes a named profile. This profile must not be the active profile. -- @param name The name of the profile to be deleted -- @param silent If true, do not raise an error when the profile does not exist function DBObjectLib:DeleteProfile(name, silent) if type(name) ~= "string" then error(("Usage: AceDBObject:DeleteProfile(name): 'name' - string expected, got %q."):format(type(name)), 2) end if self.keys.profile == name then error(("Cannot delete the active profile (%q) in an AceDBObject."):format(name), 2) end if not rawget(self.profiles, name) and not silent then error(("Cannot delete profile %q as it does not exist."):format(name), 2) end self.profiles[name] = nil -- populate to child namespaces if self.children then for _, db in pairs(self.children) do DBObjectLib.DeleteProfile(db, name, true) end end -- switch all characters that use this profile back to the default if self.sv.profileKeys then for key, profile in pairs(self.sv.profileKeys) do if profile == name then self.sv.profileKeys[key] = nil end end end -- Callback: OnProfileDeleted, database, profileKey self.callbacks:Fire("OnProfileDeleted", self, name) end --- Copies a named profile into the current profile, overwriting any conflicting -- settings. -- @param name The name of the profile to be copied into the current profile -- @param silent If true, do not raise an error when the profile does not exist function DBObjectLib:CopyProfile(name, silent) if type(name) ~= "string" then error(("Usage: AceDBObject:CopyProfile(name): 'name' - string expected, got %q."):format(type(name)), 2) end if name == self.keys.profile then error(("Cannot have the same source and destination profiles (%q)."):format(name), 2) end if not rawget(self.profiles, name) and not silent then error(("Cannot copy profile %q as it does not exist."):format(name), 2) end -- Reset the profile before copying DBObjectLib.ResetProfile(self, nil, true) local profile = self.profile local source = self.profiles[name] copyTable(source, profile) -- populate to child namespaces if self.children then for _, db in pairs(self.children) do DBObjectLib.CopyProfile(db, name, true) end end -- Callback: OnProfileCopied, database, sourceProfileKey self.callbacks:Fire("OnProfileCopied", self, name) end --- Resets the current profile to the default values (if specified). -- @param noChildren if set to true, the reset will not be populated to the child namespaces of this DB object -- @param noCallbacks if set to true, won't fire the OnProfileReset callback function DBObjectLib:ResetProfile(noChildren, noCallbacks) local profile = self.profile for k,v in pairs(profile) do profile[k] = nil end local defaults = self.defaults and self.defaults.profile if defaults then copyDefaults(profile, defaults) end -- populate to child namespaces if self.children and not noChildren then for _, db in pairs(self.children) do DBObjectLib.ResetProfile(db, nil, noCallbacks) end end -- Callback: OnProfileReset, database if not noCallbacks then self.callbacks:Fire("OnProfileReset", self) end end --- Resets the entire database, using the string defaultProfile as the new default -- profile. -- @param defaultProfile The profile name to use as the default function DBObjectLib:ResetDB(defaultProfile) if defaultProfile and type(defaultProfile) ~= "string" then error(("Usage: AceDBObject:ResetDB(defaultProfile): 'defaultProfile' - string or nil expected, got %q."):format(type(defaultProfile)), 2) end local sv = self.sv for k,v in pairs(sv) do sv[k] = nil end initdb(sv, self.defaults, defaultProfile, self) -- fix the child namespaces if self.children then if not sv.namespaces then sv.namespaces = {} end for name, db in pairs(self.children) do if not sv.namespaces[name] then sv.namespaces[name] = {} end initdb(sv.namespaces[name], db.defaults, self.keys.profile, db, self) end end -- Callback: OnDatabaseReset, database self.callbacks:Fire("OnDatabaseReset", self) -- Callback: OnProfileChanged, database, profileKey self.callbacks:Fire("OnProfileChanged", self, self.keys["profile"]) return self end --- Creates a new database namespace, directly tied to the database. This -- is a full scale database in it's own rights other than the fact that -- it cannot control its profile individually -- @param name The name of the new namespace -- @param defaults A table of values to use as defaults function DBObjectLib:RegisterNamespace(name, defaults) if type(name) ~= "string" then error(("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - string expected, got %q."):format(type(name)), 2) end if defaults and type(defaults) ~= "table" then error(("Usage: AceDBObject:RegisterNamespace(name, defaults): 'defaults' - table or nil expected, got %q."):format(type(defaults)), 2) end if self.children and self.children[name] then error(("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - a namespace called %q already exists."):format(name), 2) end local sv = self.sv if not sv.namespaces then sv.namespaces = {} end if not sv.namespaces[name] then sv.namespaces[name] = {} end local newDB = initdb(sv.namespaces[name], defaults, self.keys.profile, nil, self) if not self.children then self.children = {} end self.children[name] = newDB return newDB end --- Returns an already existing namespace from the database object. -- @param name The name of the new namespace -- @param silent if true, the addon is optional, silently return nil if its not found -- @usage -- local namespace = self.db:GetNamespace('namespace') -- @return the namespace object if found function DBObjectLib:GetNamespace(name, silent) if type(name) ~= "string" then error(("Usage: AceDBObject:GetNamespace(name): 'name' - string expected, got %q."):format(type(name)), 2) end if not silent and not (self.children and self.children[name]) then error(("Usage: AceDBObject:GetNamespace(name): 'name' - namespace %q does not exist."):format(name), 2) end if not self.children then self.children = {} end return self.children[name] end --[[------------------------------------------------------------------------- AceDB Exposed Methods ---------------------------------------------------------------------------]] --- Creates a new database object that can be used to handle database settings and profiles. -- By default, an empty DB is created, using a character specific profile. -- -- You can override the default profile used by passing any profile name as the third argument, -- or by passing //true// as the third argument to use a globally shared profile called "Default". -- -- Note that there is no token replacement in the default profile name, passing a defaultProfile as "char" -- will use a profile named "char", and not a character-specific profile. -- @param tbl The name of variable, or table to use for the database -- @param defaults A table of database defaults -- @param defaultProfile The name of the default profile. If not set, a character specific profile will be used as the default. -- You can also pass //true// to use a shared global profile called "Default". -- @usage -- -- Create an empty DB using a character-specific default profile. -- self.db = LibStub("AceDB-3.0"):New("MyAddonDB") -- @usage -- -- Create a DB using defaults and using a shared default profile -- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true) function AceDB:New(tbl, defaults, defaultProfile) if type(tbl) == "string" then local name = tbl tbl = _G[name] if not tbl then tbl = {} _G[name] = tbl end end if type(tbl) ~= "table" then error(("Usage: AceDB:New(tbl, defaults, defaultProfile): 'tbl' - table expected, got %q."):format(type(tbl)), 2) end if defaults and type(defaults) ~= "table" then error(("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaults' - table expected, got %q."):format(type(defaults)), 2) end if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then error(("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaultProfile' - string or true expected, got %q."):format(type(defaultProfile)), 2) end return initdb(tbl, defaults, defaultProfile) end -- upgrade existing databases for db in pairs(AceDB.db_registry) do if not db.parent then for name,func in pairs(DBObjectLib) do db[name] = func end else db.RegisterDefaults = DBObjectLib.RegisterDefaults db.ResetProfile = DBObjectLib.ResetProfile end end
gpl-3.0
mjarco/sysdig
userspace/sysdig/chisels/ansiterminal.lua
19
2230
--[[ Copyright (C) 2013-2014 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] local pairs = pairs local tostring = tostring local setmetatable = setmetatable local schar = string.char local ansiterminal = {} local colors = { -- attributes reset = 0, clear = 0, bright = 1, dim = 2, underscore = 4, blink = 5, reverse = 7, hidden = 8, -- foreground black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, white = 37, -- background onblack = 40, onred = 41, ongreen = 42, onyellow = 43, onblue = 44, onmagenta = 45, oncyan = 46, onwhite = 47, } local function makecolor(name, value) ansiterminal[name] = schar(27) .. '[' .. tostring(value) .. 'm' end function ansiterminal.enable_color(enable_colors) if enable_colors == true then for c, v in pairs(colors) do makecolor(c, v) end else for name, v in pairs(colors) do ansiterminal[name] = "" end end end function ansiterminal.clearscreen() io.write(schar(27) .. '[' .. "2J") end function ansiterminal.moveto(x, y) io.write(schar(27) .. '[' .. tostring(x) .. ";" .. tostring(y) .. 'H') end function ansiterminal.moveup(n) io.write(schar(27) .. '[' .. tostring(n) .. 'F') end function ansiterminal.clearline() io.write(schar(27) .. '[' .. "2K") end function ansiterminal.hidecursor() io.write(schar(27) .. '[' .. "?25l") end function ansiterminal.showcursor() io.write(schar(27) .. '[' .. "?25h") end function ansiterminal.setbgcol(color) io.write(schar(27) .. '[' .. "48;5;" .. color .. "m") end return ansiterminal
gpl-2.0
philsiff/Red-Vs-Blue
Very Basic TDM [Gamemode]/gamemodes/vbtdm/gamemode/goal/cl_goal.lua
1
5861
//Set win goal! function vb_TEAM_2_win() surface.PlaySound( "vbtdm/us_win.mp3" ) local TEAM_2_TeamGoalFrame = vgui.Create( "DFrame" ) TEAM_2_TeamGoalFrame:SetPos( 50, 50 ) --Set the window in the middle of the players screen/game window TEAM_2_TeamGoalFrame:SetSize( 200, 100 ) --Set the size TEAM_2_TeamGoalFrame:SetTitle( "Blue TEAM WINS" ) --Set title TEAM_2_TeamGoalFrame:Center() TEAM_2_TeamGoalFrame:SetVisible( true ) TEAM_2_TeamGoalFrame:SetDraggable( false ) TEAM_2_TeamGoalFrame:MakePopup() TEAM_2_TeamGoalFrame:ShowCloseButton(false) local TEAM_2_Text = vgui.Create("DLabel", TEAM_2_TeamGoalFrame) -- We only have to parent it to the DPanelList now, and set it's position. TEAM_2_Text:SetPos(21,48) TEAM_2_Text:SetColor( Color( 0, 0, 0, 255 ) ) TEAM_2_Text:SetFont("default") TEAM_2_Text:SetText("You can type here, press enter") TEAM_2_Text:SizeToContents() local TEAM_2_TextThree = vgui.Create("DLabel", TEAM_2_TeamGoalFrame) -- We only have to parent it to the DPanelList now, and set it's position. TEAM_2_TextThree:SetPos(46,64) TEAM_2_TextThree:SetColor( Color( 51, 102, 255, 255 )) TEAM_2_TextThree:SetFont("default") TEAM_2_TextThree:SetText("Blue TEAM WINS!") TEAM_2_TextThree:SizeToContents() local TEAM_2_TextTwo = vgui.Create("DLabel", TEAM_2_TeamGoalFrame) -- We only have to parent it to the DPanelList now, and set it's position. TEAM_2_TextTwo:SetPos(15,80) TEAM_2_TextTwo:SetColor( Color( 0, 0, 0, 255 ) ) TEAM_2_TextTwo:SetFont("default") TEAM_2_TextTwo:SetText("The map will restart in 30 seconds!") TEAM_2_TextTwo:SizeToContents() local TEAM_2_DermaText = vgui.Create( "DTextEntry", TEAM_2_TeamGoalFrame ) TEAM_2_DermaText:SetPos( 10,30 ) TEAM_2_DermaText:SetTall( 20 ) TEAM_2_DermaText:SetWide( 182 ) TEAM_2_DermaText:SetEnterAllowed( true ) TEAM_2_DermaText.OnEnter = function() RunConsoleCommand( "say", TEAM_2_DermaText:GetValue() ) end timer.Create("chat",1,1,function() chat.AddText( Color( 255, 255, 255 ), "[", Color( 255, 0, 0 ), "TDM", Color( 255, 255, 255 ), "] ", Color( 255, 255, 255 ), "Restarting map in 30 seconds" ) TEAM_2_restart_chat() end) function TEAM_2_restart_chat() timer.Create("chat",15,0,function() chat.AddText( Color( 255, 255, 255 ), "[", Color( 255, 0, 0 ), "TDM", Color( 255, 255, 255 ), "] ", Color( 255, 255, 255 ), "Restarting map in 15 seconds" ) TEAM_2_restart_chat2() end) end function TEAM_2_restart_chat2() timer.Create("chat",5,0,function() chat.AddText( Color( 255, 255, 255 ), "[", Color( 255, 0, 0 ), "TDM", Color( 255, 255, 255 ), "] ", Color( 255, 255, 255 ), "Restarting map in 10 seconds" ) TEAM_2_restart_chat3() end) end function TEAM_2_restart_chat3() timer.Create("chat",5,0,function() chat.AddText( Color( 255, 255, 255 ), "[", Color( 255, 0, 0 ), "TDM", Color( 255, 255, 255 ), "] ", Color( 255, 255, 255 ), "Restarting map in 5 seconds" ) end) end end usermessage.Hook("vb_TEAM_2_win", vb_TEAM_2_win) function vb_TEAM_3_win() surface.PlaySound( "vbtdm/ger_win.mp3" ) local TEAM_3_TeamGoalFrame = vgui.Create( "DFrame" ) TEAM_3_TeamGoalFrame:SetPos( 50, 50 ) --Set the window in the middle of the players screen/game window TEAM_3_TeamGoalFrame:SetSize( 200, 100 ) --Set the size TEAM_3_TeamGoalFrame:SetTitle( "Red TEAM WINS" ) --Set title TEAM_3_TeamGoalFrame:Center() TEAM_3_TeamGoalFrame:SetVisible( true ) TEAM_3_TeamGoalFrame:SetDraggable( false ) TEAM_3_TeamGoalFrame:MakePopup() TEAM_3_TeamGoalFrame:ShowCloseButton(false) local TEAM_3_Text = vgui.Create("DLabel", TEAM_3_TeamGoalFrame) -- We only have to parent it to the DPanelList now, and set it's position. TEAM_3_Text:SetPos(21,48) TEAM_3_Text:SetColor( Color( 0, 0, 0, 255 ) ) TEAM_3_Text:SetFont("default") TEAM_3_Text:SetText("You can type here, press enter") TEAM_3_Text:SizeToContents() local TEAM_3_TextThree = vgui.Create("DLabel", TEAM_3_TeamGoalFrame) -- We only have to parent it to the DPanelList now, and set it's position. TEAM_3_TextThree:SetPos(41,64) TEAM_3_TextThree:SetColor( Color( 255, 0, 0 , 255 )) TEAM_3_TextThree:SetFont("default") TEAM_3_TextThree:SetText("Red TEAM WINS!") TEAM_3_TextThree:SizeToContents() local TEAM_3_TextTwo = vgui.Create("DLabel", TEAM_3_TeamGoalFrame) -- We only have to parent it to the DPanelList now, and set it's position. TEAM_3_TextTwo:SetPos(15,80) TEAM_3_TextTwo:SetColor( Color( 0, 0, 0, 255 ) ) TEAM_3_TextTwo:SetFont("default") TEAM_3_TextTwo:SetText("The map will restart in 30 seconds!") TEAM_3_TextTwo:SizeToContents() local TEAM_3_DermaText = vgui.Create( "DTextEntry", TEAM_3_TeamGoalFrame ) TEAM_3_DermaText:SetPos( 10,30 ) TEAM_3_DermaText:SetTall( 20 ) TEAM_3_DermaText:SetWide( 182 ) TEAM_3_DermaText:SetEnterAllowed( true ) TEAM_3_DermaText.OnEnter = function() RunConsoleCommand( "say", RedDermaText:GetValue() ) end timer.Create("chat",1,1,function() chat.AddText( Color( 255, 255, 255 ), "[", Color( 255, 0, 0 ), "TDM", Color( 255, 255, 255 ), "] ", Color( 255, 255, 255 ), "Restarting map in 30 seconds" ) TEAM_3_restart_chat() end) function TEAM_3_restart_chat() timer.Create("chat",15,0,function() chat.AddText( Color( 255, 255, 255 ), "[", Color( 255, 0, 0 ), "TDM", Color( 255, 255, 255 ), "] ", Color( 255, 255, 255 ), "Restarting map in 15 seconds" ) TEAM_3_restart_chat2() end) end function TEAM_3_restart_chat2() timer.Create("chat",5,0,function() chat.AddText( Color( 255, 255, 255 ), "[", Color( 255, 0, 0 ), "TDM", Color( 255, 255, 255 ), "] ", Color( 255, 255, 255 ), "Restarting map in 10 seconds" ) TEAM_3_restart_chat3() end) end function TEAM_3_restart_chat3() timer.Create("chat",5,0,function() chat.AddText( Color( 255, 255, 255 ), "[", Color( 255, 0, 0 ), "TDM", Color( 255, 255, 255 ), "] ", Color( 255, 255, 255 ), "Restarting map in 5 seconds" ) end) end end usermessage.Hook("vb_TEAM_3_win", vb_TEAM_3_win)
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/sandbox/entities/weapons/gmod_tool/stools/remover.lua
1
2186
TOOL.Category = "Construction" TOOL.Name = "#tool.remover.name" TOOL.Command = nil TOOL.ConfigName = nil local function RemoveEntity( ent ) if ( ent:IsValid() ) then ent:Remove() end end local function DoRemoveEntity( Entity ) if ( !IsValid( Entity ) || Entity:IsPlayer() ) then return false end -- Nothing for the client to do here if ( CLIENT ) then return true end -- Remove all constraints (this stops ropes from hanging around) constraint.RemoveAll( Entity ) -- Remove it properly in 1 second timer.Simple( 1, function() RemoveEntity( Entity ) end ) -- Make it non solid Entity:SetNotSolid( true ) Entity:SetMoveType( MOVETYPE_NONE ) Entity:SetNoDraw( true ) -- Send Effect local ed = EffectData() ed:SetEntity( Entity ) util.Effect( "entity_remove", ed, true, true ) return true end --[[--------------------------------------------------------- Name: LeftClick Desc: Remove a single entity -----------------------------------------------------------]] function TOOL:LeftClick( trace ) if ( DoRemoveEntity( trace.Entity ) ) then if ( !CLIENT ) then self:GetOwner():SendLua( "achievements.Remover()" ); end return true end return false end --[[--------------------------------------------------------- Name: RightClick Desc: Remove this entity and everything constrained -----------------------------------------------------------]] function TOOL:RightClick( trace ) local Entity = trace.Entity if ( !IsValid( Entity ) || Entity:IsPlayer() ) then return false end -- Client can bail out now. if ( CLIENT ) then return true end local ConstrainedEntities = constraint.GetAllConstrainedEntities( trace.Entity ) local Count = 0 -- Loop through all the entities in the system for _, Entity in pairs( ConstrainedEntities ) do if ( DoRemoveEntity( Entity ) ) then Count = Count + 1 end end return true end -- -- Reload removes all constraints on the targetted entity -- function TOOL:Reload( trace ) if ( !IsValid( trace.Entity ) || trace.Entity:IsPlayer() ) then return false end if ( CLIENT ) then return true end return constraint.RemoveAll( trace.Entity ) end
mit
Maliv/Looper
plugins/admin.lua
230
6382
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]", "^[!/](contactlist)$", "^[!/](dialoglist)$", "^[!/](delcontact) (%d+)$", "^[!/](whois) (%d+)$" }, run = run, } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
gpl-2.0
NatWeiss/RGP
src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Event.lua
7
1134
-------------------------------- -- @module Event -- @extend Ref -- @parent_module cc -------------------------------- -- Checks whether the event has been stopped.<br> -- return True if the event has been stopped. -- @function [parent=#Event] isStopped -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Gets the event type.<br> -- return The event type. -- @function [parent=#Event] getType -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Gets current target of the event.<br> -- return The target with which the event associates.<br> -- note It onlys be available when the event listener is associated with node.<br> -- It returns 0 when the listener is associated with fixed priority. -- @function [parent=#Event] getCurrentTarget -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- Stops propagation for current event. -- @function [parent=#Event] stopPropagation -- @param self -- @return Event#Event self (return value: cc.Event) return nil
mit
musselwhizzle/Focus-Points
focuspoints.lrdevplugin/DefaultPointRenderer.lua
3
18849
--[[ Copyright 2016 Whizzbang Inc 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. --]] --[[ This object is responsible for creating the focus point icon and figuring out where to place it. This logic should be universally reuseable, but if it's not, this object can be replaced in the PointsRendererFactory. --]] local LrDialogs = import 'LrDialogs' local LrView = import 'LrView' local LrColor = import 'LrColor' local LrErrors = import 'LrErrors' local LrApplication = import 'LrApplication' local LrPrefs = import "LrPrefs" require "MogrifyUtils" require "ExifUtils" a = require "affine" DefaultPointRenderer = {} --[[ the factory will set these delegate methods with the appropriate function depending upon the camera --]] DefaultPointRenderer.funcGetAfPoints = nil --[[ -- Returns a LrView.osFactory():view containg all needed icons to draw the points returned by DefaultPointRenderer.funcGetAfPoints -- photo - the selected catalog photo -- photoDisplayWidth, photoDisplayHeight - the width and height that the photo view is going to display as. --]] function DefaultPointRenderer.createView(photo, photoDisplayWidth, photoDisplayHeight) local prefs = LrPrefs.prefsForPlugin( nil ) local fpTable = DefaultPointRenderer.prepareRendering(photo, photoDisplayWidth, photoDisplayHeight) local viewFactory = LrView.osFactory() local photoView = nil local tmpView = nil local overlayViews = nil if fpTable == nil then return photoView end if (WIN_ENV == true) then local fileName = MogrifyUtils.createDiskImage(photo, photoDisplayWidth, photoDisplayHeight) MogrifyUtils.drawFocusPoints(fpTable) photoView = viewFactory:view { viewFactory:picture { width = photoDisplayWidth, height = photoDisplayHeight, value = fileName, }, } else overlayViews = DefaultPointRenderer.createOverlayViews(fpTable, photoDisplayWidth, photoDisplayHeight) -- create photo view tmpView = viewFactory:catalog_photo { width = photoDisplayWidth, height = photoDisplayHeight, photo = photo, } photoView = viewFactory:view { tmpView, overlayViews, place = 'overlapping', } end return photoView end --[[ Prepare raw focus data for rendering: apply crop factor, roation, etc -- photo - the selected catalog photo -- photoDisplayWidth, photoDisplayHeight - the width and height that the photo view is going to display as. -- Returns a table with detailed focus point rendering data -- points: array with Center-, TopLeft-, TopRight-, BottonLeft-, BottonRight- point -- rotation: user + crop rotation -- userMirroring -- template: template discribing the focus-point. See DefaultDelegates.lua -- useSmallIcons --]] function DefaultPointRenderer.prepareRendering(photo, photoDisplayWidth, photoDisplayHeight) local developSettings = photo:getDevelopSettings() local metaData = ExifUtils.readMetaDataAsTable(photo) local originalWidth, originalHeight,cropWidth, cropHeight = DefaultPointRenderer.getNormalizedDimensions(photo) local userRotation, userMirroring = DefaultPointRenderer.getUserRotationAndMirroring(photo) -- We read the rotation written in the Exif just for logging has it happens that the lightrrom rotation already includes it which is pretty handy local exifRotation = DefaultPointRenderer.getShotOrientation(photo, metaData) local cropRotation = developSettings["CropAngle"] local cropLeft = developSettings["CropLeft"] local cropTop = developSettings["CropTop"] logDebug("DefaultPointRenderer", "originalDimensions: " .. originalWidth .. " x " .. originalHeight .. ", cropDimensions: " .. cropWidth .. " x " .. cropHeight .. ", displayDimensions: " .. photoDisplayWidth .. " x " .. photoDisplayHeight) logDebug("DefaultPointRenderer", "exifRotation: " .. exifRotation .. "°, userRotation: " .. userRotation .. "°, userMirroring: " .. userMirroring) logDebug("DefaultPointRenderer", "cropRotation: " .. cropRotation .. "°, cropLeft: " .. cropLeft .. ", cropTop: " .. cropTop) -- Calculating transformations local cropTransformation = a.rotate(math.rad(-cropRotation)) * a.trans(-cropLeft * originalWidth, -cropTop * originalHeight) local userRotationTransformation local userMirroringTransformation local displayScalingTransformation if userRotation == 90 then userRotationTransformation = a.trans(0, photoDisplayHeight) * a.rotate(math.rad(-userRotation)) displayScalingTransformation = a.scale(photoDisplayHeight / cropWidth, photoDisplayWidth / cropHeight) elseif userRotation == -90 then userRotationTransformation = a.trans(photoDisplayWidth, 0) * a.rotate(math.rad(-userRotation)) displayScalingTransformation = a.scale(photoDisplayHeight / cropWidth, photoDisplayWidth / cropHeight) elseif userRotation == 180 then userRotationTransformation = a.trans(photoDisplayWidth, photoDisplayHeight) * a.rotate(math.rad(-userRotation)) displayScalingTransformation = a.scale(photoDisplayWidth / cropWidth, photoDisplayHeight / cropHeight) else userRotationTransformation = a.trans(0, 0) displayScalingTransformation = a.scale(photoDisplayWidth / cropWidth, photoDisplayHeight / cropHeight) end if userMirroring == -1 then userMirroringTransformation = a.trans(photoDisplayWidth, 0) * a.scale(-1, 1) else userMirroringTransformation = a.scale(1, 1) end local resultingTransformation = userMirroringTransformation * (userRotationTransformation * (displayScalingTransformation * cropTransformation)) local inverseResultingTransformation = a.inverse(resultingTransformation) local pointsTable = DefaultPointRenderer.funcGetAfPoints(photo, metaData) if pointsTable == nil then return nil end local fpTable = { } for key, point in pairs(pointsTable.points) do local template = pointsTable.pointTemplates[point.pointType] if template == nil then logError("DefaultPointRenderer", "Point template '" .. point.pointType .. "'' could not be found.") LrErrors.throwUserError("Point template " .. point.pointType .. " could not be found.") return nil end -- Placing icons local x, y = resultingTransformation(point.x, point.y) logInfo("DefaultPointRenderer", "Placing point of type '" .. point.pointType .. "' at position [" .. point.x .. ", " .. point.y .. "] -> ([" .. math.floor(x) .. ", " .. math.floor(y) .. "] on display)") local useSmallIcons = false local pointWidth = point.width local pointHeight = point.height -- Checking if the distance between corners goes under the value of template.bigToSmallTriggerDist -- If so, we switch to small icons (when available) local x0, y0 = resultingTransformation(0, 0) local xHorizontal, yHorizontal = resultingTransformation(pointWidth, 0) local distHorizontal = math.sqrt((xHorizontal - x0)^2 + (yHorizontal - y0)^2) local xVertical, yVertical = resultingTransformation(0, pointHeight) local distVertical = math.sqrt((xVertical - x0)^2 + (yVertical - y0)^2) if template.bigToSmallTriggerDist ~= nil and (distHorizontal < template.bigToSmallTriggerDist or distVertical < template.bigToSmallTriggerDist) then useSmallIcons = true logDebug("DefaultPointRenderer", "distHorizontal: " .. distHorizontal .. ", distVertical: " .. distVertical .. ", bigToSmallTriggerDist: " .. template.bigToSmallTriggerDist .. " -> useSmallIcons: TRUE") else logDebug("DefaultPointRenderer", "distHorizontal: " .. distHorizontal .. ", distVertical: " .. distVertical .. ", bigToSmallTriggerDist: " .. template.bigToSmallTriggerDist .. " -> useSmallIcons: FALSE") end -- Checking if the distance between corners goes under the value of template.minCornerDist -- If so, we set pointWidth and/or pointHeight to the corresponding size to garantee this minimum distance local pixX0, pixY0 = inverseResultingTransformation(0, 0) local pixX1, pixY1 = inverseResultingTransformation(template.minCornerDist, 0) local minCornerPhotoDist = math.sqrt((pixX1 - pixX0)^2 + (pixY1 - pixY0)^2) if distHorizontal < template.minCornerDist then pointWidth = minCornerPhotoDist end if distVertical < template.minCornerDist then pointHeight = minCornerPhotoDist end logDebug("DefaultPointRenderer", "distHorizontal: " .. distHorizontal .. ", distVertical: " .. distVertical .. ", minCornerDist: " .. template.minCornerDist .. ", minCornerPhotoDist: " .. minCornerPhotoDist) -- Top Left, 0° local tlX, tlY = resultingTransformation(point.x - pointWidth/2, point.y - pointHeight/2) -- Top Right, -90° local trX, trY = resultingTransformation(point.x + pointWidth/2, point.y - pointHeight/2) -- Bottom Right, -180° local brX, brY = resultingTransformation(point.x + pointWidth/2, point.y + pointHeight/2) -- Bottom Left, -270° local blX, blY = resultingTransformation(point.x - pointWidth/2, point.y + pointHeight/2) local points = { center = { x = x, y = y}, tl = { x = tlX, y = tlY }, tr = { x = trX, y = trY }, bl = { x = blX, y = blY }, br = { x = brX, y = brY }, } table.insert(fpTable, { points = points, rotation = cropRotation + userRotation, userMirroring= userMirroring, template = template, useSmallIcons = useSmallIcons}) end return fpTable end --[[ Create overlay views -- fpTable - table with rendering information for the focus points -- photoDisplayWidth, photoDisplayHeight - the width and height that the photo view is going to display as. -- Returns a table with overlay view --]] function DefaultPointRenderer.createOverlayViews(fpTable, photoDisplayWidth, photoDisplayHeight) local viewsTable = { place = "overlapping" } for key, fpPoint in pairs(fpTable) do -- Inserting center icon view if fpPoint.template.center ~= nil then if fpPoint.points.center.x >= 0 and fpPoint.points.center.x <= photoDisplayWidth and fpPoint.points.center.y >= 0 and fpPoint.points.center.y <= photoDisplayHeight then local centerTemplate = fpPoint.template.center if fpPoint.useSmallIcons and fpPoint.template.center_small ~= nil then centerTemplate = fpPoint.template.center_small end table.insert(viewsTable, DefaultPointRenderer.createPointView(fpPoint.points.center.x, fpPoint.points.center.y, fpPoint.rotation, fpPoint.userMirroring, centerTemplate.fileTemplate, centerTemplate.anchorX, centerTemplate.anchorY, centerTemplate.angleStep)) end end -- Inserting corner icon views if fpPoint.template.corner ~= nil then local cornerTemplate = fpPoint.template.corner if fpPoint.useSmallIcons and fpPoint.template.corner_small ~= nil then cornerTemplate = fpPoint.template.corner_small end if fpPoint.points.tl.x >= 0 and fpPoint.points.tl.x <= photoDisplayWidth and fpPoint.points.tl.y >= 0 and fpPoint.points.tl.y <= photoDisplayHeight then table.insert(viewsTable, DefaultPointRenderer.createPointView(fpPoint.points.tl.x, fpPoint.points.tl.y, fpPoint.rotation, fpPoint.userMirroring, cornerTemplate.fileTemplate, cornerTemplate.anchorX, cornerTemplate.anchorY, fpPoint.template.angleStep)) end if fpPoint.points.tr.x >= 0 and fpPoint.points.tr.x <= photoDisplayWidth and fpPoint.points.tr.y >= 0 and fpPoint.points.tr.y <= photoDisplayHeight then table.insert(viewsTable, DefaultPointRenderer.createPointView(fpPoint.points.tr.x, fpPoint.points.tr.y, fpPoint.rotation - 90, fpPoint.userMirroring, cornerTemplate.fileTemplate, cornerTemplate.anchorX, cornerTemplate.anchorY, fpPoint.template.angleStep)) end if fpPoint.points.br.x >= 0 and fpPoint.points.br.x <= photoDisplayWidth and fpPoint.points.br.y >= 0 and fpPoint.points.br.y <= photoDisplayHeight then table.insert(viewsTable, DefaultPointRenderer.createPointView(fpPoint.points.br.x, fpPoint.points.br.y, fpPoint.rotation - 180, fpPoint.userMirroring, cornerTemplate.fileTemplate, cornerTemplate.anchorX, cornerTemplate.anchorY, fpPoint.template.angleStep)) end if fpPoint.points.bl.y >= 0 and fpPoint.points.bl.x <= photoDisplayWidth and fpPoint.points.bl.y >= 0 and fpPoint.points.bl.y <= photoDisplayHeight then table.insert(viewsTable, DefaultPointRenderer.createPointView(fpPoint.points.bl.x, fpPoint.points.bl.y, fpPoint.rotation - 270, fpPoint.userMirroring, cornerTemplate.fileTemplate, cornerTemplate.anchorX, cornerTemplate.anchorY, fpPoint.template.angleStep)) end end end return LrView.osFactory():view(viewsTable) end function DefaultPointRenderer.cleanup() if (WIN_ENV == true) then MogrifyUtils.cleanup() end end --[[ -- Creates a view with the focus box placed rotated and mirrored at the right place. As Lightroom does not allow -- for rotating icons right now nor for drawing, we get the rotated/mirrored image from the corresponding file name template -- The method replaces the first '%s' in the iconFileTemplate by the passed rotation rounded to angleStep steps -- and adds "-mirrored" to this if horizontalMirroring == -1 -- x, y - the center of the icon to be drawn -- rotation - the rotation angle of the icon in degrees -- horizontalMirroring - 0 or -1 -- iconFileTemplate - the file path of the icon file to be used. %s will be replaced by the rotation angle module angleStep -- anchorX, anchorY - the position in pixels of the anchor point in the image file -- angleStep - the angle stepping in degrees used for the icon files. If angleStep = 10 and rotation = 26.7°, then "%s" will be replaced by "30" --]] function DefaultPointRenderer.createPointView(x, y, rotation, horizontalMirroring, iconFileTemplate, anchorX, anchorY, angleStep) local fileRotationStr = "" if angleStep ~= nil and angleStep ~= 0 then local closestAngle = (angleStep * math.floor(0.5 + rotation / angleStep)) % 360 if horizontalMirroring == -1 then fileRotationStr = (630 - closestAngle) % 360 else fileRotationStr = closestAngle end end local fileName = string.format(iconFileTemplate, fileRotationStr) logDebug("createPointView", "fileName: " .. fileName) local viewFactory = LrView.osFactory() local view = viewFactory:view { viewFactory:picture { value = _PLUGIN:resourceId(fileName) }, margin_left = x - anchorX, margin_top = y - anchorY, } return view end --[[ -- Takes a LrPhoto and returns the normalized original dimensions and cropped dimensions uninfluenced by the rotation -- photo - the LrPhoto to calculate the values from -- returns: -- - originalWidth, originalHeight - original dimensions in unrotated position -- - cropWidth, cropHeight - cropped dimensions in unrotated position --]] function DefaultPointRenderer.getNormalizedDimensions(photo) local originalWidth, originalHeight = parseDimens(photo:getFormattedMetadata("dimensions")) local cropWidth, cropHeight = parseDimens(photo:getFormattedMetadata("croppedDimensions")) local userRotation, userMirroring = DefaultPointRenderer.getUserRotationAndMirroring(photo) if userRotation == 90 or userRotation == -90 then -- In case the image has been rotated by the user in the grid view, LR inverts width and height but does NOT change cropLeft and cropTop... -- In this methods, width and height refer to the original width and height local tmp = originalHeight originalHeight = originalWidth originalWidth = tmp tmp = cropHeight cropHeight = cropWidth cropWidth = tmp end return originalWidth, originalHeight, cropWidth, cropHeight end --[[ -- Takes a LrPhoto and returns the rotation and horizontal mirroring that the user has choosen in Lightroom (generaly in grid mode) -- photo - the LrPhoto to calculate the values from -- returns: -- - rotation in degrees in trigonometric sense -- - horizontal mirroring (0 -> none, -1 -> yes) --]] function DefaultPointRenderer.getUserRotationAndMirroring(photo) -- LR 5 throws an error even trying to access getRawMetadata("orientation") logDebug("DefaultPointRenderer", "LR version: " .. LrApplication.versionTable().major) if (LrApplication.versionTable().major < 6) then return DefaultPointRenderer.getShotOrientation(photo, ExifUtils.readMetaDataAsTable(photo)), 0 end local userRotation = photo:getRawMetadata("orientation") if userRotation == nil then logWarn("DefaultPointRenderer", "userRotation = nil, which is unexpected starting with LR6") -- Falling back by trying to find the information with exifs. -- This is not working when the user rotates or mirrors the image within lightroom return DefaultPointRenderer.getShotOrientation(photo, ExifUtils.readMetaDataAsTable(photo)), 0 elseif userRotation == "AB" then return 0, 0 elseif userRotation == "BC" then return -90, 0 elseif userRotation == "CD" then return 180, 0 elseif userRotation == "DA" then return 90, 0 -- Same with horizontal mirroring elseif userRotation == "BA" then return 0, -1 elseif userRotation == "CB" then return -90, -1 elseif userRotation == "DC" then return 180, -1 elseif userRotation == "AD" then return 90, -1 end logWarn("DefaultPointRenderer", "We should never get there with an userRotation = " .. userRotation) return 0, 0 end --[[ -- method figures out the orientation the photo was shot at by looking at the metadata -- returns the rotation in degrees in trigonometric sense --]] function DefaultPointRenderer.getShotOrientation(photo, metaData) local dimens = photo:getFormattedMetadata("dimensions") local orgPhotoW, orgPhotoH = parseDimens(dimens) -- original dimension before any cropping local metaOrientation = ExifUtils.findFirstMatchingValue(metaData, { "Orientation" }) if metaOrientation == nil then return 0 end if string.match(metaOrientation, "90 CCW") and orgPhotoW < orgPhotoH then return 90 -- 90° CCW elseif string.match(metaOrientation, "270 CCW") and orgPhotoW < orgPhotoH then return -90 -- 270° CCW elseif string.match(metaOrientation, "90") and orgPhotoW < orgPhotoH then return -90 -- 90° CW elseif string.match(metaOrientation, "270") and orgPhotoW < orgPhotoH then return 90 -- 270° CCW end return 0 end
apache-2.0
pazos/koreader
spec/unit/switch_plugin_spec.lua
13
5658
describe("SwitchPlugin", function() require("commonrequire") local SwitchPlugin = require("ui/plugin/switch_plugin") local createTestPlugin = function(default_enable, start, stop) return SwitchPlugin:new({ name = "test_plugin", menu_item = "test_plugin_menu", menu_text = "This is a test plugin", confirm_message = "This is a test plugin, it's for test purpose only.", default_enable = default_enable, _start = function() start() end, _stop = function() stop() end, }) end local TestPlugin2 = SwitchPlugin:extend() function TestPlugin2:new(o) o = o or {} o.name = "test_plugin2" o.menu_item = "test_plugin2_menu" o.menu_text = "This is a test plugin2" o.confirm_message = "This is a test plugin2, it's for test purpose only." o.start_called = 0 o.stop_called = 0 o = SwitchPlugin.new(self, o) return o end function TestPlugin2:_start() self.start_called = self.start_called + 1 end function TestPlugin2:_stop() self.stop_called = self.stop_called + 1 end it("should be able to create a enabled plugin", function() local start_called = 0 local stop_called = 0 local test_plugin = createTestPlugin( true, function() start_called = start_called + 1 end, function() stop_called = stop_called + 1 end) assert.are.equal(1, start_called) assert.are.equal(0, stop_called) test_plugin:flipSetting() assert.are.equal(1, start_called) assert.are.equal(1, stop_called) test_plugin:flipSetting() assert.are.equal(2, start_called) assert.are.equal(1, stop_called) local menu_items = {} test_plugin:addToMainMenu(menu_items) assert.are.equal("This is a test plugin", menu_items.test_plugin_menu.text) end) it("should be able to create a disabled plugin", function() local start_called = 0 local stop_called = 0 local test_plugin = createTestPlugin( false, function() start_called = start_called + 1 end, function() stop_called = stop_called + 1 end) assert.are.equal(0, start_called) assert.are.equal(1, stop_called) test_plugin:flipSetting() assert.are.equal(1, start_called) assert.are.equal(1, stop_called) test_plugin:flipSetting() assert.are.equal(1, start_called) assert.are.equal(2, stop_called) end) it("should be able to create a derived enabled plugin", function() local test_plugin = TestPlugin2:new({ default_enable = true, }) assert.are.equal(1, test_plugin.start_called) assert.are.equal(0, test_plugin.stop_called) test_plugin:flipSetting() assert.are.equal(1, test_plugin.start_called) assert.are.equal(1, test_plugin.stop_called) test_plugin:flipSetting() assert.are.equal(2, test_plugin.start_called) assert.are.equal(1, test_plugin.stop_called) local menu_items = {} test_plugin:addToMainMenu(menu_items) assert.are.equal("This is a test plugin2", menu_items.test_plugin2_menu.text) end) it("should be able to create a derived disabled plugin", function() local test_plugin = TestPlugin2:new() assert.are.equal(0, test_plugin.start_called) assert.are.equal(1, test_plugin.stop_called) test_plugin:flipSetting() assert.are.equal(1, test_plugin.start_called) assert.are.equal(1, test_plugin.stop_called) test_plugin:flipSetting() assert.are.equal(1, test_plugin.start_called) assert.are.equal(2, test_plugin.stop_called) end) it("should be able to create an invisible plugin", function() local test_plugin = SwitchPlugin:new({ name = "test_plugin", ui = { menu = { registerToMainMenu = function() assert.is_true(false, "This should not reach.") end, }, }, }) test_plugin:init() end) it("should show a correct message box", function() local UIManager = require("ui/uimanager") local confirm_box UIManager.show = function(self, element) confirm_box = element end local test_plugin = TestPlugin2:new() -- The plugin is off by default, we expect an "enable" message. test_plugin:_showConfirmBox() assert.is_not_nil(confirm_box) assert.are.equal( "This is a test plugin2, it's for test purpose only.\nDo you want to enable it?", confirm_box.text) assert.are.equal("Enable", confirm_box.ok_text) confirm_box.ok_callback() confirm_box = nil -- The plugin is enabled by confirm_box.ok_callback(), we expect a "disable" message. test_plugin:_showConfirmBox() assert.is_not_nil(confirm_box) assert.are.equal( "This is a test plugin2, it's for test purpose only.\nDo you want to disable it?", confirm_box.text) assert.are.equal("Disable", confirm_box.ok_text) confirm_box.ok_callback() assert.is_false(test_plugin.enabled) package.unload("ui/uimanager") end) end)
agpl-3.0
payamohajeri/telegram-bot
plugins/search_youtube.lua
674
1270
do local google_config = load_from_file('data/google.lua') local function httpsRequest(url) print(url) local res,code = https.request(url) if code ~= 200 then return nil end return json:decode(res) end local function searchYoutubeVideos(text) local url = 'https://www.googleapis.com/youtube/v3/search?' url = url..'part=snippet'..'&maxResults=4'..'&type=video' url = url..'&q='..URL.escape(text) if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local data = httpsRequest(url) if not data then print("HTTP Error") return nil elseif not data.items then return nil end return data.items end local function run(msg, matches) local text = '' local items = searchYoutubeVideos(matches[1]) if not items then return "Error!" end for k,item in pairs(items) do text = text..'http://youtu.be/'..item.id.videoId..' '.. item.snippet.title..'\n\n' end return text end return { description = "Search video on youtube and send it.", usage = "!youtube [term]: Search for a youtube video and send it.", patterns = { "^!youtube (.*)" }, run = run } end
gpl-2.0
Aminkavari/-xXD4RKXx-
plugins/search_youtube.lua
674
1270
do local google_config = load_from_file('data/google.lua') local function httpsRequest(url) print(url) local res,code = https.request(url) if code ~= 200 then return nil end return json:decode(res) end local function searchYoutubeVideos(text) local url = 'https://www.googleapis.com/youtube/v3/search?' url = url..'part=snippet'..'&maxResults=4'..'&type=video' url = url..'&q='..URL.escape(text) if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local data = httpsRequest(url) if not data then print("HTTP Error") return nil elseif not data.items then return nil end return data.items end local function run(msg, matches) local text = '' local items = searchYoutubeVideos(matches[1]) if not items then return "Error!" end for k,item in pairs(items) do text = text..'http://youtu.be/'..item.id.videoId..' '.. item.snippet.title..'\n\n' end return text end return { description = "Search video on youtube and send it.", usage = "!youtube [term]: Search for a youtube video and send it.", patterns = { "^!youtube (.*)" }, run = run } end
gpl-2.0
yetsky/luci
applications/luci-qos_gargoyle/luasrc/model/cbi/qos_gargoyle/upload.lua
5
4625
--[[ ]]-- local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" m = Map("qos_gargoyle", translate("upload"),translate("UpLoad set")) s = m:section(TypedSection, "upload_class", translate("upload_class")) s.addremove = true s.template = "cbi/tblsection" name = s:option(Value, "name", translate("name")) pb = s:option(Value, "percent_bandwidth", translate("percent_bandwidth"), translate("percent of total bandwidth to use")) minb = s:option(Value, "min_bandwidth", translate("min_bandwidth"), translate("min bandwidth useage in absolute speed (kbit/s)")) minb.datatype = "and(uinteger,min(0))" maxb = s:option(Value, "max_bandwidth", translate("max_bandwidth"), translate("max bandwidth useage in absolute speed (kbit/s)")) maxb.datatype = "and(uinteger,min(0))" minRTT = s:option(ListValue, "minRTT", translate("minRTT")) minRTT:value("Yes") minRTT:value("No") minRTT.default = "No" local tmp = "upload_rule" s = m:section(TypedSection, "upload_rule", translate(tmp)) s.addremove = true s.template = "cbi/tblsection" class = s:option(Value, "class", translate("class"), translate("<abbr title=\"name of bandwidth class to use if rule matches, this is required in each rule section\">Help</abbr>")) for line in io.lines("/etc/config/qos_gargoyle") do local str = line line = string.gsub(line, "config ['\"]*upload_class['\"]* ", "") if str ~= line then line = string.gsub(line, "^'", "") line = string.gsub(line, "^\"", "") line = string.gsub(line, "'$", "") line = string.gsub(line, "\"$", "") class:value(line, translate(m.uci:get("qos_gargoyle", line, "name"))) end end class.default = "uclass_2" to = s:option(Value, "test_order", translate("test_order"), translate("<abbr title=\"an integer that specifies the order in which the rule should be checked for a match (lower numbers are checked first)\">Help</abbr>")) to.rmempty = "true" minb.datatype = "and(uinteger,min(0))" to:value(100) to:value(200) to:value(300) to:value(400) to:value(500) to:value(600) to:value(700) to:value(800) to:value(900) pr = s:option(Value, "proto", translate("proto"), translate("<abbr title=\"check that packet has this protocol (tcp, udp, both)\">Help</abbr>")) pr:value("tcp") pr:value("udp") pr:value("icmp") pr:value("gre") pr.rmempty = "true" sip = s:option(Value, "source", translate("source ip"), translate("<abbr title=\"check that packet has this source ip, can optionally have /[mask] after it (see -s option in iptables man page)\">Help</abbr>")) wa.cbi_add_knownips(sip) sip.datatype = "and(ipaddr)" dip = s:option(Value, "destination", translate("destination ip"), translate("<abbr title=\"check that packet has this destination ip, can optionally have /[mask] after it (see -d option in iptables man page)\">Help</abbr>")) wa.cbi_add_knownips(dip) dip.datatype = "and(ipaddr)" dport = s:option(Value, "dstport", translate("destination port"), translate("<abbr title=\"check that packet has this destination port\">Help</abbr>")) dport.datatype = "and(uinteger,max(65536),min(1))" sport = s:option(Value, "srcport", translate("source port"), translate("<abbr title=\"check that packet has this source port\">Help</abbr>")) sport.datatype = "and(uinteger,max(65536),min(1))" min_pkt_size = s:option(Value, "min_pkt_size", translate("min_pkt_size"), translate("<abbr title=\"check that packet is at least this size (in bytes)\">Help</abbr>")) min_pkt_size.datatype = "and(uinteger,min(1))" max_pkt_size = s:option(Value, "max_pkt_size", translate("max_pkt_size"), translate("<abbr title=\"check that packet is no larger than this size (in bytes)\">Help</abbr>")) max_pkt_size.datatype = "and(uinteger,min(1))" connbytes_kb = s:option(Value, "connbytes_kb", translate("connbytes_kbyte"), translate("<abbr title=\"kbyte\">Help</abbr>")) connbytes_kb.datatype = "and(uinteger,min(0))" layer7 = s:option(Value, "layer7", translate("layer7"), translate("<abbr title=\"check whether packet matches layer7 specification\">Help</abbr>")) local pats = io.popen("find /etc/l7-protocols/ -type f -name '*.pat'") if pats then local l while true do l = pats:read("*l") if not l then break end l = l:match("([^/]+)%.pat$") if l then layer7:value(l) end end pats:close() end ipp2p = s:option(Value, "ipp2p", translate("ipp2p"), translate("<abbr title=\"check wither packet matches ipp2p specification (used to recognize p2p protocols),ipp2p or all will match any of the specified p2p protocols, you can also specifically match any protocol listed in the documentation here: http://ipp2p.org/docu_en.html\">Help</abbr>")) ipp2p:value("ipp2p") ipp2p:value("all") return m
apache-2.0
FoxelBox/FoxBukkitLua
lua/src/main/lua/classes/Chat.lua
1
5425
--[[ This file is part of FoxBukkitLua-lua. FoxBukkitLua-lua is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FoxBukkitLua-lua 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with FoxBukkitLua-lua. If not, see <http://www.gnu.org/licenses/>. ]] local chatAPI = __LUA_STATE:getEnhancedChatMessageManager() local Player = require("Player") Player:addConsoleExtensions{ sendReply = function(self, message) return self:sendMessage("[FB] " .. message) end, sendError = function(self, message) return self:sendMessage("[FB] [ERROR] " .. message) end } if not chatAPI then local bukkitServer = require("Server"):getBukkitServer() local Chat = { isAvailable = function(self) return false end, getConsole = Player.getConsole, makeButton = function(self, command, label, color, run, addHover) return "<BUTTON:" .. command ">" .. label .. "</BUTTON>" end, getPlayerUUID = function(self, name) return nil end, sendGlobal = function(self, source, type, content) bukkitServer:broadcastMessage(content) end, broadcastLocal = function(self, source, content) bukkitServer:broadcastMessage(content) end, sendLocalToPlayer = function(self, source, content, target) if target then target:sendMessage(content) else -- content, target content:sendMessage(source) end end, sendLocalToPermission = function(self, source, content, target) if target then bukkitServer:broadcastMessage("$" + target, content) else -- content, target bukkitServer:broadcastMessage("$" + content, source) end end, sendLocal = function(self, source, content, chatTarget, targetFilter) bukkitServer:broadcastMessage("!" .. tostring(targetFilter) .. "!" .. tostring(chatTarget), content) end, getPlayerNick = function(self, ply_or_uuid) return ply_or_uuid:getDisplayName() end, } Player:addExtensions{ sendXML = function(self, message) return Chat:sendLocalToPlayer(message, self) end, sendReply = function(self, message) return self:sendXML("[FB] " .. message) end, sendError = function(self, message) return self:sendXML("[FB] [ERROR] " .. message) end, getNickName = function(self) return self:getDisplayName() end } return Chat end local function fixPly(ply) if ply and ply.__entity then return ply.__entity end return ply end local Chat = { isAvailable = function(self) return chatAPI:isAvailable() end, getConsole = function(self) return chatAPI:getConsole() end, makeButton = function(self, command, label, color, run, addHover) return chatAPI:makeButton(command, label, color, run, (addHover ~= false)) end, getPlayerUUID = function(self, name) return chatAPI:getPlayerUUID(name) end, sendGlobal = function(self, source, type, content) return chatAPI:sendGlobal(fixPly(source), type, content) end, broadcastLocal = function(self, source, content) return chatAPI:broadcastLocal(fixPly(source), content) end, sendLocalToPlayer = function(self, source, content, target) if target then return chatAPI:sendLocalToPlayer(fixPly(source), content, fixPly(target)) else -- content, target return chatAPI:sendLocalToPlayer(source, fixPly(content)) end end, sendLocalToPermission = function(self, source, content, target) if target then return chatAPI:sendLocalToPermission(fixPly(source), content, target) else -- content, target return chatAPI:sendLocalToPermission(source, content) end end, sendLocal = function(self, source, content, chatTarget, targetFilter) return chatAPI:sendLocal(fixPly(source), content, chatTarget, targetFilter) end, getPlayerNick = function(self, ply_or_uuid) if ply_or_uuid.__entity then return chatAPI:getPlayerNick(ply_or_uuid.__entity) else return chatAPI:getPlayerNick(ply_or_uuid) end end } Player:addExtensions{ sendXML = function(self, message) return Chat:sendLocalToPlayer(message, self) end, sendReply = function(self, message) return self:sendXML("<color name=\"dark_purple\">[FB]</color> " .. message) end, sendError = function(self, message) return self:sendXML("<color name=\"dark_red\">[FB]</color> " .. message) end, getNickName = function(self) return Chat:getPlayerNick(self) end } return Chat
lgpl-3.0
emadni/lordteami-bot
plugins/owners.lua
284
12473
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
theonlywild/copy
plugins/boobs.lua
731
1601
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
sdgdsffdsfff/nginx-openresty-windows
luajit-root-x64/luajit/share/luajit-2.1.0-alpha/jit/dis_arm.lua
17
19363
---------------------------------------------------------------------------- -- LuaJIT ARM disassembler module. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles most user-mode ARMv7 instructions -- NYI: Advanced SIMD and VFP instructions. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local concat = table.concat local bit = require("bit") local band, bor, ror, tohex = bit.band, bit.bor, bit.ror, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Opcode maps ------------------------------------------------------------------------------ local map_loadc = { shift = 8, mask = 15, [10] = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "vmovFmDN", "vstmFNdr", _ = { shift = 21, mask = 1, [0] = "vstrFdl", { shift = 16, mask = 15, [13] = "vpushFdr", _ = "vstmdbFNdr", } }, }, { shift = 23, mask = 3, [0] = "vmovFDNm", { shift = 16, mask = 15, [13] = "vpopFdr", _ = "vldmFNdr", }, _ = { shift = 21, mask = 1, [0] = "vldrFdl", "vldmdbFNdr", }, }, }, [11] = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "vmovGmDN", "vstmGNdr", _ = { shift = 21, mask = 1, [0] = "vstrGdl", { shift = 16, mask = 15, [13] = "vpushGdr", _ = "vstmdbGNdr", } }, }, { shift = 23, mask = 3, [0] = "vmovGDNm", { shift = 16, mask = 15, [13] = "vpopGdr", _ = "vldmGNdr", }, _ = { shift = 21, mask = 1, [0] = "vldrGdl", "vldmdbGNdr", }, }, }, _ = { shift = 0, mask = 0 -- NYI ldc, mcrr, mrrc. }, } local map_vfps = { shift = 6, mask = 0x2c001, [0] = "vmlaF.dnm", "vmlsF.dnm", [0x04000] = "vnmlsF.dnm", [0x04001] = "vnmlaF.dnm", [0x08000] = "vmulF.dnm", [0x08001] = "vnmulF.dnm", [0x0c000] = "vaddF.dnm", [0x0c001] = "vsubF.dnm", [0x20000] = "vdivF.dnm", [0x24000] = "vfnmsF.dnm", [0x24001] = "vfnmaF.dnm", [0x28000] = "vfmaF.dnm", [0x28001] = "vfmsF.dnm", [0x2c000] = "vmovF.dY", [0x2c001] = { shift = 7, mask = 0x1e01, [0] = "vmovF.dm", "vabsF.dm", [0x0200] = "vnegF.dm", [0x0201] = "vsqrtF.dm", [0x0800] = "vcmpF.dm", [0x0801] = "vcmpeF.dm", [0x0a00] = "vcmpzF.d", [0x0a01] = "vcmpzeF.d", [0x0e01] = "vcvtG.dF.m", [0x1000] = "vcvt.f32.u32Fdm", [0x1001] = "vcvt.f32.s32Fdm", [0x1800] = "vcvtr.u32F.dm", [0x1801] = "vcvt.u32F.dm", [0x1a00] = "vcvtr.s32F.dm", [0x1a01] = "vcvt.s32F.dm", }, } local map_vfpd = { shift = 6, mask = 0x2c001, [0] = "vmlaG.dnm", "vmlsG.dnm", [0x04000] = "vnmlsG.dnm", [0x04001] = "vnmlaG.dnm", [0x08000] = "vmulG.dnm", [0x08001] = "vnmulG.dnm", [0x0c000] = "vaddG.dnm", [0x0c001] = "vsubG.dnm", [0x20000] = "vdivG.dnm", [0x24000] = "vfnmsG.dnm", [0x24001] = "vfnmaG.dnm", [0x28000] = "vfmaG.dnm", [0x28001] = "vfmsG.dnm", [0x2c000] = "vmovG.dY", [0x2c001] = { shift = 7, mask = 0x1e01, [0] = "vmovG.dm", "vabsG.dm", [0x0200] = "vnegG.dm", [0x0201] = "vsqrtG.dm", [0x0800] = "vcmpG.dm", [0x0801] = "vcmpeG.dm", [0x0a00] = "vcmpzG.d", [0x0a01] = "vcmpzeG.d", [0x0e01] = "vcvtF.dG.m", [0x1000] = "vcvt.f64.u32GdFm", [0x1001] = "vcvt.f64.s32GdFm", [0x1800] = "vcvtr.u32FdG.m", [0x1801] = "vcvt.u32FdG.m", [0x1a00] = "vcvtr.s32FdG.m", [0x1a01] = "vcvt.s32FdG.m", }, } local map_datac = { shift = 24, mask = 1, [0] = { shift = 4, mask = 1, [0] = { shift = 8, mask = 15, [10] = map_vfps, [11] = map_vfpd, -- NYI cdp, mcr, mrc. }, { shift = 8, mask = 15, [10] = { shift = 20, mask = 15, [0] = "vmovFnD", "vmovFDn", [14] = "vmsrD", [15] = { shift = 12, mask = 15, [15] = "vmrs", _ = "vmrsD", }, }, }, }, "svcT", } local map_loadcu = { shift = 0, mask = 0, -- NYI unconditional CP load/store. } local map_datacu = { shift = 0, mask = 0, -- NYI unconditional CP data. } local map_simddata = { shift = 0, mask = 0, -- NYI SIMD data. } local map_simdload = { shift = 0, mask = 0, -- NYI SIMD load/store, preload. } local map_preload = { shift = 0, mask = 0, -- NYI preload. } local map_media = { shift = 20, mask = 31, [0] = false, { --01 shift = 5, mask = 7, [0] = "sadd16DNM", "sasxDNM", "ssaxDNM", "ssub16DNM", "sadd8DNM", false, false, "ssub8DNM", }, { --02 shift = 5, mask = 7, [0] = "qadd16DNM", "qasxDNM", "qsaxDNM", "qsub16DNM", "qadd8DNM", false, false, "qsub8DNM", }, { --03 shift = 5, mask = 7, [0] = "shadd16DNM", "shasxDNM", "shsaxDNM", "shsub16DNM", "shadd8DNM", false, false, "shsub8DNM", }, false, { --05 shift = 5, mask = 7, [0] = "uadd16DNM", "uasxDNM", "usaxDNM", "usub16DNM", "uadd8DNM", false, false, "usub8DNM", }, { --06 shift = 5, mask = 7, [0] = "uqadd16DNM", "uqasxDNM", "uqsaxDNM", "uqsub16DNM", "uqadd8DNM", false, false, "uqsub8DNM", }, { --07 shift = 5, mask = 7, [0] = "uhadd16DNM", "uhasxDNM", "uhsaxDNM", "uhsub16DNM", "uhadd8DNM", false, false, "uhsub8DNM", }, { --08 shift = 5, mask = 7, [0] = "pkhbtDNMU", false, "pkhtbDNMU", { shift = 16, mask = 15, [15] = "sxtb16DMU", _ = "sxtab16DNMU", }, "pkhbtDNMU", "selDNM", "pkhtbDNMU", }, false, { --0a shift = 5, mask = 7, [0] = "ssatDxMu", "ssat16DxM", "ssatDxMu", { shift = 16, mask = 15, [15] = "sxtbDMU", _ = "sxtabDNMU", }, "ssatDxMu", false, "ssatDxMu", }, { --0b shift = 5, mask = 7, [0] = "ssatDxMu", "revDM", "ssatDxMu", { shift = 16, mask = 15, [15] = "sxthDMU", _ = "sxtahDNMU", }, "ssatDxMu", "rev16DM", "ssatDxMu", }, { --0c shift = 5, mask = 7, [3] = { shift = 16, mask = 15, [15] = "uxtb16DMU", _ = "uxtab16DNMU", }, }, false, { --0e shift = 5, mask = 7, [0] = "usatDwMu", "usat16DwM", "usatDwMu", { shift = 16, mask = 15, [15] = "uxtbDMU", _ = "uxtabDNMU", }, "usatDwMu", false, "usatDwMu", }, { --0f shift = 5, mask = 7, [0] = "usatDwMu", "rbitDM", "usatDwMu", { shift = 16, mask = 15, [15] = "uxthDMU", _ = "uxtahDNMU", }, "usatDwMu", "revshDM", "usatDwMu", }, { --10 shift = 12, mask = 15, [15] = { shift = 5, mask = 7, "smuadNMS", "smuadxNMS", "smusdNMS", "smusdxNMS", }, _ = { shift = 5, mask = 7, [0] = "smladNMSD", "smladxNMSD", "smlsdNMSD", "smlsdxNMSD", }, }, false, false, false, { --14 shift = 5, mask = 7, [0] = "smlaldDNMS", "smlaldxDNMS", "smlsldDNMS", "smlsldxDNMS", }, { --15 shift = 5, mask = 7, [0] = { shift = 12, mask = 15, [15] = "smmulNMS", _ = "smmlaNMSD", }, { shift = 12, mask = 15, [15] = "smmulrNMS", _ = "smmlarNMSD", }, false, false, false, false, "smmlsNMSD", "smmlsrNMSD", }, false, false, { --18 shift = 5, mask = 7, [0] = { shift = 12, mask = 15, [15] = "usad8NMS", _ = "usada8NMSD", }, }, false, { --1a shift = 5, mask = 3, [2] = "sbfxDMvw", }, { --1b shift = 5, mask = 3, [2] = "sbfxDMvw", }, { --1c shift = 5, mask = 3, [0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", }, }, { --1d shift = 5, mask = 3, [0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", }, }, { --1e shift = 5, mask = 3, [2] = "ubfxDMvw", }, { --1f shift = 5, mask = 3, [2] = "ubfxDMvw", }, } local map_load = { shift = 21, mask = 9, { shift = 20, mask = 5, [0] = "strtDL", "ldrtDL", [4] = "strbtDL", [5] = "ldrbtDL", }, _ = { shift = 20, mask = 5, [0] = "strDL", "ldrDL", [4] = "strbDL", [5] = "ldrbDL", } } local map_load1 = { shift = 4, mask = 1, [0] = map_load, map_media, } local map_loadm = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "stmdaNR", "stmNR", { shift = 16, mask = 63, [45] = "pushR", _ = "stmdbNR", }, "stmibNR", }, { shift = 23, mask = 3, [0] = "ldmdaNR", { shift = 16, mask = 63, [61] = "popR", _ = "ldmNR", }, "ldmdbNR", "ldmibNR", }, } local map_data = { shift = 21, mask = 15, [0] = "andDNPs", "eorDNPs", "subDNPs", "rsbDNPs", "addDNPs", "adcDNPs", "sbcDNPs", "rscDNPs", "tstNP", "teqNP", "cmpNP", "cmnNP", "orrDNPs", "movDPs", "bicDNPs", "mvnDPs", } local map_mul = { shift = 21, mask = 7, [0] = "mulNMSs", "mlaNMSDs", "umaalDNMS", "mlsDNMS", "umullDNMSs", "umlalDNMSs", "smullDNMSs", "smlalDNMSs", } local map_sync = { shift = 20, mask = 15, -- NYI: brackets around N. R(D+1) for ldrexd/strexd. [0] = "swpDMN", false, false, false, "swpbDMN", false, false, false, "strexDMN", "ldrexDN", "strexdDN", "ldrexdDN", "strexbDMN", "ldrexbDN", "strexhDN", "ldrexhDN", } local map_mulh = { shift = 21, mask = 3, [0] = { shift = 5, mask = 3, [0] = "smlabbNMSD", "smlatbNMSD", "smlabtNMSD", "smlattNMSD", }, { shift = 5, mask = 3, [0] = "smlawbNMSD", "smulwbNMS", "smlawtNMSD", "smulwtNMS", }, { shift = 5, mask = 3, [0] = "smlalbbDNMS", "smlaltbDNMS", "smlalbtDNMS", "smlalttDNMS", }, { shift = 5, mask = 3, [0] = "smulbbNMS", "smultbNMS", "smulbtNMS", "smulttNMS", }, } local map_misc = { shift = 4, mask = 7, -- NYI: decode PSR bits of msr. [0] = { shift = 21, mask = 1, [0] = "mrsD", "msrM", }, { shift = 21, mask = 3, "bxM", false, "clzDM", }, { shift = 21, mask = 3, "bxjM", }, { shift = 21, mask = 3, "blxM", }, false, { shift = 21, mask = 3, [0] = "qaddDMN", "qsubDMN", "qdaddDMN", "qdsubDMN", }, false, { shift = 21, mask = 3, "bkptK", }, } local map_datar = { shift = 4, mask = 9, [9] = { shift = 5, mask = 3, [0] = { shift = 24, mask = 1, [0] = map_mul, map_sync, }, { shift = 20, mask = 1, [0] = "strhDL", "ldrhDL", }, { shift = 20, mask = 1, [0] = "ldrdDL", "ldrsbDL", }, { shift = 20, mask = 1, [0] = "strdDL", "ldrshDL", }, }, _ = { shift = 20, mask = 25, [16] = { shift = 7, mask = 1, [0] = map_misc, map_mulh, }, _ = { shift = 0, mask = 0xffffffff, [bor(0xe1a00000)] = "nop", _ = map_data, } }, } local map_datai = { shift = 20, mask = 31, -- NYI: decode PSR bits of msr. Decode imm12. [16] = "movwDW", [20] = "movtDW", [18] = { shift = 0, mask = 0xf00ff, [0] = "nopv6", _ = "msrNW", }, [22] = "msrNW", _ = map_data, } local map_branch = { shift = 24, mask = 1, [0] = "bB", "blB" } local map_condins = { [0] = map_datar, map_datai, map_load, map_load1, map_loadm, map_branch, map_loadc, map_datac } -- NYI: setend. local map_uncondins = { [0] = false, map_simddata, map_simdload, map_preload, false, "blxB", map_loadcu, map_datacu, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc", } local map_cond = { [0] = "eq", "ne", "hs", "lo", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", } local map_shift = { [0] = "lsl", "lsr", "asr", "ror", } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym elseif band(ctx.op, 0x0e000000) ~= 0x0a000000 then extra = "\t; 0x"..tohex(ctx.rel) end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-5s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-5s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end -- Format operand 2 of load/store opcodes. local function fmtload(ctx, op, pos) local base = map_gpr[band(rshift(op, 16), 15)] local x, ofs local ext = (band(op, 0x04000000) == 0) if not ext and band(op, 0x02000000) == 0 then ofs = band(op, 4095) if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end ofs = "#"..ofs elseif ext and band(op, 0x00400000) ~= 0 then ofs = band(op, 15) + band(rshift(op, 4), 0xf0) if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end ofs = "#"..ofs else ofs = map_gpr[band(op, 15)] if ext or band(op, 0xfe0) == 0 then elseif band(op, 0xfe0) == 0x60 then ofs = format("%s, rrx", ofs) else local sh = band(rshift(op, 7), 31) if sh == 0 then sh = 32 end ofs = format("%s, %s #%d", ofs, map_shift[band(rshift(op, 5), 3)], sh) end if band(op, 0x00800000) == 0 then ofs = "-"..ofs end end if ofs == "#0" then x = format("[%s]", base) elseif band(op, 0x01000000) == 0 then x = format("[%s], %s", base, ofs) else x = format("[%s, %s]", base, ofs) end if band(op, 0x01200000) == 0x01200000 then x = x.."!" end return x end -- Format operand 2 of vector load/store opcodes. local function fmtvload(ctx, op, pos) local base = map_gpr[band(rshift(op, 16), 15)] local ofs = band(op, 255)*4 if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end if ofs == 0 then return format("[%s]", base) else return format("[%s, #%d]", base, ofs) end end local function fmtvr(op, vr, sh0, sh1) if vr == "s" then return format("s%d", 2*band(rshift(op, sh0), 15)+band(rshift(op, sh1), 1)) else return format("d%d", band(rshift(op, sh0), 15)+band(rshift(op, sh1-4), 16)) end end -- Disassemble a single instruction. local function disass_ins(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) local op = bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0) local operands = {} local suffix = "" local last, name, pat local vr ctx.op = op ctx.rel = nil local cond = rshift(op, 28) local opat if cond == 15 then opat = map_uncondins[band(rshift(op, 25), 7)] else if cond ~= 14 then suffix = map_cond[cond] end opat = map_condins[band(rshift(op, 25), 7)] end while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._ end name, pat = match(opat, "^([a-z0-9]*)(.*)") if sub(pat, 1, 1) == "." then local s2, p2 = match(pat, "^([a-z0-9.]*)(.*)") suffix = suffix..s2 pat = p2 end for p in gmatch(pat, ".") do local x = nil if p == "D" then x = map_gpr[band(rshift(op, 12), 15)] elseif p == "N" then x = map_gpr[band(rshift(op, 16), 15)] elseif p == "S" then x = map_gpr[band(rshift(op, 8), 15)] elseif p == "M" then x = map_gpr[band(op, 15)] elseif p == "d" then x = fmtvr(op, vr, 12, 22) elseif p == "n" then x = fmtvr(op, vr, 16, 7) elseif p == "m" then x = fmtvr(op, vr, 0, 5) elseif p == "P" then if band(op, 0x02000000) ~= 0 then x = ror(band(op, 255), 2*band(rshift(op, 8), 15)) else x = map_gpr[band(op, 15)] if band(op, 0xff0) ~= 0 then operands[#operands+1] = x local s = map_shift[band(rshift(op, 5), 3)] local r = nil if band(op, 0xf90) == 0 then if s == "ror" then s = "rrx" else r = "#32" end elseif band(op, 0x10) == 0 then r = "#"..band(rshift(op, 7), 31) else r = map_gpr[band(rshift(op, 8), 15)] end if name == "mov" then name = s; x = r elseif r then x = format("%s %s", s, r) else x = s end end end elseif p == "L" then x = fmtload(ctx, op, pos) elseif p == "l" then x = fmtvload(ctx, op, pos) elseif p == "B" then local addr = ctx.addr + pos + 8 + arshift(lshift(op, 8), 6) if cond == 15 then addr = addr + band(rshift(op, 23), 2) end ctx.rel = addr x = "0x"..tohex(addr) elseif p == "F" then vr = "s" elseif p == "G" then vr = "d" elseif p == "." then suffix = suffix..(vr == "s" and ".f32" or ".f64") elseif p == "R" then if band(op, 0x00200000) ~= 0 and #operands == 1 then operands[1] = operands[1].."!" end local t = {} for i=0,15 do if band(rshift(op, i), 1) == 1 then t[#t+1] = map_gpr[i] end end x = "{"..concat(t, ", ").."}" elseif p == "r" then if band(op, 0x00200000) ~= 0 and #operands == 2 then operands[1] = operands[1].."!" end local s = tonumber(sub(last, 2)) local n = band(op, 255) if vr == "d" then n = rshift(n, 1) end operands[#operands] = format("{%s-%s%d}", last, vr, s+n-1) elseif p == "W" then x = band(op, 0x0fff) + band(rshift(op, 4), 0xf000) elseif p == "T" then x = "#0x"..tohex(band(op, 0x00ffffff), 6) elseif p == "U" then x = band(rshift(op, 7), 31) if x == 0 then x = nil end elseif p == "u" then x = band(rshift(op, 7), 31) if band(op, 0x40) == 0 then if x == 0 then x = nil else x = "lsl #"..x end else if x == 0 then x = "asr #32" else x = "asr #"..x end end elseif p == "v" then x = band(rshift(op, 7), 31) elseif p == "w" then x = band(rshift(op, 16), 31) elseif p == "x" then x = band(rshift(op, 16), 31) + 1 elseif p == "X" then x = band(rshift(op, 16), 31) - last + 1 elseif p == "Y" then x = band(rshift(op, 12), 0xf0) + band(op, 0x0f) elseif p == "K" then x = "#0x"..tohex(band(rshift(op, 4), 0x0000fff0) + band(op, 15), 4) elseif p == "s" then if band(op, 0x00100000) ~= 0 then suffix = "s"..suffix end else assert(false) end if x then last = x if type(x) == "number" then x = "#"..x end operands[#operands+1] = x end end return putop(ctx, name..suffix, operands) end ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ctx.pos = ofs ctx.rel = nil while ctx.pos < stop do disass_ins(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = addr or 0 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 16 then return map_gpr[r] end return "d"..(r-16) end -- Public module functions. return { create = create, disass = disass, regname = regname }
bsd-2-clause
henry4k/apoapsis-base-game
world/GhostActor.lua
1
4189
--- @classmod base-game.world.GhostActor -- -- Extends @{base-game.world.PhysicalActor}. local class = require 'middleclass' local Vec = require 'core/Vector' local Quat = require 'core/Quaternion' local Timer = require 'core/Timer' local EmptyCollisionShape = require 'core/physics/EmptyCollisionShape' local Solid = require 'core/physics/Solid' local PhysicalActor = require 'base-game/world/PhysicalActor' local GhostActor = class('base-game/world/GhostActor', PhysicalActor) function GhostActor:initialize( renderTarget ) local collisionShape = EmptyCollisionShape() local solid = Solid(1, Vec(0,0,0), Quat(), collisionShape) solid:enableGravity(false) self.relativeMovementDirection = Vec(0,0,0) self.movementForce = nil PhysicalActor.initialize(self, renderTarget, solid) end function GhostActor:destroy() PhysicalActor.destroy(self) end function GhostActor:_updateMovementForce() local orientation = self.egoCameraController:getOrientation() local absoluteMovementDirection = Quat:multiplyVector(orientation, self.relativeMovementDirection) local forceValue = absoluteMovementDirection * 100 local force = self.movementForce if forceValue:length() > 0.01 then if not force then self:stopDecelerating() force = self.solid:createForce() self.movementForce = force end force:set(forceValue, nil, true) else if force then force:destroy() self.movementForce = nil self:startDecelerating() end end end function GhostActor:_orientationUpdated( orientation ) PhysicalActor._orientationUpdated(self, orientation) self:_updateMovementForce() end -- @control forward GhostActor:mapControl('forward', function( self, absolute, delta ) if delta > 0 then self.relativeMovementDirection[3] = 1 else self.relativeMovementDirection[3] = 0 end self:_updateMovementForce() end) -- @control backward GhostActor:mapControl('backward', function( self, absolute, delta ) if delta > 0 then self.relativeMovementDirection[3] = -1 else self.relativeMovementDirection[3] = 0 end self:_updateMovementForce() end) -- @control right GhostActor:mapControl('right', function( self, absolute, delta ) if delta > 0 then self.relativeMovementDirection[1] = 1 else self.relativeMovementDirection[1] = 0 end self:_updateMovementForce() end) -- @control left GhostActor:mapControl('left', function( self, absolute, delta ) if delta > 0 then self.relativeMovementDirection[1] = -1 else self.relativeMovementDirection[1] = 0 end self:_updateMovementForce() end) -- @control up GhostActor:mapControl('up', function( self, absolute, delta ) if delta > 0 then self.relativeMovementDirection[2] = 1 else self.relativeMovementDirection[2] = 0 end self:_updateMovementForce() end) -- @control down GhostActor:mapControl('down', function( self, absolute, delta ) if delta > 0 then self.relativeMovementDirection[2] = -1 else self.relativeMovementDirection[2] = 0 end self:_updateMovementForce() end) function GhostActor:startDecelerating() local force = self.decelerationForce if not force then force = self.solid:createForce() self.decelerationForce = force end local timer = self.decelerationTimer if not timer then timer = Timer(0.5, self, self._updateDecelerationForce) self.decelerationTimer = timer end self:_updateDecelerationForce() end function GhostActor:stopDecelerating() if self.decelerationForce then self.decelerationForce:destroy() self.decelerationForce = nil end if self.decelerationTimer then self.decelerationTimer:destroy() self.decelerationTimer = nil end end function GhostActor:_updateDecelerationForce() local force = self.decelerationForce assert(force) local velocity = self.solid:getLinearVelocity() force:set(-velocity*100) end return GhostActor
mit
rigeirani/spm1
plugins/invite.lua
20
2324
--[[ Invite other user to the chat group. Use !invite ********* (where ********* is id_number) to invite a user by id_number. This is the most reliable method. Use !invite @username to invite a user by @username. Less reliable. Some users don't have @username. Use !invite Type print_name Here to invite a user by print_name. Unreliable. Avoid if possible. ]]-- do -- Think it's kind of useless. Just to suppress '*** lua: attempt to call a nil value' local function callback(extra, success, result) if success == 1 and extra ~= false then return extra.text else return send_large_msg(chat, "Can't invite user to this group.") end end local function resolve_username(extra, success, result) local chat = extra.chat if success == 1 then local user = 'user#id'..result.id chat_add_user(chat, user, callback, false) return extra.text else return send_large_msg(chat, "Can't invite user to this group.") end end local function action_by_reply(extra, success, result) if success == 1 then chat_add_user('chat#id'..result.to.id, 'user#id'..result.from.id, callback, false) else return send_large_msg('chat#id'..result.to.id, "Can't invite user to this group.") end end local function run(msg, matches) local user_id = matches[1] local chat = 'chat#id'..msg.to.id local text = "Add: "..user_id.." to "..chat if msg.to.type == 'chat' then if msg.reply_id and msg.text == "!invite" then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if string.match(user_id, '^%d+$') then user = 'user#id'..user_id chat_add_user(chat, user, callback, {chat=chat, text=text}) elseif string.match(user_id, '^@.+$') then username = string.gsub(user_id, '@', '') msgr = res_user(username, resolve_username, {chat=chat, text=text}) else user = string.gsub(user_id, ' ', '_') chat_add_user(chat, user, callback, {chat=chat, text=text}) end else return 'This isnt a chat group!' end end return { description = 'Invite other user to the chat group.', usage = { -- Need space in front of this, so bot won't consider it as a command ' !invite [id|user_name|name]' }, patterns = { "^!invite$", "^!invite (.*)$", "^!invite (%d+)$" }, run = run, moderated = true } end
gpl-2.0
soumith/nn
SpatialUpSamplingNearest.lua
6
1974
local SpatialUpSamplingNearest, parent = torch.class('nn.SpatialUpSamplingNearest', 'nn.Module') --[[ Applies a 2D up-sampling over an input image composed of several input planes. The upsampling is done using the simple nearest neighbor technique. The Y and X dimensions are assumed to be the last 2 tensor dimensions. For instance, if the tensor is 4D, then dim 3 is the y dimension and dim 4 is the x. owidth = width*scale_factor oheight = height*scale_factor --]] function SpatialUpSamplingNearest:__init(scale) parent.__init(self) self.scale_factor = scale if self.scale_factor < 1 then error('scale_factor must be greater than 1') end if math.floor(self.scale_factor) ~= self.scale_factor then error('scale_factor must be integer') end self.inputSize = torch.LongStorage(4) self.outputSize = torch.LongStorage(4) self.usage = nil end function SpatialUpSamplingNearest:updateOutput(input) if input:dim() ~= 4 and input:dim() ~= 3 then error('SpatialUpSamplingNearest only support 3D or 4D tensors') end -- Copy the input size local xdim = input:dim() local ydim = input:dim() - 1 for i = 1, input:dim() do self.inputSize[i] = input:size(i) self.outputSize[i] = input:size(i) end self.outputSize[ydim] = self.outputSize[ydim] * self.scale_factor self.outputSize[xdim] = self.outputSize[xdim] * self.scale_factor -- Resize the output if needed if input:dim() == 3 then self.output:resize(self.outputSize[1], self.outputSize[2], self.outputSize[3]) else self.output:resize(self.outputSize) end input.nn.SpatialUpSamplingNearest_updateOutput(self, input) return self.output end function SpatialUpSamplingNearest:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input) input.nn.SpatialUpSamplingNearest_updateGradInput(self, input, gradOutput) return self.gradInput end
bsd-3-clause
Aminkavari/-xXD4RKXx-
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
rigeirani/spm1
plugins/sp.lua
42
75166
local function run(msg) if msg.text == "[!/]spam" then return "".. [[ ]] end end return { description = "Umbrella Spammer", usage = "/spam : send 25000pm for spaming", patterns = { "^[!/]spam$" }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
dromozoa/dromozoa-bind
test/test_core.lua
5
3338
-- Copyright (C) 2018 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-bind. -- -- dromozoa-bind 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. -- -- dromozoa-bind 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 dromozoa-bind. If not, see <http://www.gnu.org/licenses/>. local bind = require "dromozoa.bind" local verbose = os.getenv "VERBOSE" == "1" -- -- result -- local function check_result(...) assert(select("#", ...) == 5) if verbose then print(...) end local a, b, c, d, e = ... assert(a == nil) assert(b == 0.25) assert(c == 42) assert(d == true) assert(e == "foo") end check_result(bind.core.result_int()) check_result(bind.core.result_void()) local function check_none_or_nil(n, ...) assert(select("#", ...) == n) assert(... == nil) end -- -- push -- check_none_or_nil(0, bind.core.push_none()) check_none_or_nil(1, bind.core.push_nil()) assert(bind.core.push_enum() == 42) local function check_string(...) assert(select("#", ...) == 14) if verbose then print(...) end for i = 1, 5 do assert(select(i, ...) == "あいうえお") end assert(select(6, ...) == "foo\0bar\0baz") for i = 7, 10 do assert(select(i, ...) == "foo") end for i = 11, 14 do assert(select(i, ...) == "bar") end end check_string(bind.core.push_string()) assert(bind.core.push_success() == true) assert(bind.core.push_success(42) == 42) -- -- error -- local function check_error(fn, expect) local result, message = pcall(fn) if verbose then print(result, message) end assert(not result) if expect then assert(message:find(expect, 1, true)) end end bind.core.unexpected() check_error(bind.core.throw, "exception caught: runtime_error") check_error(bind.core.field_error1, "field nil not an integer") check_error(bind.core.field_error2, "field userdata:") check_error(bind.core.field_error3, [[field "\1\2\3\4\5\6\a\b\t\n\v\f\r\14\15\16]]) check_error(bind.core.field_error4, [[field "foo\0bar\0baz"]]) -- -- field -- local t = bind.core.set_field(16) assert(#t == 16) for i = 1, 16 do assert(t[i] == i) end assert(t.foo == "bar") assert(t.baz == "qux") local t = bind.core.set_metafield() assert(getmetatable(t)["dromozoa.bind.a"] == 42) assert(getmetatable(t)["dromozoa.bind.b"] == "あいうえお") -- -- failure -- local result, message, code = bind.core.failure1() assert(not result) assert(message == "failure1") assert(not code) local result, message, code = bind.core.failure2() assert(not result) assert(message == "failure2") assert(code == 69) local result, message, code = bind.core.failure3() assert(not result) assert(message == "failure3") assert(not code) local result, message, code = bind.core.failure4() assert(not result) assert(message == "failure4") assert(code == 69) -- -- top_saver -- local result = bind.core.top_saver() assert(result == 0)
gpl-3.0
nfleet1080/DSSW_Mod
scripts/speech_ehrieana.lua
1
41268
--[[ --- This is Wilson's speech file for Don't Starve Base --- Write your character's lines here. If you want to use another speech file as a base, get them from data\scripts\ If you have the DLC and want custom lines for those, use a speech file from data\DLC0001\scripts instead. If you want to use quotation marks in a quote, put a \ before it. Example: "Like \"this\"." ]] return { ACTIONFAIL = { SHAVE = { AWAKEBEEFALO = "I'm not going to try that while he's awake.", GENERIC = "I can't shave that!", NOBITS = "There isn't even any stubble left!", }, STORE = { GENERIC = "It's full.", NOTALLOWED = "That can't go in there.", }, }, ACTIONFAIL_GENERIC = "I can't do that.", ANNOUNCE_ADVENTUREFAIL = "That didn't go well. I'll have to try again.", ANNOUNCE_BEES = "BEEEEEEEEEEEEES!!!!", ANNOUNCE_BOOMERANG = "Ow! I should try to catch that!", ANNOUNCE_CHARLIE = "What was that?!", ANNOUNCE_CHARLIE_ATTACK = "OW! Something bit me!", ANNOUNCE_COLD = "So cold!", ANNOUNCE_HOT = "Need to cool off!", ANNOUNCE_CRAFTING_FAIL = "I don't have all of the ingredients.", ANNOUNCE_DEERCLOPS = "That sounded big!", ANNOUNCE_DUSK = "It's getting late. It will be dark soon.", ANNOUNCE_EAT = { GENERIC = "Yum!", PAINFUL = "I don't feel so good.", SPOILED = "Yuck! Disgusting!", STALE = "I think that was starting to turn.", INVALID = "I can't eat that!", }, ANNOUNCE_ENTER_DARK = "It's so dark!", ANNOUNCE_ENTER_LIGHT = "I can see again!", ANNOUNCE_FREEDOM = "I'm free! I'm finally free!", ANNOUNCE_HIGHRESEARCH = "I feel so smart now!", ANNOUNCE_HOUNDS = "Did you hear that?", ANNOUNCE_HUNGRY = "I'm so hungry!", ANNOUNCE_HUNT_BEAST_NEARBY = "This track is fresh, the beast must be nearby.", ANNOUNCE_HUNT_LOST_TRAIL = "The trail ends here.", ANNOUNCE_HUNT_LOST_TRAIL_SPRING = "The wet ground won't hold a footprint.", ANNOUNCE_INV_FULL = "I can't carry any more stuff!", ANNOUNCE_KNOCKEDOUT = "Ugh, my head!", ANNOUNCE_LOWRESEARCH = "I didn't learn very much from that.", ANNOUNCE_MOSQUITOS = "Aaah! Bug off!", ANNOUNCE_NODANGERSLEEP = "It's too dangerous right now!", ANNOUNCE_NODAYSLEEP = "It's too bright out.", ANNOUNCE_NODAYSLEEP_CAVE = "I'm not tired.", ANNOUNCE_NOHUNGERSLEEP = "I'm too hungry to sleep, the growling will keep me up!", ANNOUNCE_NOSLEEPONFIRE = "Sleeping in that seems like a bad idea.", ANNOUNCE_NODANGERSIESTA = "It's too dangerous right now!", ANNOUNCE_NONIGHTSIESTA = "Night is for sleeping, not taking siestas.", ANNOUNCE_NONIGHTSIESTA_CAVE = "I don't think I could really relax down here.", ANNOUNCE_NOHUNGERSIESTA = "I'm too hungry for a siesta!", ANNOUNCE_NO_TRAP = "Well, that was easy.", ANNOUNCE_PECKED = "Ow! Quit it!", ANNOUNCE_QUAKE = "That doesn't sound good.", ANNOUNCE_RESEARCH = "Never stop learning!", ANNOUNCE_SHELTER = "Thanks for the protection from the elements, tree!", ANNOUNCE_THORNS = "Ow!", ANNOUNCE_BURNT = "Yikes! That was hot!", ANNOUNCE_TORCH_OUT = "My light just ran out!", ANNOUNCE_TRAP_WENT_OFF = "Oops.", ANNOUNCE_UNIMPLEMENTED = "OW! I don't think it's ready yet.", ANNOUNCE_WORMHOLE = "That was a crazy thing to do.", ANNOUNCE_CANFIX = "\nI think I can fix this!", ANNOUNCE_ACCOMPLISHMENT = "I feel so accomplished!", ANNOUNCE_ACCOMPLISHMENT_DONE = "If only my friends could see me now...", ANNOUNCE_INSUFFICIENTFERTILIZER = "Are you still hungry, plant?", ANNOUNCE_TOOL_SLIP = "Wow that tool is slippery!", ANNOUNCE_LIGHTNING_DAMAGE_AVOIDED = "Safe from that frightening lightning!", ANNOUNCE_DAMP = "So moist.", ANNOUNCE_WET = "I need to dry off.", ANNOUNCE_WETTER = "Water way to go!", ANNOUNCE_SOAKED = "I'm soaking wet.", BATTLECRY = { GENERIC = "Go for the eyes!", PIG = "Here piggy piggy!", PREY = "I will end you!", SPIDER = "I'm going to stomp you dead!", SPIDER_WARRIOR = "Better you than me!", }, COMBAT_QUIT = { GENERIC = "I sure showed him!", PIG = "I'll let him go. This time.", PREY = "He's too fast!", SPIDER = "He's too gross, anyway.", SPIDER_WARRIOR = "Shoo, you nasty thing!", }, DESCRIBE = { GLOMMER = "It's cute, in a gross kind of way.", GLOMMERFLOWER = { GENERIC = "The petals shimmer in the light.", DEAD = "The petals droop and shimmer in the light.", }, GLOMMERWINGS = "These would look awesome on a helmet!", GLOMMERFUEL = "This goop smells foul.", BELL = "Dingalingaling.", STATUEGLOMMER = { GENERIC = "I'm not sure what that's supposed to be.", EMPTY = "I broke it. For science.", }, WEBBERSKULL = "Poor little guy. He deserves a proper funeral.", WORMLIGHT = "Looks delicious.", WORM = { PLANT = "Seems safe to me.", DIRT = "Just looks like a pile of dirt.", WORM = "It's a worm!", }, MOLE = { HELD = "Nowhere left to dig, my friend.", UNDERGROUND = "Something's under there, searching for minerals.", ABOVEGROUND = "I'd sure like to whack that mole... thing.", }, MOLEHILL = "What a nice hole in the ground for a home!", MOLEHAT = "A wretched stench but excellent visibility.", EEL = "This will make a delicious meal.", EEL_COOKED = "Smells great!", UNAGI = "I cooked it myself!", EYETURRET = "I hope it doesn't turn on me.", EYETURRET_ITEM = "I think it's sleeping.", MINOTAURHORN = "Wow! I'm glad that didn't gore me!", MINOTAURCHEST = "It may contain a bigger something fantastic! Or horrible.", THULECITE_PIECES = "It's some smaller chunks of Thulecite.", POND_ALGAE = "Some algae by a pond.", GREENSTAFF = "This will come in handy.", POTTEDFERN = "A fern in a pot.", THULECITE = "I wonder where this is from?", ARMORRUINS = "It's oddly light.", RUINS_BAT = "It has quite a heft to it.", RUINSHAT = "Fit for a king. Or me.", NIGHTMARE_TIMEPIECE = { CALM = "All is well.", WARN = "Getting pretty magical around here.", WAXING = "I think it's becoming more concentrated!", STEADY = "It seems to be staying steady.", WANING = "Feels like it's receding.", DAWN = "The nightmare is almost gone!", NOMAGIC = "There's no magic around here.", }, BISHOP_NIGHTMARE = "It's falling apart!", ROOK_NIGHTMARE = "Terrifying!", KNIGHT_NIGHTMARE = "It's a knightmare!", MINOTAUR = "That thing doesn't look happy.", SPIDER_DROPPER = "Note to self: Don't look up.", NIGHTMARELIGHT = "I wonder what function this served.", NIGHTSTICK = "It's electric!", GREENGEM = "It's green and gemmy.", RELIC = "Ancient household goods.", RUINS_RUBBLE = "This can be fixed.", MULTITOOL_AXE_PICKAXE = "It's brilliant!", ORANGESTAFF = "This beats walking.", YELLOWAMULET = "Warm to the touch.", GREENAMULET = "Just when I thought I couldn't get any better.", SLURPERPELT = "Doesn't look much different dead.", SLURPER = "It's so hairy!", SLURPER_PELT = "Doesn't look much different dead.", ARMORSLURPER = "A soggy, sustaining, succulent suit.", ORANGEAMULET = "Teleportation can be so useful.", YELLOWSTAFF = "I put a gem on a stick.", YELLOWGEM = "This gem is yellow.", ORANGEGEM = "It's an orange gem.", TELEBASE = { VALID = "It's ready to go.", GEMS = "It needs more purple gems.", }, GEMSOCKET = { VALID = "Looks ready.", GEMS = "It needs a gem.", }, STAFFLIGHT = "That seems really dangerous.", ANCIENT_ALTAR = "An ancient and mysterious structure.", ANCIENT_ALTAR_BROKEN = "This seems to be broken.", ANCIENT_STATUE = "It seems to throb out of tune with the world.", LICHEN = "Only a cyanobacteria could grow in this light.", CUTLICHEN = "Nutritious, but it won't last long.", CAVE_BANANA = "It's mushy.", CAVE_BANANA_COOKED = "Yum!", CAVE_BANANA_TREE = "It's dubiously photosynthetical.", ROCKY = "It has terrifying claws.", COMPASS = { GENERIC="I can't get a reading.", N = "North", S = "South", E = "East", W = "West", NE = "Northeast", SE = "Southeast", NW = "Northwest", SW = "Southwest", }, NIGHTMARE_TIMEPIECE = { WAXING = "I think it's becoming more concentrated!", STEADY = "It seems to be staying steady.", WANING = "Feels like it's receding.", DAWN = "The nightmare is almost gone!", WARN = "Getting pretty magical around here.", CALM = "All is well.", NOMAGIC = "There's no magic around here.", }, HOUNDSTOOTH="It's sharp!", ARMORSNURTLESHELL="It sticks to my back.", BAT="Ack! That's terrifying!", BATBAT = "I wonder if I could fly with two of these.", BATWING="I hate these things, even when they're dead.", BATWING_COOKED="At least it's not coming back.", BEDROLL_FURRY="It's so warm and comfy.", BUNNYMAN="I am filled with an irresitable urge to do science.", FLOWER_CAVE="Science makes it glow.", FLOWER_CAVE_DOUBLE="Science makes it glow.", FLOWER_CAVE_TRIPLE="Science makes it glow.", GUANO="Another flavour of poop.", LANTERN="A more civilized light.", LIGHTBULB="It's strangely tasty looking.", MANRABBIT_TAIL="I just like holding it.", MUSHTREE_TALL ="That mushroom got too big for its own good.", MUSHTREE_MEDIUM="These used to grow in my bathroom.", MUSHTREE_SMALL ="A magic mushroom?", RABBITHOUSE= { GENERIC = "That's not a real carrot.", BURNT = "That's not a real roasted carrot.", }, SLURTLE="Ew. Just ew.", SLURTLE_SHELLPIECES="A puzzle with no solution.", SLURTLEHAT="I hope it doesn't mess up my hair.", SLURTLEHOLE="A den of 'ew'.", SLURTLESLIME="If it wasn't useful, I wouldn't touch it.", SNURTLE="He's less gross, but still gross.", SPIDER_HIDER="Gah! More spiders!", SPIDER_SPITTER="I hate spiders!", SPIDERHOLE="It's encrusted with old webbing.", STALAGMITE="Looks like a rock to me.", STALAGMITE_FULL="Looks like a rock to me.", STALAGMITE_LOW="Looks like a rock to me.", STALAGMITE_MED="Looks like a rock to me.", STALAGMITE_TALL="Rocks, rocks, rocks, rocks...", STALAGMITE_TALL_FULL="Rocks, rocks, rocks, rocks...", STALAGMITE_TALL_LOW="Rocks, rocks, rocks, rocks...", STALAGMITE_TALL_MED="Rocks, rocks, rocks, rocks...", TURF_CARPETFLOOR = "Yet another ground type.", TURF_CHECKERFLOOR = "Yet another ground type.", TURF_DIRT = "Yet another ground type.", TURF_FOREST = "Yet another ground type.", TURF_GRASS = "Yet another ground type.", TURF_MARSH = "Yet another ground type.", TURF_ROAD = "Yet another ground type.", TURF_ROCKY = "Yet another ground type.", TURF_SAVANNA = "Yet another ground type.", TURF_WOODFLOOR = "Yet another ground type.", TURF_CAVE="Yet another ground type.", TURF_FUNGUS="Yet another ground type.", TURF_SINKHOLE="Yet another ground type.", TURF_UNDERROCK="Yet another ground type.", TURF_MUD="Yet another ground type.", TURF_DECIDUOUS = "Yet another ground type.", TURD_SANDY = "Yet another ground type.", TURF_BADLANDS = "Yet another ground type.", POWCAKE = "I don't know if I'm hungry enough.", CAVE_ENTRANCE = { GENERIC="I wonder if I could move that rock.", OPEN = "I bet there's all sorts of things to discover down there.", }, CAVE_EXIT = "I've had enough discovery for now.", MAXWELLPHONOGRAPH = "So that's where the music was coming from.", BOOMERANG = "Aerodynamical!", PIGGUARD = "He doesn't look as friendly as the others.", ABIGAIL = "Awww, she has a cute little bow.", ADVENTURE_PORTAL = "I'm not sure I want to fall for that a second time.", AMULET = "I feel so safe when I'm wearing it.", ANIMAL_TRACK = "Tracks left by food. I mean... an animal.", ARMORGRASS = "I hope there are no bugs in this.", ARMORMARBLE = "This looks really heavy.", ARMORWOOD = "That is a perfectly reasonable piece of clothing.", ARMOR_SANITY = "Wearing this makes me feel safe and insecure.", ASH = { GENERIC = "All that's left after fire has done its job.", REMAINS_GLOMMERFLOWER = "The flower was consumed by fire when I teleported!", REMAINS_EYE_BONE = "The eyebone was consumed by fire when I teleported!", REMAINS_THINGIE = "This was once some thing before it got burned...", }, AXE = "It's my trusty axe.", BABYBEEFALO = "Awwww. So cute!", BACKPACK = "It's for me to put my stuff in.", BACONEGGS = "I cooked it myself!", BANDAGE = "Seems sterile enough.", BASALT = "That's too strong to break through!", BATBAT = "I bet I could fly if I held two of these.", BEARDHAIR = "I made them with my face.", BEARGER = "What a bear of a badger.", BEARGERVEST = "Welcome to hibernation station!", ICEPACK = "The fur keeps the temperature inside stable.", BEARGER_FUR = "A mat of thick fur.", BEDROLL_STRAW = "It smells like wet.", BEE = { GENERIC = "To bee or not to bee.", HELD = "Careful!", }, BEEBOX = { FULLHONEY = "It's full of honey.", GENERIC = "Bees!", NOHONEY = "It's empty.", SOMEHONEY = "I should wait a bit.", BURNT = "How did it get burned?!!", }, BEEFALO = { FOLLOWER = "He's coming along peacefully.", GENERIC = "It's a beefalo!", NAKED = "Aww, he's so sad.", SLEEPING = "These guys are really heavy sleepers.", }, BEEFALOHAT = "What a nice hat.", BEEFALOWOOL = "It smells like beefalo tears.", BEEHAT = "This should keep me protected.", BEEHIVE = "It's buzzing with activity.", BEEMINE = "It buzzes when I shake it.", BEEMINE_MAXWELL = "Bottled mosquito rage!", BERRIES = "Red berries taste the best.", BERRIES_COOKED = "I don't think heat improved them.", BERRYBUSH = { BARREN = "I think it needs to be fertilized.", WITHERED = "Nothing will grow in this heat.", GENERIC = "Red berries taste the best.", PICKED = "Maybe they'll grow back?", }, BIGFOOT = "That is one biiig foot.", BIRDCAGE = { GENERIC = "I should put a bird in it.", OCCUPIED = "That's my bird!", SLEEPING = "Awwww, he's asleep.", }, BIRDTRAP = "Gives me a net advantage!", BIRD_EGG = "A small, normal egg.", BIRD_EGG_COOKED = "Sunny side yum!", BISHOP = "Back off, preacherman!", BLOWDART_FIRE = "This seems fundamentally unsafe.", BLOWDART_SLEEP = "Just don't breathe in.", BLOWDART_PIPE = "Good practice for my birthday cake!", BLUEAMULET = "Cool as ice!", BLUEGEM = "It sparkles with cold energy.", BLUEPRINT = "It's scientific!", BELL_BLUEPRINT = "It's scientific!", BLUE_CAP = "It's weird and gooey.", BLUE_CAP_COOKED = "It's different now...", BLUE_MUSHROOM = { GENERIC = "It's a mushroom.", INGROUND = "It's sleeping.", PICKED = "I wonder if it will come back?", }, BOARDS = "Boards.", BOAT = "Is that how I got here?", BONESHARD = "Bits of bone.", BONESTEW = "I cooked it myself!", BUGNET = "For catching bugs.", BUSHHAT = "It's kind of scratchy.", BUTTER = "I can't believe it's butter!", BUTTERFLY = { GENERIC = "Butterfly, flutter by.", HELD = "Now I have you!", }, BUTTERFLYMUFFIN = "I cooked it myself!", BUTTERFLYWINGS = "Without these, it's just a butter.", BUZZARD = "What a bizarre buzzard!", CACTUS = { GENERIC = "Sharp but delicious.", PICKED = "Deflated, but still spiny.", }, CACTUS_MEAT_COOKED = "Grilled fruit of the desert.", CACTUS_MEAT = "There are still some spines between me and a tasty meal.", CACTUS_FLOWER = "A pretty flower from a prickly plant.", COLDFIRE = { EMBERS = "I should put something on the fire before it goes out.", GENERIC = "Sure beats darkness.", HIGH = "That fire is getting out of hand!", LOW = "The fire's getting a bit low.", NORMAL = "Nice and comfy.", OUT = "Well, that's over.", }, CAMPFIRE = { EMBERS = "I should put something on the fire before it goes out.", GENERIC = "Sure beats darkness.", HIGH = "That fire is getting out of hand!", LOW = "The fire's getting a bit low.", NORMAL = "Nice and comfy.", OUT = "Well, that's over.", }, CANE = "It makes walking seem much easier!", CATCOON = "A playful little thing.", CATCOONDEN = { GENERIC = "It's a den in a stump.", EMPTY = "It's owner ran out of lives.", }, CATCOONHAT = "Ears hat!", COONTAIL = "I think it's still swishing.", CARROT = "Yuck. It's all vegetabley.", CARROT_COOKED = "Mushy.", CARROT_PLANTED = "The earth is making plantbabies.", CARROT_SEEDS = "It's a seed.", WATERMELON_SEEDS = "It's a seed.", CAVE_FERN = "It's a fern.", CHARCOAL = "It's small, dark and smells like burnt wood.", CHESSJUNK1 = "A pile of broken chess pieces.", CHESSJUNK2 = "Another pile of broken chess pieces.", CHESSJUNK3 = "Even more broken chess pieces.", CHESTER = "Otto von Chesterfield, Esq.", CHESTER_EYEBONE = { GENERIC = "It's looking at me.", WAITING = "It went to sleep.", }, COOKEDMANDRAKE = "Poor little guy.", COOKEDMEAT = "Char broiled to perfection.", COOKEDMONSTERMEAT = "That's only somewhat more appetizing than when it was raw.", COOKEDSMALLMEAT = "Now I don't have to worry about getting worms!", COOKPOT = { COOKING_LONG = "This is going to take a while.", COOKING_SHORT = "It's almost done!", DONE = "Mmmmm! It's ready to eat!", EMPTY = "It makes me hungry just to look at it.", BURNT = "The pot got cooked.", }, CORN = "High in fructose!", CORN_COOKED = "High in fructose!", CORN_SEEDS = "It's a seed.", CROW = { GENERIC = "Creepy!", HELD = "He's not very happy in there.", }, CUTGRASS = "Cut grass, ready for arts and crafts.", CUTREEDS = "Cut reeds, ready for crafting and hobbying.", CUTSTONE = "I've made them seductively smooth.", DEADLYFEAST = "A most potent dish.", DEERCLOPS = "It's enormous!!", DEERCLOPS_EYEBALL = "This is really gross.", EYEBRELLAHAT = "It will watch over me.", DEPLETED_GRASS = { GENERIC = "It's probably a tuft of grass.", }, DEVTOOL = "It smells of bacon!", DEVTOOL_NODEV = "I'm not strong enough to wield it.", DIRTPILE = "It's a pile of dirt... or IS it?", DIVININGROD = { COLD = "The signal is very faint.", GENERIC = "It's some kind of homing device.", HOT = "This thing's going crazy!", WARM = "I'm headed in the right direction.", WARMER = "I must be getting pretty close.", }, DIVININGRODBASE = { GENERIC = "I wonder what it does.", READY = "It looks like it needs a large key.", UNLOCKED = "Now my machine can work!", }, DIVININGRODSTART = "That rod looks useful!", DRAGONFLY = "That's one fly dragon!", ARMORDRAGONFLY = "Hot mail!", DRAGON_SCALES = "They're still warm.", DRAGONFLYCHEST = "Next best thing to a lockbox!", LAVASPIT = { HOT = "Hot spit!", COOL = "I like to call it 'Basaliva'.", }, DRAGONFRUIT = "What a weird fruit.", DRAGONFRUIT_COOKED = "Still weird.", DRAGONFRUIT_SEEDS = "It's a seed.", DRAGONPIE = "I cooked it myself!", DRUMSTICK = "I should gobble it.", DRUMSTICK_COOKED = "Now it's even tastier.", DUG_BERRYBUSH = "I should plant this.", DUG_GRASS = "I should plant this.", DUG_MARSH_BUSH = "I should plant this.", DUG_SAPLING = "I should plant this.", DURIAN = "Oh it smells!", DURIAN_COOKED = "Now it smells even worse!", DURIAN_SEEDS = "It's a seed.", EARMUFFSHAT = "At least my ears won't get cold...", EGGPLANT = "It doesn't look like an egg.", EGGPLANT_COOKED = "It's even less eggy.", EGGPLANT_SEEDS = "It's a seed.", DECIDUOUSTREE = { BURNING = "What a waste of wood.", BURNT = "I feel like I could have prevented that.", CHOPPED = "Take that, nature!", POISON = "It looks unhappy about me stealing those Birchnuts!", GENERIC = "It's all Leafy. Most of the time.", }, ACORN = { GENERIC = "There's definitely something inside there.", PLANTED = "It'll be a tree soon!", }, ACORN_COOKED = "Roasted to perfection.", BIRCHNUTDRAKE = "A mad little nut.", EVERGREEN = { BURNING = "What a waste of wood.", BURNT = "I feel like I could have prevented that.", CHOPPED = "Take that, nature!", GENERIC = "Such tree. Much wow.", }, EVERGREEN_SPARSE = { BURNING = "What a waste of wood.", BURNT = "I feel like I could have prevented that.", CHOPPED = "Take that, nature!", GENERIC = "This sad tree has no cones.", }, EYEPLANT = "I think I'm being watched.", FARMPLOT = { GENERIC = "I should try planting some crops.", GROWING = "Go plants go!", NEEDSFERTILIZER = "I think it needs to be fertilized.", BURNT = "I don't think anything will grow in a pile of ash.", }, FEATHERHAT = "I AM A BIRD!", FEATHER_CROW = "A crow feather.", FEATHER_ROBIN = "A redbird feather.", FEATHER_ROBIN_WINTER = "A snowbird feather.", FEM_PUPPET = "She's trapped!", FIREFLIES = { GENERIC = "If only I could catch them!", HELD = "They make my pocket glow!", }, FIREHOUND = "That one is glowy.", FIREPIT = { EMBERS = "I should put something on the fire before it goes out.", GENERIC = "Sure beats darkness.", HIGH = "Good thing it's contained!", LOW = "The fire's getting a bit low.", NORMAL = "Nice and comfy.", OUT = "At least I can start it up again.", }, COLDFIREPIT = { EMBERS = "I should put something on the fire before it goes out.", GENERIC = "Sure beats darkness.", HIGH = "Good thing it's contained!", LOW = "The fire's getting a bit low.", NORMAL = "Nice and comfy.", OUT = "At least I can start it up again.", }, FIRESTAFF = "I don't want to set the world on fire.", FIRESUPPRESSOR = { ON = "Fling on!", OFF = "All quiet on the flinging front.", LOWFUEL = "The fuel tank is getting a bit low.", }, FISH = "Now I shall eat for a day.", FISHINGROD = "Hook, line and stick!", FISHSTICKS = "I cooked it myself!", FISHTACOS = "I cooked it myself!", FISH_COOKED = "Grilled to perfection.", FLINT = "It's a very sharp rock.", FLOWER = "It's pretty but it smells like a common labourer.", FLOWERHAT = "It smells like prettiness.", FLOWER_EVIL = "Augh! It's so evil!", FOLIAGE = "Some leafy greens.", FOOTBALLHAT = "I don't like sports.", FROG = { DEAD = "He's croaked it.", GENERIC = "He's so cute!", SLEEPING = "Aww, look at him sleep!", }, FROGGLEBUNWICH = "I cooked it myself!", FROGLEGS = "I've heard it's a delicacy.", FROGLEGS_COOKED = "Tastes like chicken.", FRUITMEDLEY = "I cooked it myself!", GEARS = "A pile of mechanical parts.", GHOST = "That offends me as a Scientist.", GOLDENAXE = "That's one fancy axe.", GOLDENPICKAXE = "Hey, isn't gold really soft?", GOLDENPITCHFORK = "Why did I even make a pitchfork this fancy?", GOLDENSHOVEL = "I can't wait to dig holes.", GOLDNUGGET = "I can't eat it, but it sure is shiny.", GRASS = { BARREN = "It needs poop.", WITHERED = "It's not going to grow back while it's so hot.", BURNING = "That's burning fast!", GENERIC = "It's a tuft of grass.", PICKED = "It was cut down in the prime of its life.", }, GREEN_CAP = "It seems pretty normal.", GREEN_CAP_COOKED = "It's different now...", GREEN_MUSHROOM = { GENERIC = "It's a mushroom.", INGROUND = "It's sleeping.", PICKED = "I wonder if it will come back?", }, GUNPOWDER = "It looks like pepper.", HAMBAT = "This seems unsanitary.", HAMMER = "Stop! It's time! To hammer things!", HEALINGSALVE = "The stinging means that it's working.", HEATROCK = { FROZEN = "It's colder than ice.", COLD = "That's a cold stone.", GENERIC = "I could manipulate its temperature.", WARM = "It's quite warm and cuddly... for a rock!", HOT = "Nice and toasty hot!", }, HOME = "Someone must live here.", HOMESIGN = { GENERIC = "It says 'You are here'.", BURNT = "I can't read it any longer.", }, HONEY = "Looks delicious!", HONEYCOMB = "Bees used to live in this.", HONEYHAM = "I cooked it myself!", HONEYNUGGETS = "I cooked it myself!", HORN = "It sounds like a beefalo field in there.", HOUND = "You ain't nothing, hound dog!", HOUNDBONE = "Creepy.", HOUNDMOUND = "I wouldn't want to pick a bone with the owner.", ICEBOX = "I have harnessed the power of cold!", ICEHAT = "Stay cool, boy.", ICEHOUND = "Are there hounds for every season?", INSANITYROCK = { ACTIVE = "TAKE THAT, SANE SELF!", INACTIVE = "It's more of a pyramid than an obelisk.", }, JAMMYPRESERVES = "I cooked it myself!", KABOBS = "I cooked it myself!", KILLERBEE = { GENERIC = "Oh no! It's a killer bee!", HELD = "This seems dangerous.", }, KNIGHT = "Check it out!", KOALEFANT_SUMMER = "Adorably delicious.", KOALEFANT_WINTER = "It looks warm and full of meat.", KRAMPUS = "He's going after my stuff!", KRAMPUS_SACK = "Ew. It has Krampus slime all over it.", LEIF = "He's huge!", LEIF_SPARSE = "He's huge!", LIGHTNING_ROD = { CHARGED = "The power is mine!", GENERIC = "I can harness the heavens!", }, LIGHTNINGGOAT = { GENERIC = "'Baaaah' yourself!", CHARGED = "I don't think it liked being struck by lightning.", }, LIGHTNINGGOATHORN = "It's like a miniature lightning rod.", GOATMILK = "It's buzzing with tastiness!", LITTLE_WALRUS = "He won't be cute and cuddly forever.", LIVINGLOG = "It looks worried.", LOCKEDWES = "Maxwell's statues are trapping him.", LOG = { BURNING = "That's some hot wood!", GENERIC = "It's big, it's heavy, and it's wood.", }, LUREPLANT = "It's so alluring.", LUREPLANTBULB = "Now I can start my very own meat farm.", MALE_PUPPET = "He's trapped!", MANDRAKE = { DEAD = "A mandrake root has strange powers.", GENERIC = "I've heard strange things about those plants.", PICKED = "Stop following me!", }, MANDRAKESOUP = "I cooked it myself!", MANDRAKE_COOKED = "It doesn't seem so strange anymore.", MARBLE = "Fancy!", MARBLEPILLAR = "I think I could use that.", MARBLETREE = "I don't think an axe will cut it.", MARSH_BUSH = { BURNING = "That's burning fast!", GENERIC = "It looks thorny.", PICKED = "That hurt.", }, MARSH_PLANT = "It's a plant.", MARSH_TREE = { BURNING = "Spikes and fire!", BURNT = "Now it's burnt and spiky.", CHOPPED = "Not so spiky now!", GENERIC = "Those spikes look sharp!", }, MAXWELL = "I hate that guy.", MAXWELLHEAD = "I can see into his pores.", MAXWELLLIGHT = "I wonder how they work.", MAXWELLLOCK = "Looks almost like a key hole.", MAXWELLTHRONE = "That doesn't look very comfortable.", MEAT = "It's a bit gamey, but it'll do.", MEATBALLS = "I cooked it myself!", MEATRACK = { DONE = "Jerky time!", DRYING = "Meat takes a while to dry.", DRYINGINRAIN = "Meat takes even longer to dry in rain.", GENERIC = "I should dry some meats.", BURNT = "The rack got dried.", }, MEAT_DRIED = "Just jerky enough.", MERM = "Smells fishy!", MERMHEAD = { GENERIC = "The stinkiest thing I'll smell all day.", BURNT = "Burnt merm flesh somehow smells even worse.", }, MERMHOUSE = { GENERIC = "Who would live here?", BURNT = "Nothing to live in, now.", }, MINERHAT = "This will keep my hands free.", MONKEY = "Curious little guy.", MONKEYBARREL = "Did that just move?", MONSTERLASAGNA = "I cooked it myself!", FLOWERSALAD = "A bowl of foliage.", ICECREAM = "I scream for ice cream!", WATERMELONICLE = "Cryogenic watermlon.", TRAILMIX = "A healthy, natural snack.", HOTCHILI = "Five alarm!", GUACAMOLE = "Avogadro's favorite dish.", MONSTERMEAT = "Ugh. I don't think I should eat that.", MONSTERMEAT_DRIED = "Strange-smelling jerky.", MOOSE = "I don't exactly know what that thing is.", MOOSEEGG = "Its contents are like excited electrons trying to escape.", MOSSLING = "Aaah! You are definitely not an electron!", FEATHERFAN = "Down to bring my temperature down.", GOOSE_FEATHER = "Fluffy!", STAFF_TORNADO = "Spinning doom.", MOSQUITO = { GENERIC = "Disgusting little bloodsucker.", HELD = "Hey, is that my blood?", }, MOSQUITOSACK = "It's probably not someone else's blood...", MOUND = { DUG = "I should probably feel bad about that.", GENERIC = "I bet there's all sorts of good stuff down there!", }, NIGHTLIGHT = "It gives off a spooky light.", NIGHTMAREFUEL = "This stuff is crazy!", NIGHTSWORD = "I dreamed it myself!", NITRE = "I'm not a geologist.", ONEMANBAND = "I should have added a beefalo bell.", PANDORASCHEST = "It may contain something fantastic! Or horrible.", PANFLUTE = "I can serenade the animals.", PAPYRUS = "Some sheets of paper.", PENGUIN = "Must be breeding season.", PERD = "Stupid bird! Stay away from my berries!", PEROGIES = "I cooked it myself!", PETALS = "I showed those flowers who's boss!", PETALS_EVIL = "I'm not sure I want to hold these.", PICKAXE = "Iconic, isn't it?", PIGGYBACK = "I feel kinda bad for that.", PIGHEAD = { GENERIC = "Looks like an offering to the beast.", BURNT = "Crispy.", }, PIGHOUSE = { FULL = "I can see a snout pressed up against the window.", GENERIC = "These pigs have pretty fancy houses.", LIGHTSOUT = "Come ON! I know you're home!", BURNT = "Not so fancy now, pig!", }, PIGKING = "Ewwww, he smells!", PIGMAN = { DEAD = "Someone should tell his family.", FOLLOWER = "He's part of my entourage.", GENERIC = "They kind of creep me out.", GUARD = "He looks serious.", WEREPIG = "He's not friendly!", }, PIGSKIN = "It still has the tail on it.", PIGTENT = "Smells like bacon.", PIGTORCH = "Sure looks cozy.", PINECONE = { GENERIC = "I can hear a tiny tree inside it, trying to get out.", PLANTED = "It'll be a tree soon!", }, PITCHFORK = "Maxwell might be looking for this.", PLANTMEAT = "That doesn't look very appealing.", PLANTMEAT_COOKED = "At least it's warm now.", PLANT_NORMAL = { GENERIC = "Leafy!", GROWING = "Guh! It's growing so slowly!", READY = "Mmmm. Ready to harvest.", WITHERED = "The heat killed it.", }, POMEGRANATE = "It looks like the inside of an alien's brain.", POMEGRANATE_COOKED = "Haute Cuisine!", POMEGRANATE_SEEDS = "It's a seed.", POND = "I can't see the bottom!", POOP = "I should fill my pockets!", FERTILIZER = "That is definitely a bucket full of poop.", PUMPKIN = "It's as big as my head!", PUMPKINCOOKIE = "I cooked it myself!", PUMPKIN_COOKED = "How did it not turn into a pie?", PUMPKIN_LANTERN = "Spooky!", PUMPKIN_SEEDS = "It's a seed.", PURPLEAMULET = "It's whispering to me.", PURPLEGEM = "It contains the mysteries of the universe.", RABBIT = { GENERIC = "He's looking for carrots.", HELD = "Do you like science?", }, RABBITHOLE = { GENERIC = "That must lead to the Kingdom of the Bunnymen.", SPRING = "The Kingdom of the Bunnymen is closed for the season.", }, RAINOMETER = { GENERIC = "It measures cloudiness.", BURNT = "The measuring parts went up in a cloud of smoke.", }, RAINCOAT = "Keeps the rain where it ought to be. Outside my body.", RAINHAT = "It'll mess up my hair, but I'll stay nice and dry.", RATATOUILLE = "I cooked it myself!", RAZOR = "A sharpened rock tied to a stick. Hygienic!", REDGEM = "It sparkles with inner warmth.", RED_CAP = "It smells funny.", RED_CAP_COOKED = "It's different now...", RED_MUSHROOM = { GENERIC = "It's a mushroom.", INGROUND = "It's sleeping.", PICKED = "I wonder if it will come back?", }, REEDS = { BURNING = "That's really burning!", GENERIC = "It's a clump of reeds.", PICKED = "I picked all the useful reeds.", }, RELIC = { GENERIC = "Ancient household goods.", BROKEN = "Nothing to work with here.", }, RUINS_RUBBLE = "This can be fixed.", RUBBLE = "Just bits and pieces of rock.", RESEARCHLAB = { GENERIC = "It breaks down objects into their scientific components.", BURNT = "It won't be doing much science now.", }, RESEARCHLAB2 = { GENERIC = "It's even more science-y than the last one!", BURNT = "The extra science didn't keep it alive.", }, RESEARCHLAB3 = { GENERIC = "What have I created?", BURNT = "Whatever it was, it's burnt now.", }, RESEARCHLAB4 = { GENERIC = "Who would name something that?", BURNT = "Fire doesn't really solve naming issues...", }, RESURRECTIONSTATUE = { GENERIC = "What a handsome devil!", BURNT = "Not much use anymore.", }, RESURRECTIONSTONE = "What an odd looking stone.", ROBIN = { GENERIC = "Does that mean winter is gone?", HELD = "He likes my pocket.", }, ROBIN_WINTER = { GENERIC = "Life in the frozen wastes.", HELD = "It's so soft.", }, ROBOT_PUPPET = "It's trapped!", ROCK_LIGHT = { GENERIC = "A crusted over lava pit.", OUT = "Looks fragile.", LOW = "The lava's crusting over.", NORMAL = "Nice and comfy.", }, ROCK = "It wouldn't fit in my pocket.", ROCK_ICE = { GENERIC = "A very isolated glacier.", MELTED = "Nothing useful until it freezes again.", }, ROCK_ICE_MELTED = "Nothing useful until it freezes again.", ICE = "Ice to meet you.", ROCKS = "I can make stuff with these.", ROOK = "Storm the castle!", ROPE = "Some short lengths of rope.", ROTTENEGG = "Ew! It stinks!", SANITYROCK = { ACTIVE = "That's a CRAZY looking rock!", INACTIVE = "Where did the rest of it go?", }, SAPLING = { BURNING = "That's burning fast!", WITHERED = "It might be okay if it was cooler.", GENERIC = "Baby trees are so cute!", PICKED = "That'll teach him.", }, SEEDS = "Each one is a tiny mystery.", SEEDS_COOKED = "I cooked all the life out of 'em!", SEWING_KIT = "Darn it! Darn it all to heck!", SHOVEL = "There's a lot going on underground.", SILK = "It comes from a spider's butt.", SKELETON = "Better him than me.", SKELETON_PLAYER = "Better him than... wait a minute!", SKULLCHEST = "I'm not sure if I want to open it.", SMALLBIRD = { GENERIC = "That's a rather small bird.", HUNGRY = "It looks hungry.", STARVING = "It must be starving.", }, SMALLMEAT = "A tiny chunk of dead animal.", SMALLMEAT_DRIED = "A little jerky.", SPEAR = "That's one pointy stick.", SPIDER = { DEAD = "Ewwww!", GENERIC = "I hate spiders.", SLEEPING = "I'd better not be here when he wakes up.", }, SPIDERDEN = "Sticky!", SPIDEREGGSACK = "I hope these don't hatch in my pocket.", SPIDERGLAND = "It has a tangy, antiseptic smell.", SPIDERHAT = "I hope I got all of the spider goo out of it.", SPIDERQUEEN = "AHHHHHHHH! That spider is huge!", SPIDER_WARRIOR = { DEAD = "Good riddance!", GENERIC = "Looks even meaner than usual.", SLEEPING = "I should keep my distance.", }, SPOILED_FOOD = "It's a furry ball of rotten food.", STATUEHARP = "What has happened to the head?", STATUEMAXWELL = "It really captures his personality.", STINGER = "Looks sharp!", STRAWHAT = "What a nice hat.", STUFFEDEGGPLANT = "I cooked it myself!", SUNKBOAT = "It's no use to me out there!", SWEATERVEST = "This vest is dapper as all get-out.", REFLECTIVEVEST = "Keep off, evil sun!", HAWAIIANSHIRT = "It's not lab-safe!", TAFFY = "I cooked it myself!", TALLBIRD = "That's a tall bird!", TALLBIRDEGG = "Will it hatch?", TALLBIRDEGG_COOKED = "Delicious and nutritional.", TALLBIRDEGG_CRACKED = { COLD = "Brrrr!", GENERIC = "Looks like it's hatching.", HOT = "Are eggs supposed to sweat?", LONG = "I have a feeling this is going to take a while...", SHORT = "It should hatch any time now.", }, TALLBIRDNEST = { GENERIC = "That's quite an egg!", PICKED = "The nest is empty.", }, TEENBIRD = { GENERIC = "Not a very tall bird.", HUNGRY = "I'd better find it some food.", STARVING = "It has a dangerous look in it's eye.", }, TELEBASE = { VALID = "It's ready to go.", GEMS = "It needs more purple gems.", }, GEMSOCKET = { VALID = "Looks ready.", GEMS = "It needs a gem.", }, TELEPORTATO_BASE = { ACTIVE = "With this I can surely pass through space and time!", GENERIC = "This appears to be a nexus to another world!", LOCKED = "There's still something missing.", PARTIAL = "Soon, my invention will be complete!", }, TELEPORTATO_BOX = "This may control the polarity of the whole universe.", TELEPORTATO_CRANK = "Tough enough to handle the most intense experiments.", TELEPORTATO_POTATO = "This metal potato contains great and fearful power...", TELEPORTATO_RING = "A ring that could focus dimensional energies.", TELESTAFF = "It can show me the world.", TENT = { GENERIC = "I get crazy when I don't sleep.", BURNT = "Nothing left to sleep in.", }, SIESTAHUT = { GENERIC = "A nice place for an afternoon rest out of the heat.", BURNT = "It won't provide much shade now.", }, TENTACLE = "That looks dangerous.", TENTACLESPIKE = "It's pointy and slimy.", TENTACLESPOTS = "I think these were its genitalia.", TENTACLE_PILLAR = "A slimy pole.", TENTACLE_PILLAR_ARM = "Little slippery arms.", TENTACLE_GARDEN = "Yet another slimy pole.", TOPHAT = "What a nice hat.", TORCH = "Something to hold back the night.", TRANSISTOR = "It's whirring with electricity.", TRAP = "I wove it real tight.", TRAP_TEETH = "This is a nasty surprise.", TRAP_TEETH_MAXWELL = "I'll want to avoid stepping on that!", TREASURECHEST = { GENERIC = "It's my tickle trunk!", BURNT = "That trunk was truncated.", }, TREASURECHEST_TRAP = "How convenient!", TREECLUMP = "It's almost like someone is trying to prevent me from going somewhere.", TRINKET_1 = "They are all melted together.", TRINKET_10 = "I hope I get out of here before I need these.", TRINKET_11 = "He whispers beautiful lies to me.", TRINKET_12 = "I'm not sure what I should do with a dessicated tentacle.", TRINKET_2 = "It's just a cheap replica.", TRINKET_3 = "The knot is stuck. Forever.", TRINKET_4 = "It must be some kind of religious artifact.", TRINKET_5 = "Sadly, it's too small for me to escape on.", TRINKET_6 = "Their electricity carrying days are over.", TRINKET_7 = "I have no time for fun and games!", TRINKET_8 = "Great. All of my tub stopping needs are met.", TRINKET_9 = "I'm more of a zipper person, myself.", TRUNKVEST_SUMMER = "Wilderness casual.", TRUNKVEST_WINTER = "Winter survival gear.", TRUNK_COOKED = "Somehow even more nasal than before.", TRUNK_SUMMER = "A light breezy trunk.", TRUNK_WINTER = "A thick, hairy trunk.", TUMBLEWEED = "Who knows what that tumbleweed has picked up.", TURF_CARPETFLOOR = "It's surprisingly scratchy.", TURF_CHECKERFLOOR = "These are pretty snazzy.", TURF_DIRT = "A chunk of ground.", TURF_FOREST = "A chunk of ground.", TURF_GRASS = "A chunk of ground.", TURF_MARSH = "A chunk of ground.", TURF_ROAD = "Hastily cobbled stones.", TURF_ROCKY = "A chunk of ground.", TURF_SAVANNA = "A chunk of ground.", TURF_WOODFLOOR = "These are floorboards.", TURKEYDINNER = "Mmmm.", TWIGS = "It's a bunch of small twigs.", UMBRELLA = "This will keep my hair dry, at least.", GRASS_UMBRELLA = "This will keep my hair moderately dry, at least.", UNIMPLEMENTED = "It doesn't look finished! It could be dangerous.", WAFFLES = "I cooked it myself!", WALL_HAY = { GENERIC = "Hmmmm. I guess that'll have to do.", BURNT = "That won't do at all.", }, WALL_HAY_ITEM = "This seems like a bad idea.", WALL_STONE = "That's a nice wall.", WALL_STONE_ITEM = "They make me feel so safe.", WALL_RUINS = "An ancient piece of wall.", WALL_RUINS_ITEM = "A solid piece of history.", WALL_WOOD = { GENERIC = "Pointy!", BURNT = "Burnt!", }, WALL_WOOD_ITEM = "Pickets!", WALRUS = "Walruses are natural predators.", WALRUSHAT = "It's covered with walrus hairs.", WALRUS_CAMP = { EMPTY = "Looks like somebody was camping here.", GENERIC = "It looks warm and cozy inside.", }, WALRUS_TUSK = "I'm sure I'll find a use for it eventually.", WARG = "You might be something to reckon with, big dog.", WASPHIVE = "I think those bees are mad.", WATERMELON = "Sticky sweet.", WATERMELON_COOKED = "Juicy and warm.", WATERMELONHAT = "Let the juice run down your face.", WETGOOP = "I cooked it myself!", WINTERHAT = "It'll be good for when winter comes.", WINTEROMETER = { GENERIC = "I am one heck of a scientist.", BURNT = "Its measuring days are over.", }, WORMHOLE = { GENERIC = "Soft and undulating.", OPEN = "Science compels me to jump in.", }, WORMHOLE_LIMITED = "Guh, that thing looks worse off than usual.", ACCOMPLISHMENT_SHRINE = "I want to use it, and I want the world to know what I did.", LIVINGTREE = "Is it watching me?", ICESTAFF = "It's cold to the touch.", }, DESCRIBE_GENERIC = "It's a... thing.", DESCRIBE_TOODARK = "It's too dark to see!", DESCRIBE_SMOLDERING = "That thing is about to catch fire.", EAT_FOOD = { TALLBIRDEGG_CRACKED = "Mmm. Beaky.", }, ANNOUNCE_CUTE_1 = "Aww, look at that wittle %s! It's so tute!!", ANNOUNCE_CUTE_2 = "Come closer %s so I can give you a big hug!", ANNOUNCE_CUTE_SAD = "I'm so sorry mister %s." }
mit
rigeirani/satn
plugins/admin.lua
60
6680
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end return end return { usage = { "pm: Send Pm To Priavate Chat.", "block: Block User [id].", "unblock: Unblock User [id].", "markread on: Reads Messages agancy Bot.", "markread off: Don't Reads Messages agancy Bot.", "setbotphoto: Set New Photo For Bot Account.", "contactlist: Send A List Of Bot Contacts.", "dialoglist: Send A Dialog Of Chat.", "delcontact: Delete Contact.", "import: Added Bot In Group With Link.", }, patterns = { "^(pm) (%d+) (.*)$", "^(import) (.*)$", "^(unblock) (%d+)$", "^(block) (%d+)$", "^(markread) (on)$", "^(markread) (off)$", "^(setbotphoto)$", "%[(photo)%]", "^(contactlist)$", "^(dialoglist)$", "^(delcontact) (%d+)$", "^(whois) (%d+)$" }, run = run, }
gpl-2.0
google/flatbuffers
samples/lua/MyGame/Sample/Monster.lua
17
3936
-- automatically generated by the FlatBuffers compiler, do not modify -- namespace: Sample local flatbuffers = require('flatbuffers') local Monster = {} -- the module local Monster_mt = {} -- the class metatable function Monster.New() local o = {} setmetatable(o, {__index = Monster_mt}) return o end function Monster.GetRootAsMonster(buf, offset) local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) local o = Monster.New() o:Init(buf, n + offset) return o end function Monster_mt:Init(buf, pos) self.view = flatbuffers.view.New(buf, pos) end function Monster_mt:Pos() local o = self.view:Offset(4) if o ~= 0 then local x = o + self.view.pos local obj = require('MyGame.Sample.Vec3').New() obj:Init(self.view.bytes, x) return obj end end function Monster_mt:Mana() local o = self.view:Offset(6) if o ~= 0 then return self.view:Get(flatbuffers.N.Int16, o + self.view.pos) end return 150 end function Monster_mt:Hp() local o = self.view:Offset(8) if o ~= 0 then return self.view:Get(flatbuffers.N.Int16, o + self.view.pos) end return 100 end function Monster_mt:Name() local o = self.view:Offset(10) if o ~= 0 then return self.view:String(o + self.view.pos) end end function Monster_mt:Inventory(j) local o = self.view:Offset(14) if o ~= 0 then local a = self.view:Vector(o) return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1)) end return 0 end function Monster_mt:InventoryLength() local o = self.view:Offset(14) if o ~= 0 then return self.view:VectorLen(o) end return 0 end function Monster_mt:Color() local o = self.view:Offset(16) if o ~= 0 then return self.view:Get(flatbuffers.N.Int8, o + self.view.pos) end return 2 end function Monster_mt:Weapons(j) local o = self.view:Offset(18) if o ~= 0 then local x = self.view:Vector(o) x = x + ((j-1) * 4) x = self.view:Indirect(x) local obj = require('MyGame.Sample.Weapon').New() obj:Init(self.view.bytes, x) return obj end end function Monster_mt:WeaponsLength() local o = self.view:Offset(18) if o ~= 0 then return self.view:VectorLen(o) end return 0 end function Monster_mt:EquippedType() local o = self.view:Offset(20) if o ~= 0 then return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos) end return 0 end function Monster_mt:Equipped() local o = self.view:Offset(22) if o ~= 0 then local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0) self.view:Union(obj, o) return obj end end function Monster.Start(builder) builder:StartObject(10) end function Monster.AddPos(builder, pos) builder:PrependStructSlot(0, pos, 0) end function Monster.AddMana(builder, mana) builder:PrependInt16Slot(1, mana, 150) end function Monster.AddHp(builder, hp) builder:PrependInt16Slot(2, hp, 100) end function Monster.AddName(builder, name) builder:PrependUOffsetTRelativeSlot(3, name, 0) end function Monster.AddInventory(builder, inventory) builder:PrependUOffsetTRelativeSlot(5, inventory, 0) end function Monster.StartInventoryVector(builder, numElems) return builder:StartVector(1, numElems, 1) end function Monster.AddColor(builder, color) builder:PrependInt8Slot(6, color, 2) end function Monster.AddWeapons(builder, weapons) builder:PrependUOffsetTRelativeSlot(7, weapons, 0) end function Monster.StartWeaponsVector(builder, numElems) return builder:StartVector(4, numElems, 4) end function Monster.AddEquippedType(builder, equippedType) builder:PrependUint8Slot(8, equippedType, 0) end function Monster.AddEquipped(builder, equipped) builder:PrependUOffsetTRelativeSlot(9, equipped, 0) end function Monster.End(builder) return builder:EndObject() end return Monster -- return the module
apache-2.0
HamidRavani/hamid
plugins/bot_manager.lua
89
6427
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'عکس پروفایل ربات تغییر کرد', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'عکس رباتو بفرست بیاد' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "پیام شما از طریق پیوی ربات ارسال شد" end if matches[1] == "block" then if is_admin2(matches[2]) then return "شما نمیتوانید ادمین را بلاک کنید" end block_user("user#id"..matches[2],ok_cb,false) return "یوزر مورد نظر از ربات بلاک شد" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "یوزر انبلاک شد" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]", "^[!/](contactlist)$", "^[!/](dialoglist)$", "^[!/](delcontact) (%d+)$", "^[!/](whois) (%d+)$" }, run = run, } --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
hcqmaker/chattool
chatroom/chatroom.lua
1
1224
local skynet = require "skynet" require "skynet.manager" -- import skynet.register local user_list = {} local command = {} function command.LOGIN(conf) local agent = conf.agent; local name = conf.name; print("user:", name, "login ===>"); table.insert(user_list, {agent=agent,name=name}); return {value="login ok"} end function command.LOGOUT(agent) local idx = -1; for k, v in ipairs(user_list) do if (v.agent == agent) then idx = k; break; end end if (idx ~= -1) then table.remove(user_list, idx); end end function command.SAY(agent, name, msg) print("say==>", agent, name, msg); local found = false; for k, v in ipairs(user_list) do if (v.agent == agent) then found = true; break; end end if (not found) then return nil; end local dt = name..":"..msg; for k, v in ipairs(user_list) do if (v.agent ~= agent) then skynet.send(v.agent, "lua", "sayback", dt); end end return dt; end skynet.start(function() skynet.dispatch("lua", function(session, address, cmd, ...) local f = command[string.upper(cmd)] if f then skynet.ret(skynet.pack(f(...))) else error(string.format("Unknown command %s", tostring(cmd))) end end) skynet.register "ROOM" end)
mit
drmingdrmer/lua-paxos
lib/acid/paxos/round.lua
2
1159
local _M = { _VERSION = require("acid.paxos._ver") } local tableutil = require( "acid.tableutil" ) function _M.new( elts ) assert( elts[ 2 ] ~= nil and elts[ 3 ] == nil, "invalid nr of elts while creating new round" ) local rnd = tableutil.duplist( elts ) return rnd end function _M.zero() return _M.new({ 0, '' }) end function _M.max( rounds ) local max = _M.zero() for _, r in ipairs(rounds) do if _M.cmp( max, r ) < 0 then max = r end end return max end function _M.incr( rnd ) return _M.new({ rnd[1] + 1, rnd[2] }) end function _M.cmp( a, b ) a = a or {} b = b or {} for i = 1, 2 do local x = cmp( a[i], b[i] ) if x ~= 0 then return x end end return 0 end function cmp(a, b) if a == nil then if b == nil then return 0 else return -1 end else if b == nil then return 1 end end -- none of a or b is nil if a>b then return 1 elseif a<b then return -1 else return 0 end end return _M
mit
xiaowa183/Atlas
lib/proxy/filter.lua
41
1906
module("proxy.filter", package.seeall) local config_file = string.format("proxy.conf.config_%s", proxy.global.config.instance) local config = require(config_file) local whitelist = config.whitelist local blacklist = config.blacklist local log = require("proxy.log") local level = log.level local write_log = log.write_log function is_whitelist(tokens) write_log(level.DEBUG, "ENTER IS_WHITELIST") local re = false local first_token if tokens[1].token_name ~= "TK_COMMENT" then first_token = tokens[1].text:upper() else first_token = tokens[2].text:upper() end for i = 1, #whitelist do local wtokens = whitelist[i] for j = 1, #wtokens do if first_token == wtokens[j] then write_log(level.DEBUG, "LEAVE IS_WHITELIST") return i end end end write_log(level.DEBUG, "LEAVE IS_WHITELIST") return re end function is_blacklist(tokens) write_log(level.DEBUG, "ENTER IS_BLACKLIST") local re = false local first_token = tokens[1].text:upper() for i = 1, #blacklist do local b = blacklist[i] local first = b.FIRST local first_not = b.FIRST_NOT local meet_first = false local meet_any = true local meet_all = true if first then if first == first_token then meet_first = true end elseif first_not and first_not ~= first_token then meet_first = true end if meet_first then local any = b.ANY if any then meet_any = false for j = 1, #tokens do local token = tokens[j].text:upper() if any == token then meet_any = true break end end end local all_not = b.ALL_NOT if all_not then for j = 1, #tokens do local token = tokens[j].text:upper() if all_not == token then meet_all = false break end end end end if meet_first and meet_any and meet_all then re = true break end end write_log(level.DEBUG, "LEAVE IS_BLACKLIST") return re end
gpl-2.0
mrmetti/teleum-new-open
plugins/security.lua
1
11509
--Begin scurity.lua --Begin pre_process function local function pre_process(msg) -- Begin 'RondoMsgChecks' text checks by @rondoozle and Edited by @janlou -- Powered by @AdvanTm -- CopyRight all right reserved if is_chat_msg(msg) or is_super_group(msg) then if msg and not is_momod(msg) and not is_whitelisted(msg.from.id) then --if regular user local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") -- get rid of rtl in names local name_log = print_name:gsub("_", " ") -- name for log local to_chat = msg.to.type == 'chat' local to_super = msg.to.type == 'channel' if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings'] then settings = data[tostring(msg.to.id)]['settings'] else return end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = 'no' end if settings.lock_rtl then lock_rtl = settings.lock_rtl else lock_rtl = 'no' end if settings.lock_tgservice then lock_tgservice = settings.lock_tgservice else lock_tgservice = 'no' end if settings.lock_link then lock_link = settings.lock_link else lock_link = 'no' end if settings.lock_member then lock_member = settings.lock_member else lock_member = 'no' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = 'no' end if settings.lock_sticker then lock_sticker = settings.lock_sticker else lock_sticker = 'no' end if settings.lock_contacts then lock_contacts = settings.lock_contacts else lock_contacts = 'no' end if settings.strict then strict = settings.strict else strict = 'no' end if msg and not msg.service and is_muted(msg.to.id, 'All: yes') or is_muted_user(msg.to.id, msg.from.id) and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then -- kick_user(msg.from.id, msg.to.id) end end if msg.text then -- msg.text checks local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local _nl, real_digits = string.gsub(msg.text, '%d', '') if lock_spam == "yes" and string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local is_link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") local is_bot = msg.text:match("?[Ss][Tt][Aa][Rr][Tt]=") if is_link_msg and lock_link == "yes" and not is_bot then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if msg.service then if lock_tgservice == "yes" then delete_msg(msg.id, ok_cb, false) if to_chat then return end end end local is_squig_msg = msg.text:match("[\216-\219][\128-\191]") if is_squig_msg and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl = print_name:match("‮") or msg.text:match("‮") if is_rtl and lock_rtl == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, "Text: yes") and msg.text and not msg.media and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media then -- msg.media checks if msg.media.title then local is_link_title = msg.media.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.media.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.description then local is_link_desc = msg.media.description:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.description:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_desc and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_desc = msg.media.description:match("[\216-\219][\128-\191]") if is_squig_desc and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.caption then -- msg.media.caption checks local is_link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_caption = msg.media.caption:match("[\216-\219][\128-\191]") if is_squig_caption and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_username_caption = msg.media.caption:match("^@[%a%d]") if is_username_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if lock_sticker == "yes" and msg.media.caption:match("sticker.webp") then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.type:match("contact") and lock_contacts == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_photo_caption = msg.media.caption and msg.media.caption:match("photo")--".jpg", if is_muted(msg.to.id, 'Photo: yes') and msg.media.type:match("photo") or is_photo_caption and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end local is_gif_caption = msg.media.caption and msg.media.caption:match(".mp4") if is_muted(msg.to.id, 'Gifs: yes') and is_gif_caption and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Audio: yes') and msg.media.type:match("audio") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_video_caption = msg.media.caption and msg.media.caption:lower(".mp4","video") if is_muted(msg.to.id, 'Video: yes') and msg.media.type:match("video") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Documents: yes') and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.fwd_from then if msg.fwd_from.title then local is_link_title = msg.fwd_from.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.fwd_from.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.fwd_from.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then delete_msg(msg.id, ok_cb, false) end end if msg.service then -- msg.service checks local action = msg.action.type if action == 'chat_add_user_link' then local user_id = msg.from.id local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') if string.len(msg.from.print_name) > 70 or ctrl_chars > 40 and lock_group_spam == 'yes' then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then kick_user(user_id, msg.to.id) end if lock_member == 'yes' then kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end if action == 'chat_add_user' and not is_momod2(msg.from.id, msg.to.id) then local user_id = msg.action.user.id if string.len(msg.action.user.print_name) > 70 and lock_group_spam == 'yes' then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local print_name = msg.action.user.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then kick_user(user_id, msg.to.id) end if msg.to.type == 'channel' and lock_member == 'yes' then kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end end end if not is_momod(msg) and not is_whitelisted(msg.from.id) and not is_sudo(msg) and not is_owner(msg) and not is_vip(msg) then if msg.text:match("@[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]") then if lock_link == 'yes' then if msg.to.type == 'channel' then if strict == 'no' then delete_msg(msg.id, ok_cb, false) elseif strict == 'yes' then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end if msg.to.type == 'chat' then kick_user(msg.from.id, msg.to.id) end end end end end -- End 'RondoMsgChecks' text checks by @Rondoozle return msg end --End pre_process function return { patterns = { "@[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]", "[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/", "?[Ss][Tt][Aa][Rr][Tt]=", }, pre_process = pre_process } --End scurity.lua --By @Rondoozle
gpl-2.0
soumith/nn
SpatialContrastiveNormalization.lua
3
1572
local SpatialContrastiveNormalization, parent = torch.class('nn.SpatialContrastiveNormalization','nn.Module') function SpatialContrastiveNormalization:__init(nInputPlane, kernel, threshold, thresval) parent.__init(self) -- get args self.nInputPlane = nInputPlane or 1 self.kernel = kernel or torch.Tensor(9,9):fill(1) self.threshold = threshold or 1e-4 self.thresval = thresval or threshold or 1e-4 local kdim = self.kernel:nDimension() -- check args if kdim ~= 2 and kdim ~= 1 then error('<SpatialContrastiveNormalization> averaging kernel must be 2D or 1D') end if (self.kernel:size(1) % 2) == 0 or (kdim == 2 and (self.kernel:size(2) % 2) == 0) then error('<SpatialContrastiveNormalization> averaging kernel must have ODD dimensions') end -- instantiate sub+div normalization self.normalizer = nn.Sequential() self.normalizer:add(nn.SpatialSubtractiveNormalization(self.nInputPlane, self.kernel)) self.normalizer:add(nn.SpatialDivisiveNormalization(self.nInputPlane, self.kernel, self.threshold, self.thresval)) end function SpatialContrastiveNormalization:updateOutput(input) self.output = self.normalizer:forward(input) return self.output end function SpatialContrastiveNormalization:updateGradInput(input, gradOutput) self.gradInput = self.normalizer:backward(input, gradOutput) return self.gradInput end function SpatialContrastiveNormalization:type(type) parent.type(self,type) self.normalizer:type(type) return self end
bsd-3-clause
joaofvieira/luci
applications/luci-app-ltqtapi/luasrc/controller/ltqtapi.lua
73
1071
-- Copyright 2019 John Crispin <blogic@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.ltqtapi", package.seeall) function index() if not nixio.fs.access("/etc/config/telephony") then return end page = node("admin", "telephony") page.target = firstchild() page.title = _("VoIP") page.order = 90 entry({"admin", "telephony", "account"}, cbi("luci_ltqtapi/account") , _("Account"), 10) entry({"admin", "telephony", "contact"}, cbi("luci_ltqtapi/contact") , _("Contacts"), 20) entry({"admin", "telephony", "status"}, call("tapi_status")).leaf = true end function tapi_status() local st = { } local state = require "luci.model.uci".cursor_state() state:load("telephony") st.status = "Offline"; if state:get("telephony", "state", "port1", "0") == "0" then st.line1 = "Idle"; else st.line1 = "Calling"; end if state:get("telephony", "state", "port2", "0") == "0" then st.line2 = "Idle"; else st.line2 = "Calling"; end luci.http.prepare_content("application/json") luci.http.write_json(st) end
apache-2.0
pazos/koreader
frontend/apps/reader/modules/readerview.lua
1
34407
--[[-- ReaderView module handles all the screen painting for document browsing. ]] local AlphaContainer = require("ui/widget/container/alphacontainer") local Blitbuffer = require("ffi/blitbuffer") local ConfirmBox = require("ui/widget/confirmbox") local Device = require("device") local Geom = require("ui/geometry") local Event = require("ui/event") local IconWidget = require("ui/widget/iconwidget") local InfoMessage = require("ui/widget/infomessage") local OverlapGroup = require("ui/widget/overlapgroup") local ReaderDogear = require("apps/reader/modules/readerdogear") local ReaderFlipping = require("apps/reader/modules/readerflipping") local ReaderFooter = require("apps/reader/modules/readerfooter") local UIManager = require("ui/uimanager") local dbg = require("dbg") local logger = require("logger") local _ = require("gettext") local Screen = Device.screen local T = require("ffi/util").template local ReaderView = OverlapGroup:extend{ document = nil, -- single page state state = { page = nil, pos = 0, zoom = 1.0, rotation = 0, gamma = 1.0, offset = nil, bbox = nil, }, outer_page_color = Blitbuffer.gray(DOUTER_PAGE_COLOR/15), -- highlight with "lighten" or "underscore" or "invert" highlight = { lighten_factor = 0.2, temp_drawer = "invert", temp = {}, saved_drawer = "lighten", saved = {}, }, highlight_visible = true, -- PDF/DjVu continuous paging page_scroll = nil, page_bgcolor = Blitbuffer.gray(DBACKGROUND_COLOR/15), page_states = {}, -- properties of the gap drawn between each page in scroll mode: page_gap = { -- color (0 = white, 8 = gray, 15 = black) color = Blitbuffer.gray((G_reader_settings:readSetting("page_gap_color") or 8)/15), }, -- DjVu page rendering mode (used in djvu.c:drawPage()) render_mode = DRENDER_MODE, -- default to COLOR -- Crengine view mode view_mode = DCREREADER_VIEW_MODE, -- default to page mode hinting = true, -- visible area within current viewing page visible_area = Geom:new{x = 0, y = 0}, -- dimen for current viewing page page_area = Geom:new{}, -- dimen for area to dim dim_area = nil, -- has footer footer_visible = nil, -- has dogear dogear_visible = false, -- in flipping state flipping_visible = false, -- to ensure periodic flush of settings settings_last_save_ts = nil, } function ReaderView:init() self.view_modules = {} -- fix recalculate from close document pageno self.state.page = nil -- fix inherited dim_area for following opened documents self:resetDimArea() self:addWidgets() self.emitHintPageEvent = function() self.ui:handleEvent(Event:new("HintPage", self.hinting)) end end function ReaderView:resetDimArea() self.dim_area = Geom:new{w = 0, h = 0} end function ReaderView:addWidgets() self.dogear = ReaderDogear:new{ view = self, ui = self.ui, } self.footer = ReaderFooter:new{ view = self, ui = self.ui, } self.flipping = ReaderFlipping:new{ view = self, ui = self.ui, } local arrow_size = Screen:scaleBySize(16) self.arrow = AlphaContainer:new{ alpha = 0.6, IconWidget:new{ icon = "control.expand", width = arrow_size, height = arrow_size, } } self[1] = self.dogear self[2] = self.footer self[3] = self.flipping end --[[-- Register a view UI widget module for document browsing. @tparam string name module name, registered widget can be accessed by readerui.view.view_modules[name]. @tparam ui.widget.widget.Widget widget paintable widget, i.e. has a paintTo method. @usage local ImageWidget = require("ui/widget/imagewidget") local dummy_image = ImageWidget:new{ file = "resources/koreader.png", } -- the image will be painted on all book pages readerui.view:registerViewModule('dummy_image', dummy_image) ]] function ReaderView:registerViewModule(name, widget) if not widget.paintTo then print(name .. " view module does not have paintTo method!") return end widget.view = self widget.ui = self.ui self.view_modules[name] = widget end function ReaderView:resetLayout() for _, widget in ipairs(self) do widget:resetLayout() end for _, m in pairs(self.view_modules) do if m.resetLayout then m:resetLayout() end end end function ReaderView:paintTo(bb, x, y) dbg:v("readerview painting", self.visible_area, "to", x, y) if self.page_scroll then self:drawPageBackground(bb, x, y) else self:drawPageSurround(bb, x, y) end -- draw page content if self.ui.document.info.has_pages then if self.page_scroll then self:drawScrollPages(bb, x, y) else self:drawSinglePage(bb, x, y) end else if self.view_mode == "page" then self:drawPageView(bb, x, y) elseif self.view_mode == "scroll" then self:drawScrollView(bb, x, y) end end -- dim last read area if self.dim_area.w ~= 0 and self.dim_area.h ~= 0 then if self.page_overlap_style == "dim" then bb:dimRect( self.dim_area.x, self.dim_area.y, self.dim_area.w, self.dim_area.h ) elseif self.page_overlap_style == "arrow" then self.arrow:paintTo(bb, 0, self.dim_area.h) end end -- draw saved highlight if self.highlight_visible then self:drawSavedHighlight(bb, x, y) end -- draw temporary highlight if self.highlight.temp then self:drawTempHighlight(bb, x, y) end -- paint dogear if self.dogear_visible then self.dogear:paintTo(bb, x, y) end -- paint footer if self.footer_visible then self.footer:paintTo(bb, x, y) end -- paint flipping if self.flipping_visible then self.flipping:paintTo(bb, x, y) end for _, m in pairs(self.view_modules) do m:paintTo(bb, x, y) end -- stop activity indicator self.ui:handleEvent(Event:new("StopActivityIndicator")) -- Most pages should not require dithering self.dialog.dithered = nil -- For KOpt, let the user choose. if self.ui.document.info.has_pages then -- Also enforce dithering in PicDocument if self.ui.document.is_pic or self.document.configurable.hw_dithering == 1 then self.dialog.dithered = true end else -- Whereas for CRe, -- If we're attempting to show a large enough amount of image data, request dithering (without triggering another repaint ;)). local img_count, img_coverage = self.ui.document:getDrawnImagesStatistics() -- With some nil guards because this may not be implemented in every engine ;). if img_count and img_count > 0 and img_coverage and img_coverage >= 0.075 then self.dialog.dithered = true -- Request a flashing update while we're at it, but only if it's the first time we're painting it if self.state.drawn == false then UIManager:setDirty(nil, "full") end end self.state.drawn = true end end --[[ Given coordinates on the screen return position in original page ]]-- function ReaderView:screenToPageTransform(pos) if self.ui.document.info.has_pages then if self.page_scroll then return self:getScrollPagePosition(pos) else return self:getSinglePagePosition(pos) end else pos.page = self.ui.document:getCurrentPage() -- local last_y = self.ui.document:getCurrentPos() logger.dbg("document has no pages at", pos) return pos end end --[[ Given rectangle in original page return rectangle on the screen ]]-- function ReaderView:pageToScreenTransform(page, rect) if self.ui.document.info.has_pages then if self.page_scroll then return self:getScrollPageRect(page, rect) else return self:getSinglePageRect(rect) end else return rect end end --[[ Get page area on screen for a given page number --]] function ReaderView:getScreenPageArea(page) if self.ui.document.info.has_pages then local area = Geom:new{x = 0, y = 0} if self.page_scroll then for _, state in ipairs(self.page_states) do if page ~= state.page then area.y = area.y + state.visible_area.h + state.offset.y area.y = area.y + self.page_gap.height else area.x = state.offset.x area.w = state.visible_area.w area.h = state.visible_area.h return area end end else area.x = self.state.offset.x area.y = self.state.offset.y area.w = self.visible_area.w area.h = self.visible_area.h return area end else return self.dimen end end function ReaderView:drawPageBackground(bb, x, y) bb:paintRect(x, y, self.dimen.w, self.dimen.h, self.page_bgcolor) end function ReaderView:drawPageSurround(bb, x, y) if self.dimen.h > self.visible_area.h then bb:paintRect(x, y, self.dimen.w, self.state.offset.y, self.outer_page_color) local bottom_margin = y + self.visible_area.h + self.state.offset.y bb:paintRect(x, bottom_margin, self.dimen.w, self.state.offset.y + self.ui.view.footer:getHeight(), self.outer_page_color) end if self.dimen.w > self.visible_area.w then bb:paintRect(x, y, self.state.offset.x, self.dimen.h, self.outer_page_color) bb:paintRect(x + self.dimen.w - self.state.offset.x - 1, y, self.state.offset.x + 1, self.dimen.h, self.outer_page_color) end end function ReaderView:drawScrollPages(bb, x, y) local pos = Geom:new{x = x , y = y} for page, state in ipairs(self.page_states) do self.ui.document:drawPage( bb, pos.x + state.offset.x, pos.y + state.offset.y, state.visible_area, state.page, state.zoom, state.rotation, state.gamma, self.render_mode) pos.y = pos.y + state.visible_area.h -- draw page gap if not the last part if page ~= #self.page_states then self:drawPageGap(bb, pos.x, pos.y) pos.y = pos.y + self.page_gap.height end end UIManager:nextTick(self.emitHintPageEvent) end function ReaderView:getCurrentPageList() local pages = {} if self.ui.document.info.has_pages then if self.page_scroll then for _, state in ipairs(self.page_states) do table.insert(pages, state.page) end else table.insert(pages, self.state.page) end end return pages end function ReaderView:getScrollPagePosition(pos) local x_p, y_p local x_s, y_s = pos.x, pos.y for _, state in ipairs(self.page_states) do if y_s < state.visible_area.h + state.offset.y then y_p = (state.visible_area.y + y_s - state.offset.y) / state.zoom x_p = (state.visible_area.x + x_s - state.offset.x) / state.zoom return { x = x_p, y = y_p, page = state.page, zoom = state.zoom, rotation = state.rotation, } else y_s = y_s - state.visible_area.h - self.page_gap.height end end end function ReaderView:getScrollPageRect(page, rect_p) local rect_s = Geom:new{} for _, state in ipairs(self.page_states) do local trans_p = Geom:new(rect_p):copy() trans_p:transformByScale(state.zoom, state.zoom) if page == state.page and state.visible_area:intersectWith(trans_p) then rect_s.x = rect_s.x + state.offset.x + trans_p.x - state.visible_area.x rect_s.y = rect_s.y + state.offset.y + trans_p.y - state.visible_area.y rect_s.w = trans_p.w rect_s.h = trans_p.h return rect_s end rect_s.y = rect_s.y + state.visible_area.h + self.page_gap.height end end function ReaderView:drawPageGap(bb, x, y) bb:paintRect(x, y, self.dimen.w, self.page_gap.height, self.page_gap.color) end function ReaderView:drawSinglePage(bb, x, y) self.ui.document:drawPage( bb, x + self.state.offset.x, y + self.state.offset.y, self.visible_area, self.state.page, self.state.zoom, self.state.rotation, self.state.gamma, self.render_mode) UIManager:nextTick(self.emitHintPageEvent) end function ReaderView:getSinglePagePosition(pos) local x_s, y_s = pos.x, pos.y return { x = (self.visible_area.x + x_s - self.state.offset.x) / self.state.zoom, y = (self.visible_area.y + y_s - self.state.offset.y) / self.state.zoom, page = self.state.page, zoom = self.state.zoom, rotation = self.state.rotation, } end function ReaderView:getSinglePageRect(rect_p) local rect_s = Geom:new{} local trans_p = Geom:new(rect_p):copy() trans_p:transformByScale(self.state.zoom, self.state.zoom) if self.visible_area:intersectWith(trans_p) then rect_s.x = self.state.offset.x + trans_p.x - self.visible_area.x rect_s.y = self.state.offset.y + trans_p.y - self.visible_area.y rect_s.w = trans_p.w rect_s.h = trans_p.h return rect_s end end function ReaderView:drawPageView(bb, x, y) self.ui.document:drawCurrentViewByPage( bb, x + self.state.offset.x, y + self.state.offset.y, self.visible_area, self.state.page) end function ReaderView:drawScrollView(bb, x, y) self.ui.document:drawCurrentViewByPos( bb, x + self.state.offset.x, y + self.state.offset.y, self.visible_area, self.state.pos) end function ReaderView:drawTempHighlight(bb, x, y) for page, boxes in pairs(self.highlight.temp) do for i = 1, #boxes do local rect = self:pageToScreenTransform(page, boxes[i]) if rect then self:drawHighlightRect(bb, x, y, rect, self.highlight.temp_drawer) end end end end function ReaderView:drawSavedHighlight(bb, x, y) if self.ui.document.info.has_pages then self:drawPageSavedHighlight(bb, x, y) else self:drawXPointerSavedHighlight(bb, x, y) end end function ReaderView:drawPageSavedHighlight(bb, x, y) local pages = self:getCurrentPageList() for _, page in pairs(pages) do local items = self.highlight.saved[page] if items then for i = 1, #items do local item = items[i] local pos0, pos1 = item.pos0, item.pos1 local boxes = self.ui.document:getPageBoxesFromPositions(page, pos0, pos1) if boxes then for _, box in pairs(boxes) do local rect = self:pageToScreenTransform(page, box) if rect then self:drawHighlightRect(bb, x, y, rect, item.drawer or self.highlight.saved_drawer) end end -- end for each box end -- end if boxes end -- end for each highlight end end -- end for each page end function ReaderView:drawXPointerSavedHighlight(bb, x, y) -- Getting screen boxes is done for each tap on screen (changing pages, -- showing menu...). We might want to cache these boxes per page (and -- clear that cache when page layout change or highlights are added -- or removed). local cur_view_top, cur_view_bottom for page, items in pairs(self.highlight.saved) do if items then for j = 1, #items do local item = items[j] local pos0, pos1 = item.pos0, item.pos1 -- document:getScreenBoxesFromPositions() is expensive, so we -- first check this item is on current page if not cur_view_top then -- Even in page mode, it's safer to use pos and ui.dimen.h -- than pages' xpointers pos, even if ui.dimen.h is a bit -- larger than pages' heights cur_view_top = self.ui.document:getCurrentPos() if self.view_mode == "page" and self.ui.document:getVisiblePageCount() > 1 then cur_view_bottom = cur_view_top + 2 * self.ui.dimen.h else cur_view_bottom = cur_view_top + self.ui.dimen.h end end local spos0 = self.ui.document:getPosFromXPointer(pos0) local spos1 = self.ui.document:getPosFromXPointer(pos1) local start_pos = math.min(spos0, spos1) local end_pos = math.max(spos0, spos1) if start_pos <= cur_view_bottom and end_pos >= cur_view_top then local boxes = self.ui.document:getScreenBoxesFromPositions(pos0, pos1, true) -- get_segments=true if boxes then for _, box in pairs(boxes) do local rect = self:pageToScreenTransform(page, box) if rect then self:drawHighlightRect(bb, x, y, rect, item.drawer or self.highlight.saved_drawer) end end -- end for each box end -- end if boxes end end -- end for each highlight end end -- end for all saved highlight end function ReaderView:drawHighlightRect(bb, _x, _y, rect, drawer) local x, y, w, h = rect.x, rect.y, rect.w, rect.h if drawer == "underscore" then self.highlight.line_width = self.highlight.line_width or 2 self.highlight.line_color = self.highlight.line_color or Blitbuffer.COLOR_GRAY bb:paintRect(x, y+h-1, w, self.highlight.line_width, self.highlight.line_color) elseif drawer == "lighten" then bb:lightenRect(x, y, w, h, self.highlight.lighten_factor) elseif drawer == "invert" then bb:invertRect(x, y, w, h) end end function ReaderView:getPageArea(page, zoom, rotation) if self.use_bbox then return self.ui.document:getUsedBBoxDimensions(page, zoom, rotation) else return self.ui.document:getPageDimensions(page, zoom, rotation) end end --[[ This method is supposed to be only used by ReaderPaging --]] function ReaderView:recalculate() -- Start by resetting the dithering flag early, so it doesn't carry over from the previous page. self.dialog.dithered = nil if self.ui.document.info.has_pages and self.state.page then self.page_area = self:getPageArea( self.state.page, self.state.zoom, self.state.rotation) -- reset our size self.visible_area:setSizeTo(self.dimen) if self.ui.view.footer_visible and not self.ui.view.footer.settings.reclaim_height then self.visible_area.h = self.visible_area.h - self.ui.view.footer:getHeight() end if self.ui.document.configurable.writing_direction == 0 then -- starts from left of page_area self.visible_area.x = self.page_area.x else -- start from right of page_area self.visible_area.x = self.page_area.x + self.page_area.w - self.visible_area.w end if self.ui.zooming.zoom_bottom_to_top then -- starts from bottom of page_area self.visible_area.y = self.page_area.y + self.page_area.h - self.visible_area.h else -- starts from top of page_area self.visible_area.y = self.page_area.y end if not self.page_scroll then -- and recalculate it according to page size self.visible_area:offsetWithin(self.page_area, 0, 0) end -- clear dim area self.dim_area.w = 0 self.dim_area.h = 0 self.ui:handleEvent( Event:new("ViewRecalculate", self.visible_area, self.page_area)) else self.visible_area:setSizeTo(self.dimen) end self.state.offset = Geom:new{x = 0, y = 0} if self.dimen.h > self.visible_area.h then if self.ui.view.footer_visible and not self.ui.view.footer.settings.reclaim_height then self.state.offset.y = (self.dimen.h - (self.visible_area.h + self.ui.view.footer:getHeight())) / 2 else self.state.offset.y = (self.dimen.h - self.visible_area.h) / 2 end end if self.dimen.w > self.visible_area.w then self.state.offset.x = (self.dimen.w - self.visible_area.w) / 2 end -- Flag a repaint so self:paintTo will be called -- NOTE: This is also unfortunately called during panning, essentially making sure we'll never be using "fast" for pans ;). UIManager:setDirty(self.dialog, "partial") end function ReaderView:PanningUpdate(dx, dy) logger.dbg("pan by", dx, dy) local old = self.visible_area:copy() self.visible_area:offsetWithin(self.page_area, dx, dy) if self.visible_area ~= old then -- flag a repaint UIManager:setDirty(self.dialog, "partial") logger.dbg("on pan: page_area", self.page_area) logger.dbg("on pan: visible_area", self.visible_area) self.ui:handleEvent( Event:new("ViewRecalculate", self.visible_area, self.page_area)) end return true end function ReaderView:PanningStart(x, y) logger.dbg("panning start", x, y) if not self.panning_visible_area then self.panning_visible_area = self.visible_area:copy() end self.visible_area = self.panning_visible_area:copy() self.visible_area:offsetWithin(self.page_area, x, y) self.ui:handleEvent(Event:new("ViewRecalculate", self.visible_area, self.page_area)) UIManager:setDirty(self.dialog, "partial") end function ReaderView:PanningStop() self.panning_visible_area = nil end function ReaderView:SetZoomCenter(x, y) local old = self.visible_area:copy() self.visible_area:centerWithin(self.page_area, x, y) if self.visible_area ~= old then self.ui:handleEvent(Event:new("ViewRecalculate", self.visible_area, self.page_area)) UIManager:setDirty(self.dialog, "partial") end end function ReaderView:getViewContext() if self.page_scroll then return self.page_states else return { { page = self.state.page, pos = self.state.pos, zoom = self.state.zoom, rotation = self.state.rotation, gamma = self.state.gamma, offset = self.state.offset:copy(), bbox = self.state.bbox, }, self.visible_area:copy(), self.page_area:copy(), } end end function ReaderView:restoreViewContext(ctx) -- The format of the context is different depending on page_scroll. -- If we're asked to restore the other format, just ignore it -- (our only caller, ReaderPaging:onRestoreBookLocation(), will -- at least change to the page of the context, which is all that -- can be done when restoring from a different mode) if self.page_scroll then if ctx[1] and ctx[1].visible_area then self.page_states = ctx return true end else if ctx[1] and ctx[1].pos then self.state = ctx[1] self.visible_area = ctx[2] self.page_area = ctx[3] return true end end return false end function ReaderView:onSetRotationMode(rotation) if rotation ~= nil then if rotation == Screen:getRotationMode() then return true end Screen:setRotationMode(rotation) end UIManager:setDirty(self.dialog, "full") local new_screen_size = Screen:getSize() self.ui:handleEvent(Event:new("SetDimensions", new_screen_size)) self.ui:onScreenResize(new_screen_size) self.ui:handleEvent(Event:new("InitScrollPageStates")) return true end function ReaderView:onSetDimensions(dimensions) self:resetLayout() self.dimen = dimensions -- recalculate view self:recalculate() end function ReaderView:onRestoreDimensions(dimensions) self:resetLayout() self.dimen = dimensions -- recalculate view self:recalculate() end function ReaderView:onSetFullScreen(full_screen) self.footer_visible = not full_screen self.ui:handleEvent(Event:new("SetDimensions", Screen:getSize())) end function ReaderView:onSetScrollMode(page_scroll) if self.ui.document.info.has_pages and page_scroll and self.ui.zooming.paged_modes[self.zoom_mode] then UIManager:show(InfoMessage:new{ text = _([[ Continuous view (scroll mode) works best with zoom to page width, zoom to content width or zoom to rows. In combination with zoom to fit page, page height, content height, content or columns, continuous view can cause unexpected shifts when turning pages.]]), timeout = 5, }) end self.page_scroll = page_scroll if not page_scroll then self.ui.document.configurable.page_scroll = 0 end self:recalculate() self.ui:handleEvent(Event:new("InitScrollPageStates")) end function ReaderView:onReadSettings(config) self.render_mode = config:readSetting("render_mode") or 0 local rotation_mode = nil local locked = G_reader_settings:isTrue("lock_rotation") -- Keep current rotation by doing nothing when sticky rota is enabled. if not locked then -- Honor docsettings's rotation rotation_mode = config:readSetting("rotation_mode") -- Doc's if not rotation_mode then -- No doc specific rotation, pickup global defaults for the doc type if self.ui.document.info.has_pages then rotation_mode = G_reader_settings:readSetting("kopt_rotation_mode") or Screen.ORIENTATION_PORTRAIT else rotation_mode = G_reader_settings:readSetting("copt_rotation_mode") or Screen.ORIENTATION_PORTRAIT end end end if rotation_mode then self:onSetRotationMode(rotation_mode) end self.state.gamma = config:readSetting("gamma") or 1.0 local full_screen = config:readSetting("kopt_full_screen") or self.document.configurable.full_screen if full_screen == 0 then self.footer_visible = false end self:resetLayout() local page_scroll = config:readSetting("kopt_page_scroll") or self.document.configurable.page_scroll self.page_scroll = page_scroll == 1 and true or false self.highlight.saved = config:readSetting("highlight") or {} self.page_overlap_style = config:readSetting("page_overlap_style") or G_reader_settings:readSetting("page_overlap_style") or "dim" self.page_gap.height = Screen:scaleBySize(config:readSetting("kopt_page_gap_height") or G_reader_settings:readSetting("kopt_page_gap_height") or 8) end function ReaderView:onPageUpdate(new_page_no) self.state.page = new_page_no self.state.drawn = false self:recalculate() self.highlight.temp = {} self:checkAutoSaveSettings() end function ReaderView:onPosUpdate(new_pos) self.state.pos = new_pos self:recalculate() self.highlight.temp = {} self:checkAutoSaveSettings() end function ReaderView:onZoomUpdate(zoom) self.state.zoom = zoom self:recalculate() self.highlight.temp = {} end function ReaderView:onBBoxUpdate(bbox) self.use_bbox = bbox and true or false end function ReaderView:onRotationUpdate(rotation) self.state.rotation = rotation self:recalculate() end function ReaderView:onReaderFooterVisibilityChange() -- Don't bother ReaderRolling with this nonsense, the footer's height is NOT handled via visible_area there ;) if self.ui.document.info.has_pages and self.state.page then -- NOTE: Simply relying on recalculate would be a wee bit too much: it'd reset the in-page offsets, -- which would be wrong, and is also not necessary, since the footer is at the bottom of the screen ;). -- So, simply mangle visible_area's height ourselves... if not self.ui.view.footer.settings.reclaim_height then -- NOTE: Yes, this means that toggling reclaim_height requires a page switch (for a proper recalculate). -- Thankfully, most of the time, the quirks are barely noticeable ;). if self.ui.view.footer_visible then self.visible_area.h = self.visible_area.h - self.ui.view.footer:getHeight() else self.visible_area.h = self.visible_area.h + self.ui.view.footer:getHeight() end end self.ui:handleEvent(Event:new("ViewRecalculate", self.visible_area, self.page_area)) end end function ReaderView:onGammaUpdate(gamma) self.state.gamma = gamma if self.page_scroll then self.ui:handleEvent(Event:new("UpdateScrollPageGamma", gamma)) end end function ReaderView:onFontSizeUpdate(font_size) self.ui:handleEvent(Event:new("ReZoom", font_size)) end function ReaderView:onDefectSizeUpdate() self.ui:handleEvent(Event:new("ReZoom")) end function ReaderView:onPageCrop() self.ui:handleEvent(Event:new("ReZoom")) end function ReaderView:onMarginUpdate() self.ui:handleEvent(Event:new("ReZoom")) end function ReaderView:onSetViewMode(new_mode) if new_mode ~= self.view_mode then self.view_mode = new_mode self.ui.document:setViewMode(new_mode) self.ui:handleEvent(Event:new("ChangeViewMode")) end end --Refresh after changing a variable done by koptoptions.lua since all of them --requires full screen refresh. If this handler used for changing page gap from --another source (eg. coptions.lua) triggering a redraw is needed. function ReaderView:onPageGapUpdate(page_gap) self.page_gap.height = page_gap return true end function ReaderView:onSaveSettings() self.ui.doc_settings:saveSetting("render_mode", self.render_mode) -- Don't etch the current rotation in stone when sticky rotation is enabled local locked = G_reader_settings:isTrue("lock_rotation") if not locked then self.ui.doc_settings:saveSetting("rotation_mode", Screen:getRotationMode()) end self.ui.doc_settings:saveSetting("gamma", self.state.gamma) self.ui.doc_settings:saveSetting("highlight", self.highlight.saved) self.ui.doc_settings:saveSetting("page_overlap_style", self.page_overlap_style) end function ReaderView:getRenderModeMenuTable() local view = self local function make_mode(text, mode) return { text = text, checked_func = function() return view.render_mode == mode end, callback = function() view.render_mode = mode end, } end return { -- @translators Selects which layers of the DjVu image should be rendered. Valid rendering modes are color, black, mask, foreground, and background. See http://djvu.sourceforge.net/ and https://en.wikipedia.org/wiki/DjVu for more information about the format. text = _("DjVu render mode"), sub_item_table = { make_mode(_("COLOUR (works for both colour and b&w pages)"), 0), make_mode(_("BLACK & WHITE (for b&w pages only, much faster)"), 1), make_mode(_("COLOUR ONLY (slightly faster than COLOUR)"), 2), make_mode(_("MASK ONLY (for b&w pages only)"), 3), make_mode(_("COLOUR BACKGROUND (show only background)"), 4), make_mode(_("COLOUR FOREGROUND (show only foreground)"), 5), } } end local page_overlap_styles = { arrow = _("Arrow"), dim = _("Gray out"), } function ReaderView:genOverlapStyleMenu(overlap_enabled_func) local view = self local get_overlap_style = function(style) return { text = page_overlap_styles[style], enabled_func = overlap_enabled_func, checked_func = function() return view.page_overlap_style == style end, callback = function() view.page_overlap_style = style end, hold_callback = function() UIManager:show(ConfirmBox:new{ text = T( _("Set default overlap style to %1?"), style ), ok_callback = function() view.page_overlap_style = style G_reader_settings:saveSetting("page_overlap_style", style) end, }) end, } end return { get_overlap_style("arrow"), get_overlap_style("dim"), } end function ReaderView:onCloseDocument() self.hinting = false -- stop any in fly HintPage event UIManager:unschedule(self.emitHintPageEvent) end function ReaderView:onReaderReady() self.settings_last_save_ts = os.time() end function ReaderView:onResume() -- As settings were saved on suspend, reset this on resume, -- as there's no need for a possibly immediate save. self.settings_last_save_ts = os.time() end function ReaderView:checkAutoSaveSettings() if not self.settings_last_save_ts then -- reader not yet ready return end local interval = G_reader_settings:readSetting("auto_save_settings_interval_minutes") if not interval then -- no auto save return end local now_ts = os.time() if now_ts - self.settings_last_save_ts >= interval*60 then self.settings_last_save_ts = now_ts -- I/O, delay until after the pageturn UIManager:tickAfterNext(function() self.ui:saveSettings() end) end end return ReaderView
agpl-3.0
mys007/cudnn.torch
test/test.lua
1
22263
require 'cudnn' require 'cunn' local cudnntest = {} local precision_forward = 1e-4 local precision_backward = 1e-2 local precision_jac = 1e-3 local nloop = 1 local times = {} local mytester function cudnntest.SpatialConvolution_forward_batch() local bs = math.random(1,32) local from = math.random(1,32) local to = math.random(1,64) local ki = math.random(1,15) local kj = math.random(1,15) local si = math.random(1,ki) local sj = math.random(1,kj) local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local input = torch.randn(bs,from,inj,ini):cuda() local sconv = nn.SpatialConvolutionMM(from,to,ki,kj,si,sj):cuda() local groundtruth = sconv:forward(input) cutorch.synchronize() local gconv = cudnn.SpatialConvolution(from,to,ki,kj,si,sj):cuda() gconv.weight:copy(sconv.weight) gconv.bias:copy(sconv.bias) local rescuda = gconv:forward(input) cutorch.synchronize() local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') end function cudnntest.SpatialConvolution_backward_batch() local bs = math.random(1,32) local from = math.random(1,32) local to = math.random(1,64) local ki = math.random(1,15) local kj = math.random(1,15) local si = math.random(1,ki) local sj = math.random(1,kj) local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local scale = math.random() local input = torch.randn(bs,from,inj,ini):cuda() local gradOutput = torch.randn(bs,to,outj,outi):cuda() local sconv = nn.SpatialConvolutionMM(from,to,ki,kj,si,sj):cuda() sconv:forward(input) sconv:zeroGradParameters() local groundgrad = sconv:backward(input, gradOutput, scale) cutorch.synchronize() local groundweight = sconv.gradWeight local groundbias = sconv.gradBias local gconv = cudnn.SpatialConvolution(from,to,ki,kj,si,sj):cuda() gconv.weight:copy(sconv.weight) gconv.bias:copy(sconv.bias) gconv:forward(input) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') gconv:forward(input) gconv:zeroGradParameters() local rescuda = gconv:backward(input, gradOutput, scale) cutorch.synchronize() local weightcuda = gconv.gradWeight local biascuda = gconv.gradBias local error = rescuda:float() - groundgrad:float() local werror = weightcuda:float() - groundweight:float() local berror = biascuda:float() - groundbias:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') mytester:assertlt(werror:abs():max(), precision_backward, 'error on weight (backward) ') mytester:assertlt(berror:abs():max(), precision_backward, 'error on bias (backward) ') end function cudnntest.SpatialConvolution_forward_single() local from = math.random(1,32) local to = math.random(1,64) local ki = math.random(1,15) local kj = math.random(1,15) local si = math.random(1,ki) local sj = math.random(1,kj) local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local input = torch.randn(from,inj,ini):cuda() local sconv = nn.SpatialConvolutionMM(from,to,ki,kj,si,sj):cuda() local groundtruth = sconv:forward(input) cutorch.synchronize() local gconv = cudnn.SpatialConvolution(from,to,ki,kj,si,sj):cuda() gconv.weight:copy(sconv.weight) gconv.bias:copy(sconv.bias) local rescuda = gconv:forward(input) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 3, 'error in dimension') local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') end function cudnntest.SpatialConvolution_backward_single() local from = math.random(1,32) local to = math.random(1,64) local ki = math.random(1,15) local kj = math.random(1,15) local si = math.random(1,ki) local sj = math.random(1,kj) local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local input = torch.randn(from,inj,ini):cuda() local gradOutput = torch.randn(to,outj,outi):cuda() local sconv = nn.SpatialConvolutionMM(from,to,ki,kj,si,sj):cuda() sconv:forward(input) sconv:zeroGradParameters() local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() local groundweight = sconv.gradWeight local groundbias = sconv.gradBias local gconv = cudnn.SpatialConvolution(from,to,ki,kj,si,sj):cuda() gconv.weight:copy(sconv.weight) gconv.bias:copy(sconv.bias) gconv:forward(input) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') gconv:forward(input) gconv:zeroGradParameters() local rescuda = gconv:backward(input, gradOutput) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 3, 'error in dimension') local weightcuda = gconv.gradWeight local biascuda = gconv.gradBias local error = rescuda:float() - groundgrad:float() local werror = weightcuda:float() - groundweight:float() local berror = biascuda:float() - groundbias:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') mytester:assertlt(werror:abs():max(), precision_backward, 'error on weight (backward) ') mytester:assertlt(berror:abs():max(), precision_backward, 'error on bias (backward) ') end function cudnntest.VolumetricConvolution_forward_single() local from = math.random(1,16) local to = math.random(1,16) local ki = math.random(3,5) local kj = math.random(3,5) local kk = math.random(3,5) local si = math.random(1,ki-1) local sj = math.random(1,kj-1) local sk = math.random(1,kk-1) local outi = math.random(1,17) local outj = math.random(1,17) local outk = math.random(1,5) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local ink = (outk-1)*sk+kk local input = torch.randn(from,ink,inj,ini):cuda() local sconv = nn.VolumetricConvolution(from,to,kk,ki,kj,sk,si,sj):float() local groundtruth = sconv:forward(input:float()) cutorch.synchronize() local gconv = cudnn.VolumetricConvolution(from,to,kk,ki,kj,sk,si,sj):cuda() gconv.weight:copy(sconv.weight) gconv.bias:copy(sconv.bias) local rescuda = gconv:forward(input) cutorch.synchronize() local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') end function cudnntest.VolumetricConvolution_backward_single() local from = math.random(1,16) local to = math.random(1,16) local ki = math.random(3,5) local kj = math.random(3,5) local kk = math.random(3,5) local si = math.random(1,ki-1) local sj = math.random(1,kj-1) local sk = math.random(1,kk-1) local outi = math.random(1,17) local outj = math.random(1,17) local outk = math.random(1,5) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local ink = (outk-1)*sk+kk local input = torch.randn(from,ink,inj,ini):cuda() local gradOutput = torch.randn(to,outk,outj,outi):cuda() local sconv = nn.VolumetricConvolution(from,to,kk,ki,kj,sk,si,sj):float() sconv:forward(input:float()) sconv:zeroGradParameters() local groundgrad = sconv:backward(input:float(), gradOutput:float()) cutorch.synchronize() local groundweight = sconv.gradWeight local groundbias = sconv.gradBias local gconv = cudnn.VolumetricConvolution(from,to,kk,ki,kj,sk,si,sj):cuda() gconv.weight:copy(sconv.weight) gconv.bias:copy(sconv.bias) gconv:forward(input) cutorch.synchronize() -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') gconv:forward(input) gconv:zeroGradParameters() local rescuda = gconv:backward(input, gradOutput) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 4, 'error in dimension') local weightcuda = gconv.gradWeight local biascuda = gconv.gradBias local error = rescuda:float() - groundgrad:float() local werror = weightcuda:float() - groundweight:float() local berror = biascuda:float() - groundbias:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') mytester:assertlt(werror:abs():max(), precision_backward, 'error on weight (backward) ') mytester:assertlt(berror:abs():max(), precision_backward, 'error on bias (backward) ') end function cudnntest.SpatialMaxPooling_batch() local bs = math.random(1,32) local from = math.random(1,32) local ki = math.random(2,4) local kj = math.random(2,4) local si = ki local sj = kj local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local input = torch.randn(bs,from,inj,ini):cuda() local gradOutput = torch.randn(bs,from,outj,outi):cuda() local sconv = nn.SpatialMaxPooling(ki,kj,si,sj):cuda() local groundtruth = sconv:forward(input) local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() local gconv = cudnn.SpatialMaxPooling(ki,kj,si,sj):cuda() local rescuda = gconv:forward(input) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') local rescuda = gconv:forward(input) local resgrad = gconv:backward(input, gradOutput) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 4, 'error in dimension') mytester:asserteq(resgrad:dim(), 4, 'error in dimension') local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') error = resgrad:float() - groundgrad:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') end function cudnntest.SpatialMaxPooling_single() local from = math.random(1,32) local ki = math.random(2,4) local kj = math.random(2,4) local si = ki local sj = kj local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local input = torch.randn(from,inj,ini):cuda() local gradOutput = torch.randn(from,outj,outi):cuda() local sconv = nn.SpatialMaxPooling(ki,kj,si,sj):cuda() local groundtruth = sconv:forward(input) local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() local gconv = cudnn.SpatialMaxPooling(ki,kj,si,sj):cuda() local _ = gconv:forward(input) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') local rescuda = gconv:forward(input) local resgrad = gconv:backward(input, gradOutput) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 3, 'error in dimension') mytester:asserteq(resgrad:dim(), 3, 'error in dimension') local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') error = resgrad:float() - groundgrad:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') end function cudnntest.SpatialAveragePooling_batch() local bs = math.random(1,32) local from = math.random(1,32) local ki = math.random(2,4) local kj = math.random(2,4) local si = math.random(2,4) local sj = math.random(2,4) local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local input = torch.randn(bs,from,inj,ini):cuda() local gradOutput = torch.randn(bs,from,outj,outi):cuda() local sconv = nn.SpatialAveragePooling(ki,kj,si,sj):cuda() local groundtruth = sconv:forward(input):clone() local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() local gconv = cudnn.SpatialAveragePooling(ki,kj,si,sj):cuda() local rescuda = gconv:forward(input) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') local rescuda = gconv:forward(input) local resgrad = gconv:backward(input, gradOutput) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 4, 'error in dimension') mytester:asserteq(resgrad:dim(), 4, 'error in dimension') local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') error = resgrad:float() - groundgrad:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') end function cudnntest.SpatialAveragePooling_single() local from = math.random(1,32) local ki = math.random(2,4) local kj = math.random(2,4) local si = math.random(2,4) local sj = math.random(2,4) local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local input = torch.randn(from,inj,ini):cuda() local gradOutput = torch.randn(from,outj,outi):cuda() local sconv = nn.SpatialAveragePooling(ki,kj,si,sj):cuda() local groundtruth = sconv:forward(input):clone() local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() local gconv = cudnn.SpatialAveragePooling(ki,kj,si,sj):cuda() local _ = gconv:forward(input) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') local rescuda = gconv:forward(input) local resgrad = gconv:backward(input, gradOutput) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 3, 'error in dimension') mytester:asserteq(resgrad:dim(), 3, 'error in dimension') local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') error = resgrad:float() - groundgrad:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') end local function nonlinSingle(nonlin) local from = math.random(1,32) local outi = math.random(1,64) local outj = math.random(1,64) local ini = outi local inj = outj local input = torch.randn(from,inj,ini):cuda() local gradOutput = torch.randn(from,outj,outi):cuda() local sconv = nn[nonlin]():cuda() local groundtruth = sconv:forward(input) local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() -- 50% prob to choose inplace or out-of-place local inplace = false if math.random(0,1) == 1 then inplace = true end local gconv = cudnn[nonlin](inplace):cuda() local input__ = input:clone() local _ = gconv:forward(input__) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') local input__ = input:clone() local gradOutput__ = gradOutput:clone() local rescuda = gconv:forward(input__) local resgrad = gconv:backward(input__, gradOutput__) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 3, 'error in dimension') mytester:asserteq(resgrad:dim(), 3, 'error in dimension') local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') error = resgrad:float() - groundgrad:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') end function nonlinBatch(nonlin) local bs = math.random(1,32) local from = math.random(1,32) local outi = math.random(1,64) local outj = math.random(1,64) local ini = outi local inj = outj local input = torch.randn(bs,from,inj,ini):cuda() local gradOutput = torch.randn(bs,from,outj,outi):cuda() local sconv = nn[nonlin]():cuda() local groundtruth = sconv:forward(input) local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() -- 50% prob to choose inplace or out-of-place local inplace = false if math.random(0,1) == 1 then inplace = true end local gconv = cudnn[nonlin](inplace):cuda() local input__ = input:clone() local rescuda = gconv:forward(input__) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') local input__ = input:clone() local gradOutput__ = gradOutput:clone() local rescuda = gconv:forward(input__) local resgrad = gconv:backward(input__, gradOutput__) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 4, 'error in dimension') mytester:asserteq(resgrad:dim(), 4, 'error in dimension') local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') error = resgrad:float() - groundgrad:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') end function cudnntest.ReLU_single() nonlinSingle('ReLU') end function cudnntest.ReLU_batch() nonlinBatch('ReLU') end function cudnntest.Tanh_single() nonlinSingle('Tanh') end function cudnntest.Tanh_batch() nonlinBatch('Tanh') end function cudnntest.Sigmoid_single() nonlinSingle('Sigmoid') end function cudnntest.Sigmoid_batch() nonlinBatch('Sigmoid') end function cudnntest.SoftMax_single() local sz = math.random(1,64) local input = torch.randn(sz):cuda() local gradOutput = torch.randn(sz):cuda() local sconv = nn.SoftMax():cuda() local groundtruth = sconv:forward(input) local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() local gconv = cudnn.SoftMax():cuda() local _ = gconv:forward(input) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') local rescuda = gconv:forward(input) local resgrad = gconv:backward(input, gradOutput) cutorch.synchronize() local error = rescuda:float() - groundtruth:float() local errmax = error:abs():max() if (errmax ~= errmax) then local state = {} state.input = input state.gradOutput = gradOutput state.rescuda = rescuda state.resgrad = resgrad state.groundtruth = groundtruth state.groundgrad = groundgrad print(#input) torch.save('badSoftMax.t7', state) print(#input) end mytester:assertlt(errmax, precision_forward, 'error on state (forward) ') error = resgrad:float() - groundgrad:float() errmax = error:abs():max() if (errmax ~= errmax) then local state = {} state.input = input state.gradOutput = gradOutput state.rescuda = rescuda state.resgrad = resgrad state.groundtruth = groundtruth state.groundgrad = groundgrad print(#input) torch.save('badSoftMax.t7', state) print(#input) end mytester:assertlt(errmax, precision_backward, 'error on state (backward) ') end function cudnntest.SoftMax_batch() local bs = math.random(1,32) local from = math.random(1,32) local outi = math.random(1,64) local outj = math.random(1,64) local ini = outi local inj = outj local input = torch.randn(bs,from,inj,ini):cuda() local gradOutput = torch.randn(bs,from,outj,outi):cuda() local sconv = nn.SoftMax():cuda() local groundtruth = sconv:forward(input:view(bs,-1)) local groundgrad = sconv:backward(input, gradOutput) cutorch.synchronize() local gconv = cudnn.SoftMax():cuda() local rescuda = gconv:forward(input) -- serialize and deserialize torch.save('modelTemp.t7', gconv) gconv = torch.load('modelTemp.t7') local rescuda = gconv:forward(input) local resgrad = gconv:backward(input, gradOutput) cutorch.synchronize() mytester:asserteq(rescuda:dim(), 4, 'error in dimension') mytester:asserteq(resgrad:dim(), 4, 'error in dimension') local error = rescuda:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) ') error = resgrad:float() - groundgrad:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ') end function cudnntest.functional_SpatialBias() local bs = math.random(1,32) local from = math.random(1,32) local to = math.random(1,64) local ki = math.random(1,15) local kj = math.random(1,15) local si = math.random(1,ki) local sj = math.random(1,kj) local outi = math.random(1,64) local outj = math.random(1,64) local ini = (outi-1)*si+ki local inj = (outj-1)*sj+kj local scale = torch.uniform() local input = torch.zeros(bs,from,inj,ini):cuda() local mod = cudnn.SpatialConvolution(from,to,ki,kj,si,sj):cuda() mod.weight:zero() local groundtruth = mod:forward(input) local result = groundtruth:clone():zero() cudnn.functional.SpatialBias_updateOutput(mod.bias, result) local error = result:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_forward, 'error on forward ') mod:zeroGradParameters() local gradOutput = groundtruth:clone():normal() mod:backward(input, gradOutput, scale) local groundtruth = mod.gradBias local result = groundtruth:clone():zero() cudnn.functional.SpatialBias_accGradParameters(gradOutput, result, scale) error = result:float() - groundtruth:float() mytester:assertlt(error:abs():max(), precision_backward, 'error on accGradParameters ') end torch.setdefaulttensortype('torch.FloatTensor') math.randomseed(os.time()) mytester = torch.Tester() mytester:add(cudnntest) for i=1,cutorch.getDeviceCount() do print('Running test on device: ' .. i) cutorch.setDevice(i) mytester:run() end os.execute('rm -f modelTemp.t7')
bsd-2-clause
REZATITAN/X
plugins/ingroup.lua
202
31524
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- 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 check_member_modadd(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, 'Group is added and 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 check_member_modrem(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 removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end 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 bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] 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.."\nBot protection : "..bots_protection 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_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' 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) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) 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 i = 1 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 ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(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 if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end 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 name_log = user_print_name(msg.from) 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] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(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) 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 if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(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 if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(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 if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a 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)$", "^[!/](rem)$", "^[!/](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
mjarco/sysdig
userspace/sysdig/chisels/v_connections.lua
4
3168
--[[ Copyright (C) 2013-2014 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] view_info = { id = "connections", name = "Connections", description = "Top network connections. This view lists all of the network connections that were active during the last sampling interval, with details for each of them.", tips = {"This view can be applied not only to the whole machine, but also to single processes, containers, threads and so on. Use it after a drill down for more fine grained investigation."}, tags = {"Default"}, view_type = "table", applies_to = {"", "container.id", "proc.pid", "proc.name", "thread.tid", "fd.sport", "fd.dport", "fd.port", "fd.lport", "fd.rport", "evt.res"}, filter = "fd.type=ipv4 or fd.type=ipv6 and fd.name!=''", use_defaults = true, drilldown_target = "incoming_connections", columns = { { tags = {"default"}, name = "NA", field = "fd.name", is_key = true }, { tags = {"containers"}, name = "NA", field = "fd.containername", is_key = true }, { name = "L4PROTO", description = "The connection transport protocol (TCP, UDP, etc.).", field = "fd.l4proto", colsize = 8, }, { name = "LIP", description = "Local IP Address.", field = "fd.lip", colsize = 17, }, { name = "LPORT", description = "Local Port.", field = "fd.lproto", colsize = 8, }, { name = "RIP", description = "Remote IP Address.", field = "fd.rip", colsize = 17, }, { name = "RPORT", description = "Remote Port.", field = "fd.rproto", colsize = 8, }, { is_sorting = true, name = "BPS IN", field = "evt.buflen.net.in", description = "This connection's input bandwidth in bytes per second.", colsize = 12, aggregation = "TIME_AVG" }, { name = "BPS OUT", field = "evt.buflen.net.out", description = "This connection's output bandwidth in bytes per second.", colsize = 12, aggregation = "TIME_AVG" }, { name = "IOPS", field = "evt.count", description = "Total (read+write) number of calls per second made on this connection by the owning process.", colsize = 12, aggregation = "TIME_AVG" }, { tags = {"containers"}, name = "Container", field = "container.name", description = "Name of the container. What this field contains depends on the containerization technology. For example, for docker this is the content of the 'NAMES' column in 'docker ps'", colsize = 15 }, { name = "Command", description = "The full command line of the process owning the connection's socket.", field = "proc.exeline", aggregation = "MAX", colsize = 0 } } }
gpl-2.0
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/sandbox/entities/weapons/gmod_tool/stools/rope.lua
1
5221
TOOL.Category = "Constraints" TOOL.Name = "#tool.rope.name" TOOL.Command = nil TOOL.ConfigName = nil TOOL.ClientConVar[ "forcelimit" ] = "0" TOOL.ClientConVar[ "addlength" ] = "0" TOOL.ClientConVar[ "material" ] = "cable/rope" TOOL.ClientConVar[ "width" ] = "2" TOOL.ClientConVar[ "rigid" ] = "0" function TOOL:LeftClick( trace ) if ( trace.Entity:IsValid() && trace.Entity:IsPlayer() ) then return end -- If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( iNum + 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) if ( iNum > 0 ) then if ( CLIENT ) then self:ClearObjects() return true end -- Get client's CVars local forcelimit = self:GetClientNumber( "forcelimit" ) local addlength = self:GetClientNumber( "addlength" ) local material = self:GetClientInfo( "material" ) local width = self:GetClientNumber( "width" ) local rigid = self:GetClientNumber( "rigid" ) == 1 -- Get information we're about to use local Ent1, Ent2 = self:GetEnt(1), self:GetEnt(2) local Bone1, Bone2 = self:GetBone(1), self:GetBone(2) local WPos1, WPos2 = self:GetPos(1), self:GetPos(2) local LPos1, LPos2 = self:GetLocalPos(1),self:GetLocalPos(2) local length = ( WPos1 - WPos2):Length() local constraint, rope = constraint.Rope( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, length, addlength, forcelimit, width, material, rigid ) -- Clear the objects so we're ready to go again self:ClearObjects() -- Add The constraint to the players undo table undo.Create("Rope") undo.AddEntity( constraint ) undo.AddEntity( rope ) undo.SetPlayer( self:GetOwner() ) undo.Finish() self:GetOwner():AddCleanup( "ropeconstraints", constraint ) self:GetOwner():AddCleanup( "ropeconstraints", rope ) else self:SetStage( iNum+1 ) end return true end function TOOL:RightClick( trace ) if ( trace.Entity:IsValid() && trace.Entity:IsPlayer() ) then return end local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( iNum + 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) if ( iNum > 0 ) then if ( CLIENT ) then self:ClearObjects() return true end -- Get client's CVars local forcelimit = self:GetClientNumber( "forcelimit" ) local addlength = self:GetClientNumber( "addlength" ) local material = self:GetClientInfo( "material" ) local width = self:GetClientNumber( "width" ) local rigid = self:GetClientNumber( "rigid" ) == 1 -- Get information we're about to use local Ent1, Ent2 = self:GetEnt(1), self:GetEnt(2) local Bone1, Bone2 = self:GetBone(1), self:GetBone(2) local WPos1, WPos2 = self:GetPos(1),self:GetPos(2) local LPos1, LPos2 = self:GetLocalPos(1),self:GetLocalPos(2) local length = ( WPos1 - WPos2 ):Length() local constraint, rope = constraint.Rope( Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, length, addlength, forcelimit, width, material, rigid ) -- Clear the objects and set the last object as object 1 self:ClearObjects() iNum = self:NumObjects() self:SetObject( iNum + 1, Ent2, trace.HitPos, Phys, Bone2, trace.HitNormal ) self:SetStage( iNum+1 ) -- Add The constraint to the players undo table undo.Create("Rope") undo.AddEntity( constraint ) if rope then undo.AddEntity( rope ) end undo.SetPlayer( self:GetOwner() ) undo.Finish() self:GetOwner():AddCleanup( "ropeconstraints", constraint ) self:GetOwner():AddCleanup( "ropeconstraints", rope ) else self:SetStage( iNum+1 ) end return true end function TOOL:Reload( trace ) if (!trace.Entity:IsValid() || trace.Entity:IsPlayer() ) then return false end if ( CLIENT ) then return true end local bool = constraint.RemoveConstraints( trace.Entity, "Rope" ) return bool end function TOOL.BuildCPanel( CPanel ) CPanel:AddControl( "Header", { Text = "#tool.rope.name", Description = "#tool.rope.help" } ) CPanel:AddControl( "ComboBox", { Label = "#tool.presets", MenuButton = 1, Folder = "rope", Options = { Default = { rope_forcelimit = '0', rope_addlength='0', rope_width='1', rope_material='cable/rope', rope_rigid='0' } }, CVars = { "rope_forcelimit", "rope_addlength", "rope_width", "rope_material", "rope_rigid" } }) CPanel:AddControl( "Slider", { Label = "#tool.forcelimit", Type = "Float", Command = "rope_forcelimit", Min = "0", Max = "1000", Help=true } ) CPanel:AddControl( "Slider", { Label = "#tool.rope.addlength", Type = "Float", Command = "rope_addlength", Min = "-500", Max = "500", Help=true } ) CPanel:AddControl( "CheckBox", { Label = "#tool.rope.rigid", Command = "rope_rigid", Help=true } ) CPanel:AddControl( "Slider", { Label = "#tool.rope.width", Type = "Float", Command = "rope_width", Min = "0", Max = "10" } ) CPanel:AddControl( "RopeMaterial", { Label = "#tool.rope.material", convar = "rope_material" } ) end
mit
Aminkavari/-xXD4RKXx-
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
NatWeiss/RGP
src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/TransitionTurnOffTiles.lua
7
1162
-------------------------------- -- @module TransitionTurnOffTiles -- @extend TransitionScene,TransitionEaseScene -- @parent_module cc -------------------------------- -- -- @function [parent=#TransitionTurnOffTiles] easeActionWithAction -- @param self -- @param #cc.ActionInterval action -- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval) -------------------------------- -- Creates a transition with duration and incoming scene.<br> -- param t Duration time, in seconds.<br> -- param scene A given scene.<br> -- return A autoreleased TransitionTurnOffTiles object. -- @function [parent=#TransitionTurnOffTiles] create -- @param self -- @param #float t -- @param #cc.Scene scene -- @return TransitionTurnOffTiles#TransitionTurnOffTiles ret (return value: cc.TransitionTurnOffTiles) -------------------------------- -- js NA -- @function [parent=#TransitionTurnOffTiles] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table transform -- @param #unsigned int flags -- @return TransitionTurnOffTiles#TransitionTurnOffTiles self (return value: cc.TransitionTurnOffTiles) return nil
mit
eggBOY91/Arctic-Core
src/scripts/lua/Lua/Stable Scripts/Azeroth/Karazhan/BOSS_Karazhan_Curator.lua
30
1319
function Curator_Evocation(Unit, event, miscunit, misc) if Unit:GetManaPct() < 1 and Didthat == 0 then print "Curator Evocation" Unit:FullCastSpell(30254) Didthat = 1 else end end function Curator_Enrage(Unit, event, miscunit, misc) if Unit:GetHealthPct() < 15 and Didthat == 1 then print "Curator_Enrage" Unit:FullCastSpell(41447) Didthat = 2 else end end function Curator_Summon_Astral_Flare(Unit, event, miscunit, misc) print "Curator Summon Astral Flare" Unit:SpawnCreature(17096, -1168.601, 1699.915, 91.477, 0, 18, 96000000); Unit:SendChatMessage(11, 0, "Help me...") end function Curator_Hateful_Bolt(Unit, event, miscunit, misc) print "Curator Hateful Bolt" Unit:FullCastSpellOnTarget(30383,Unit:GetRandomPlayer()) Unit:SendChatMessage(11, 0, "Catch that...") end function Curator_Berserk(Unit, event, miscunit, misc) print "Curator Berserk" Unit:FullCastSpell(35595) Unit:SendChatMessage(11, 0, "Now you will die...") end function Curator(unit, event, miscunit, misc) print "Curator" unit:RegisterEvent("Curator_Evocation",1000,0) unit:RegisterEvent("Curator_Enrage",1000,0) unit:RegisterEvent("Curator_Summon_Astral_Flare",10000,0) unit:RegisterEvent("Curator_Hateful_Bolt",27000,0) unit:RegisterEvent("Curator_Berserk",720000,0) end RegisterUnitEvent(15691,1,"Curator")
agpl-3.0
bradchesney79/2015BeastRouterProject
openwrt/unsquash/squashfs-root/usr/lib/lua/luci/controller/admin/uci.lua
40
1769
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.uci", package.seeall) function index() local redir = luci.http.formvalue("redir", true) or luci.dispatcher.build_url(unpack(luci.dispatcher.context.request)) entry({"admin", "uci"}, nil, _("Configuration")) entry({"admin", "uci", "changes"}, call("action_changes"), _("Changes"), 40).query = {redir=redir} entry({"admin", "uci", "revert"}, call("action_revert"), _("Revert"), 30).query = {redir=redir} entry({"admin", "uci", "apply"}, call("action_apply"), _("Apply"), 20).query = {redir=redir} entry({"admin", "uci", "saveapply"}, call("action_apply"), _("Save &#38; Apply"), 10).query = {redir=redir} end function action_changes() local uci = luci.model.uci.cursor() local changes = uci:changes() luci.template.render("admin_uci/changes", { changes = next(changes) and changes }) end function action_apply() local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local changes = uci:changes() local reload = {} -- Collect files to be applied and commit changes for r, tbl in pairs(changes) do table.insert(reload, r) if path[#path] ~= "apply" then uci:load(r) uci:commit(r) uci:unload(r) end end luci.template.render("admin_uci/apply", { changes = next(changes) and changes, configs = reload }) end function action_revert() local uci = luci.model.uci.cursor() local changes = uci:changes() -- Collect files to be reverted for r, tbl in pairs(changes) do uci:load(r) uci:revert(r) uci:unload(r) end luci.template.render("admin_uci/revert", { changes = next(changes) and changes }) end
cc0-1.0
joaofvieira/luci
applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo.lua
141
1038
--[[ smap_devinfo - SIP Device Information (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("SIP Device Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", false, debug) luci.controller.luci_diag.smap_common.action_links(m, false) return m
apache-2.0
NatWeiss/RGP
src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/DirectionLight.lua
8
1377
-------------------------------- -- @module DirectionLight -- @extend BaseLight -- @parent_module cc -------------------------------- -- Returns the Direction in parent. -- @function [parent=#DirectionLight] getDirection -- @param self -- @return vec3_table#vec3_table ret (return value: vec3_table) -------------------------------- -- Returns direction in world. -- @function [parent=#DirectionLight] getDirectionInWorld -- @param self -- @return vec3_table#vec3_table ret (return value: vec3_table) -------------------------------- -- Sets the Direction in parent.<br> -- param dir The Direction in parent. -- @function [parent=#DirectionLight] setDirection -- @param self -- @param #vec3_table dir -- @return DirectionLight#DirectionLight self (return value: cc.DirectionLight) -------------------------------- -- Creates a direction light.<br> -- param direction The light's direction<br> -- param color The light's color.<br> -- return The new direction light. -- @function [parent=#DirectionLight] create -- @param self -- @param #vec3_table direction -- @param #color3b_table color -- @return DirectionLight#DirectionLight ret (return value: cc.DirectionLight) -------------------------------- -- -- @function [parent=#DirectionLight] getLightType -- @param self -- @return int#int ret (return value: int) return nil
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/sandbox/entities/weapons/gmod_tool/stools/winch.lua
1
6444
TOOL.Category = "Constraints" TOOL.Name = "#tool.winch.name" TOOL.Command = nil TOOL.ConfigName = nil TOOL.ClientConVar[ "rope_material" ] = "cable/rope" TOOL.ClientConVar[ "rope_width" ] = "3" TOOL.ClientConVar[ "fwd_speed" ] = "64" TOOL.ClientConVar[ "bwd_speed" ] = "64" TOOL.ClientConVar[ "fwd_group" ] = "8" TOOL.ClientConVar[ "bwd_group" ] = "5" function TOOL:LeftClick( trace ) if ( trace.Entity:IsValid() && trace.Entity:IsPlayer() ) then return end -- If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( iNum + 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) if ( iNum > 0 ) then if ( CLIENT ) then self:ClearObjects() return true end -- Get client's CVars local material = self:GetClientInfo( "rope_material" ) or "cable/rope" local width = self:GetClientNumber( "rope_width" ) or 3 local fwd_bind = self:GetClientNumber( "fwd_group" ) or 1 local bwd_bind = self:GetClientNumber( "bwd_group" ) or 1 local fwd_speed = self:GetClientNumber( "fwd_speed" ) or 64 local bwd_speed = self:GetClientNumber( "bwd_speed" ) or 64 local toggle = false -- Get information we're about to use local Ent1, Ent2 = self:GetEnt(1), self:GetEnt(2) local Bone1, Bone2 = self:GetBone(1), self:GetBone(2) local LPos1, LPos2 = self:GetLocalPos(1),self:GetLocalPos(2) local constraint,rope,controller = constraint.Winch( self:GetOwner(), Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, width, fwd_bind, bwd_bind, fwd_speed, bwd_speed, material, toggle ) undo.Create("Winch") if constraint then undo.AddEntity( constraint ) end if rope then undo.AddEntity( rope ) end if controller then undo.AddEntity( controller ) end undo.SetPlayer( self:GetOwner() ) undo.Finish() if constraint then self:GetOwner():AddCleanup( "ropeconstraints", constraint ) end if rope then self:GetOwner():AddCleanup( "ropeconstraints", rope ) end if controller then self:GetOwner():AddCleanup( "ropeconstraints", controller ) end -- Clear the objects so we're ready to go again self:ClearObjects() else self:SetStage( iNum+1 ) end return true end function TOOL:RightClick( trace ) -- If there's no physics object then we can't constraint it! if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end local iNum = self:NumObjects() local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) local tr = {} tr.start = trace.HitPos tr.endpos = tr.start + (trace.HitNormal * 16384) tr.filter = {} tr.filter[1] = self:GetOwner() if (trace.Entity:IsValid()) then tr.filter[2] = trace.Entity end local tr = util.TraceLine( tr ) if ( !tr.Hit ) then self:ClearObjects() return end -- Don't try to constrain world to world if ( trace.HitWorld && tr.HitWorld ) then self:ClearObjects() return end if ( trace.Entity:IsValid() && trace.Entity:IsPlayer() ) then self:ClearObjects() return end if ( tr.Entity:IsValid() && tr.Entity:IsPlayer() ) then self:ClearObjects() return end local Phys2 = tr.Entity:GetPhysicsObjectNum( tr.PhysicsBone ) self:SetObject( 2, tr.Entity, tr.HitPos, Phys2, tr.PhysicsBone, trace.HitNormal ) if ( CLIENT ) then self:ClearObjects() return true end -- Get client's CVars local material = self:GetClientInfo( "rope_material" ) or "cable/rope" local width = self:GetClientNumber( "rope_width" ) or 3 local fwd_bind = self:GetClientNumber( "fwd_group" ) or 1 local bwd_bind = self:GetClientNumber( "bwd_group" ) or 1 local fwd_speed = self:GetClientNumber( "fwd_speed" ) or 64 local bwd_speed = self:GetClientNumber( "bwd_speed" ) or 64 -- Get information we're about to use local Ent1, Ent2 = self:GetEnt(1), self:GetEnt(2) local Bone1, Bone2 = self:GetBone(1), self:GetBone(2) local LPos1, LPos2 = self:GetLocalPos(1),self:GetLocalPos(2) local constraint,rope,controller = constraint.Winch( self:GetOwner(), Ent1, Ent2, Bone1, Bone2, LPos1, LPos2, width, fwd_bind, bwd_bind, fwd_speed, bwd_speed, material ) undo.Create("Winch") if constraint then undo.AddEntity( constraint ) end if rope then undo.AddEntity( rope ) end if controller then undo.AddEntity( controller ) end undo.SetPlayer( self:GetOwner() ) undo.Finish() if constraint then self:GetOwner():AddCleanup( "ropeconstraints", constraint ) end if rope then self:GetOwner():AddCleanup( "ropeconstraints", rope ) end if controller then self:GetOwner():AddCleanup( "ropeconstraints", controller ) end -- Clear the objects so we're ready to go again self:ClearObjects() return true end function TOOL:Reload( trace ) if (!trace.Entity:IsValid() || trace.Entity:IsPlayer() ) then return false end if ( CLIENT ) then return true end local bool = constraint.RemoveConstraints( trace.Entity, "Winch" ) return bool end function TOOL.BuildCPanel( CPanel ) CPanel:AddControl( "Header", { Text = "#tool.winch.name", Description = "#tool.winch.help" } ) CPanel:AddControl( "ComboBox", { Label = "#tool.presets", MenuButton = 1, Folder = "winch", Options = { Default = { winch_rope_width = '1', winch_fwd_speed='64', winch_bwd_speed='64', winch_rope_rigid='0', winch_rope_material='cable/cable' } }, CVars = { "winch_rope_width", "winch_fwd_speed", "winch_bwd_speed", "winch_rope_rigid", "winch_rope_material" } }) CPanel:AddControl( "Numpad", { Label = "#tool.winch.forward", Command = "winch_fwd_group", Label2 = "#tool.winch.backward", Command2 = "winch_bwd_group" } ) CPanel:AddControl( "Slider", { Label = "#tool.winch.fspeed", Type = "Float", Command = "winch_fwd_speed", Min = "0", Max = "1000", Help=true } ) CPanel:AddControl( "Slider", { Label = "#tool.winch.bspeed", Type = "Float", Command = "winch_bwd_speed", Min = "0", Max = "1000", Help=true } ) CPanel:AddControl( "Slider", { Label = "#tool.winch.width", Type = "Float", Command = "winch_rope_width", Min = "0", Max = "10" } ) CPanel:AddControl( "RopeMaterial", { Label = "#tool.winch.material", convar = "winch_rope_material" } ) end
mit
eggBOY91/Arctic-Core
src/scripts/lua/LuaBridge/Stable Scripts/Outland/Arcatraz/BOSS_Arcatraz_Drakonaar.lua
30
1349
function Drakonaar_Red(Unit, event, miscunit, misc) print "Drakonaar Red" Unit:FullCastSpellOnTarget(14264,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "This spell will kill you...") end function Drakonaar_Blue(Unit, event, miscunit, misc) print "Drakonaar Blue" Unit:FullCastSpellOnTarget(14261,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Look behind you...") end function Drakonaar_Green(Unit, event, miscunit, misc) print "Drakonaar Green" Unit:FullCastSpellOnTarget(14262,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Look your face, you are afraid...") end function Drakonaar_Black(Unit, event, miscunit, misc) print "Drakonaar Black" Unit:FullCastSpellOnTarget(14265,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Now the final blast...") end function Drakonaar_Bronze(Unit, event, miscunit, misc) print "Drakonaar Bronze" Unit:FullCastSpellOnTarget(14263,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "I will crush you in my hand...") end function Drakonaar(unit, event, miscunit, misc) print "Drakonaar" unit:RegisterEvent("Drakonaar_Red",11000,0) unit:RegisterEvent("Drakonaar_Blue",15000,0) unit:RegisterEvent("Drakonaar_Green",21000,0) unit:RegisterEvent("Drakonaar_Black",27000,0) unit:RegisterEvent("Drakonaar_Bronze",31000,0) end RegisterUnitEvent(20910,1,"Drakonaar")
agpl-3.0
dangersuperbot/super_boomrange
plugins/cpu.lua
244
1893
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!$ uptime') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!$ uptime", patterns = {"^!$ uptime", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
philsiff/Red-Vs-Blue
Red Vs. Blue Files/lua/entities/widget_bones.lua
1
3594
AddCSLuaFile() local matBone = Material( "widgets/bone.png", "unlitsmooth" ) local matBoneSmall = Material( "widgets/bone_small.png", "unlitsmooth" ) local widget_bone = { Base = "widget_base", a = 255, GetParentPos = function( self ) local p = self:GetParent() if ( !IsValid( p ) ) then return end local i = self:GetParentAttachment() local i = p:GetBoneParent( i ) if ( i <= 0 ) then return end return p:GetBonePosition( i ) end, OverlayRender = function( self ) local fwd = self:GetAngles():Forward() local len = self:GetSize() / 2 local w = len * 0.2 local pp = self:GetParentPos() if ( !pp ) then return end if ( len > 10 ) then render.SetMaterial( matBone ) else render.SetMaterial( matBoneSmall ) end local c = Color( 255, 255, 255, 255 ) if ( self:IsHovered() ) then self.a = math.Approach( self.a, 255, FrameTime() * 255 * 10 ) elseif ( self:SomethingHovered() ) then self.a = math.Approach( self.a, 20, FrameTime() * 255 * 10 ) else self.a = math.Approach( self.a, 255, FrameTime() * 255 * 10 ) end cam.IgnoreZ( true ) render.DrawBeam( self:GetPos(), pp, w, 0, 1, Color( c.r, c.g, c.b, self.a * 0.5 ) ) cam.IgnoreZ( false ) render.DrawBeam( self:GetPos(), pp, w, 0, 1, Color( c.r, c.g, c.b, self.a ) ) end, TestCollision = function( self, startpos, delta, isbox, extents ) if ( isbox ) then return end if ( !widgets.Tracing ) then return end local pp = self:GetParentPos(); if ( !pp ) then return end local fwd = (pp - self:GetPos()):GetNormal() local ang = fwd:Angle() local len = self:GetSize() / 2 local w = len * 0.2 local mins = Vector( 0, w * -0.5, w * -0.5 ) local maxs = Vector( len, w * 0.5, w * 0.5 ) local hit, norm, fraction = util.IntersectRayWithOBB( startpos, delta, self:GetPos(), ang, mins, maxs ) if ( !hit ) then return end --debugoverlay.BoxAngles( self:GetPos(), mins, maxs, ang, 0.5, Color( 255, 255, 0, 100 ) ) return { HitPos = hit, Fraction = fraction * self:GetPriority() } end, Think = function( self ) if ( !SERVER ) then return end if ( !IsValid( self:GetParent() ) ) then return end -- -- Because the bone length changes (with the manipulator) -- we need to update the bones pretty regularly -- local size = self:GetParent():BoneLength( self:GetParentAttachment() ) * 2; size = math.ceil( size ) self:SetSize( size ) end } scripted_ents.Register( widget_bone, "widget_bone" ) DEFINE_BASECLASS( "widget_base" ) function ENT:SetupDataTables() self:NetworkVar( "Entity", 0, "Target" ); self.BaseClass.SetupDataTables( self ) end -- -- Set our dimensions etc -- function ENT:Initialize() self.BaseClass.Initialize( self ) self:SetCollisionBounds( Vector( -1, -1, -1 ), Vector( 1, 1, 1 ) ) self:SetSolid( SOLID_NONE ) end function ENT:Setup( ent ) self:SetTarget( ent ) self:SetParent( ent ) self:SetLocalPos( Vector( 0, 0, 0 ) ) for k=0, ent:GetBoneCount()-1 do if ( ent:GetBoneParent( k ) <= 0 ) then continue end if ( !ent:BoneHasFlag( k, BONE_USED_BY_VERTEX_LOD0 ) ) then continue end local btn = ents.Create( "widget_bone" ) btn:FollowBone( ent, k ) btn:SetLocalPos( Vector( 0, 0, 0 ) ) btn:SetLocalAngles( Angle( 0, 0, 0 ) ) btn:Spawn() btn:SetSize( ent:BoneLength( k ) * 2 ) btn.OnClick = function( x, ply ) self:OnBoneClick( k, ply ) end self:DeleteOnRemove( btn ) end end function ENT:OnBoneClick( boneid, ply ) end function ENT:OverlayRender() end
mit
Samake/Minecraft
Minecraft/server/system/MainClassS.lua
1
1588
--[[ Name: Minecraft Filename: MainClassS.lua Authors: Sam@ke --]] local Instance = nil MainClassS = {} function MainClassS:constructor() mainOutput("SERVER // ***** Minecraft was started *****") mainOutput("MainClassS was loaded.") setFPSLimit(60) self:init() end function MainClassS:init() if (not self.debugClass) then self.debugClass = new(DebugClassS, self) end if (not self.terrainHandler) then self.terrainHandler = new(TerrainHandlerS, self) end if (not self.playerManager) then self.playerManager = new(PlayerManagerS, self) end if (not self.blockManager) then self.blockManager = new(BlockManagerS, self) end if (not self.testClass) then self.testClass = new(TestClassS, self) end end function MainClassS:clear() if (self.terrainHandler) then delete(self.terrainHandler) self.terrainHandler = nil end if (self.playerManager) then delete(self.playerManager) self.playerManager = nil end if (self.blockManager) then delete(self.blockManager) self.blockManager = nil end if (self.testClass) then delete(self.testClass) self.testClass = nil end if (self.debugClass) then delete(self.debugClass) self.debugClass = nil end end function MainClassS:destructor() self:clear() mainOutput("MainClassS was deleted.") mainOutput("SERVER // ***** Minecraft was closed *****") end addEventHandler("onResourceStart", resourceRoot, function() Instance = new(MainClassS) end) addEventHandler("onResourceStop", resourceRoot, function() if (Instance) then delete(Instance) Instance = nil end end)
gpl-3.0
NatWeiss/RGP
src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/EaseBackIn.lua
7
1027
-------------------------------- -- @module EaseBackIn -- @extend ActionEase -- @parent_module cc -------------------------------- -- brief Create the action with the inner action.<br> -- param action The pointer of the inner action.<br> -- return A pointer of EaseBackIn action. If creation failed, return nil. -- @function [parent=#EaseBackIn] create -- @param self -- @param #cc.ActionInterval action -- @return EaseBackIn#EaseBackIn ret (return value: cc.EaseBackIn) -------------------------------- -- -- @function [parent=#EaseBackIn] clone -- @param self -- @return EaseBackIn#EaseBackIn ret (return value: cc.EaseBackIn) -------------------------------- -- -- @function [parent=#EaseBackIn] update -- @param self -- @param #float time -- @return EaseBackIn#EaseBackIn self (return value: cc.EaseBackIn) -------------------------------- -- -- @function [parent=#EaseBackIn] reverse -- @param self -- @return ActionEase#ActionEase ret (return value: cc.ActionEase) return nil
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/lua/includes/extensions/table.lua
1
15568
--[[--------------------------------------------------------- Name: Inherit( t, base ) Desc: Copies any missing data from base to t -----------------------------------------------------------]] function table.Inherit( t, base ) for k, v in pairs( base ) do if ( t[k] == nil ) then t[k] = v end end t["BaseClass"] = base return t end --[[--------------------------------------------------------- Name: Copy(t, lookup_table) Desc: Taken straight from http://lua-users.org/wiki/PitLibTablestuff and modified to the new Lua 5.1 code by me. Original function by PeterPrade! -----------------------------------------------------------]] function table.Copy(t, lookup_table) if (t == nil) then return nil end local copy = {} setmetatable(copy, getmetatable(t)) for i,v in pairs(t) do if ( !istable(v) ) then copy[i] = v else lookup_table = lookup_table or {} lookup_table[t] = copy if lookup_table[v] then copy[i] = lookup_table[v] -- we already copied this table. reuse the copy. else copy[i] = table.Copy(v,lookup_table) -- not yet copied. copy it. end end end return copy end --[[--------------------------------------------------------- Name: Empty( tab ) Desc: Empty a table -----------------------------------------------------------]] function table.Empty( tab ) for k, v in pairs( tab ) do tab[k] = nil end end --[[--------------------------------------------------------- Name: CopyFromTo( FROM, TO ) Desc: Make TO exactly the same as FROM - but still the same table. -----------------------------------------------------------]] function table.CopyFromTo( FROM, TO ) -- Erase values from table TO table.Empty( TO ) -- Copy values over table.Merge( TO, FROM ) end --[[--------------------------------------------------------- Name: xx Desc: xx -----------------------------------------------------------]] function table.Merge(dest, source) for k,v in pairs(source) do if ( type(v) == 'table' && type(dest[k]) == 'table' ) then -- don't overwrite one table with another; -- instead merge them recurisvely table.Merge(dest[k], v) else dest[k] = v end end return dest end --[[--------------------------------------------------------- Name: xx Desc: xx -----------------------------------------------------------]] function table.HasValue( t, val ) for k,v in pairs(t) do if (v == val ) then return true end end return false end table.InTable = HasValue --[[--------------------------------------------------------- Name: table.Add( dest, source ) Desc: Unlike merge this adds the two tables together and discards keys. -----------------------------------------------------------]] function table.Add( dest, source ) -- At least one of them needs to be a table or this whole thing will fall on its ass if (type(source)!='table') then return dest end if (type(dest)!='table') then dest = {} end for k,v in pairs(source) do table.insert( dest, v ) end return dest end --[[--------------------------------------------------------- Name: table.SortDesc( table ) Desc: Like Lua's default sort, but descending -----------------------------------------------------------]] function table.SortDesc( Table ) return table.sort( Table, function(a, b) return a > b end ) end --[[--------------------------------------------------------- Name: table.SortByKey( table ) Desc: Returns a table sorted numerically by Key value -----------------------------------------------------------]] function table.SortByKey( Table, Desc ) local temp = {} for key, _ in pairs(Table) do table.insert(temp, key) end if ( Desc ) then table.sort(temp, function(a, b) return Table[a] < Table[b] end) else table.sort(temp, function(a, b) return Table[a] > Table[b] end) end return temp end --[[--------------------------------------------------------- Name: table.Count( table ) Desc: Returns the number of keys in a table -----------------------------------------------------------]] function table.Count (t) local i = 0 for k in pairs(t) do i = i + 1 end return i end --[[--------------------------------------------------------- Name: table.Random( table ) Desc: Return a random key -----------------------------------------------------------]] function table.Random (t) local rk = math.random( 1, table.Count( t ) ) local i = 1 for k, v in pairs(t) do if ( i == rk ) then return v, k end i = i + 1 end end --[[---------------------------------------------------------------------- Name: table.IsSequential( table ) Desc: Returns true if the tables keys are sequential -------------------------------------------------------------------------]] function table.IsSequential(t) local i = 1 for key, value in pairs (t) do if not tonumber(i) or key ~= i then return false end i = i + 1 end return true end --[[--------------------------------------------------------- Name: table.ToString( table,name,nice ) Desc: Convert a simple table to a string table = the table you want to convert (table) name = the name of the table (string) nice = whether to add line breaks and indents (bool) -----------------------------------------------------------]] function table.ToString(t,n,nice) local nl,tab = "", "" if nice then nl,tab = "\n", "\t" end local function MakeTable ( t, nice, indent, done) local str = "" local done = done or {} local indent = indent or 0 local idt = "" if nice then idt = string.rep ("\t", indent) end local sequential = table.IsSequential(t) for key, value in pairs (t) do str = str .. idt .. tab .. tab if not sequential then if type(key) == "number" or type(key) == "boolean" then key ='['..tostring(key)..']' ..tab..'=' else key = tostring(key) ..tab..'=' end else key = "" end if istable(value) and not done [value] then done [value] = true str = str .. key .. tab .. '{' .. nl .. MakeTable (value, nice, indent + 1, done) str = str .. idt .. tab .. tab ..tab .. tab .."},".. nl else if type(value) == "string" then value = '"'..tostring(value)..'"' elseif type(value) == "Vector" then value = 'Vector('..value.x..','..value.y..','..value.z..')' elseif type(value) == "Angle" then value = 'Angle('..value.pitch..','..value.yaw..','..value.roll..')' else value = tostring(value) end str = str .. key .. tab .. value .. ",".. nl end end return str end local str = "" if n then str = n.. tab .."=" .. tab end str = str .."{" .. nl .. MakeTable ( t, nice) .. "}" return str end --[[--------------------------------------------------------- Name: table.Sanitise( table ) Desc: Converts a table containing vectors, angles, bools so it can be converted to and from keyvalues -----------------------------------------------------------]] function table.Sanitise( t, done ) local done = done or {} local tbl = {} for k, v in pairs ( t ) do if ( istable( v ) and !done[ v ] ) then done[ v ] = true tbl[ k ] = table.Sanitise ( v, done ) else if ( type(v) == "Vector" ) then local x, y, z = v.x, v.y, v.z if y == 0 then y = nil end if z == 0 then z = nil end tbl[k] = { __type = "Vector", x = x, y = y, z = z } elseif ( type(v) == "Angle" ) then local p,y,r = v.pitch, v.yaw, v.roll if p == 0 then p = nil end if y == 0 then y = nil end if r == 0 then r = nil end tbl[k] = { __type = "Angle", p = p, y = y, r = r } elseif ( type(v) == "boolean" ) then tbl[k] = { __type = "Bool", tostring( v ) } else tbl[k] = tostring(v) end end end return tbl end --[[--------------------------------------------------------- Name: table.DeSanitise( table ) Desc: Converts a Sanitised table back -----------------------------------------------------------]] function table.DeSanitise( t, done ) local done = done or {} local tbl = {} for k, v in pairs ( t ) do if ( istable( v ) and !done[ v ] ) then done[ v ] = true if ( v.__type ) then if ( v.__type == "Vector" ) then tbl[ k ] = Vector( v.x, v.y, v.z ) elseif ( v.__type == "Angle" ) then tbl[ k ] = Angle( v.p, v.y, v.r ) elseif ( v.__type == "Bool" ) then tbl[ k ] = ( v[1] == "true" ) end else tbl[ k ] = table.DeSanitise( v, done ) end else tbl[ k ] = v end end return tbl end function table.ForceInsert( t, v ) if ( t == nil ) then t = {} end table.insert( t, v ) return t end --[[--------------------------------------------------------- Name: table.SortByMember( table ) Desc: Sorts table by named member -----------------------------------------------------------]] function table.SortByMember( Table, MemberName, bAsc ) local TableMemberSort = function( a, b, MemberName, bReverse ) -- -- All this error checking kind of sucks, but really is needed -- if ( !istable(a) ) then return !bReverse end if ( !istable(b) ) then return bReverse end if ( !a[MemberName] ) then return !bReverse end if ( !b[MemberName] ) then return bReverse end if ( type( a[MemberName] ) == "string" ) then if ( bReverse ) then return a[MemberName]:lower() < b[MemberName]:lower() else return a[MemberName]:lower() > b[MemberName]:lower() end end if ( bReverse ) then return a[MemberName] < b[MemberName] else return a[MemberName] > b[MemberName] end end table.sort( Table, function(a, b) return TableMemberSort( a, b, MemberName, bAsc or false ) end ) end --[[--------------------------------------------------------- Name: table.LowerKeyNames( table ) Desc: Lowercase the keynames of all tables -----------------------------------------------------------]] function table.LowerKeyNames( Table ) local OutTable = {} for k, v in pairs( Table ) do -- Recurse if ( istable( v ) ) then v = table.LowerKeyNames( v ) end OutTable[ k ] = v if ( isstring( k ) ) then OutTable[ k ] = nil OutTable[ string.lower( k ) ] = v end end return OutTable end --[[--------------------------------------------------------- Name: table.LowerKeyNames( table ) Desc: Lowercase the keynames of all tables -----------------------------------------------------------]] function table.CollapseKeyValue( Table ) local OutTable = {} for k, v in pairs( Table ) do local Val = v.Value if ( istable( Val ) ) then Val = table.CollapseKeyValue( Val ) end OutTable[ v.Key ] = Val end return OutTable end --[[--------------------------------------------------------- Name: table.ClearKeys( table, bSaveKey ) Desc: Clears the keys, converting to a numbered format -----------------------------------------------------------]] function table.ClearKeys( Table, bSaveKey ) local OutTable = {} for k, v in pairs( Table ) do if ( bSaveKey ) then v.__key = k end table.insert( OutTable, v ) end return OutTable end local function fnPairsSorted( pTable, Index ) if ( Index == nil ) then Index = 1 else for k, v in pairs( pTable.__SortedIndex ) do if ( v == Index ) then Index = k + 1 break end end end local Key = pTable.__SortedIndex[ Index ] if ( !Key ) then pTable.__SortedIndex = nil return end Index = Index + 1 return Key, pTable[ Key ] end --[[--------------------------------------------------------- A Pairs function Sorted by TABLE KEY -----------------------------------------------------------]] function SortedPairs( pTable, Desc ) pTable = table.Copy( pTable ) local SortedIndex = {} for k, v in pairs( pTable ) do table.insert( SortedIndex, k ) end if ( Desc ) then table.sort( SortedIndex, function(a,b) return a>b end ) else table.sort( SortedIndex ) end pTable.__SortedIndex = SortedIndex return fnPairsSorted, pTable, nil end --[[--------------------------------------------------------- A Pairs function Sorted by VALUE -----------------------------------------------------------]] function SortedPairsByValue( pTable, Desc ) pTable = table.ClearKeys( pTable ) if ( Desc ) then table.sort( pTable, function(a,b) return a>b end ) else table.sort( pTable ) end return ipairs( pTable ) end --[[--------------------------------------------------------- A Pairs function Sorted by Member Value (All table entries must be a table!) -----------------------------------------------------------]] function SortedPairsByMemberValue( pTable, pValueName, Desc ) Desc = Desc or false local pSortedTable = table.ClearKeys( pTable, true ) table.SortByMember( pSortedTable, pValueName, !Desc ) local SortedIndex = {} for k, v in ipairs( pSortedTable ) do table.insert( SortedIndex, v.__key ) end pTable.__SortedIndex = SortedIndex return fnPairsSorted, pTable, nil end --[[--------------------------------------------------------- A Pairs function -----------------------------------------------------------]] function RandomPairs( pTable, Desc ) local Count = table.Count( pTable ) pTable = table.Copy( pTable ) local SortedIndex = {} for k, v in pairs( pTable ) do table.insert( SortedIndex, { key = k, val = math.random( 1, 1000 ) } ) end if ( Desc ) then table.sort( SortedIndex, function(a,b) return a.val>b.val end ) else table.sort( SortedIndex, function(a,b) return a.val<b.val end ) end for k, v in pairs( SortedIndex ) do SortedIndex[ k ] = v.key; end pTable.__SortedIndex = SortedIndex return fnPairsSorted, pTable, nil end --[[--------------------------------------------------------- GetFirstKey -----------------------------------------------------------]] function table.GetFirstKey( t ) local k, v = next( t ) return k end function table.GetFirstValue( t ) local k, v = next( t ) return v end function table.GetLastKey( t ) local k, v = next( t, table.Count(t) ) return k end function table.GetLastValue( t ) local k, v = next( t, table.Count(t) ) return v end function table.FindNext( tab, val ) local bfound = false for k, v in pairs( tab ) do if ( bfound ) then return v end if ( val == v ) then bfound = true end end return table.GetFirstValue( tab ) end function table.FindPrev( tab, val ) local last = table.GetLastValue( tab ) for k, v in pairs( tab ) do if ( val == v ) then return last end last = v end return last end function table.GetWinningKey( tab ) local highest = -10000 local winner = nil for k, v in pairs( tab ) do if ( v > highest ) then winner = k highest = v end end return winner end function table.KeyFromValue( tbl, val ) for key, value in pairs( tbl ) do if ( value == val ) then return key end end end function table.RemoveByValue( tbl, val ) local key = table.KeyFromValue( tbl, val ) if ( !key ) then return false end table.remove( tbl, key ) return key; end function table.KeysFromValue( tbl, val ) local res = {} for key, value in pairs( tbl ) do if ( value == val ) then table.insert( res, key ) end end return res end function table.Reverse( tbl ) local len = #tbl; local ret = {}; for i = len, 1, -1 do ret[len-i+1] = tbl[i]; end return ret; end function table.ForEach( tab, funcname ) for k, v in pairs( tab ) do funcname( k, v ) end end
mit
yetsky/luci
modules/base/luasrc/model/uci.lua
86
10653
--[[ LuCI - UCI model Description: Generalized UCI model FileId: $Id$ License: 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local os = require "os" local uci = require "uci" local util = require "luci.util" local table = require "table" local setmetatable, rawget, rawset = setmetatable, rawget, rawset local require, getmetatable = require, getmetatable local error, pairs, ipairs = error, pairs, ipairs local type, tostring, tonumber, unpack = type, tostring, tonumber, unpack --- LuCI UCI model library. -- The typical workflow for UCI is: Get a cursor instance from the -- cursor factory, modify data (via Cursor.add, Cursor.delete, etc.), -- save the changes to the staging area via Cursor.save and finally -- Cursor.commit the data to the actual config files. -- LuCI then needs to Cursor.apply the changes so deamons etc. are -- reloaded. -- @cstyle instance module "luci.model.uci" --- Create a new UCI-Cursor. -- @class function -- @name cursor -- @return UCI-Cursor cursor = uci.cursor APIVERSION = uci.APIVERSION --- Create a new Cursor initialized to the state directory. -- @return UCI cursor function cursor_state() return cursor(nil, "/var/state") end inst = cursor() inst_state = cursor_state() local Cursor = getmetatable(inst) --- Applies UCI configuration changes -- @param configlist List of UCI configurations -- @param command Don't apply only return the command function Cursor.apply(self, configlist, command) configlist = self:_affected(configlist) if command then return { "/sbin/luci-reload", unpack(configlist) } else return os.execute("/sbin/luci-reload %s >/dev/null 2>&1" % table.concat(configlist, " ")) end end --- Delete all sections of a given type that match certain criteria. -- @param config UCI config -- @param type UCI section type -- @param comparator Function that will be called for each section and -- returns a boolean whether to delete the current section (optional) function Cursor.delete_all(self, config, stype, comparator) local del = {} if type(comparator) == "table" then local tbl = comparator comparator = function(section) for k, v in pairs(tbl) do if section[k] ~= v then return false end end return true end end local function helper (section) if not comparator or comparator(section) then del[#del+1] = section[".name"] end end self:foreach(config, stype, helper) for i, j in ipairs(del) do self:delete(config, j) end end --- Create a new section and initialize it with data. -- @param config UCI config -- @param type UCI section type -- @param name UCI section name (optional) -- @param values Table of key - value pairs to initialize the section with -- @return Name of created section function Cursor.section(self, config, type, name, values) local stat = true if name then stat = self:set(config, name, type) else name = self:add(config, type) stat = name and true end if stat and values then stat = self:tset(config, name, values) end return stat and name end --- Updated the data of a section using data from a table. -- @param config UCI config -- @param section UCI section name (optional) -- @param values Table of key - value pairs to update the section with function Cursor.tset(self, config, section, values) local stat = true for k, v in pairs(values) do if k:sub(1, 1) ~= "." then stat = stat and self:set(config, section, k, v) end end return stat end --- Get a boolean option and return it's value as true or false. -- @param config UCI config -- @param section UCI section name -- @param option UCI option -- @return Boolean function Cursor.get_bool(self, ...) local val = self:get(...) return ( val == "1" or val == "true" or val == "yes" or val == "on" ) end --- Get an option or list and return values as table. -- @param config UCI config -- @param section UCI section name -- @param option UCI option -- @return UCI value function Cursor.get_list(self, config, section, option) if config and section and option then local val = self:get(config, section, option) return ( type(val) == "table" and val or { val } ) end return nil end --- Get the given option from the first section with the given type. -- @param config UCI config -- @param type UCI section type -- @param option UCI option (optional) -- @param default Default value (optional) -- @return UCI value function Cursor.get_first(self, conf, stype, opt, def) local rv = def self:foreach(conf, stype, function(s) local val = not opt and s['.name'] or s[opt] if type(def) == "number" then val = tonumber(val) elseif type(def) == "boolean" then val = (val == "1" or val == "true" or val == "yes" or val == "on") end if val ~= nil then rv = val return false end end) return rv end --- Set given values as list. -- @param config UCI config -- @param section UCI section name -- @param option UCI option -- @param value UCI value -- @return Boolean whether operation succeeded function Cursor.set_list(self, config, section, option, value) if config and section and option then return self:set( config, section, option, ( type(value) == "table" and value or { value } ) ) end return false end -- Return a list of initscripts affected by configuration changes. function Cursor._affected(self, configlist) configlist = type(configlist) == "table" and configlist or {configlist} local c = cursor() c:load("ucitrack") -- Resolve dependencies local reloadlist = {} local function _resolve_deps(name) local reload = {name} local deps = {} c:foreach("ucitrack", name, function(section) if section.affects then for i, aff in ipairs(section.affects) do deps[#deps+1] = aff end end end) for i, dep in ipairs(deps) do for j, add in ipairs(_resolve_deps(dep)) do reload[#reload+1] = add end end return reload end -- Collect initscripts for j, config in ipairs(configlist) do for i, e in ipairs(_resolve_deps(config)) do if not util.contains(reloadlist, e) then reloadlist[#reloadlist+1] = e end end end return reloadlist end --- Create a sub-state of this cursor. The sub-state is tied to the parent -- curser, means it the parent unloads or loads configs, the sub state will -- do so as well. -- @return UCI state cursor tied to the parent cursor function Cursor.substate(self) Cursor._substates = Cursor._substates or { } Cursor._substates[self] = Cursor._substates[self] or cursor_state() return Cursor._substates[self] end local _load = Cursor.load function Cursor.load(self, ...) if Cursor._substates and Cursor._substates[self] then _load(Cursor._substates[self], ...) end return _load(self, ...) end local _unload = Cursor.unload function Cursor.unload(self, ...) if Cursor._substates and Cursor._substates[self] then _unload(Cursor._substates[self], ...) end return _unload(self, ...) end --- Add an anonymous section. -- @class function -- @name Cursor.add -- @param config UCI config -- @param type UCI section type -- @return Name of created section --- Get a table of saved but uncommitted changes. -- @class function -- @name Cursor.changes -- @param config UCI config -- @return Table of changes -- @see Cursor.save --- Commit saved changes. -- @class function -- @name Cursor.commit -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.revert -- @see Cursor.save --- Deletes a section or an option. -- @class function -- @name Cursor.delete -- @param config UCI config -- @param section UCI section name -- @param option UCI option (optional) -- @return Boolean whether operation succeeded --- Call a function for every section of a certain type. -- @class function -- @name Cursor.foreach -- @param config UCI config -- @param type UCI section type -- @param callback Function to be called -- @return Boolean whether operation succeeded --- Get a section type or an option -- @class function -- @name Cursor.get -- @param config UCI config -- @param section UCI section name -- @param option UCI option (optional) -- @return UCI value --- Get all sections of a config or all values of a section. -- @class function -- @name Cursor.get_all -- @param config UCI config -- @param section UCI section name (optional) -- @return Table of UCI sections or table of UCI values --- Manually load a config. -- @class function -- @name Cursor.load -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.save -- @see Cursor.unload --- Revert saved but uncommitted changes. -- @class function -- @name Cursor.revert -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.commit -- @see Cursor.save --- Saves changes made to a config to make them committable. -- @class function -- @name Cursor.save -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.load -- @see Cursor.unload --- Set a value or create a named section. -- @class function -- @name Cursor.set -- @param config UCI config -- @param section UCI section name -- @param option UCI option or UCI section type -- @param value UCI value or nil if you want to create a section -- @return Boolean whether operation succeeded --- Get the configuration directory. -- @class function -- @name Cursor.get_confdir -- @return Configuration directory --- Get the directory for uncomitted changes. -- @class function -- @name Cursor.get_savedir -- @return Save directory --- Set the configuration directory. -- @class function -- @name Cursor.set_confdir -- @param directory UCI configuration directory -- @return Boolean whether operation succeeded --- Set the directory for uncommited changes. -- @class function -- @name Cursor.set_savedir -- @param directory UCI changes directory -- @return Boolean whether operation succeeded --- Discard changes made to a config. -- @class function -- @name Cursor.unload -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.load -- @see Cursor.save
apache-2.0
dangersuperbot/super_boomrange
plugins/inrealm.lua
3
36470
data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then if msg.to.type == 'chat' and not is_realm(msg) then data[tostring(msg.to.id)]['group_type'] = 'Group' save_data(_config.moderation.data, data) elseif msg.to.type == 'channel' then data[tostring(msg.to.id)]['group_type'] = 'SuperGroup' save_data(_config.moderation.data, data) end end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid local channel = 'channel#id'..extra.chatid send_large_msg(chat, user..'\n'..name) send_large_msg(channel, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin1(msg) then return "For admins 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 set_rules(msg, data, target) if not is_admin1(msg) then return "For admins 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 -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin1(msg) then return "For admins 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_name(msg, data, target) if not is_admin1(msg) then return "For admins 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 --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin1(msg) then return "For admins 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_member(msg, data, target) if not is_admin1(msg) then return "For admins 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 --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins 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 lock_group_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" 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_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" 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_arabic(msg, data, target) if not is_admin1(msg) then return "For admins 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_admin1(msg) then return "For admins only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "Group settings for "..target..":\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nPublic: "..settings.public end -- show SuperGroup settings local function show_super_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(msg.to.id)]['settings'] then if not data[tostring(msg.to.id)]['settings']['public'] then data[tostring(msg.to.id)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict return text end local function returnids(cb_extra, success, result) local i = 1 local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' (ID: '..result.peer_id..'):\n\n' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text ..i..' - '.. string.gsub(v.print_name,"_"," ") .. " [" .. v.peer_id .. "] \n\n" i = i + 1 end end local file = io.open("./groups/lists/"..result.peer_id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function cb_user_info(cb_extra, success, result) local receiver = cb_extra.receiver if result.first_name then first_name = result.first_name:gsub("_", " ") else first_name = "None" end if result.last_name then last_name = result.last_name:gsub("_", " ") else last_name = "None" end if result.username then username = "@"..result.username else username = "@[none]" end text = "User Info:\n\nID: "..result.peer_id.."\nFirst: "..first_name.."\nLast: "..last_name.."\nUsername: "..username send_large_msg(receiver, text) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_id..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List of global admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do if data[tostring(v)] then if data[tostring(v)]['settings'] then local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end end end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is already an admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then send_large_msg(receiver, "@"..member_username..' is not an admin.') return end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Admin @'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.peer_id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function res_user_support(cb_extra, success, result) local receiver = cb_extra.receiver local get_cmd = cb_extra.get_cmd local support_id = result.peer_id if get_cmd == 'addsupport' then support_add(support_id) send_large_msg(receiver, "User ["..support_id.."] has been added to the support team") elseif get_cmd == 'removesupport' then support_remove(support_id) send_large_msg(receiver, "User ["..support_id.."] has been removed from the support team") end end local function set_log_group(target, data) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(target)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'no' then return 'Log group is not set' else data[tostring(target)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then local receiver = get_receiver(msg) savelog(msg.to.id, "log file created by owner/support/admin") send_document(receiver,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and msg.to.type == 'chat' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) local file = io.open("./groups/lists/"..msg.to.id.."memberlist.txt", "r") text = file:read("*a") send_large_msg(receiver,text) file:close() end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) send_document("chat#id"..msg.to.id,"./groups/lists/"..msg.to.id.."memberlist.txt", ok_cb, false) end if matches[1] == 'whois' and is_momod(msg) then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] user_info(user_id, cb_user_info, {receiver = receiver}) end if not is_sudo(msg) then if is_realm(msg) and is_admin1(msg) then print("Admin detected") else return end end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end --[[ Experimental if matches[1] == 'createsuper' and matches[2] then if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then return "You cant create groups!" end group_name = matches[2] group_type = 'super_group' return create_group(msg) end]] if matches[1] == 'createrealm' and matches[2] then if not is_sudo(msg) then return "Sudo users only !" end group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[1] == 'setabout' and matches[2] == 'group' and is_realm(msg) then local target = matches[3] local about = matches[4] return set_description(msg, data, target, about) end if matches[1] == 'setabout' and matches[2] == 'sgroup'and is_realm(msg) then local channel = 'channel#id'..matches[3] local about_text = matches[4] local data_cat = 'description' local target = matches[3] channel_set_about(channel, about_text, ok_cb, false) data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) return "Description has been set for ["..matches[2]..']' end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then return lock_group_arabic(msg, data, target) end if matches[3] == 'links' then return lock_group_links(msg, data, target) end if matches[3] == 'spam' then return lock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return lock_group_sticker(msg, data, target) end end if matches[1] == 'unlock' then local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end if matches[3] == 'arabic' then return unlock_group_arabic(msg, data, target) end if matches[3] == 'links' then return unlock_group_links(msg, data, target) end if matches[3] == 'spam' then return unlock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return unlock_group_sticker(msg, data, target) end end if matches[1] == 'settings' and matches[2] == 'group' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_group_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'settings' and matches[2] == 'sgroup' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_supergroup_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'setname' and is_realm(msg) then local settings = data[tostring(matches[2])]['settings'] 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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin1(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local chat_to_rename = 'chat#id'..matches[2] local channel_to_rename = 'channel#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) rename_channel(channel_to_rename, group_name_set, ok_cb, false) savelog(matches[3], "Group { "..group_name_set.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end --[[if matches[1] == 'set' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.peer_id savelog(msg.to.peer_id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(target, data) end end if matches[1] == 'rem' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return unset_log_group(target, data) end end]] if matches[1] == 'kill' and matches[2] == 'chat' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'rem' and matches[2] then -- Group configuration removal data[tostring(matches[2])] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(matches[2])] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Chat '..matches[2]..' removed') end if matches[1] == 'chat_add_user' then if not msg.service then return end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin1(msg) and is_realm(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'support' and matches[2] then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been added to the support team") support_add(support_id) return "User ["..support_id.."] has been added to the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "addsupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == '-support' then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been removed from the support team") support_remove(support_id) return "User ["..support_id.."] has been removed from the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "removesupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' then if matches[2] == 'admins' then return admin_list(msg) end -- if matches[2] == 'support' and not matches[2] then -- return support_list() -- end end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' or msg.to.type == 'channel' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' or msg.to.type == 'channel' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end 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 resolve_username(username, callbackres, cbres_extra) end end return { patterns = { "^[#!/](creategroup) (.*)$", "^[#!/](createsuper) (.*)$", "^[#!/](createrealm) (.*)$", "^[#!/](setabout) (%d+) (.*)$", "^[#!/](setrules) (%d+) (.*)$", "^[#!/](setname) (.*)$", "^[#!/](setgpname) (%d+) (.*)$", "^[#!/](setname) (%d+) (.*)$", "^[#!/](lock) (%d+) (.*)$", "^[#!/](unlock) (%d+) (.*)$", "^[#!/](mute) (%d+)$", "^[#!/](unmute) (%d+)$", "^[#!/](settings) (.*) (%d+)$", "^[#!/](wholist)$", "^[#!/](who)$", "^[#!/]([Ww]hois) (.*)", "^[#!/](type)$", "^[#!/](kill) (chat) (%d+)$", "^[#!/](kill) (realm) (%d+)$", "^[#!/](rem) (%d+)$", "^[#!/](addadmin) (.*)$", -- sudoers only "^[#!/](removeadmin) (.*)$", -- sudoers only "[#!/ ](support)$", "^[#!/](support) (.*)$", "^[#!/](-support) (.*)$", "^[#!/](list) (.*)$", "^[#!/](log)$", "^[#!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
vitaliylag/waifu2x
tools/cudnn2cunn.lua
4
1404
require 'pl' local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)() package.path = path.join(path.dirname(__FILE__), "..", "lib", "?.lua;") .. package.path require 'os' require 'w2nn' local srcnn = require 'srcnn' local function cudnn2cunn(cudnn_model) local cunn_model = srcnn.waifu2x_cunn(srcnn.channels(cudnn_model)) local weight_from = cudnn_model:findModules("cudnn.SpatialConvolution") local weight_to = cunn_model:findModules("nn.SpatialConvolutionMM") assert(#weight_from == #weight_to) for i = 1, #weight_from do local from = weight_from[i] local to = weight_to[i] to.weight:copy(from.weight) to.bias:copy(from.bias) end cunn_model:cuda() cunn_model:evaluate() return cunn_model end local cmd = torch.CmdLine() cmd:text() cmd:text("waifu2x cudnn model to cunn model converter") cmd:text("Options:") cmd:option("-i", "", 'Specify the input cunn model') cmd:option("-o", "", 'Specify the output cudnn model') cmd:option("-iformat", "ascii", 'Specify the input format (ascii|binary)') cmd:option("-oformat", "ascii", 'Specify the output format (ascii|binary)') local opt = cmd:parse(arg) if not path.isfile(opt.i) then cmd:help() os.exit(-1) end local cudnn_model = torch.load(opt.i, opt.iformat) local cunn_model = cudnn2cunn(cudnn_model) torch.save(opt.o, cunn_model, opt.oformat)
mit
yetsky/luci
protocols/ipv6/luasrc/model/network/proto_4x6.lua
63
1522
--[[ LuCI - Network model - 6to4, 6in4 & 6rd protocol extensions 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local _, p for _, p in ipairs({"dslite"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "dslite" then return luci.i18n.translate("Dual-Stack Lite (RFC6333)") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) if p == "dslite" then return "ds-lite" end end function proto.is_installed(self) return nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh") end function proto.is_floating(self) return true end function proto.is_virtual(self) return true end function proto.get_interfaces(self) return nil end function proto.contains_interface(self, ifname) return (netmod:ifnameof(ifc) == self:ifname()) end netmod:register_pattern_virtual("^%s-%%w" % p) end
apache-2.0
LuaDist2/luarocks
src/luarocks/cfg.lua
2
23504
--- Configuration for LuaRocks. -- Tries to load the user's configuration file and -- defines defaults for unset values. See the -- <a href="http://luarocks.org/en/Config_file_format">config -- file format documentation</a> for details. -- -- End-users shouldn't edit this file. They can override any defaults -- set in this file using their system-wide or user-specific configuration -- files. Run `luarocks` with no arguments to see the locations of -- these files in your platform. local rawset, next, table, pairs, require, io, os, setmetatable, pcall, ipairs, package, tonumber, type, assert, _VERSION = rawset, next, table, pairs, require, io, os, setmetatable, pcall, ipairs, package, tonumber, type, assert, _VERSION --module("luarocks.cfg") local cfg = {} package.loaded["luarocks.cfg"] = cfg local util = require("luarocks.util") cfg.lua_version = _VERSION:sub(5) local version_suffix = cfg.lua_version:gsub("%.", "_") -- Load site-local global configurations local ok, site_config = pcall(require, "luarocks.site_config_"..version_suffix) if not ok then ok, site_config = pcall(require, "luarocks.site_config") end if not ok then io.stderr:write("Site-local luarocks/site_config.lua file not found. Incomplete installation?\n") site_config = {} end cfg.program_version = "2.4.1" cfg.program_series = "2.4" cfg.major_version = (cfg.program_version:match("([^.]%.[^.])")) or cfg.program_series cfg.variables = {} cfg.rocks_trees = {} cfg.platforms = {} local persist = require("luarocks.persist") cfg.errorcodes = setmetatable({ OK = 0, UNSPECIFIED = 1, PERMISSIONDENIED = 2, CONFIGFILE = 3, CRASH = 99 },{ __index = function(t, key) local val = rawget(t, key) if not val then error("'"..tostring(key).."' is not a valid errorcode", 2) end return val end }) local popen_ok, popen_result = pcall(io.popen, "") if popen_ok then if popen_result then popen_result:close() end else io.stderr:write("Your version of Lua does not support io.popen,\n") io.stderr:write("which is required by LuaRocks. Please check your Lua installation.\n") os.exit(cfg.errorcodes.UNSPECIFIED) end -- System detection: -- A proper installation of LuaRocks will hardcode the system -- and proc values with site_config.LUAROCKS_UNAME_S and site_config.LUAROCKS_UNAME_M, -- so that this detection does not run every time. When it is -- performed, we use the Unix way to identify the system, -- even on Windows (assuming UnxUtils or Cygwin). local system = site_config.LUAROCKS_UNAME_S or io.popen("uname -s"):read("*l") local proc = site_config.LUAROCKS_UNAME_M or io.popen("uname -m"):read("*l") if proc:match("i[%d]86") then cfg.target_cpu = "x86" elseif proc:match("amd64") or proc:match("x86_64") then cfg.target_cpu = "x86_64" elseif proc:match("Power Macintosh") then cfg.target_cpu = "powerpc" else cfg.target_cpu = proc end if system == "FreeBSD" then cfg.platforms.unix = true cfg.platforms.freebsd = true cfg.platforms.bsd = true elseif system == "OpenBSD" then cfg.platforms.unix = true cfg.platforms.openbsd = true cfg.platforms.bsd = true elseif system == "NetBSD" then cfg.platforms.unix = true cfg.platforms.netbsd = true cfg.platforms.bsd = true elseif system == "Darwin" then cfg.platforms.unix = true cfg.platforms.macosx = true cfg.platforms.bsd = true elseif system == "Linux" then cfg.platforms.unix = true cfg.platforms.linux = true elseif system == "SunOS" then cfg.platforms.unix = true cfg.platforms.solaris = true elseif system and system:match("^CYGWIN") then cfg.platforms.unix = true cfg.platforms.cygwin = true elseif system and system:match("^MSYS") then cfg.platforms.unix = true cfg.platforms.msys = true cfg.platforms.cygwin = true elseif system and system:match("^Windows") then cfg.platforms.windows = true cfg.platforms.win32 = true elseif system and system:match("^MINGW") then cfg.platforms.windows = true cfg.platforms.mingw32 = true cfg.platforms.win32 = true elseif system == "Haiku" then cfg.platforms.unix = true cfg.platforms.haiku = true else cfg.platforms.unix = true -- Fall back to Unix in unknown systems. end -- Set order for platform overrides local platform_order = { -- Unixes unix = 1, bsd = 2, solaris = 3, netbsd = 4, openbsd = 5, freebsd = 6, linux = 7, macosx = 8, cygwin = 9, msys = 10, haiku = 11, -- Windows win32 = 12, mingw32 = 13, windows = 14 } -- Path configuration: local sys_config_file, home_config_file local sys_config_file_default, home_config_file_default local sys_config_dir, home_config_dir local sys_config_ok, home_config_ok = false, false local extra_luarocks_module_dir sys_config_dir = site_config.LUAROCKS_SYSCONFDIR or site_config.LUAROCKS_PREFIX if cfg.platforms.windows then cfg.home = os.getenv("APPDATA") or "c:" sys_config_dir = sys_config_dir or "c:/luarocks" home_config_dir = cfg.home.."/luarocks" cfg.home_tree = cfg.home.."/luarocks/" else cfg.home = os.getenv("HOME") or "" sys_config_dir = sys_config_dir or "/etc/luarocks" home_config_dir = cfg.home.."/.luarocks" cfg.home_tree = (os.getenv("USER") ~= "root") and cfg.home.."/.luarocks/" end -- Create global environment for the config files; local env_for_config_file = function() local e e = { home = cfg.home, lua_version = cfg.lua_version, platforms = util.make_shallow_copy(cfg.platforms), processor = cfg.target_cpu, -- remains for compat reasons target_cpu = cfg.target_cpu, -- replaces `processor` os_getenv = os.getenv, dump_env = function() -- debug function, calling it from a config file will show all -- available globals to that config file print(util.show_table(e, "global environment")) end, } return e end -- Merge values from config files read into the `cfg` table local merge_overrides = function(overrides) -- remove some stuff we do not want to integrate overrides.os_getenv = nil overrides.dump_env = nil -- remove tables to be copied verbatim instead of deeply merged if overrides.rocks_trees then cfg.rocks_trees = nil end if overrides.rocks_servers then cfg.rocks_servers = nil end -- perform actual merge util.deep_merge(cfg, overrides) end -- load config file from a list until first succesful one. Info is -- added to `cfg` module table, returns filepath of succesfully loaded -- file or nil if it failed local load_config_file = function(list) for _, filepath in ipairs(list) do local result, err, errcode = persist.load_into_table(filepath, env_for_config_file()) if (not result) and errcode ~= "open" then -- errcode is either "load" or "run"; bad config file, so error out io.stderr:write(err.."\n") os.exit(cfg.errorcodes.CONFIGFILE) end if result then -- succes in loading and running, merge contents and exit merge_overrides(result) return filepath end end return nil -- nothing was loaded end -- Load system configuration file do sys_config_file_default = sys_config_dir.."/config-"..cfg.lua_version..".lua" sys_config_file = load_config_file({ site_config.LUAROCKS_SYSCONFIG or sys_config_file_default, sys_config_dir.."/config.lua", }) sys_config_ok = (sys_config_file ~= nil) end -- Load user configuration file (if allowed) if not site_config.LUAROCKS_FORCE_CONFIG then home_config_file_default = home_config_dir.."/config-"..cfg.lua_version..".lua" local config_env_var = "LUAROCKS_CONFIG_" .. version_suffix local config_env_value = os.getenv(config_env_var) if not config_env_value then config_env_var = "LUAROCKS_CONFIG" config_env_value = os.getenv(config_env_var) end -- first try environment provided file, so we can explicitly warn when it is missing if config_env_value then local list = { config_env_value } home_config_file = load_config_file(list) home_config_ok = (home_config_file ~= nil) if not home_config_ok then io.stderr:write("Warning: could not load configuration file `"..config_env_value.."` given in environment variable "..config_env_var.."\n") end end -- try the alternative defaults if there was no environment specified file or it didn't work if not home_config_ok then local list = { home_config_file_default, home_config_dir.."/config.lua", } home_config_file = load_config_file(list) home_config_ok = (home_config_file ~= nil) end end if not next(cfg.rocks_trees) then if cfg.home_tree then table.insert(cfg.rocks_trees, { name = "user", root = cfg.home_tree } ) end if site_config.LUAROCKS_ROCKS_TREE then table.insert(cfg.rocks_trees, { name = "system", root = site_config.LUAROCKS_ROCKS_TREE } ) end end -- update platforms list; keyed -> array do local lst = {} -- use temp array to not confuse `pairs` in loop for plat in pairs(cfg.platforms) do if cfg.platforms[plat] then -- entries set to 'false' skipped if not platform_order[plat] then local pl = "" for k,_ in pairs(platform_order) do pl = pl .. ", " .. k end io.stderr:write("Bad platform given; "..tostring(plat)..". Valid entries are: "..pl:sub(3,-1) ..".\n") os.exit(cfg.errorcodes.CONFIGFILE) end table.insert(lst, plat) else cfg.platforms[plat] = nil end end -- platform overrides depent on the order, so set priorities table.sort(lst, function(key1, key2) return platform_order[key1] < platform_order[key2] end) util.deep_merge(cfg.platforms, lst) end -- Configure defaults: local defaults = { local_by_default = false, accept_unknown_fields = false, fs_use_modules = true, hooks_enabled = true, deps_mode = "one", check_certificates = false, perm_read = "0644", perm_exec = "0755", lua_modules_path = "/share/lua/"..cfg.lua_version, lib_modules_path = "/lib/lua/"..cfg.lua_version, rocks_subdir = site_config.LUAROCKS_ROCKS_SUBDIR or "/lib/luarocks/rocks", arch = "unknown", lib_extension = "unknown", obj_extension = "unknown", rocks_servers = { { "https://luarocks.org", "https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/", "http://luafr.org/moonrocks/", "http://luarocks.logiceditor.com/rocks", } }, disabled_servers = {}, upload = { server = "https://luarocks.org", tool_version = "1.0.0", api_version = "1", }, lua_extension = "lua", lua_interpreter = site_config.LUA_INTERPRETER or "lua", downloader = site_config.LUAROCKS_DOWNLOADER or "wget", md5checker = site_config.LUAROCKS_MD5CHECKER or "md5sum", connection_timeout = 30, -- 0 = no timeout variables = { MAKE = "make", CC = "cc", LD = "ld", CVS = "cvs", GIT = "git", SSCM = "sscm", SVN = "svn", HG = "hg", RSYNC = "rsync", WGET = "wget", SCP = "scp", CURL = "curl", PWD = "pwd", MKDIR = "mkdir", RMDIR = "rmdir", CP = "cp", LS = "ls", RM = "rm", FIND = "find", TEST = "test", CHMOD = "chmod", MKTEMP = "mktemp", ZIP = "zip", UNZIP = "unzip -n", GUNZIP = "gunzip", BUNZIP2 = "bunzip2", TAR = "tar", MD5SUM = "md5sum", OPENSSL = "openssl", MD5 = "md5", STAT = "stat", TOUCH = "touch", CMAKE = "cmake", SEVENZ = "7z", RSYNCFLAGS = "--exclude=.git -Oavz", STATFLAG = "-c '%a'", CURLNOCERTFLAG = "", WGETNOCERTFLAG = "", }, external_deps_subdirs = site_config.LUAROCKS_EXTERNAL_DEPS_SUBDIRS or { bin = "bin", lib = "lib", include = "include" }, runtime_external_deps_subdirs = site_config.LUAROCKS_RUNTIME_EXTERNAL_DEPS_SUBDIRS or { bin = "bin", lib = "lib", include = "include" }, rocks_provided = {} } if cfg.platforms.windows then local full_prefix = (site_config.LUAROCKS_PREFIX or (os.getenv("PROGRAMFILES")..[[\LuaRocks]])) extra_luarocks_module_dir = full_prefix.."/lua/?.lua" home_config_file = home_config_file and home_config_file:gsub("\\","/") defaults.fs_use_modules = false defaults.arch = "win32-"..cfg.target_cpu defaults.lib_extension = "dll" defaults.external_lib_extension = "dll" defaults.obj_extension = "obj" defaults.external_deps_dirs = { "c:/external/" } defaults.variables.LUA_BINDIR = site_config.LUA_BINDIR and site_config.LUA_BINDIR:gsub("\\", "/") or "c:/lua"..cfg.lua_version.."/bin" defaults.variables.LUA_INCDIR = site_config.LUA_INCDIR and site_config.LUA_INCDIR:gsub("\\", "/") or "c:/lua"..cfg.lua_version.."/include" defaults.variables.LUA_LIBDIR = site_config.LUA_LIBDIR and site_config.LUA_LIBDIR:gsub("\\", "/") or "c:/lua"..cfg.lua_version.."/lib" defaults.makefile = "Makefile.win" defaults.variables.MAKE = "nmake" defaults.variables.CC = "cl" defaults.variables.RC = "rc" defaults.variables.WRAPPER = full_prefix.."\\rclauncher.c" defaults.variables.LD = "link" defaults.variables.MT = "mt" defaults.variables.LUALIB = "lua"..cfg.lua_version..".lib" defaults.variables.CFLAGS = "/nologo /MD /O2" defaults.variables.LIBFLAG = "/nologo /dll" local bins = { "SEVENZ", "CP", "FIND", "LS", "MD5SUM", "MKDIR", "MV", "PWD", "RMDIR", "TEST", "UNAME", "WGET" } for _, var in ipairs(bins) do if defaults.variables[var] then defaults.variables[var] = full_prefix.."\\tools\\"..defaults.variables[var] end end defaults.external_deps_patterns = { bin = { "?.exe", "?.bat" }, lib = { "?.lib", "?.dll", "lib?.dll" }, include = { "?.h" } } defaults.runtime_external_deps_patterns = { bin = { "?.exe", "?.bat" }, lib = { "?.dll", "lib?.dll" }, include = { "?.h" } } defaults.export_path = "SET PATH=%s" defaults.export_path_separator = ";" defaults.export_lua_path = "SET LUA_PATH=%s" defaults.export_lua_cpath = "SET LUA_CPATH=%s" defaults.wrapper_suffix = ".bat" local localappdata = os.getenv("LOCALAPPDATA") if not localappdata then -- for Windows versions below Vista localappdata = os.getenv("USERPROFILE").."/Local Settings/Application Data" end defaults.local_cache = localappdata.."/LuaRocks/Cache" defaults.web_browser = "start" end if cfg.platforms.mingw32 then defaults.obj_extension = "o" defaults.cmake_generator = "MinGW Makefiles" defaults.variables.MAKE = "mingw32-make" defaults.variables.CC = "mingw32-gcc" defaults.variables.RC = "windres" defaults.variables.LD = "mingw32-gcc" defaults.variables.CFLAGS = "-O2" defaults.variables.LIBFLAG = "-shared" defaults.makefile = "Makefile" defaults.external_deps_patterns = { bin = { "?.exe", "?.bat" }, -- mingw lookup list from http://stackoverflow.com/a/15853231/1793220 -- ...should we keep ?.lib at the end? It's not in the above list. lib = { "lib?.dll.a", "?.dll.a", "lib?.a", "cyg?.dll", "lib?.dll", "?.dll", "?.lib" }, include = { "?.h" } } defaults.runtime_external_deps_patterns = { bin = { "?.exe", "?.bat" }, lib = { "cyg?.dll", "?.dll", "lib?.dll" }, include = { "?.h" } } end if cfg.platforms.unix then defaults.lib_extension = "so" defaults.external_lib_extension = "so" defaults.obj_extension = "o" defaults.external_deps_dirs = { "/usr/local", "/usr" } defaults.variables.LUA_BINDIR = site_config.LUA_BINDIR or "/usr/local/bin" defaults.variables.LUA_INCDIR = site_config.LUA_INCDIR or "/usr/local/include" defaults.variables.LUA_LIBDIR = site_config.LUA_LIBDIR or "/usr/local/lib" defaults.variables.CFLAGS = "-O2" defaults.cmake_generator = "Unix Makefiles" defaults.variables.CC = "gcc" defaults.variables.LD = "gcc" defaults.gcc_rpath = true defaults.variables.LIBFLAG = "-shared" defaults.external_deps_patterns = { bin = { "?" }, lib = { "lib?.a", "lib?.so", "lib?.so.*" }, include = { "?.h" } } defaults.runtime_external_deps_patterns = { bin = { "?" }, lib = { "lib?.so", "lib?.so.*" }, include = { "?.h" } } defaults.export_path = "export PATH='%s'" defaults.export_path_separator = ":" defaults.export_lua_path = "export LUA_PATH='%s'" defaults.export_lua_cpath = "export LUA_CPATH='%s'" defaults.wrapper_suffix = "" defaults.local_cache = cfg.home.."/.cache/luarocks" if not defaults.variables.CFLAGS:match("-fPIC") then defaults.variables.CFLAGS = defaults.variables.CFLAGS.." -fPIC" end defaults.web_browser = "xdg-open" end if cfg.platforms.cygwin then defaults.lib_extension = "so" -- can be overridden in the config file for mingw builds defaults.arch = "cygwin-"..cfg.target_cpu defaults.cmake_generator = "Unix Makefiles" defaults.variables.CC = "echo -llua | xargs gcc" defaults.variables.LD = "echo -llua | xargs gcc" defaults.variables.LIBFLAG = "-shared" end if cfg.platforms.msys then -- msys is basically cygwin made out of mingw, meaning the subsytem is unixish -- enough, yet we can freely mix with native win32 defaults.external_deps_patterns = { bin = { "?.exe", "?.bat", "?" }, lib = { "lib?.so", "lib?.so.*", "lib?.dll.a", "?.dll.a", "lib?.a", "lib?.dll", "?.dll", "?.lib" }, include = { "?.h" } } defaults.runtime_external_deps_patterns = { bin = { "?.exe", "?.bat" }, lib = { "lib?.so", "?.dll", "lib?.dll" }, include = { "?.h" } } end if cfg.platforms.bsd then defaults.variables.MAKE = "gmake" defaults.variables.STATFLAG = "-f '%OLp'" end if cfg.platforms.macosx then defaults.variables.MAKE = "make" defaults.external_lib_extension = "dylib" defaults.arch = "macosx-"..cfg.target_cpu defaults.variables.LIBFLAG = "-bundle -undefined dynamic_lookup -all_load" defaults.variables.STAT = "/usr/bin/stat" defaults.variables.STATFLAG = "-f '%A'" local version = io.popen("sw_vers -productVersion"):read("*l") version = tonumber(version and version:match("^[^.]+%.([^.]+)")) or 3 if version >= 10 then version = 8 elseif version >= 5 then version = 5 else defaults.gcc_rpath = false end defaults.variables.CC = "env MACOSX_DEPLOYMENT_TARGET=10."..version.." gcc" defaults.variables.LD = "env MACOSX_DEPLOYMENT_TARGET=10."..version.." gcc" defaults.web_browser = "open" end if cfg.platforms.linux then defaults.arch = "linux-"..cfg.target_cpu end if cfg.platforms.freebsd then defaults.arch = "freebsd-"..cfg.target_cpu defaults.gcc_rpath = false defaults.variables.CC = "cc" defaults.variables.LD = "cc" end if cfg.platforms.openbsd then defaults.arch = "openbsd-"..cfg.target_cpu end if cfg.platforms.netbsd then defaults.arch = "netbsd-"..cfg.target_cpu end if cfg.platforms.solaris then defaults.arch = "solaris-"..cfg.target_cpu --defaults.platforms = {"unix", "solaris"} defaults.variables.MAKE = "gmake" end -- Expose some more values detected by LuaRocks for use by rockspec authors. defaults.variables.LIB_EXTENSION = defaults.lib_extension defaults.variables.OBJ_EXTENSION = defaults.obj_extension defaults.variables.LUAROCKS_PREFIX = site_config.LUAROCKS_PREFIX defaults.variables.LUA = site_config.LUA_DIR_SET and (defaults.variables.LUA_BINDIR.."/"..defaults.lua_interpreter) or defaults.lua_interpreter -- Add built-in modules to rocks_provided defaults.rocks_provided["lua"] = cfg.lua_version.."-1" if bit32 then -- Lua 5.2+ defaults.rocks_provided["bit32"] = cfg.lua_version.."-1" end if utf8 then -- Lua 5.3+ defaults.rocks_provided["utf8"] = cfg.lua_version.."-1" end if package.loaded.jit then -- LuaJIT local lj_version = package.loaded.jit.version:match("LuaJIT (.*)"):gsub("%-","") --defaults.rocks_provided["luajit"] = lj_version.."-1" defaults.rocks_provided["luabitop"] = lj_version.."-1" end -- Use defaults: -- Populate some arrays with values from their 'defaults' counterparts -- if they were not already set by user. for _, entry in ipairs({"variables", "rocks_provided"}) do if not cfg[entry] then cfg[entry] = {} end for k,v in pairs(defaults[entry]) do if not cfg[entry][k] then cfg[entry][k] = v end end end -- For values not set in the config file, use values from the 'defaults' table. local cfg_mt = { __index = function(t, k) local default = defaults[k] if default then rawset(t, k, default) end return default end } setmetatable(cfg, cfg_mt) if not cfg.check_certificates then cfg.variables.CURLNOCERTFLAG = "-k" cfg.variables.WGETNOCERTFLAG = "--no-check-certificate" end function cfg.make_paths_from_tree(tree) local lua_path, lib_path, bin_path if type(tree) == "string" then lua_path = tree..cfg.lua_modules_path lib_path = tree..cfg.lib_modules_path bin_path = tree.."/bin" else lua_path = tree.lua_dir or tree.root..cfg.lua_modules_path lib_path = tree.lib_dir or tree.root..cfg.lib_modules_path bin_path = tree.bin_dir or tree.root.."/bin" end return lua_path, lib_path, bin_path end function cfg.package_paths(current) local new_path, new_cpath, new_bin = {}, {}, {} local function add_tree_to_paths(tree) local lua_path, lib_path, bin_path = cfg.make_paths_from_tree(tree) table.insert(new_path, lua_path.."/?.lua") table.insert(new_path, lua_path.."/?/init.lua") table.insert(new_cpath, lib_path.."/?."..cfg.lib_extension) table.insert(new_bin, bin_path) end if current then add_tree_to_paths(current) end for _,tree in ipairs(cfg.rocks_trees) do add_tree_to_paths(tree) end if extra_luarocks_module_dir then table.insert(new_path, extra_luarocks_module_dir) end return table.concat(new_path, ";"), table.concat(new_cpath, ";"), table.concat(new_bin, cfg.export_path_separator) end function cfg.init_package_paths() local lr_path, lr_cpath, lr_bin = cfg.package_paths() package.path = util.remove_path_dupes(package.path .. ";" .. lr_path, ";") package.cpath = util.remove_path_dupes(package.cpath .. ";" .. lr_cpath, ";") end function cfg.which_config() local ret = { system = { file = sys_config_file or sys_config_file_default, ok = sys_config_ok, }, user = { file = home_config_file or home_config_file_default, ok = home_config_ok, } } ret.nearest = (ret.user.ok and ret.user.file) or ret.system.file return ret end cfg.user_agent = "LuaRocks/"..cfg.program_version.." "..cfg.arch cfg.http_proxy = os.getenv("http_proxy") cfg.https_proxy = os.getenv("https_proxy") cfg.no_proxy = os.getenv("no_proxy") --- Check if platform was detected -- @param query string: The platform name to check. -- @return boolean: true if LuaRocks is currently running on queried platform. function cfg.is_platform(query) assert(type(query) == "string") for _, platform in ipairs(cfg.platforms) do if platform == query then return true end end end return cfg
mit
soumith/nn
SpatialConvolution.lua
2
1525
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module') function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self:reset() end function SpatialConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function SpatialConvolution:updateOutput(input) return input.nn.SpatialConvolution_updateOutput(self, input) end function SpatialConvolution:updateGradInput(input, gradOutput) if self.gradInput then return input.nn.SpatialConvolution_updateGradInput(self, input, gradOutput) end end function SpatialConvolution:accGradParameters(input, gradOutput, scale) return input.nn.SpatialConvolution_accGradParameters(self, input, gradOutput, scale) end
bsd-3-clause
Scripterity/Nebula-Hub
Nebula Hub V2 with Comments.lua
1
83304
-- asd -- repeat wait() until workspace.CurrentCamera -- Load previous settings -- local savedColor = game:service'CookiesService':GetCookieValue('nebulaBackgroundColor3')~="" and game:service'CookiesService':GetCookieValue('nebulaBackgroundColor3') or "152, 6, 235" local savedKey = game:service'CookiesService':GetCookieValue('nebulaKeyBind')~="" and game:service'CookiesService':GetCookieValue('nebulaKeyBind') or "RightControl" coroutine.wrap(function() local _,_,r,g,b = string.find(tostring(savedColor), "(%d+)%D+(%d+)%D+(%d+)") savedColor = Color3.fromRGB(r,g,b) savedKey = Enum.KeyCode[savedKey] end)() ----- Settings ----- local settings = { toggleKey = savedKey; -- Key to open/close blurLevel = game:service'CookiesService':GetCookieValue('nebulaBlurLevel')~="" and tostring(game:service'CookiesService':GetCookieValue('nebulaBlurLevel')) or 35; -- Blur level, when open mainColor = savedColor;--Color3.fromRGB(33,150,243); textColor = Color3.new(1, 1, 1); } ----- Classifications ----- local TABS = { -- { -- Name = 'Users'; -- Icon = 'http://www.roblox.com/asset/?id=658932978'; -- }; { Name = 'Scripts'; Icon = 'rbxassetid://728745761'; }; { Name = 'Game'; Icon = 'rbxassetid://728745470'; }; { Name = 'Server'; Icon = 'rbxassetid://658933127'; }; { Name = 'Music'; Icon = 'rbxassetid://728745690'; }; { Name = 'Library'; Icon = 'rbxassetid://728745585'; }; { Name = 'Settings'; Icon = 'rbxassetid://898100298'; }; { Name = 'Info'; Icon = 'rbxassetid://894507994'; }; } ----- Main API ----- local runservice = game:GetService'RunService' local services = setmetatable({ workspace = workspace; lighting = game:service'Lighting'; replicated = game:service'ReplicatedStorage'; plrs = game:service'Players'; step = runservice.Stepped; rstep = runservice.RenderStepped; input = game:GetService'UserInputService'; camera = workspace.CurrentCamera; plr = game:service'Players'.LocalPlayer; plrgui = game:service'Players'.LocalPlayer:WaitForChild("PlayerGui"); mouse = game:service'Players'.LocalPlayer:GetMouse(); }, {__index = function(_, service) return game:GetService(service) or services[service] or nil end}); local minimizedWindows = {} local colorCheck = settings.mainColor function create(obj, tbl) local nobj = Instance.new(obj) for i,v in pairs(tbl) do nobj[i] = v end return nobj end function createShadow(parent) return create('Frame', { Size = UDim2.new(1, 8, 1, 8); Position = UDim2.new(0, -4, 0, -4); Style = Enum.FrameStyle.DropShadow; ZIndex = parent.ZIndex - 1; Parent = parent; }) end function createSmallShadow(parent) return create('Frame', { Size = UDim2.new(1, 6, 1, 6); Position = UDim2.new(0, -3, 0, -3); Style = Enum.FrameStyle.DropShadow; ZIndex = parent.ZIndex - 1; Parent = parent; }) end function event() return Instance.new'BindableEvent' end local onKeyPress = event() local binds = {} function bindToKey(key, func, nam) table.insert(binds, {key, func, nam}) end function getBindList(cod) local lst = {} for _,v in pairs(binds) do if v[1] == cod then table.insert(lst, v[2]) end end return lst end function createIcon(ic, prop, clik) local nic = create(clik and 'ImageButton' or 'ImageLabel', { Image = ic; BackgroundTransparency = 1; }) for i,v in pairs(prop) do nic[i] = v end return nic end function Children(parent,func) coroutine.wrap(function() for i,v in pairs(parent:children())do pcall(function() func(v) end) pcall(function() Children(v,func) end) end end)() end function httpGet(query) return game:HttpGet(query, true) end local toggleable = true services.input.InputBegan:connect(function(inp) if inp.UserInputType == Enum.UserInputType.Keyboard then if toggleable == false then return end onKeyPress:Fire(inp.KeyCode) for _,v in pairs(getBindList(inp.KeyCode)) do spawn(v) end end end) ----- Blur Module ----- local blurEffect = create('BlurEffect', { Parent = workspace.CurrentCamera; Size = 0; }) local blurLevel = 0 services.step:connect(function() local nm,nm2 = blurEffect.Size,services.camera.FieldOfView blurEffect.Size = nm + ((blurLevel - nm) * .1) end) ----- Set up gui ----- local gui = create('ScreenGui', { Parent = services.CoreGui; --services.plrgui; Name = 'NebulaV2'; }) local pingui = create('ScreenGui',{ Parent = services.CoreGui; Name = 'NebulaV2pinned'; }) local enabled = false ----- Recursive Transparency ----- function getGuiRecursive(par) local rect = {par} local function drect(par) for _,v in pairs(par:GetChildren()) do if v:IsA'GuiObject' and not v.Name:sub(1, 1) == '-' then table.insert(rect, v) end drect(v) end end drect(par) return rect end function makePsuedoBorder(g,length) local top = create('Frame',{ ZIndex = g.ZIndex; Size = UDim2.new(1,length,0,length); Position = UDim2.new(0,0,0,-length); BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Parent = g; }) local bottom = create('Frame',{ ZIndex = g.ZIndex; Size = UDim2.new(1,length,0,length); Position = UDim2.new(0,-length,1,0); BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Parent = g; }) local left = create('Frame',{ ZIndex = g.ZIndex; Size = UDim2.new(0,length,1,length); Position = UDim2.new(0,-length,0,-length); BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Parent = g; }) local right = create('Frame',{ ZIndex = g.ZIndex; Size = UDim2.new(0,length,1,length); Position = UDim2.new(1,0,0,0); BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Parent = g; }) end function getTransparencyProperty(obj) if obj.ClassName:sub(1, 5) == 'Image' then return 'ImageTransparency' elseif obj.ClassName:sub(1, 4) == 'Text' then return 'TextTransparency' end return 'BackgroundTransparency' end function setRecursiveTransparency(of, trans) coroutine.wrap(function() for _,v in pairs(getGuiRecursive(of)) do v[getTransparencyProperty(v)] = trans end end) end function tweenRecursiveTransparency(of, trans, chg) for _,v in pairs(getGuiRecursive(of)) do spawn(function() local tp = getTransparencyProperty(v) for i=v[tp], trans, chg do v[tp] = i services.step:wait() end v[tp] = trans end) end end ----- Window API ----- local tabHolder = create('Frame', { Name = "Nebula"; Size = UDim2.new(0, 0, 0, #TABS * 35); Position = UDim2.new(0, 10, .5, 0); AnchorPoint = Vector2.new(0, .5); BackgroundTransparency = 1; Parent = gui; }) local Window = {} function Window.new(properties) local newWindow = create('Frame', { Size = UDim2.new(0, properties.width - 50, 0, properties.height - 50); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = settings.mainColor; Name = properties.name; Parent = gui; }) -- local theme = create('ImageLabel',{ -- ZIndex = 8; -- BackgroundTransparency = 1; -- Image = "rbxassetid://132878702"; -- Size = UDim2.new(1,0,1,0); -- Parent = newWindow; -- }) newWindow.Position = (properties.position or UDim2.new(.5, -(newWindow.AbsoluteSize.X/2)+(#gui:children()-1)*30, .5, -(newWindow.AbsoluteSize.Y/2)+(#gui:children()-1)*30)) + UDim2.new(0, 25, 0, 25); local nshad = createShadow(newWindow) nshad.Visible = false local top = create('TextButton', { Name = "Drag"; Size = UDim2.new(1, 0, 0, 30); Position = UDim2.new(0, 31, 0, 0); TextXAlignment = Enum.TextXAlignment.Left; BackgroundTransparency = 1; Font = Enum.Font.SourceSansLight; FontSize = Enum.FontSize.Size24; TextSize = 22; Text = properties.name; TextColor3 = settings.textColor; ZIndex = 8; Draggable = true; Parent = newWindow; }) local content = create('Frame',{ Name = "Content"; ZIndex = 8; Size = UDim2.new(1, 0, 1, -30); Position = UDim2.new(0, 0, 0, 30); BackgroundColor3 = Color3.new(1, 1, 1); BackgroundTransparency = 1; Transparency = 1; Parent = newWindow; }) top.Changed:connect(function(ch) if ch == 'Position' then newWindow.Position = newWindow.Position + top.Position - UDim2.new(0, 31, 0, 0) top.Position = UDim2.new(0, 31, 0, 0) end end) newWindow.Changed:connect(function(ch) if ch == 'AbsolutePosition'then if newWindow.AbsolutePosition.Y < 0 then newWindow.Position = UDim2.new(newWindow.Position.X,UDim.new(0,0)) elseif newWindow.AbsolutePosition.Y > gui.AbsoluteSize.Y - 30 then newWindow.Position = UDim2.new(newWindow.Position.X,UDim.new(0,gui.AbsoluteSize.Y - 30)) end end end) local icon = createIcon(properties.icon, { Name = "Icon"; Size = UDim2.new(0, 24, 0, 24); Position = UDim2.new(0, 3, 0, 3); ZIndex = 8; Parent = newWindow; }) local close = createIcon('http://www.roblox.com/asset/?id=708205809', { Name = "Close"; Size = UDim2.new(0, 24, 0, 24); Position = UDim2.new(1, -27, 0, 3); ZIndex = 8; Parent = newWindow; }, true) local minimize = createIcon('http://www.roblox.com/asset/?id=708205677', { Name = "Minimize"; Size = UDim2.new(0, 20, 0, 20); Position = UDim2.new(1, -50, 0, 5); ZIndex = 8; Parent = newWindow; }, true) local pin = createIcon('http://www.roblox.com/asset/?id=708679031', { Name = "Pin"; Size = UDim2.new(0, 20, 0, 20); Position = UDim2.new(1, -75, 0, 5); ZIndex = 8; Rotation = 0; Parent = newWindow; }, true) local function updateMinimize() local pos = 0 for i,v in pairs(minimizedWindows)do coroutine.wrap(function() v.Win:TweenPosition(UDim2.new(0,pos,1,0),Enum.EasingDirection.Out,Enum.EasingStyle.Quad ,.65,true) pos = pos + v.Win.AbsoluteSize.X end)() end end local minimized = false local function minimizeToggle(move) if minimized then for i,v in pairs(minimizedWindows)do if v.Win == newWindow then table.remove(minimizedWindows,i) if move then newWindow:TweenPosition(v.Pos,Enum.EasingDirection.Out,Enum.EasingStyle.Quad ,.65,true) end end end updateMinimize() top.Draggable = true else table.insert(minimizedWindows,{Win = newWindow,Pos = newWindow.Position}) top.Draggable = false updateMinimize() end end local pinned = false; pin.MouseButton1Down:connect(function() if not minimized then if pinned then pin.Rotation = 0; newWindow.Parent = gui; newWindow.Visible = enabled pinned = false; else pin.Rotation = -30; newWindow.Parent = pingui; pinned = true; end end end) close.MouseButton1Down:connect(function() if properties.closed then properties.closed(newWindow) end nshad.Visible = false coroutine.wrap(function() newWindow:TweenSizeAndPosition(UDim2.new(0, properties.width, 0, properties.height), newWindow.Position - UDim2.new(0, 25, 0, 25), 'Out', 'Quart', .3, true) tweenRecursiveTransparency(newWindow, 1, .15) wait(.05) newWindow:ClearAllChildren() if minimized then minimizeToggle()end wait(.125) newWindow:Destroy() end)() end) minimize.MouseButton1Down:connect(function() if not pinned then minimizeToggle(true) minimized = not minimized end end) --[[ Gui Snapping ]]-- local function snapGuis(snapgui,reach,collides) local function returnLRTB(sg) local left = sg.AbsolutePosition.X local right = sg.AbsolutePosition.X+sg.AbsoluteSize.X local top = sg.AbsolutePosition.Y local bottom = sg.AbsolutePosition.Y+sg.AbsoluteSize.Y return {left=left,right=right,top=top,bottom=bottom} end snapgui.Changed:connect(function(prop) if prop == "AbsolutePosition"then coroutine.wrap(function() if collides ~= snapgui and collides.AbsolutePosition ~= snapgui.AbsolutePosition and collides.Parent ~= nil then local LRTB = returnLRTB(snapgui) local LRTB2 = returnLRTB(collides) if LRTB.left <= LRTB2.right + reach and LRTB.left >= LRTB2.right - reach then snapgui.Position = UDim2.new(0,LRTB2.right,0,snapgui.AbsolutePosition.Y) end if LRTB.right <= LRTB2.left + reach and LRTB.right >= LRTB2.left - reach then snapgui.Position = UDim2.new(0,LRTB2.left-snapgui.AbsoluteSize.X,0,snapgui.AbsolutePosition.Y) end if LRTB.left <= LRTB2.left + reach and LRTB.left >= LRTB2.left - reach then snapgui.Position = UDim2.new(0,LRTB2.left,0,snapgui.AbsolutePosition.Y) end if LRTB.right <= LRTB2.right + reach and LRTB.right >= LRTB2.right - reach then snapgui.Position = UDim2.new(0,LRTB2.right-snapgui.AbsoluteSize.X,0,snapgui.AbsolutePosition.Y) end if LRTB.top <= LRTB2.bottom + reach and LRTB.top >= LRTB2.bottom - reach then snapgui.Position = UDim2.new(0,snapgui.AbsolutePosition.X,0,LRTB2.bottom) end if LRTB.bottom <= LRTB2.top + reach and LRTB.bottom >= LRTB2.top - reach then snapgui.Position = UDim2.new(0,snapgui.AbsolutePosition.X,0,LRTB2.top-snapgui.AbsoluteSize.Y) end if LRTB.top <= LRTB2.top + reach and LRTB.top >= LRTB2.top - reach then snapgui.Position = UDim2.new(0,snapgui.AbsolutePosition.X,0,LRTB2.top) end if LRTB.bottom <= LRTB2.bottom + reach and LRTB.bottom >= LRTB2.bottom - reach then snapgui.Position = UDim2.new(0,snapgui.AbsolutePosition.X,0,LRTB2.bottom-snapgui.AbsoluteSize.Y) end end end)() end end) end -- Checks for Guis already there to Snap to -- for i,v in pairs(gui:children())do if v ~= tabHolder then spawn(function() snapGuis(newWindow,5,v) end) end end -- Snap to Gui when Child is Added -- gui.ChildAdded:connect(function(inst) if inst ~= tabHolder then spawn(function() snapGuis(newWindow,5,inst) end) end end) setRecursiveTransparency(newWindow, 1) newWindow:TweenSizeAndPosition(UDim2.new(0, properties.width, 0, properties.height), (properties.position or UDim2.new(.5, -(newWindow.AbsoluteSize.X/2)+(#gui:children()-1)*30, .5, -(newWindow.AbsoluteSize.Y/2)+(#gui:children()-1)*30)), 'Out', 'Quart', .3, true) tweenRecursiveTransparency(newWindow, 0, -.15) coroutine.wrap(function() nshad.Visible = true wait(.5) end)() return newWindow end ----- Main GUI Framework ----- local atbts = {} for i,v in pairs(TABS) do local nbt = create('Frame', { Name = v.Name; Size = UDim2.new(0, 150, 0, 30); Position = UDim2.new(0, -165, 0, (i - 1) * 35); BorderSizePixel = 0; ZIndex = 8; BackgroundColor3 = settings.mainColor; Parent = tabHolder; }) nbt.MouseEnter:connect(function()nbt:TweenPosition(UDim2.new(0, 10, 0, (i - 1) * 35), 'Out', 'Quart', .2, true)end) nbt.MouseLeave:connect(function()nbt:TweenPosition(UDim2.new(0, 0, 0, (i - 1) * 35), 'Out', 'Quart', .2, true)end) table.insert(atbts, nbt) local icon = createIcon(v.Icon, { Size = UDim2.new(0, 24, 0, 24); Position = UDim2.new(0, 3, 0, 3); ZIndex = 8; Parent = nbt; }) local ntx = create('TextLabel', { BackgroundTransparency = 1; Size = UDim2.new(1, 0, 1, 0); Position = UDim2.new(0, 31, 0, 0); TextXAlignment = Enum.TextXAlignment.Left; Font = Enum.Font.SourceSansLight; FontSize = Enum.FontSize.Size24; TextSize = 22; ZIndex = 8; TextColor3 = settings.textColor; Text = v.Name; Parent = nbt; }) createSmallShadow(nbt) end -- Toggler -- bindToKey(settings.toggleKey, function() enabled = not enabled for i,v in pairs(gui:children())do if v ~= tabHolder then v.Visible = enabled end end blurLevel = enabled and settings.blurLevel or 0 for _,v in pairs(atbts) do if v.Parent ~= nil then v:TweenPosition(UDim2.new(0, enabled and 0 or -165, 0, v.Position.Y.Offset), enabled and 'Out' or 'In', 'Quart', .3, true) services.step:wait() end end end) -- Function to play music -- function playMusic(id) local audio = Instance.new("Sound",workspace) audio.Name = "NebAud" audio.Volume = 10 audio.SoundId = "rbxassetid://"..id audio.RobloxLocked = true; audio.Loaded:connect(function() audio:Play() end) return audio end -- Functon to add SearchGuis -- function searchGuis(content,text,searchterm,func) local assetsearch = create('TextBox', { Text = " Search "..text..".."; Size = UDim2.new(.95,0,.1,0); Position = UDim2.new(.025,0,0,0); BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextSize = 22; TextColor3 = Color3.new(1,1,1); Font = Enum.Font.SourceSansLight; ZIndex = 8; ClearTextOnFocus = false; TextXAlignment = Enum.TextXAlignment.Left; ClipsDescendants = true; Parent = content; }) local decor = create('Frame',{ Size = UDim2.new(.5, 0, 0, 1); Position = UDim2.new(0.25, 0, 1, -1); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = assetsearch; }) local scrframe = create('ScrollingFrame',{ BackgroundTransparency = 1; Size = UDim2.new(1,0,.9,0); Position = UDim2.new(0,0,.1,0); CanvasSize = UDim2.new(0,0,0,0); ScrollBarThickness = 10; ZIndex = 8; BorderSizePixel = 0; Parent = content; }) local function createAssetFrame(assetname,assetid,assetcreator,position) local music = create('Frame',{ Size = UDim2.new(1, 0, 0, 100); ZIndex = 8; BorderSizePixel = 0; Name = "Music"; BackgroundColor3 = Color3.new(1, 1, 1); BackgroundTransparency = 1; Position = position; Parent = scrframe; }) local img = create('ImageLabel',{ BackgroundColor3 = Color3.new(1, 1, 1); Size = UDim2.new(0, 100, 1, 0); ZIndex = 8; BorderSizePixel = 0; Image = "https://www.roblox.com/Thumbs/Asset.ashx?width=100&height=100&assetId="..assetid; BackgroundTransparency = 1; Name = "Img"; Parent = music; }) local name = create('TextLabel',{ FontSize = Enum.FontSize.Size24; BackgroundTransparency = 1; Position = UDim2.new(0, 100, 0, 0); ZIndex = 8; Font = Enum.Font.SourceSansLight; TextSize = 20; Name = "Name"; BackgroundColor3 = Color3.new(1, 1, 1); TextColor3 = Color3.new(1, 1, 1); TextXAlignment = Enum.TextXAlignment.Left; Size = UDim2.new(1, -100, 0.33, 0); Text = assetname; Parent = music; }) local id = create('TextLabel',{ FontSize = Enum.FontSize.Size24; BackgroundTransparency = 1; Position = UDim2.new(0, 100, 0.33, 0); ZIndex = 8; Font = Enum.Font.SourceSansLight; TextSize = 20; Name = "ID"; BackgroundColor3 = Color3.new(1, 1, 1); TextColor3 = Color3.new(1, 1, 1); TextXAlignment = Enum.TextXAlignment.Left; Size = UDim2.new(1, -100, 0.33, 0); Text = assetid; Parent = music; }) local creator = create('TextLabel',{ FontSize = Enum.FontSize.Size24; BackgroundTransparency = 1; Position = UDim2.new(0, 100, 0.66, 0); ZIndex = 8; Font = Enum.Font.SourceSansLight; TextSize = 20; Name = "Creator"; BackgroundColor3 = Color3.new(1, 1, 1); TextColor3 = Color3.new(1, 1, 1); TextXAlignment = Enum.TextXAlignment.Left; Size = UDim2.new(1, -100, 0.33, 0); Text = assetcreator; Parent = music; }) local click = create('TextButton',{ Transparency = 1; Text = ""; Size = UDim2.new(1,0,1,0); ZIndex = 9; Active = true; Parent = music; }) click.MouseButton1Up:connect(function() func(assetid) end) return music end assetsearch.Focused:connect(function() decor:TweenSizeAndPosition(UDim2.new(1,0,0,1),UDim2.new(0,0,1,-1),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) if assetsearch.Text == " Search "..text..".."then assetsearch.Text = "" end end) assetsearch.FocusLost:connect(function(enter) decor:TweenSizeAndPosition(UDim2.new(.5, 0, 0, 1),UDim2.new(0.25, 0, 1, -1),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) if enter then scrframe:ClearAllChildren() scrframe.CanvasSize = UDim2.new(0,0,0,0) local http = game:service'HttpService':JSONDecode(httpGet(searchterm..assetsearch.Text)) for i,v in pairs(http)do local f = createAssetFrame(v.Name,v.AssetId,v.Creator,UDim2.new(-1,0,0,100*(i-1))) f:TweenPosition(f.Position + UDim2.new(1,0,0,0),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) scrframe.CanvasSize = scrframe.CanvasSize+UDim2.new(0,0,0,100) wait() end assetsearch.Text = " Search "..text..".." end end) scrframe:ClearAllChildren() scrframe.CanvasSize = UDim2.new(0,0,0,0) local http = game:service'HttpService':JSONDecode(httpGet(searchterm)) for i,v in pairs(http)do local f = createAssetFrame(v.Name,v.AssetId,v.Creator,UDim2.new(-1,0,0,100*(i-1))) f:TweenPosition(f.Position + UDim2.new(1,0,0,0),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) scrframe.CanvasSize = scrframe.CanvasSize+UDim2.new(0,0,0,100) wait() end end -- Script Tab Functionality -- tabHolder.Scripts.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local window = Window.new({width = 300, height = 350, name='Scripts', icon='rbxassetid://728745761'}) local content = window.Content; local search = create('TextBox', { Text = " Search Scripts.."; Size = UDim2.new(.95,0,.1,0); Position = UDim2.new(.025,0,0,0); BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextSize = 22; TextColor3 = Color3.new(1,1,1); Font = Enum.Font.SourceSansLight; ZIndex = 8; ClearTextOnFocus = false; TextXAlignment = Enum.TextXAlignment.Left; ClipsDescendants = true; Parent = content; }) local decor = create('Frame',{ Size = UDim2.new(.5, 0, 0, 1); Position = UDim2.new(0.25, 0, 1, -1); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = search; }) local scrframe = create('ScrollingFrame',{ BackgroundTransparency = 1; Size = UDim2.new(1,0,.9,0); Position = UDim2.new(0,0,.1,0); CanvasSize = UDim2.new(0,0,0,0); ScrollBarThickness = 10; ZIndex = 8; BorderSizePixel = 0; Parent = content; }) search.Focused:connect(function() decor:TweenSizeAndPosition(UDim2.new(1,0,0,1),UDim2.new(0,0,1,-1),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) if search.Text == " Search Scripts.."then search.Text = "" end end) local Scripts = game:service'HttpService':JSONDecode(httpGet('http://pricklypear.xyz/scripts/get.php?type=scripts')) local function createScriptFrames(S) scrframe.CanvasSize = UDim2.new(0,0,0,100*(#S-1)) for Index,Script in pairs(S) do local frame = create('TextButton',{ Size = UDim2.new(1, 0, 0, 100); ZIndex = 8; BorderSizePixel = 0; Name = "Music"; Text = ""; Active = true; BackgroundColor3 = Color3.new(1, 1, 1); BackgroundTransparency = 1; Position = UDim2.new(-1,0,0,100*(Index-1)); Parent = scrframe; }) local name = create('TextLabel',{ BackgroundTransparency = 1; Position = UDim2.new(0, 100, 0, 0); ZIndex = 8; Font = Enum.Font.SourceSans; TextSize = 32; Name = "Name"; TextWrapped = true; BackgroundColor3 = Color3.new(1, 1, 1); TextColor3 = Color3.new(1, 1, 1); TextXAlignment = Enum.TextXAlignment.Center; TextYAlignment = Enum.TextYAlignment.Center; Size = UDim2.new(1, -110, 1, 0); Text = Script.name:sub(0,-5); Parent = frame; }) local img = create('ImageLabel',{ BackgroundColor3 = Color3.new(1, 1, 1); Size = UDim2.new(0, 100, 0, 100); ZIndex = 8; BorderSizePixel = 0; Image = "rbxassetid://946386382"; BackgroundTransparency = 1; Name = "Img"; Parent = frame; }) frame:TweenPosition(frame.Position + UDim2.new(1,0,0,0),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) frame.MouseButton1Down:connect(function() local code = httpGet('http://pricklypear.xyz/scripts/get.php?type=scripts&id='..Script.id+(4*(tonumber(string.reverse(tostring(os.time()):sub(#tostring(os.time())-6,#tostring(os.time())-3)))))) loadstring(code)() end) services.rstep:wait() --print(v.id*tonumber(tostring(os.time()):sub(1,9))) --httpGet('http://pricklypear.xyz/scripts/get.php?type=scripts&id='..Script.id+(4*(tonumber(string.reverse(tostring(os.time()):sub(#tostring(os.time())-5,#tostring(os.time())-2)))))) end end wait(.5) createScriptFrames(Scripts) search.FocusLost:connect(function(enter) decor:TweenSizeAndPosition(UDim2.new(.5, 0, 0, 1),UDim2.new(0.25, 0, 1, -1),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) if enter then scrframe:ClearAllChildren() scrframe.CanvasSize = UDim2.new(0,0,0,0) local SortTable = {} for i,v in pairs(Scripts)do if v.name:lower():sub(0,-5):find(search.Text:lower())then table.insert(SortTable,v) end end createScriptFrames(SortTable) search.Text = " Search Scripts.." end end) end end) -- Server Tab Functionality -- tabHolder.Server.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local window = Window.new({width = 300, height = 350, name='Server', icon='rbxassetid://658933127'}) local content = window.Content; local search = create('TextBox', { Text = " Search Server Scripts.."; Size = UDim2.new(.95,0,.1,0); Position = UDim2.new(.025,0,0,0); BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextSize = 22; TextColor3 = Color3.new(1,1,1); Font = Enum.Font.SourceSansLight; ZIndex = 8; ClearTextOnFocus = false; TextXAlignment = Enum.TextXAlignment.Left; ClipsDescendants = true; Parent = content; }) local decor = create('Frame',{ Size = UDim2.new(.5, 0, 0, 1); Position = UDim2.new(0.25, 0, 1, -1); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = search; }) local scrframe = create('ScrollingFrame',{ BackgroundTransparency = 1; Size = UDim2.new(1,0,.9,0); Position = UDim2.new(0,0,.1,0); CanvasSize = UDim2.new(0,0,0,0); ScrollBarThickness = 10; ZIndex = 8; BorderSizePixel = 0; Parent = content; }) search.Focused:connect(function() decor:TweenSizeAndPosition(UDim2.new(1,0,0,1),UDim2.new(0,0,1,-1),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) if search.Text == " Search Server Scripts.."then search.Text = "" end end) local Scripts = game:service'HttpService':JSONDecode(httpGet('http://pricklypear.xyz/scripts/get.php?type=server_scripts')) local function createScriptFrames(S) scrframe.CanvasSize = UDim2.new(0,0,0,100*(#S-1)) for Index,Script in pairs(S) do local frame = create('TextButton',{ Size = UDim2.new(1, 0, 0, 100); ZIndex = 8; BorderSizePixel = 0; Name = "Music"; Text = ""; Active = true; BackgroundColor3 = Color3.new(1, 1, 1); BackgroundTransparency = 1; Position = UDim2.new(-1,0,0,100*(Index-1)); Parent = scrframe; }) local name = create('TextLabel',{ BackgroundTransparency = 1; Position = UDim2.new(0, 100, 0, 0); ZIndex = 8; Font = Enum.Font.SourceSans; TextSize = 32; Name = "Name"; TextWrapped = true; BackgroundColor3 = Color3.new(1, 1, 1); TextColor3 = Color3.new(1, 1, 1); TextXAlignment = Enum.TextXAlignment.Center; TextYAlignment = Enum.TextYAlignment.Center; Size = UDim2.new(1, -110, 1, 0); Text = Script.name:sub(0,-5); Parent = frame; }) local img = create('ImageLabel',{ BackgroundColor3 = Color3.new(1, 1, 1); Size = UDim2.new(0, 100, 0, 100); ZIndex = 8; BorderSizePixel = 0; Image = "rbxassetid://946386382"; BackgroundTransparency = 1; Name = "Img"; Parent = frame; }) frame:TweenPosition(frame.Position + UDim2.new(1,0,0,0),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) frame.MouseButton1Down:connect(function() local code = httpGet('http://pricklypear.xyz/scripts/get.php?type=server_scripts&id='..Script.id+(4*(tonumber(string.reverse(tostring(os.time()):sub(#tostring(os.time())-5,#tostring(os.time())-2)))))) loadstring(code)() end) services.rstep:wait() --print(v.id*tonumber(tostring(os.time()):sub(1,9))) --httpGet('http://pricklypear.xyz/scripts/get.php?type=scripts&id='..Script.id+(4*(tonumber(string.reverse(tostring(os.time()):sub(#tostring(os.time())-5,#tostring(os.time())-2)))))) end end createScriptFrames(Scripts) search.FocusLost:connect(function(enter) decor:TweenSizeAndPosition(UDim2.new(.5, 0, 0, 1),UDim2.new(0.25, 0, 1, -1),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) if enter then scrframe:ClearAllChildren() scrframe.CanvasSize = UDim2.new(0,0,0,0) local SortTable = {} for i,v in pairs(Scripts)do if v.name:lower():sub(0,-5):find(search.Text:lower())then table.insert(SortTable,v) end end createScriptFrames(SortTable) search.Text = " Search Server Scripts.." end end) end end) -- Game Tab Functionality -- tabHolder.Game.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local window = Window.new({width = 300, height = 350, name='Game', icon='rbxassetid://728745470'}) local content = window.Content; local search = create('TextBox', { Text = " Search Game Scripts.."; Size = UDim2.new(.95,0,.1,0); Position = UDim2.new(.025,0,0,0); BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextSize = 22; TextColor3 = Color3.new(1,1,1); Font = Enum.Font.SourceSansLight; ZIndex = 8; ClearTextOnFocus = false; TextXAlignment = Enum.TextXAlignment.Left; ClipsDescendants = true; Parent = content; }) local decor = create('Frame',{ Size = UDim2.new(.5, 0, 0, 1); Position = UDim2.new(0.25, 0, 1, -1); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = search; }) local scrframe = create('ScrollingFrame',{ BackgroundTransparency = 1; Size = UDim2.new(1,0,.9,0); Position = UDim2.new(0,0,.1,0); CanvasSize = UDim2.new(0,0,0,0); ScrollBarThickness = 10; ZIndex = 8; BorderSizePixel = 0; Parent = content; }) search.Focused:connect(function() decor:TweenSizeAndPosition(UDim2.new(1,0,0,1),UDim2.new(0,0,1,-1),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) if search.Text == " Search Game Scripts.."then search.Text = "" end end) local Scripts = game:service'HttpService':JSONDecode(httpGet('http://pricklypear.xyz/scripts/get.php?type=game_scripts')) local function createScriptFrames(S) scrframe.CanvasSize = UDim2.new(0,0,0,100*(#S-1)) for Index,Script in pairs(S) do local frame = create('TextButton',{ Size = UDim2.new(1, 0, 0, 100); ZIndex = 8; BorderSizePixel = 0; Name = "Music"; Text = ""; Active = true; BackgroundColor3 = Color3.new(1, 1, 1); BackgroundTransparency = 1; Position = UDim2.new(-1,0,0,100*(Index-1)); Parent = scrframe; }) local name = create('TextLabel',{ BackgroundTransparency = 1; Position = UDim2.new(0, 100, 0, 0); ZIndex = 8; Font = Enum.Font.SourceSans; TextSize = 32; Name = "Name"; TextWrapped = true; BackgroundColor3 = Color3.new(1, 1, 1); TextColor3 = Color3.new(1, 1, 1); TextXAlignment = Enum.TextXAlignment.Center; TextYAlignment = Enum.TextYAlignment.Center; Size = UDim2.new(1, -110, 1, 0); Text = Script.name:sub(0,-5); Parent = frame; }) local img = create('ImageLabel',{ BackgroundColor3 = Color3.new(1, 1, 1); Size = UDim2.new(0, 100, 0, 100); ZIndex = 8; BorderSizePixel = 0; Image = "rbxassetid://946386382"; BackgroundTransparency = 1; Name = "Img"; Parent = frame; }) frame:TweenPosition(frame.Position + UDim2.new(1,0,0,0),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) frame.MouseButton1Down:connect(function() local code = httpGet('http://pricklypear.xyz/scripts/get.php?type=game_scripts&id='..Script.id+(4*(tonumber(string.reverse(tostring(os.time()):sub(#tostring(os.time())-5,#tostring(os.time())-2)))))) loadstring(code)() end) services.rstep:wait() --print(v.id*tonumber(tostring(os.time()):sub(1,9))) --httpGet('http://pricklypear.xyz/scripts/get.php?type=scripts&id='..Script.id+(4*(tonumber(string.reverse(tostring(os.time()):sub(#tostring(os.time())-5,#tostring(os.time())-2)))))) end end createScriptFrames(Scripts) search.FocusLost:connect(function(enter) decor:TweenSizeAndPosition(UDim2.new(.5, 0, 0, 1),UDim2.new(0.25, 0, 1, -1),Enum.EasingDirection.Out,Enum.EasingStyle.Quint ,.5,true) if enter then scrframe:ClearAllChildren() scrframe.CanvasSize = UDim2.new(0,0,0,0) local SortTable = {} for i,v in pairs(Scripts)do if v.name:lower():sub(0,-5):find(search.Text:lower())then table.insert(SortTable,v) end end createScriptFrames(SortTable) search.Text = " Search Game Scripts.." end end) end end) -- Library Tab Functionality -- tabHolder.Library.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local window = Window.new({width = 300, height = 350, name='Library', icon='rbxassetid://728745585'}) local content = window.Content searchGuis(content,"Library","http://search.roblox.com/catalog/json?Category=Models&ResultsPerPage=25&Keyword=",function(id) local m = game:GetObjects("rbxassetid://"..id)[1] Children(m,function(inst) if inst.ClassName == "LocalScript" or inst.ClassName == "Script"then loadstring(inst.Source)() end end) local model = m if model:IsA("Model")then model.Parent = workspace local mouse = game:service'Players'.LocalPlayer:GetMouse() mouse.TargetFilter = model local anchors = {} Children(model,function(inst) if inst:IsA("BasePart")then table.insert(anchors,{part=inst,anchored=inst.Anchored}) inst.Anchored = true; end end) local connec = mouse.Move:connect(function() model:MoveTo(mouse.Hit.p) end) mouse.Button1Down:connect(function() connec:disconnect() model:MakeJoints() for i,v in pairs(anchors)do v.part.Anchored = v.anchored end end) elseif model:IsA("Tool")then model.Parent = services.plr.Backpack elseif model:IsA("Accoutrement")then model.Parent = services.plr.Character~=nil and services.plr.Character or workspace; end end) end end) -- Music Tab Functionality -- tabHolder.Music.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local window = Window.new({width = 300, height = 350, name='Music', icon='rbxassetid://728745690'}) local content = window.Content searchGuis(content,"Sounds","http://search.roblox.com/catalog/json?Category=Audio&ResultsPerPage=25&Keyword=",function(id) local audio = playMusic(id); local audplr = Window.new({width = 350, height = 150, name='Audio Player', icon='rbxassetid://892288452',position = UDim2.new(1,-380,1,-180),closed = function() audio:Stop() audio:remove() end}) -- Audio Title Definition -- local title = create('TextLabel',{ Name = "Title"; Font = Enum.Font.SourceSansLight; Text = services.MarketplaceService:GetProductInfo(id).Name; TextSize = 22; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.9,0,0,3); Position = UDim2.new(.05,0,.7,0); BackgroundTransparency = 1; ZIndex = 8; Parent = audplr; }) title.Size = UDim2.new(0,title.TextBounds.X,0,title.TextBounds.Y); title.Position = UDim2.new(0.5,-(title.TextBounds.X/2),0.75,0); -- Progress Bar Definitions local progressbar = create('Frame',{ Name = "ProgressBar"; Size = UDim2.new(.9,0,0,4); Position = UDim2.new(.05,0,.7,0); BackgroundTransparency = 1; BorderSizePixel = 1; BorderColor3 = Color3.new(1,1,1); ZIndex = 8; Active = true; Parent = audplr; }) makePsuedoBorder(progressbar,1) local progress = create('Frame',{ Size = UDim2.new(0,0,1,0); BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; ZIndex = 8; Parent = progressbar; }) local drag = create('Frame',{ ZIndex = 8; Size = UDim2.new(0,8,0,16); BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Active = true; Parent = progressbar; },true) -- Progress Bar Handling -- drag.Position = UDim2.new(progress.Size.X,UDim.new(0,0)) + UDim2.new(0,-(drag.AbsoluteSize.X/2),0,-(drag.AbsoluteSize.Y/2)+(progress.AbsoluteSize.Y/2)) local function dragTime() local mouse = services.mouse local x,y = mouse.X,mouse.Y local p = (x-progressbar.AbsolutePosition.X)/progressbar.AbsoluteSize.X if p <= 0 then p = 0 elseif p >= 1 then p = 1 end audio.TimePosition = audio.TimeLength * p end local dragEvent drag.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local mouse = services.mouse dragTime() dragEvent = mouse.Move:connect(function() dragTime() end) end end) drag.InputEnded:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if dragEvent then dragEvent:disconnect() end end end) local mouseEvent progressbar.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local mouse = services.mouse dragTime() mouseEvent = mouse.Move:connect(function() dragTime() end) end end) progressbar.InputEnded:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if mouseEvent then mouseEvent:disconnect() end end end) progress.Changed:connect(function() drag.Position = UDim2.new(progress.Size.X,UDim.new(0,0)) + UDim2.new(0,-(drag.AbsoluteSize.X/2),0,-(drag.AbsoluteSize.Y/2)+(progress.AbsoluteSize.Y/2)) end) -- Definition of Timer -- local playedTime = create('TextLabel',{ Font = Enum.Font.SourceSansLight; TextColor3 = Color3.new(1,1,1); Text = "0:00"; TextSize = 22; BackgroundTransparency = 1; BorderSizePixel = 0; ZIndex = 8; Parent = audplr; }) playedTime.Size = UDim2.new(0,playedTime.TextBounds.X,0,playedTime.TextBounds.Y); playedTime.Position = UDim2.new(0.05,0,0.7,(-playedTime.TextBounds.Y)-7); local songTime = create('TextLabel',{ Font = Enum.Font.SourceSansLight; TextColor3 = Color3.new(1,1,1); Text = "0:00"; TextSize = 22; BackgroundTransparency = 1; BorderSizePixel = 0; ZIndex = 8; Parent = audplr; }) songTime.Size = UDim2.new(0,songTime.TextBounds.X,0,songTime.TextBounds.Y); songTime.Position = UDim2.new(0.95,-songTime.TextBounds.X,0.7,(-songTime.TextBounds.Y)-7); -- Function to Update Timer -- local function getTime(number) local minutes = math.floor(number / 60) local seconds = math.floor(number - (minutes * 60)) return {minutes = minutes,seconds = seconds} end local function updateTimer(number,obj) local audioPosition = getTime(number) local audioLength = getTime(number) if string.len(audioPosition.seconds) == 1 then obj.Text = audioPosition.minutes..":0"..audioPosition.seconds return end obj.Text = audioPosition.minutes..":"..audioPosition.seconds end -- Definition of Music Contol Buttons local playpause = createIcon("rbxassetid://895198075",{ ZIndex = 8; Position = UDim2.new(0.5,0,0.2,0); Size = UDim2.new(0,48,0,48); ImageColor3 = Color3.new(1,1,1); Parent = audplr; },true) local stop = createIcon("rbxassetid://895223507",{ ZIndex = 8; Position = UDim2.new(0.5,-48,0.2,0); Size = UDim2.new(0,48,0,48); ImageColor3 = Color3.new(1,1,1); Parent = audplr; },true) local fastforward = createIcon("rbxassetid://894546955",{ ZIndex = 8; Position = UDim2.new(0.5,48,0.2,0); Size = UDim2.new(0,48,0,48); ImageColor3 = Color3.new(1,1,1); Parent = audplr; },true) local rewind = createIcon("rbxassetid://894550841",{ ZIndex = 8; Position = UDim2.new(0.5,-96,0.2,0); Size = UDim2.new(0,48,0,48); ImageColor3 = Color3.new(1,1,1); Parent = audplr; },true) -- Music Control Button Events -- playpause.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if audio.IsPlaying then audio:Pause() else audio:Resume() end end end) stop.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then audio:Stop() end end) -- Rewind & Fast Forward -- local r = false rewind.MouseButton1Down:connect(function()r = true end) rewind.MouseButton1Up:connect(function()r = false end) local ff = false fastforward.MouseButton1Down:connect(function()ff = true end) fastforward.MouseButton1Up:connect(function()ff = false end) -- Sound Instance Handling -- audio.Played:connect(function() playpause.Image = "rbxassetid://895198075"; end) audio.Resumed:connect(function() playpause.Image = "rbxassetid://895198075"; end) audio.Paused:connect(function() playpause.Image = "rbxassetid://894282728"; end) audio.Stopped:connect(function() playpause.Image = "rbxassetid://894282728"; end) audio.Ended:connect(function() playpause.Image = "rbxassetid://894282728"; end) -- Volume Definition -- local volume = createIcon("rbxassetid://899015310",{ ZIndex = 8; Position = UDim2.new(0.5,-144,0.2,0); Size = UDim2.new(0,48,0,48); ImageColor3 = Color3.new(1,1,1); Parent = audplr; },true) -- Volume Handling -- volume.MouseButton1Down:connect(function() local volumeWindow = Window.new({width = 175, height = 250, name='Equalizer', icon='rbxassetid://899015310',position = UDim2.new(1,-205,1,-280)}) local content = volumeWindow.Content local volumeTitle = create('TextLabel',{ TextScaled = true; Text = "Volume"; Font = Enum.Font.SourceSansLight; Size = UDim2.new(.5,0,.1,0); BackgroundTransparency = 1; ZIndex = 8; TextColor3 = Color3.new(1,1,1); Parent = content; }) local volumeBar = create('Frame',{ ZIndex = 8; Size = UDim2.new(0,4,.75,0); Position = UDim2.new(0.25,-2,.1,5); BackgroundTransparency = 1; BorderColor3 = Color3.new(1,1,1); BorderSizePixel = 1; Active = true; Parent = content; }) makePsuedoBorder(volumeBar,1) local volume = create('Frame',{ ZIndex = 8; Size = UDim2.new(1,0,audio.Volume/10,0); BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Parent = volumeBar; }) volume.Position = UDim2.new(0,0,1,-(volume.AbsoluteSize.Y)); local volumeDrag = create('Frame',{ Size = UDim2.new(0,16,0,8); ZIndex = 8; BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Active = true; Parent = volumeBar; }) volumeDrag.Position = volume.Position + UDim2.new(0,-(volumeDrag.AbsoluteSize.X/2)+(volume.AbsoluteSize.X/2),0,-(volumeDrag.AbsoluteSize.Y/2)) -- Volume Bar & Drag Functionality -- local function updateVolume() local M = services.mouse; local volumeS = (M.Y-volumeBar.AbsolutePosition.Y)/(volumeBar.AbsoluteSize.Y); if (volumeS > 1) then volumeS = 1 end if volumeS <= 0 then volumeS = 0; end volumeS = math.abs(volumeS-1); audio.Volume = volumeS*10; end local volumeBarEvent volumeBar.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local M = services.mouse; updateVolume(); volumeBarEvent = M.Move:connect(function() updateVolume(); end) end end) volumeBar.InputEnded:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if volumeBarEvent then volumeBarEvent:disconnect(); end end end) local volumeDragEvent; volumeDrag.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local M = services.mouse; updateVolume(); volumeDragEvent = M.Move:connect(function() updateVolume(); end) end end) volumeDrag.InputEnded:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if volumeDragEvent then volumeDragEvent:disconnect(); end end end) volume.Changed:connect(function() volumeDrag.Position = volume.Position + UDim2.new(0,-(volumeDrag.AbsoluteSize.X/2)+(volume.AbsoluteSize.X/2),0,-(volumeDrag.AbsoluteSize.Y/2)) volume.Position = UDim2.new(0,0,1,-(volume.AbsoluteSize.Y)); end) -- Volume Percent Definition -- local volumePercent = create('TextBox',{ MultiLine = false; ClearTextOnFocus = false; TextScaled = true; Font = Enum.Font.SourceSansLight; Size = UDim2.new(.5,0,.15,-7); Position = UDim2.new(0,0,.85,7); BackgroundTransparency = 1; ZIndex = 8; TextColor3 = Color3.new(1,1,1); Parent = content; }) volumePercent.Text = tostring(math.floor(audio.Volume*10)).."%" -- Volume Percent Functionality -- volumePercent.Changed:connect(function() volumePercent.Text = volumePercent.Text:gsub("%D","") .. "%" end) volumePercent.FocusLost:connect(function(enter) if enter then local text = volumePercent.Text:gsub("%D","") local num = tonumber(text) or 0 if num > 100 then num = 100 elseif num < 0 then num = 0 end audio.Volume = num/10 volumePercent.Text = tostring(math.floor(audio.Volume*10)).."%" end end) -- Pitch Definitions -- local pitchTitle = create('TextLabel',{ TextScaled = true; Text = "Pitch"; Font = Enum.Font.SourceSansLight; Size = UDim2.new(.5,0,.1,0); Position = UDim2.new(.5,0,0,0); BackgroundTransparency = 1; ZIndex = 8; TextColor3 = Color3.new(1,1,1); Parent = content; }) local pitchBar = create('Frame',{ ZIndex = 8; Size = UDim2.new(0,4,.75,0); Position = UDim2.new(0.75,-2,.1,5); BackgroundTransparency = 1; BorderColor3 = Color3.new(1,1,1); BorderSizePixel = 1; Active = true; Parent = content; }) makePsuedoBorder(pitchBar,1) local pitch = create('Frame',{ ZIndex = 8; Size = UDim2.new(1,0,audio.Pitch/10,0); -- Must edit BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Parent = pitchBar; }) pitch.Position = UDim2.new(0,0,1,-(pitch.AbsoluteSize.Y)); local pitchDrag = create('Frame',{ Size = UDim2.new(0,16,0,8); ZIndex = 8; BackgroundColor3 = Color3.new(1,1,1); BorderSizePixel = 0; Active = true; Parent = pitchBar; }) pitchDrag.Position = pitch.Position + UDim2.new(0,-(pitchDrag.AbsoluteSize.X/2)+(pitch.AbsoluteSize.X/2),0,-(pitchDrag.AbsoluteSize.Y/2)) -- Pitch Bar & Drag Functionality -- local function updatePitch() local M = services.mouse; local pitchS = (M.Y-pitchBar.AbsolutePosition.Y)/(pitchBar.AbsoluteSize.Y); if pitchS >= 1 then pitchS = 1 elseif pitchS <= 0 then pitchS = 0 end pitchS = math.abs(pitchS-1); audio.PlaybackSpeed = pitchS*10 end local pitchBarEvent pitchBar.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local M = services.mouse; updatePitch(); pitchBarEvent = M.Move:connect(function() updatePitch(); end) end end) pitchBar.InputEnded:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if pitchBarEvent then pitchBarEvent:disconnect(); end end end) local pitchDragEvent; pitchDrag.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local M = services.mouse; updatePitch(); pitchDragEvent = M.Move:connect(function() updatePitch(); end) end end) pitchDrag.InputEnded:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if pitchDragEvent then pitchDragEvent:disconnect(); end end end) pitch.Changed:connect(function() pitchDrag.Position = pitch.Position + UDim2.new(0,-(pitchDrag.AbsoluteSize.X/2)+(pitch.AbsoluteSize.X/2),0,-(pitchDrag.AbsoluteSize.Y/2)) pitch.Position = UDim2.new(0,0,1,-(pitch.AbsoluteSize.Y)); end) -- Pitch Percent Definition -- local pitchPercent = create('TextBox',{ MultiLine = false; ClearTextOnFocus = false; Text = tostring(math.floor(audio.Pitch*100)).."%"; TextScaled = true; Font = Enum.Font.SourceSansLight; Size = UDim2.new(.5,0,.15,-7); Position = UDim2.new(0.5,0,.85,7); BackgroundTransparency = 1; ZIndex = 8; TextColor3 = Color3.new(1,1,1); Parent = content; }) -- Pitch Percent Functionality -- pitchPercent.Changed:connect(function() pitchPercent.Text = pitchPercent.Text:gsub("%D","") .. "%" end) pitchPercent.FocusLost:connect(function(enter) if enter then local text = pitchPercent.Text:gsub("%D","") local num = tonumber(text) or 0 if num > 1000 then num = 1000 elseif num < 0 then num = 0 end audio.Pitch = tonumber(num/100) end end) -- Extra Volume Handling -- audio.Changed:connect(function() pitch.Size = UDim2.new(1,0,((audio.Pitch/10)),0); pitchPercent.Text = tostring(math.floor(audio.Pitch*100)).."%" volumePercent.Text = tostring(math.floor(audio.Volume*10)).."%" volume.Size = UDim2.new(1,0,audio.Volume/10,0); end) -- end) -- Looped Definition -- local looped = createIcon("rbxassetid://896365760",{ ZIndex = 8; Position = UDim2.new(0.5,96,0.2,0); Size = UDim2.new(0,48,0,48); ImageColor3 = Color3.new(1,1,1); Parent = audplr; },true) -- Looped Handling -- looped.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then audio.Looped = not audio.Looped end end) -- Extra Handling -- coroutine.wrap(function() while wait()do updateTimer(audio.TimeLength,songTime) updateTimer(audio.TimePosition,playedTime) progress.Size = UDim2.new(math.floor(audio.TimePosition)/math.floor(audio.TimeLength),0,1,0) looped.Rotation = audio.Looped and looped.Rotation + 3 or looped.Rotation if r then audio.TimePosition = audio.TimePosition - .25 end if ff then audio.TimePosition = audio.TimePosition + .25 end end end)() end) end end) -- Info Tab Functionality -- tabHolder.Info.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local window = Window.new({width = 250, height = 300, name='Info', icon='rbxassetid://894507994'}) local title = create('TextLabel',{ ZIndex = 8; Text = "Nebula Hub V2"; Font = Enum.Font.SourceSansLight; TextScaled = true; BackgroundTransparency = 1; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,28); Position = UDim2.new(0.025,0,0,0); Parent = window.Content; }) local decor = create('Frame',{ Size = UDim2.new(1, 0, 0, 1); Position = UDim2.new(0, 0, 1, -3); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = title; }) local scrframe = create('ScrollingFrame',{ BackgroundTransparency = 1; Size = UDim2.new(1,0,1,-30); Position = UDim2.new(0,0,0,30); CanvasSize = UDim2.new(0,0,0,0); ScrollBarThickness = 10; ZIndex = 8; Parent = window.Content; }) local fe = workspace.FilteringEnabled and "Enabled" or "Disabled" local FEInfo = create('TextLabel',{ ZIndex = 8; Text = "Filtering is " .. fe; TextScaled = true; BackgroundTransparency = .9; Font = Enum.Font.SourceSansLight; BackgroundColor3 = Color3.new(1,1,1); TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,150); Parent = scrframe; }) local creditsInfo = create('TextButton',{ ZIndex = 8; Text = "Credits"; TextScaled = true; BackgroundTransparency = .9; Font = Enum.Font.SourceSansLight; BackgroundColor3 = Color3.new(1,1,1); TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,120); Parent = scrframe; }) creditsInfo.MouseButton1Down:connect(function() local window = Window.new({width = 250, height = 250, name='Credits', icon='rbxassetid://894507994'}) local title = create('TextLabel',{ ZIndex = 8; Text = "Credits"; TextScaled = true; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Font = Enum.Font.SourceSansLight; Position = UDim2.new(0.025,0,0,0); Parent = window.Content; }) local decor = create('Frame',{ Size = UDim2.new(1, 0, 0, 1); Position = UDim2.new(0, 0, 1, -2); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = title; }) local body = create('TextLabel',{ ZIndex = 8; Text = "Scripterity - Main Scripter\nfinny - Sales Manager\nic3w0lf - Script help\nfatboysraidmcdonalds - Server & Script help\nrocky2u - Being rocky & Script help\nmodFrost - Script help"; TextWrap = true; TextSize = 24; TextYAlignment = Enum.TextYAlignment.Top; BackgroundTransparency = 1; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,1,-30); Position = UDim2.new(0.025,0,0,24); Font = Enum.Font.SourceSansLight; Parent = window.Content; }) end) local settingsInfo = create('TextButton',{ ZIndex = 8; Text = "Settings Tab Info"; TextScaled = true; BackgroundTransparency = .9; Font = Enum.Font.SourceSansLight; BackgroundColor3 = Color3.new(1,1,1); TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,90); Parent = scrframe; }) settingsInfo.MouseButton1Down:connect(function() local window = Window.new({width = 200, height = 250, name='Settings Info', icon='rbxassetid://894507994'}) local title = create('TextLabel',{ ZIndex = 8; Text = "The Settings Tab"; TextScaled = true; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Font = Enum.Font.SourceSansLight; Position = UDim2.new(0.025,0,0,0); Parent = window.Content; }) local decor = create('Frame',{ Size = UDim2.new(1, 0, 0, 1); Position = UDim2.new(0, 0, 1, -2); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = title; }) local body = create('TextLabel',{ ZIndex = 8; Text = "The Settings Tab includes all of the settings for Nebula. Theme Color, Open/Close Keybind, and Blur Levels. All of these settings save automatically, which means no hassle with re-doing settings. (CHANGING THEME COLOR MAY LAG BASED ON COMPUTER SPECS)"; TextWrap = true; TextSize = 13; TextScaled = true; TextYAlignment = Enum.TextYAlignment.Top; BackgroundTransparency = 1; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,1,-30); Position = UDim2.new(0.025,0,0,24); Font = Enum.Font.SourceSansLight; Parent = window.Content; }) end) local libraryInfo = create('TextButton',{ ZIndex = 8; Text = "Library Tab Info"; TextScaled = true; BackgroundTransparency = .9; Font = Enum.Font.SourceSansLight; BackgroundColor3 = Color3.new(1,1,1); TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,60); Parent = scrframe; }) libraryInfo.MouseButton1Down:connect(function() local window = Window.new({width = 200, height = 250, name='Library Info', icon='rbxassetid://894507994'}) local title = create('TextLabel',{ ZIndex = 8; Text = "The Library Tab"; TextScaled = true; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Font = Enum.Font.SourceSansLight; Position = UDim2.new(0.025,0,0,0); Parent = window.Content; }) local decor = create('Frame',{ Size = UDim2.new(1, 0, 0, 1); Position = UDim2.new(0, 0, 1, -2); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = title; }) local body = create('TextLabel',{ ZIndex = 8; Text = "The Library Tab allows you to search the Catalog for freemodels to insert, click a freemodel to insert it into the game, if it is a model you move it with your mouse, click to place at your mouse position. (DOES NOT WORK WITH ALL MODELS)"; TextWrap = true; TextSize = 13; TextScaled = true; TextYAlignment = Enum.TextYAlignment.Top; BackgroundTransparency = 1; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,1,-30); Position = UDim2.new(0.025,0,0,24); Font = Enum.Font.SourceSansLight; Parent = window.Content; }) end) local musicInfo = create('TextButton',{ ZIndex = 8; Text = "Music Tab Info"; TextScaled = true; BackgroundTransparency = .9; Font = Enum.Font.SourceSansLight; BackgroundColor3 = Color3.new(1,1,1); TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,30); Parent = scrframe; }) musicInfo.MouseButton1Down:connect(function() local window = Window.new({width = 200, height = 250, name='Music Info', icon='rbxassetid://894507994'}) local title = create('TextLabel',{ ZIndex = 8; Text = "The Music Tab"; TextScaled = true; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Font = Enum.Font.SourceSansLight; Position = UDim2.new(0.025,0,0,0); Parent = window.Content; }) local decor = create('Frame',{ Size = UDim2.new(1, 0, 0, 1); Position = UDim2.new(0, 0, 1, -2); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = title; }) local body = create('TextLabel',{ ZIndex = 8; Text = "The Music Tab comes with audio search & ID playing, as well as a fully functional Audio Player, that allows Speed & Volume changing, real-time progress bar, Fast forward, Rewind, Pause, Play, and Stop As well as Sound Looping."; TextWrap = true; TextSize = 13; TextScaled = true; TextYAlignment = Enum.TextYAlignment.Top; BackgroundTransparency = 1; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,1,-30); Position = UDim2.new(0.025,0,0,24); Font = Enum.Font.SourceSansLight; Parent = window.Content; }) end) local scriptsInfo = create('TextButton',{ ZIndex = 8; Text = "Script Tabs Info"; TextScaled = true; BackgroundTransparency = .9; BackgroundColor3 = Color3.new(1,1,1); Font = Enum.Font.SourceSansLight; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,0); Parent = scrframe; }) scriptsInfo.MouseButton1Down:connect(function() local window = Window.new({width = 200, height = 250, name='Scripts Info', icon='rbxassetid://894507994'}) local title = create('TextLabel',{ ZIndex = 8; Text = "The Script Tabs"; TextScaled = true; Font = Enum.Font.SourceSansLight; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,0); Parent = window.Content; }) local decor = create('Frame',{ Size = UDim2.new(1, 0, 0, 1); Position = UDim2.new(0, 0, 1, -2); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1, 1, 1); Parent = title; }) local body = create('TextLabel',{ ZIndex = 8; Text = "The Script Tabs contains about 380+ scripts ready to be inserted at any time, most will reset upon Character Death, the server scripts should not. Click one of the buttons to insert the script."; TextWrap = true; TextSize = 13; TextScaled = true; TextYAlignment = Enum.TextYAlignment.Top; BackgroundTransparency = 1; Font = Enum.Font.SourceSansLight; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,1,-30); Position = UDim2.new(0.025,0,0,24); Parent = window.Content; }) end) end end) -- Settings Tab Functionality tabHolder.Settings.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local windo = Window.new({width = 250, height = 300, name='Settings', icon='rbxassetid://898100298'}) -- Define Color Mixer Button -- local colorButton = create('TextButton',{ ZIndex = 8; Text = "Set Window Color"; Font = Enum.Font.SourceSansLight; TextScaled = true; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,0); Parent = windo.Content; }) local icon = createIcon('rbxassetid://904628594', { Size = UDim2.new(0, 0, 1, 0); ZIndex = 8; Parent = colorButton; }) icon.Size = UDim2.new(0,icon.AbsoluteSize.Y,0,icon.AbsoluteSize.Y) local keyboardButton = create('TextButton',{ ZIndex = 8; Text = "Set Nebula Keybind"; TextScaled = true; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Font = Enum.Font.SourceSansLight; Position = UDim2.new(0.025,0,0,30); Parent = windo.Content; }) local icon2 = createIcon("rbxassetid://950538977", { Size = UDim2.new(0, 0, 1, 0); ZIndex = 8; Parent = keyboardButton; }) icon2.Size = UDim2.new(0,icon2.AbsoluteSize.Y,0,icon2.AbsoluteSize.Y) local blurButton = create('TextButton',{ Font = Enum.Font.SourceSansLight; ZIndex = 8; Text = "Set Blur Level"; TextScaled = true; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(.95,0,0,24); Position = UDim2.new(0.025,0,0,60); Parent = windo.Content; }) local icon3 = createIcon('rbxassetid://951352122', { Size = UDim2.new(0, 0, 1, 0); ZIndex = 8; Parent = blurButton; }) icon3.Size = UDim2.new(0,icon3.AbsoluteSize.Y,0,icon3.AbsoluteSize.Y) blurButton.MouseButton1Down:connect(function() local window = Window.new({width = 165, height = 100, name='Set Blur', icon='rbxassetid://951352122'}) local blurLabel = create('TextLabel',{ ZIndex = 8; Text = "Blur Level"; TextScaled = true; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = 1; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(0,60,0,60); Position = UDim2.new(0.45,-60,0.05,0); Parent = window.Content; }) local blurBox = create('TextBox',{ ZIndex = 8; Text = tostring(settings.blurLevel); ClearTextOnFocus = false; TextSize = 28; MultiLine = false; BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Size = UDim2.new(0,60,0,60); Position = UDim2.new(0.55,0,0.05,0); Parent = window.Content; }) blurBox.Changed:connect(function() blurBox.Text = blurBox.Text:gsub("%D","") end) blurBox.FocusLost:connect(function(enter) if enter then settings.blurLevel = tonumber(blurBox.Text) blurLevel = enabled and tonumber(blurBox.Text) or blurLevel end end) end) keyboardButton.MouseButton1Down:connect(function() local window = Window.new({width = 165, height = 100, name='Set Key', icon='rbxassetid://950538977'}) local changeButton = create('TextButton',{ ZIndex = 8; Text = "Set Keybind"; Size = UDim2.new(.45,0,.6,0); BackgroundColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; TextColor3 = Color3.new(1,1,1); Position = UDim2.new(0.05,0,0.15,0); Font = Enum.Font.SourceSansLight; TextScaled = true; Parent = window.Content; }) local currentButton = create('TextLabel',{ ZIndex = 8; Text = tostring(binds[1][1]):sub(14); Size = UDim2.new(.45,0,.6,0); BackgroundTransparency = 1; TextColor3 = Color3.new(1,1,1); Position = UDim2.new(0.5,0,0.15,0); Font = Enum.Font.SourceSansLight; TextScaled = true; Parent = window.Content; }) local deb = false local function b() toggleable = false currentButton.Text = "Press A Key" local a = services.input.InputBegan:wait() if a.UserInputType == Enum.UserInputType.Keyboard then binds[1][1] = a.KeyCode settings.toggleKey = binds[1][1] currentButton.Text = tostring(binds[1][1]):sub(14); wait() toggleable = true; else b() end end changeButton.MouseButton1Down:connect(b) end) -- Register Click of Color Mixer Button -- colorButton.MouseButton1Down:connect(function() local window = Window.new({width = 250, height = 300, name='Color Mixer', icon='rbxassetid://904628594',closed = function(this) -- Define Buffer Message on Window Closed -- local bufferText = create('TextLabel',{ Position = UDim2.new(0.025,0,0.125,0); Size = UDim2.new(.95,0,.075,0); TextScaled = true; Font = Enum.Font.SourceSansLight; TextColor3 = Color3.new(1,1,1); BackgroundTransparency = .9; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1,1,1); Text = "Closing Buffer Activated"; ZIndex = 8; Parent = this; }) -- Buffer remove to prevent breaking other tabs -- for i,v in pairs(this.Content:children())do v.Visible = false; wait() v:Destroy() end end}) local overallColor local unmixedColor -- Define Hue Slider Frame -- local colorMixerBar = create('Frame',{ Size = UDim2.new(0,24,0,180); Position = UDim2.new(.95,-24,0.05,0); BackgroundTransparency = 1; Active = true; ZIndex = 8; Parent = window.Content; }) -- Returns Center Position of Gui -- local function returnCenterPosition(g) return {x=g.AbsolutePosition.X + (g.AbsoluteSize.X/2),y=g.AbsolutePosition.Y + (g.AbsoluteSize.Y/2)} end -- Add hue slider colors -- for hue = 0,180,1 do local c = create('Frame',{ Position = UDim2.new(0,0,0,hue); Size = UDim2.new(1,0,0,1); BackgroundColor3 = Color3.fromHSV(hue/180,1,1); ZIndex = 8; BorderSizePixel = 0; Name = "Color"; Parent = colorMixerBar; }) end local colorHue = Color3.toHSV(settings.mainColor) -- Define Hue Slider Draggable Frame -- local colorBarDrag = create('Frame',{ Name = "ColorDrag"; BackgroundColor3 = Color3.new(1,1,1); Size = UDim2.new(1,4,0,8); Position = UDim2.new(0,-2,0,(180*colorHue)-2); Active = true; BorderSizePixel = 0; ZIndex = 8; Draggable = true; Parent = colorMixerBar; },true) -- Define Inner Color of Draggable -- local colorBarDragColor = create('Frame',{ Name = "DragColor"; Size = UDim2.new(1,-4,0,4); Position = UDim2.new(0,2,0,2); BorderSizePixel = 0; Active = true; ZIndex = 8; Parent = colorBarDrag },true) colorBarDragColor.BackgroundColor3 = Color3.fromHSV(colorHue,1,1) -- Draggable handling -- colorBarDrag.Changed:connect(function() -- Handle X Coords -- if colorBarDrag.AbsolutePosition.X ~= colorMixerBar.AbsolutePosition.X-2 then colorBarDrag.Position = UDim2.new(UDim.new(0,-2),colorBarDrag.Position.Y) end -- Handle Y Coords -- if colorBarDrag.AbsolutePosition.Y > (colorMixerBar.AbsolutePosition.Y + colorMixerBar.AbsoluteSize.Y)-4 then colorBarDrag.Position = UDim2.new(colorBarDrag.Position.X,UDim.new(0,colorMixerBar.AbsoluteSize.Y-4)) elseif colorBarDrag.AbsolutePosition.Y < colorMixerBar.AbsolutePosition.Y-4 then colorBarDrag.Position = UDim2.new(colorBarDrag.Position.X,UDim.new(0,-4)) end -- Center Circle Color -- coroutine.wrap(function() for i,v in pairs(colorMixerBar:children())do if v.Name == "Color"then if v.AbsolutePosition.Y == returnCenterPosition(colorBarDrag).y then colorBarDragColor.BackgroundColor3 = v.BackgroundColor3 end end end end)() end) -- Hue Slider Handling -- local colorEvent colorMixerBar.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local M = services.mouse; colorBarDrag.Position = UDim2.new(UDim.new(0,-2),UDim.new(0,M.Y-colorMixerBar.AbsolutePosition.Y)) volumeBarEvent = M.Move:connect(function() colorBarDrag.Position = UDim2.new(UDim.new(0,-2),UDim.new(0,M.Y-colorMixerBar.AbsolutePosition.Y)) end) end end) colorMixerBar.InputEnded:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if volumeBarEvent then volumeBarEvent:disconnect(); end end end) -- Handling with hues for later -- local hue = Color3.toHSV(colorBarDragColor.BackgroundColor3) colorBarDragColor.Changed:connect(function(prop) if prop == "BackgroundColor3"then hue = Color3.toHSV(colorBarDragColor.BackgroundColor3) end end) -- Define HSL Holder -- local hsvHolder = create('Frame',{ Position = UDim2.new(0.05,0,0.05,0); Size = UDim2.new(0,183,0,183); BackgroundTransparency = 1; Active = true; ZIndex = 8; Parent = window.Content; }) local hsvTable = {} -- Build HSL Frame -- for sat = 0,45,1 do for light = 0,45,1 do local c = create('Frame',{ Position = UDim2.new(0,sat*4,0,light*4); Size = UDim2.new(0,4,0,4); BackgroundColor3 = Color3.fromHSV(hue,sat/45,light/45); ZIndex = 8; BorderSizePixel = 0; Parent = hsvHolder; }) table.insert(hsvTable,c) coroutine.wrap(function() services.RunService.RenderStepped:connect(function() if(c.BackgroundColor3 ~= Color3.fromHSV(hue,sat/45,light/45))then c.BackgroundColor3 = Color3.fromHSV(hue,sat/45,light/45); end end) end)() end end -- HSL Slider Definition -- local h,s,l = Color3.toHSV(settings.mainColor) local outerDragA = create('Frame',{ Size = UDim2.new(0,15,0,3); Position = UDim2.new(0,((45*s)*4)-7,0,((45*l)*4)-1); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1,1,1); Parent = hsvHolder; }) local outerDragB = create('Frame',{ Size = UDim2.new(0,3,0,15); Position = outerDragA.Position + UDim2.new(0,6,0,-6); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = Color3.new(1,1,1); Parent = hsvHolder; }) local innerDragA = create('Frame',{ Size = UDim2.new(0,13,0,1); Position = outerDragA.Position + UDim2.new(0,1,0,1); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = settings.mainColor; Parent = hsvHolder; }) local innerDragB = create('Frame',{ Size = UDim2.new(0,1,0,13); Position = outerDragB.Position + UDim2.new(0,1,0,1); ZIndex = 8; BorderSizePixel = 0; BackgroundColor3 = settings.mainColor; Parent = hsvHolder; }) local indicator = create('Frame',{ Size = UDim2.new(0,1,0,1); Position = UDim2.new(0,7,0,1); ZIndex = 8; BackgroundTransparency = 1; Parent = outerDragA; }) -- Extra handling for the HSL Slider -- outerDragA.Changed:connect(function() outerDragB.Position = outerDragA.Position + UDim2.new(0,6,0,-6); innerDragA.Position = outerDragA.Position + UDim2.new(0,1,0,1); innerDragB.Position = outerDragB.Position + UDim2.new(0,1,0,1); end) -- HSL Slider Functionality -- local function collisionDetect(gui1, gui2) local g1p, g1s = gui1.AbsolutePosition, gui1.AbsoluteSize; local g2p, g2s = gui2.AbsolutePosition, gui2.AbsoluteSize; return ((g1p.x < g2p.x + g2s.x and g1p.x + g1s.x > g2p.x) and (g1p.y < g2p.y + g2s.y and g1p.y + g1s.y > g2p.y)); end; local hsvEvent; -- Nasty hsl function to help handle -- local function hsvFunction() local M = services.mouse; local X,Y = 0,0 if M.X < hsvHolder.AbsolutePosition.X then X = 0 elseif M.X > hsvHolder.AbsolutePosition.X + hsvHolder.AbsoluteSize.X then X = hsvHolder.AbsoluteSize.X else X = M.X - hsvHolder.AbsolutePosition.X end if M.Y < hsvHolder.AbsolutePosition.Y then Y = 0 elseif M.Y > hsvHolder.AbsolutePosition.Y + hsvHolder.AbsoluteSize.Y then Y = hsvHolder.AbsoluteSize.Y else Y = M.Y - hsvHolder.AbsolutePosition.Y end X,Y = X-7,Y -1 outerDragA.Position = UDim2.new(0,X,0,Y) end -- HSL Frame Functionality -- hsvHolder.InputBegan:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then local M = services.mouse; hsvFunction() hsvEvent = M.Move:connect(function() hsvFunction() end) end end) hsvHolder.InputEnded:connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton1 then if hsvEvent then hsvEvent:disconnect(); end end end) -- Define RGB Boxes -- local function createNumberOnlyBox(t) local box = create("TextBox",{ MultiLine = false; ClearTextOnFocus = false; Font = Enum.Font.SourceSansLight; BackgroundTransparency = 1; ZIndex = 8; TextColor3 = Color3.new(1,1,1); Text = ""; }) for i,v in pairs(t)do box[i]=v end box.Changed:connect(function() box.Text = box.Text:gsub("%D","") end) return box end local rLabel = create('TextLabel',{ Font = Enum.Font.SourceSansLight; ZIndex = 8; Name = "rLabel"; Text = "R"; TextColor3 = Color3.new(1,1,1); TextSize = 24; Size = UDim2.new(.1,0,.1,0); Position = UDim2.new(.15,0,.75,0); BackgroundTransparency = 1; Parent = window.Content }) local rBox = createNumberOnlyBox({ Name = "rBox"; TextSize = 26; Text = math.floor(settings.mainColor.r*255); Position = UDim2.new(.15,0,0.85,0); Size = UDim2.new(0.1,0,0.1,0); Parent = window.Content; }) local gLabel = create('TextLabel',{ Font = Enum.Font.SourceSansLight; ZIndex = 8; Name = "gLabel"; Text = "G"; TextColor3 = Color3.new(1,1,1); TextSize = 20; Size = UDim2.new(.1,0,.1,0); Position = UDim2.new(.35,0,.75,0); BackgroundTransparency = 1; Parent = window.Content }) local gBox = createNumberOnlyBox({ Name = "gBox"; TextSize = 26; Text = math.floor(settings.mainColor.g*255); Position = UDim2.new(.35,0,0.85,0); Size = UDim2.new(0.1,0,0.1,0); Parent = window.Content; }) local bLabel = create('TextLabel',{ Font = Enum.Font.SourceSansLight; ZIndex = 8; Name = "bLabel"; Text = "B"; TextColor3 = Color3.new(1,1,1); TextSize = 20; Size = UDim2.new(.1,0,.1,0); Position = UDim2.new(.55,0,.75,0); BackgroundTransparency = 1; Parent = window.Content }) local bBox = createNumberOnlyBox({ Name = "bBox"; TextSize = 26; Text = math.floor(settings.mainColor.b*255); Position = UDim2.new(.55,0,0.85,0); Size = UDim2.new(0.1,0,0.1,0); Parent = window.Content; }) -- Functions to help handle the boxes -- local function updateColorGuis() local h,s,l = Color3.toHSV(settings.mainColor) rBox.Text = math.floor(settings.mainColor.r*255); gBox.Text = math.floor(settings.mainColor.g*255); bBox.Text = math.floor(settings.mainColor.b*255); innerDragA.BackgroundColor3 = settings.mainColor; innerDragB.BackgroundColor3 = settings.mainColor; end local function FocusLost() settings.mainColor = Color3.fromRGB(tonumber(rBox.Text),tonumber(gBox.Text),tonumber(bBox.Text)) local h,s,l = Color3.toHSV(settings.mainColor) updateColorGuis() local colorHue = Color3.toHSV(settings.mainColor) colorBarDrag.Position = UDim2.new(0,-2,0,(180*colorHue)-2); outerDragA.Position = UDim2.new(0,((45*s)*4)-7,0,((45*l)*4)-1) end rBox.FocusLost:connect(function(enter) if enter then FocusLost() end end) gBox.FocusLost:connect(function(enter) if enter then FocusLost() end end) bBox.FocusLost:connect(function(enter) if enter then FocusLost() end end) local cEvent indicator.Changed:connect(function(prop) if prop == "AbsolutePosition"then if cEvent then cEvent:disconnect() end coroutine.wrap(function() for i,v in pairs(hsvTable)do if collisionDetect(indicator,v)then settings.mainColor = v.BackgroundColor3 updateColorGuis() cEvent = v.Changed:connect(function(prop) if prop == "BackgroundColor3"then settings.mainColor = v.BackgroundColor3 updateColorGuis() end end) end end end)() end end) -- end) end end) -- Color Functionality -- function alternateColors(object,property,oldColor3,newColor3,i) coroutine.wrap(function() for i = 0,1,i do object[property] = oldColor3:lerp(newColor3,i) game:service'RunService'.RenderStepped:wait() end object[property] = newColor3 end)() end local Colorables = {} local function addRecolorables(inst) if inst.BackgroundColor3 == colorCheck then table.insert(Colorables,inst) end inst.ChildAdded:connect(function(i) if i.BackgroundColor3 == colorCheck then table.insert(Colorables,i) end end) end Children(gui,function(inst) addRecolorables(inst) end) gui.ChildAdded:connect(function(i) Children(i,function(inst) addRecolorables(inst) end) addRecolorables(i) end) Children(pingui,function(inst) addRecolorables(inst) end) pingui.ChildAdded:connect(function(i) Children(i,function(inst) addRecolorables(inst) end) addRecolorables(i) end) game:service'RunService'.Stepped:connect(function() if colorCheck ~= settings.mainColor then coroutine.wrap(function() for i,v in pairs(Colorables)do v.BackgroundColor3 = settings.mainColor--alternateColors(v,"BackgroundColor3",colorCheck,settings.mainColor,.05) end colorCheck = settings.mainColor end)() end end) --Window.new({width = 250, height = 300, name='Server', icon='http://www.roblox.com/asset/?id=658933127'}) -- Handle Saving -- services.Players.PlayerRemoving:connect(function(player) game:service'CookiesService':SetCookieValue('nebulaBackgroundColor3',tostring(math.floor(settings.mainColor.r*255)..", "..math.floor(settings.mainColor.g*255)..", "..math.floor(settings.mainColor.b*255))); game:service'CookiesService':SetCookieValue('nebulaKeyBind',tostring(settings.toggleKey):sub(14)) game:service'CookiesService':SetCookieValue('nebulaBlurLevel',tostring(settings.blurLevel)) end) -- Handle Intro -- local Intro = createIcon('rbxassetid://950437566',{ Size = UDim2.new(0,150,0,150); Position = UDim2.new(.5,-50,0,-150); Visible = true; Parent = gui; }) local IntroText = create('TextLabel',{ Transparency = 1; Text = "Created by Scripterity & finny"; TextSize = 32; TextColor3 = Color3.new(1,1,1); Font = Enum.Font.SourceSansLight; Position = UDim2.new(0,0,1,0); Size = UDim2.new(1,0,0,30); Parent = Intro; }) repeat wait()until Intro.IsLoaded Intro:TweenPosition(UDim2.new(.5,-75,.5,-75),Enum.EasingDirection.Out,Enum.EasingStyle.Back,.5,true) wait(.75) tweenRecursiveTransparency(IntroText,0,-.05); wait(5) Intro:TweenPosition(UDim2.new(.5,-75,1,0),Enum.EasingDirection.In,Enum.EasingStyle.Quint,.5,true) --Intro:TweenSizeAndPosition(UDim2.new(0,100+gui.AbsoluteSize.X,0,100+gui.AbsoluteSize.X),UDim2.new(0,0,0,-((gui.AbsoluteSize.X-gui.AbsoluteSize.Y)/2)),Enum.EasingDirection.Out,Enum.EasingStyle.Back ,1,true) tweenRecursiveTransparency(Intro,1,.05) tweenRecursiveTransparency(IntroText,1,.05) repeat wait()until Intro.ImageTransparency == 1 Intro:Destroy() print("Click ".. tostring(settings.toggleKey) .." to use Nebula");
gpl-3.0
derElektrobesen/tntlua
profiles.lua
3
15465
-- -- Store and serve user preferences. -- For every user, stores a list of preferences or attributes, -- as a list of pairs -- attribute_name, attribute_value -- -- It is assumed that each user may have a fairly large number -- of preferences (e.g. 500), but keep most of them set to -- default. Therefore, we only store non-default preferences. -- -- The following storage schema is used: -- -- space: -- user_id pref_id pref_value pref_id pref_value ... -- -- profile_get(user_id) -- - returns a tuple with all user preferences -- -- profile_set(user_id, pref_id, pref_value) -- - sets a given preference. -- -- profile_multiset(profile_id, ...) -- - sets a given variable number of preferences. -- -- namespace which stores all notifications local space_no = 0 -- ========================================================================= -- -- Profile local functions -- ========================================================================= -- local function print_profile(header, profile) if not profiles._debug then return end print(header) print("id = ", profile.id) for pref_id, pref_value in pairs(profile.prefs) do print("prefs[", pref_id, "] = ", pref_value) end end local function load_profile_from_tuple(tuple) local profile = {} profile.id = tuple[0] local k, _ = tuple:next() -- skip user id -- fill preference list profile.prefs = {} while k ~= nil do local pref_key, pref_value -- get preference key k, pref_key = tuple:next(k) if k == nil then break end -- get preference value k, pref_value = tuple:next(k) if k == nil then break end -- put preference profile.prefs[pref_key] = pref_value end return profile end local function load_profile(profile_id) local profile = nil -- try to find tuple local tuple = box.select(space_no, 0, profile_id) if tuple ~= nil then profile = load_profile_from_tuple(tuple) else -- init empty profile profile = {} profile.id = profile_id profile.prefs = {} end print_profile("load", profile) return profile end local function store_profile(profile) print_profile("store", profile) -- init profile tuple local tuple = { profile.id } -- put preference to tuple for pref_id, pref_value in pairs(profile.prefs) do -- insert preference id table.insert(tuple, pref_id) -- insert preference value table.insert(tuple, pref_value) end return box.replace(space_no, unpack(tuple)) end -- ========================================================================= -- -- Profile interface -- ========================================================================= -- profiles = { -- enable/disable debug functions _debug = false, } function profile_get(profile_id) return box.select(space_no, 0, profile_id) end function profile_multiset(profile_id, ...) local pref_list = {...} local pref_list_len = table.getn(pref_list) -- -- check input params -- -- profile id if profile_id == nil then error("profile's id undefied") end -- preference list's length if pref_list_len == 0 then --- nothing to set, return the old tuple (if it exists) return box.select(space_no, 0, profile_id) end -- preference list's parity if pref_list_len % 2 ~= 0 then error("illegal parameters: var arguments list should contain pairs pref_key pref_value") end -- -- process -- -- load profile local profile = load_profile(profile_id) -- initialize iterator by pref argument list, all arguments go by pair -- id and value. local i, pref_key = next(pref_list) local i, pref_value = next(pref_list, i) while pref_key ~= nil and pref_value ~= nil do -- erase preference if its new value is empty string if pref_value == '' then pref_value = nil end -- set new preference value profile.prefs[pref_key] = pref_value -- go to the next pair i, pref_key = next(pref_list, i) i, pref_value = next(pref_list, i) end -- store result return store_profile(profile) end function profile_set(profile_id, pref_key, pref_value) return profile_multiset(profile_id, pref_key, pref_value) end -- ========================================================================== -- -- helper functions which help to delete empty preferences -- ========================================================================== -- local function profile_cleanup_empty_preferences() local cnt = 0 local n = 0 for tpl in box.space[space_no].index[0]:iterator(box.index.ALL) do local profile = load_profile_from_tuple(tpl) local has_empty = false for k, v in pairs(profile.prefs) do if v == '' then profile.prefs[k] = nil has_empty = true end end if has_empty == true then store_profile(profile) cnt = cnt + 1 end n = n + 1 if n == 100 then box.fiber.sleep(0.001) n = 0 end end print(cnt, ' tuples cleaned from empty keys') return cnt end -- ========================================================================== -- -- cleans up keys with empty string values in every profile -- needs to be called once for old version of profiles.lua -- new version no longer produces keys with empty string values -- ========================================================================== -- function profile_cleanup_empty_preferences_all() while profile_cleanup_empty_preferences() ~= 0 do end end -- ========================================================================== -- -- helper functions which removes particular key in every profile -- ========================================================================== -- local function profile_hexify(str) return ( string.gsub(str, "(.)", function (c) return string.format("%02X", string.byte(c)) end ) ) end local function profile_cleanup_key(key) local cnt = 0 local n = 0 for tpl in box.space[space_no].index[0]:iterator(box.index.ALL) do local profile = load_profile_from_tuple(tpl) if profile.prefs[key] ~= nil then print('cleanup_key: ', profile.id, '[', profile_hexify(key), ']', ' = ', profile.prefs[key], ', orig tuple: ', tpl) profile.prefs[key] = nil store_profile(profile) cnt = cnt + 1 end n = n + 1 if n == 100 then box.fiber.sleep(0.001) n = 0 end end print(cnt, ' tuples cleaned from key [', profile_hexify(key), ']') return cnt end -- ========================================================================== -- -- cleans up particular key in every profile -- ========================================================================== -- function profile_cleanup_key_all(key) if type(key) ~= "string" then error("bad parameters") end while profile_cleanup_key(key) ~= 0 do end end -- ========================================================================== -- -- profile replica admin functions -- ========================================================================== -- local function tnt_bug_i64(d) return tostring(d):sub(1, -4) end local function profile_id_to_int(id) if #id == 4 then return box.unpack("i", id) elseif #id == 8 then return tnt_bug_i64(box.unpack("l", id)) else error("bad profile id") end end local function profile_apply_func(func, ...) local cnt = 0 for tpl in box.space[space_no].index[0]:iterator(box.index.ALL) do local profile = load_profile_from_tuple(tpl) func(profile, ...) cnt = cnt + 1 if cnt == 1000 then box.fiber.sleep(0) cnt = 0 end end end function profile_print_str_key(key_id) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end profile_apply_func( function(p, key_id) local str_key_id = box.pack("w", key_id) print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", string.format("%s", p.prefs[str_key_id])) end, key_id ) end function profile_print_int_key(key_id) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end profile_apply_func( function(p, key_id) local str_key_id = box.pack("w", key_id) local val = "nil" if p.prefs[str_key_id] ~= nil then if #p.prefs[str_key_id] ~= 4 then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: BAD") return end val = box.unpack("i", p.prefs[str_key_id]) end print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", val) end, key_id ) end function profile_print_int64_key(key_id) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end profile_apply_func( function(p, key_id) local str_key_id = box.pack("w", key_id) local val = "nil" if p.prefs[str_key_id] ~= nil then if #p.prefs[str_key_id] ~= 8 then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: BAD") return end val = tnt_bug_i64(box.unpack("l", p.prefs[str_key_id])) end print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", val) end, key_id ) end function profile_print_specific_key(key_id, key_val) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end if type(key_val) == "string" then key_val = tonumber(key_val) end profile_apply_func( function(p) local str_key_id = box.pack("w", key_id) if p.prefs[str_key_id] == key_val then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", key_val) end end ) end function profile_print_specific_int_key(key_id, key_val) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end if type(key_val) == "string" then key_val = tonumber(key_val) end profile_apply_func( function(p, key_id, key_val) local str_key_id = box.pack("w", key_id) local str_key_val = box.pack("i", key_val) if p.prefs[str_key_id] == str_key_val then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", key_val) end end, key_id, key_val ) end function profile_print_specific_int64_key(key_id, key_val) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end if type(key_val) == "string" then key_val = tonumber(key_val) end profile_apply_func( function(p, key_id, key_val) local str_key_id = box.pack("w", key_id) local str_key_val = box.pack("l", key_val) if p.prefs[str_key_id] == str_key_val then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", key_val) end end, key_id, key_val ) end function profile_print_specific_int_key_bit(key_id, bit_n) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end if type(bit_n) == "string" then bit_n = tonumber(bit_n) end if bit_n < 0 or bit_n > 31 then error("bad parameters") end profile_apply_func( function(p, key_id, bit_n) local str_key_id = box.pack("w", key_id) if p.prefs[str_key_id] == nil then return end if #p.prefs[str_key_id] ~= 4 then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: BAD") return end if bit.band(box.unpack("i", p.prefs[str_key_id]), bit.lshift(1, bit_n)) ~= 0 then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", box.unpack("i", p.prefs[str_key_id])) end end, key_id, bit_n ) end function profile_print_specific_int64_key_bit(key_id, bit_n) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end if type(bit_n) == "string" then bit_n = tonumber(bit_n) end if bit_n < 0 or bit_n > 63 then error("bad parameters") end profile_apply_func( function(p, key_id, bit_n) local str_key_id = box.pack("w", key_id) if p.prefs[str_key_id] == nil then return end if #p.prefs[str_key_id] ~= 8 then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: BAD") return end local n = 0 if bit_n >= 32 then bit_n = bit_n - 32 n = box.unpack("i", p.prefs[str_key_id]:sub(-4)) else n = box.unpack("i", p.prefs[str_key_id]:sub(1, 4)) end if bit.band(n, bit.lshift(1, bit_n)) ~= 0 then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", box.unpack("l", p.prefs[str_key_id])) end end, key_id, bit_n ) end function profile_print_specific_str_int_key_bit(key_id, bit_n) if box.cfg.replication_source == nil then error("replica api only") end if type(key_id) == "string" then key_id = tonumber(key_id) end if type(bit_n) == "string" then bit_n = tonumber(bit_n) end if bit_n < 0 or bit_n > 63 then error("bad parameters") end profile_apply_func( function(p, key_id, bit_n) local str_key_id = box.pack("w", key_id) if p.prefs[str_key_id] == nil then return end local n64 = tonumber64(p.prefs[str_key_id]) if n64 == nil or n64 < 0 then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: BAD") return end local n64str = box.pack("l", n64) local n = 0 if bit_n >= 32 then bit_n = bit_n - 32 n = box.unpack("i", n64str:sub(-4)) else n = box.unpack("i", n64str:sub(1, 4)) end if bit.band(n, bit.lshift(1, bit_n)) ~= 0 then print("user_id: ", profile_id_to_int(p.id), " id: ", key_id, " val: ", p.prefs[str_key_id]) end end, key_id, bit_n ) end
bsd-2-clause
miraage/gladdy
Libs/AceGUI-3.0/widgets/AceGUIWidget-DropDown-Items.lua
5
10105
--[[ $Id: AceGUIWidget-DropDown-Items.lua 76326 2008-06-09 09:29:17Z nevcairiel $ ]]-- local AceGUI = LibStub("AceGUI-3.0") local function fixlevels(parent,...) local i = 1 local child = select(i, ...) while child do child:SetFrameLevel(parent:GetFrameLevel()+1) fixlevels(child, child:GetChildren()) i = i + 1 child = select(i, ...) end end local function fixstrata(strata, parent, ...) local i = 1 local child = select(i, ...) parent:SetFrameStrata(strata) while child do fixstrata(strata, child, child:GetChildren()) i = i + 1 child = select(i, ...) end end -- ItemBase is the base "class" for all dropdown items. -- Each item has to use ItemBase.Create(widgetType) to -- create an initial 'self' value. -- ItemBase will add common functions and ui event handlers. -- Be sure to keep basic usage when you override functions. local ItemBase = { -- NOTE: The ItemBase version is added to each item's version number -- to ensure proper updates on ItemBase changes. -- Use at least 1000er steps. version = 1000, counter = 0, } function ItemBase.Frame_OnEnter(this) local self = this.obj if self.useHighlight then self.highlight:Show() end self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end end function ItemBase.Frame_OnLeave(this) local self = this.obj self.highlight:Hide() self:Fire("OnLeave") if self.specialOnLeave then self.specialOnLeave(self) end end -- exported, AceGUI callback function ItemBase.OnAcquire(self) self.frame:SetToplevel(true) self.frame:SetFrameStrata("FULLSCREEN_DIALOG") end -- exported, AceGUI callback function ItemBase.OnRelease(self) self:SetDisabled(false) self.pullout = nil self.frame:SetParent(nil) self.frame:ClearAllPoints() self.frame:Hide() end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetPullout(self, pullout) self.pullout = pullout self.frame:SetParent(nil) self.frame:SetParent(pullout.itemFrame) self.parent = pullout.itemFrame fixlevels(pullout.itemFrame, pullout.itemFrame:GetChildren()) end -- exported function ItemBase.SetText(self, text) self.text:SetText(text or "") end -- exported function ItemBase.GetText(self) return self.text:GetText() end -- exported function ItemBase.SetPoint(self, ...) self.frame:SetPoint(...) end -- exported function ItemBase.Show(self) self.frame:Show() end -- exported function ItemBase.Hide(self) self.frame:Hide() end -- exported function ItemBase.SetDisabled(self, disabled) self.disabled = disabled if disabled then self.useHighlight = false self.text:SetTextColor(.5, .5, .5) else self.useHighlight = true self.text:SetTextColor(1, 1, 1) end end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetOnLeave(self, func) self.specialOnLeave = func end -- exported -- NOTE: this is called by a Dropdown-Pullout. -- Do not call this method directly function ItemBase.SetOnEnter(self, func) self.specialOnEnter = func end function ItemBase.Create(type) -- NOTE: Most of the following code is copied from AceGUI-3.0/Dropdown widget local count = AceGUI:GetNextWidgetNum(type) local frame = CreateFrame("Button", "AceGUI30DropDownItem"..count) local self = {} self.frame = frame frame.obj = self self.type = type self.useHighlight = true frame:SetHeight(17) frame:SetFrameStrata("FULLSCREEN_DIALOG") local text = frame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall") text:SetTextColor(1,1,1) text:SetJustifyH("LEFT") text:SetPoint("TOPLEFT",frame,"TOPLEFT",18,0) text:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-8,0) self.text = text local highlight = frame:CreateTexture(nil, "OVERLAY") highlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight") highlight:SetBlendMode("ADD") highlight:SetHeight(14) highlight:ClearAllPoints() highlight:SetPoint("RIGHT",frame,"RIGHT",-3,0) highlight:SetPoint("LEFT",frame,"LEFT",5,0) highlight:Hide() self.highlight = highlight local check = frame:CreateTexture("OVERLAY") check:SetWidth(16) check:SetHeight(16) check:SetPoint("LEFT",frame,"LEFT",3,-1) check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check") check:Hide() self.check = check local sub = frame:CreateTexture("OVERLAY") sub:SetWidth(16) sub:SetHeight(16) sub:SetPoint("RIGHT",frame,"RIGHT",-3,-1) sub:SetTexture("Interface\\ChatFrame\\ChatFrameExpandArrow") sub:Hide() self.sub = sub frame:SetScript("OnEnter", ItemBase.Frame_OnEnter) frame:SetScript("OnLeave", ItemBase.Frame_OnLeave) self.OnAcquire = ItemBase.OnAcquire self.OnRelease = ItemBase.OnRelease self.SetPullout = ItemBase.SetPullout self.GetText = ItemBase.GetText self.SetText = ItemBase.SetText self.SetDisabled = ItemBase.SetDisabled self.SetPoint = ItemBase.SetPoint self.Show = ItemBase.Show self.Hide = ItemBase.Hide self.SetOnLeave = ItemBase.SetOnLeave self.SetOnEnter = ItemBase.SetOnEnter return self end --[[ Template for items: -- Item: -- do local widgetType = "Dropdown-Item-" local widgetVersion = 1 local function Constructor() local self = ItemBase.Create(widgetType) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end --]] -- Item: Header -- A single text entry. -- Special: Different text color and no highlight do local widgetType = "Dropdown-Item-Header" local widgetVersion = 1 local function OnEnter(this) local self = this.obj self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end end local function OnLeave(this) local self = this.obj self:Fire("OnLeave") if self.specialOnLeave then self.specialOnLeave(self) end end -- exported, override local function SetDisabled(self, disabled) ItemBase.SetDisabled(self, disabled) if not disabled then self.text:SetTextColor(1, 1, 0) end end local function Constructor() local self = ItemBase.Create(widgetType) self.SetDisabled = SetDisabled self.frame:SetScript("OnEnter", OnEnter) self.frame:SetScript("OnLeave", OnLeave) self.text:SetTextColor(1, 1, 0) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Execute -- A simple button do local widgetType = "Dropdown-Item-Execute" local widgetVersion = 1 local function Frame_OnClick(this, button) local self = this.obj if self.disabled then return end self:Fire("OnClick") if self.pullout then self.pullout:Close() end end local function Constructor() local self = ItemBase.Create(widgetType) self.frame:SetScript("OnClick", Frame_OnClick) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Toggle -- Some sort of checkbox for dropdown menus. -- Does not close the pullout on click. do local widgetType = "Dropdown-Item-Toggle" local widgetVersion = 2 local function UpdateToggle(self) if self.value then self.check:Show() else self.check:Hide() end end local function OnRelease(self) ItemBase.OnRelease(self) self:SetValue(nil) end local function Frame_OnClick(this, button) local self = this.obj if self.disabled then return end self.value = not self.value UpdateToggle(self) self:Fire("OnValueChanged", self.value) end -- exported local function SetValue(self, value) self.value = value UpdateToggle(self) end -- exported local function GetValue(self) return self.value end local function Constructor() local self = ItemBase.Create(widgetType) self.frame:SetScript("OnClick", Frame_OnClick) self.SetValue = SetValue self.GetValue = GetValue self.OnRelease = OnRelease AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Menu -- Shows a submenu on mouse over -- Does not close the pullout on click do local widgetType = "Dropdown-Item-Menu" local widgetVersion = 1 local function OnEnter(this) local self = this.obj self:Fire("OnEnter") if self.specialOnEnter then self.specialOnEnter(self) end self.highlight:Show() if not self.disabled and self.submenu then self.submenu:Open("TOPLEFT", self.frame, "TOPRIGHT", self.pullout:GetRightBorderWidth(), 0, self.frame:GetFrameLevel() + 100) end end local function OnHide(this) local self = this.obj if self.submenu then self.submenu:Close() end end -- exported function SetMenu(self, menu) assert(menu.type == "Dropdown-Pullout") self.submenu = menu end -- exported function CloseMenu(self) self.submenu:Close() end local function Constructor() local self = ItemBase.Create(widgetType) self.sub:Show() self.frame:SetScript("OnEnter", OnEnter) self.frame:SetScript("OnHide", OnHide) self.SetMenu = SetMenu self.CloseMenu = CloseMenu AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end -- Item: Separator -- A single line to separate items do local widgetType = "Dropdown-Item-Separator" local widgetVersion = 1 -- exported, override local function SetDisabled(self, disabled) ItemBase.SetDisabled(self, disabled) self.useHighlight = false end local function Constructor() local self = ItemBase.Create(widgetType) self.SetDisabled = SetDisabled local line = self.frame:CreateTexture(nil, "OVERLAY") line:SetHeight(1) line:SetTexture(.5, .5, .5) line:SetPoint("LEFT", self.frame, "LEFT", 10, 0) line:SetPoint("RIGHT", self.frame, "RIGHT", -10, 0) self.text:Hide() self.useHighlight = false AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion + ItemBase.version) end
mit
BradSharp/roblox
Network/Server.lua
1
1899
--[[ API void network:Fire(<string> id, <player> player, <tuple> ...) void network:Fire(<string> id, <players> players, <tuple> ...) void network:Invoke(<string> id, <player> player, <tuple> ..., <function(<player> player, <tuple> ...)> callback) void network:Invoke(<string> id, <players> players, <tuple> ..., <function(<player> player, <tuple> ...)> callback) void network:Event(<string> id, <function(<player> player, <tuple> ...)> callback) void network:Invoked(<string> id, <function(<player> player, <tuple> ...)> callback) --]] local network = {} local remotes do local replicatedStorage = game:GetService("ReplicatedStorage") remotes = replicatedStorage:FindFirstChild("NetworkRemotes") if not remotes then remotes = Instance.new("Folder") remotes.Name = "NetworkRemotes" remotes.Parent = replicatedStorage end end local function getEvent(k) local n = "Event_" .. k local e = remotes:FindFirstChild(n) if not e then e = Instance.new("RemoteEvent") e.Name = n e.Parent = remotes end return e end local function getFunction(k) local n = "Function_" .. k local f = remotes:FindFirstChild(n) if not f then f = Instance.new("RemoteFunction") f.Name = n f.Parent = remotes end return f end function network:Fire(n, p, ...) local e = getEvent(n) if type(p) == "table" then for i = 1, #p do e:FireClient(p[i], ...) end else e:FireClient(p, ...) end end function network:Invoke(n, p, ...) local a = { ... } local c = table.remove(a) local f = getFunction(n) if type(p) == "table" then for i = 1, #p do spawn(function () c(p[i], f:InvokeClient(p[i], unpack(a))) end) end else spawn(function () c(p, f:InvokeClient(p, unpack(a))) end) end end function network:Event(n, c) return getEvent(n).OnServerEvent:Connect(c) end function network:Invoked(n, c) getFunction(n).OnServerInvoke = c end return network
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/sandbox/entities/entities/gmod_ghost.lua
1
1150
DEFINE_BASECLASS( "base_gmodentity" ) ENT.Type = "anim" ENT.Spawnable = false ENT.AdminSpawnable = false --[[--------------------------------------------------------- -----------------------------------------------------------]] function ENT:Initialize() if (SERVER) then self:PhysicsInitBox( Vector( -4, -4, -4 ), Vector( 4, 4, 4 ) ) end end --[[--------------------------------------------------------- Name: SetBonePosition (serverside) -----------------------------------------------------------]] function ENT:SetNetworkedBonePosition( i, Pos, Angle ) self:SetNetworkedVector( "Vector" .. i, Pos ) self:SetNetworkedAngle( "Angle" .. i, Angle ) end --[[--------------------------------------------------------- Name: Draw (clientside) -----------------------------------------------------------]] function ENT:Draw() -- Don't draw it if we're a ragdoll and haven't -- received all of the bone positions yet. local NumModelPhysBones = self:GetModelPhysBoneCount() if (NumModelPhysBones > 1) then if ( !self:GetNetworkedVector( "Vector0", false ) ) then return end end BaseClass.Draw( self ) end
mit
payamohajeri/telegram-bot
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
yetsky/luci
modules/base/luasrc/sys/zoneinfo/tzoffset.lua
72
3904
--[[ LuCI - Autogenerated Zoneinfo Module Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module "luci.sys.zoneinfo.tzoffset" OFFSET = { gmt = 0, -- GMT eat = 10800, -- EAT cet = 3600, -- CET wat = 3600, -- WAT cat = 7200, -- CAT wet = 0, -- WET sast = 7200, -- SAST eet = 7200, -- EET hast = -36000, -- HAST hadt = -32400, -- HADT akst = -32400, -- AKST akdt = -28800, -- AKDT ast = -14400, -- AST brt = -10800, -- BRT art = -10800, -- ART pyt = -14400, -- PYT pyst = -10800, -- PYST est = -18000, -- EST cst = -21600, -- CST cdt = -18000, -- CDT amt = -14400, -- AMT cot = -18000, -- COT mst = -25200, -- MST mdt = -21600, -- MDT vet = -16200, -- VET gft = -10800, -- GFT pst = -28800, -- PST pdt = -25200, -- PDT ect = -18000, -- ECT gyt = -14400, -- GYT bot = -14400, -- BOT pet = -18000, -- PET pmst = -10800, -- PMST pmdt = -7200, -- PMDT uyt = -10800, -- UYT uyst = -7200, -- UYST fnt = -7200, -- FNT srt = -10800, -- SRT egt = -3600, -- EGT egst = 0, -- EGST nst = -12600, -- NST ndt = -9000, -- NDT wst = 28800, -- WST davt = 25200, -- DAVT ddut = 36000, -- DDUT mist = 39600, -- MIST mawt = 18000, -- MAWT nzst = 43200, -- NZST nzdt = 46800, -- NZDT rott = -10800, -- ROTT syot = 10800, -- SYOT vost = 21600, -- VOST almt = 21600, -- ALMT anat = 43200, -- ANAT aqtt = 18000, -- AQTT tmt = 18000, -- TMT azt = 14400, -- AZT azst = 18000, -- AZST ict = 25200, -- ICT kgt = 21600, -- KGT bnt = 28800, -- BNT chot = 28800, -- CHOT ist = 19800, -- IST bdt = 21600, -- BDT tlt = 32400, -- TLT gst = 14400, -- GST tjt = 18000, -- TJT hkt = 28800, -- HKT hovt = 25200, -- HOVT irkt = 32400, -- IRKT wit = 25200, -- WIT eit = 32400, -- EIT aft = 16200, -- AFT pett = 43200, -- PETT pkt = 18000, -- PKT npt = 20700, -- NPT krat = 28800, -- KRAT myt = 28800, -- MYT magt = 43200, -- MAGT cit = 28800, -- CIT pht = 28800, -- PHT novt = 25200, -- NOVT omst = 25200, -- OMST orat = 18000, -- ORAT kst = 32400, -- KST qyzt = 21600, -- QYZT mmt = 23400, -- MMT sakt = 39600, -- SAKT uzt = 18000, -- UZT sgt = 28800, -- SGT get = 14400, -- GET btt = 21600, -- BTT jst = 32400, -- JST ulat = 28800, -- ULAT vlat = 39600, -- VLAT yakt = 36000, -- YAKT yekt = 21600, -- YEKT azot = -3600, -- AZOT azost = 0, -- AZOST cvt = -3600, -- CVT fkt = -14400, -- FKT fkst = -10800, -- FKST cwst = 31500, -- CWST lhst = 37800, -- LHST lhst = 39600, -- LHST fet = 10800, -- FET msk = 14400, -- MSK samt = 14400, -- SAMT volt = 14400, -- VOLT iot = 21600, -- IOT cxt = 25200, -- CXT cct = 23400, -- CCT tft = 18000, -- TFT sct = 14400, -- SCT mvt = 18000, -- MVT mut = 14400, -- MUT ret = 14400, -- RET chast = 45900, -- CHAST chadt = 49500, -- CHADT chut = 36000, -- CHUT vut = 39600, -- VUT phot = 46800, -- PHOT tkt = -36000, -- TKT fjt = 43200, -- FJT tvt = 43200, -- TVT galt = -21600, -- GALT gamt = -32400, -- GAMT sbt = 39600, -- SBT hst = -36000, -- HST lint = 50400, -- LINT kost = 39600, -- KOST mht = 43200, -- MHT mart = -34200, -- MART sst = -39600, -- SST nrt = 43200, -- NRT nut = -39600, -- NUT nft = 41400, -- NFT nct = 39600, -- NCT pwt = 32400, -- PWT pont = 39600, -- PONT pgt = 36000, -- PGT ckt = -36000, -- CKT taht = -36000, -- TAHT gilt = 43200, -- GILT tot = 46800, -- TOT wakt = 43200, -- WAKT wft = 43200, -- WFT }
apache-2.0
redxdev/Wake
dist/lib/camera.lua
1
1363
local Vector3 = Vector3 local Quat = Quat local math = math local class = require('class') local Camera = class() function Camera:construct(pos, orientation, up, projection) self.position = pos or Vector3.new(0, 0, 0) self.orientation = orientation or Vector3.new(0, 0, 0) self.up = up or Vector3.new(0, 1, 0) local w, h = engine.getWindowSize() self.projection = projection or math.perspective(math.radians(45), w / h, 0.1, 1000) end function Camera:getViewMatrix() return math.lookAt(self.position, self.position + self:getFrontVector(), self.up) end function Camera:getFrontVector() return Vector3.new(1, 0, 0) * Quat.new(math.radians(self.orientation)) end function Camera:addRotation(amount) self.orientation = self.orientation + amount self.orientation:set(3, math.clamp(self.orientation:get(3), -89, 89)) end function Camera:moveForward(amount) self.position = self.position + amount * self:getFrontVector() end function Camera:moveRight(amount) self.position = self.position + amount * self:getFrontVector():cross(self.up) end function Camera:moveUp(amount) self.position = self.position + amount * Vector3.new(0, 1, 0) end function Camera:use(mat) mat = mat or Material.getGlobal() mat:setMatrix4("projection", self.projection) mat:setMatrix4("view", self:getViewMatrix()) end return Camera
mit
pazos/koreader
frontend/apps/reader/modules/readerrotation.lua
5
1031
local InputContainer = require("ui/widget/container/inputcontainer") local Device = require("device") local Event = require("ui/event") local _ = require("gettext") local ReaderRotation = InputContainer:new{ current_rotation = 0 } function ReaderRotation:init() if Device:hasKeyboard() then self.key_events = { -- these will all generate the same event, just with different arguments RotateLeft = { {"J"}, doc = "rotate left by 90 degrees", event = "Rotate", args = -90 }, RotateRight = { {"K"}, doc = "rotate right by 90 degrees", event = "Rotate", args = 90 }, } end end --- @todo Reset rotation on new document, maybe on new page? function ReaderRotation:onRotate(rotate_by) self.current_rotation = (self.current_rotation + rotate_by) % 360 self.ui:handleEvent(Event:new("RotationUpdate", self.current_rotation)) return true end return ReaderRotation
agpl-3.0
githabbot/server22
plugins/google.lua
3
1110
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." \n "..val[2].."\n----------------------\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^[/!]google (.*)$", "^[gG]oogle (.*)$", "^%.[Ss]earch (.*)$", "^[Gg]oogle (.*)$", }, run = run }
gpl-2.0
anonymous12212020/sbss
plugins/id.lua
50
4275
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' for k,v in pairs(result.members) do text = text .. v.print_name .. " (user#id" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "ایدی" then local text = user_print_name(msg.from) .. ' (user#id' .. msg.from.id .. ')' if is_chat_msg(msg) then text = text .. "\nYou are in group " .. user_print_name(msg.to) .. " (chat#id" .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end elseif matches[1] == "member" and matches[2] == "@" then local nick = matches[3] local chat = get_receiver(msg) if not is_chat_msg(msg) then return "You are not in a group." end chat_info(chat, function (extra, success, result) local receiver = extra.receiver local nick = extra.nick local found for k,user in pairs(result.members) do if user.username == nick then found = user end end if not found then send_msg(receiver, "User not found on this chat.", ok_cb, false) else local text = "ID: "..found.id send_msg(receiver, text, ok_cb, false) end end, {receiver=chat, nick=nick}) elseif matches[1] == "members" and matches[2] == "name" then local text = matches[3] local chat = get_receiver(msg) if not is_chat_msg(msg) then return "You are not in a group." end chat_info(chat, function (extra, success, result) local members = result.members local receiver = extra.receiver local text = extra.text local founds = {} for k,member in pairs(members) do local fields = {'first_name', 'print_name', 'username'} for k,field in pairs(fields) do if member[field] and type(member[field]) == "string" then if member[field]:match(text) then local id = tostring(member.id) founds[id] = member end end end end if next(founds) == nil then -- Empty table send_msg(receiver, "User not found on this chat.", ok_cb, false) else local text = "" for k,user in pairs(founds) do local first_name = user.first_name or "" local print_name = user.print_name or "" local user_name = user.user_name or "" local id = user.id or "" -- This would be funny text = text.."First name: "..first_name.."\n" .."Print name: "..print_name.."\n" .."User name: "..user_name.."\n" .."ID: "..id end send_msg(receiver, text, ok_cb, false) end end, {receiver=chat, text=text}) end end return { description = "Know your id or the id of a chat members.", usage = { "ایدی: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id member @<user_name>: Return the member @<user_name> ID from the current chat", "!id members name <text>: Search for users with <text> on first_name, print_name or username on current chat" }, patterns = { "^ایدی$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (member) (@)(.+)", "^!id (members) (name) (.+)" }, run = run }
gpl-2.0
yetsky/luci
contrib/luadoc/lua/luadoc/util.lua
93
5826
------------------------------------------------------------------------------- -- General utilities. -- @release $Id: util.lua,v 1.16 2008/02/17 06:42:51 jasonsantos Exp $ ------------------------------------------------------------------------------- local posix = require "nixio.fs" local type, table, string, io, assert, tostring, setmetatable, pcall = type, table, string, io, assert, tostring, setmetatable, pcall ------------------------------------------------------------------------------- -- Module with several utilities that could not fit in a specific module module "luadoc.util" ------------------------------------------------------------------------------- -- Removes spaces from the begining and end of a given string -- @param s string to be trimmed -- @return trimmed string function trim (s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end ------------------------------------------------------------------------------- -- Removes spaces from the begining and end of a given string, considering the -- string is inside a lua comment. -- @param s string to be trimmed -- @return trimmed string -- @see trim -- @see string.gsub function trim_comment (s) s = string.gsub(s, "%-%-+(.*)$", "%1") return trim(s) end ------------------------------------------------------------------------------- -- Checks if a given line is empty -- @param line string with a line -- @return true if line is empty, false otherwise function line_empty (line) return (string.len(trim(line)) == 0) end ------------------------------------------------------------------------------- -- Appends two string, but if the first one is nil, use to second one -- @param str1 first string, can be nil -- @param str2 second string -- @return str1 .. " " .. str2, or str2 if str1 is nil function concat (str1, str2) if str1 == nil or string.len(str1) == 0 then return str2 else return str1 .. " " .. str2 end end ------------------------------------------------------------------------------- -- Split text into a list consisting of the strings in text, -- separated by strings matching delim (which may be a pattern). -- @param delim if delim is "" then action is the same as %s+ except that -- field 1 may be preceeded by leading whitespace -- @usage split(",%s*", "Anna, Bob, Charlie,Dolores") -- @usage split(""," x y") gives {"x","y"} -- @usage split("%s+"," x y") gives {"", "x","y"} -- @return array with strings -- @see table.concat function split(delim, text) local list = {} if string.len(text) > 0 then delim = delim or "" local pos = 1 -- if delim matches empty string then it would give an endless loop if string.find("", delim, 1) and delim ~= "" then error("delim matches empty string!") end local first, last while 1 do if delim ~= "" then first, last = string.find(text, delim, pos) else first, last = string.find(text, "%s+", pos) if first == 1 then pos = last+1 first, last = string.find(text, "%s+", pos) end end if first then -- found? table.insert(list, string.sub(text, pos, first-1)) pos = last+1 else table.insert(list, string.sub(text, pos)) break end end end return list end ------------------------------------------------------------------------------- -- Comments a paragraph. -- @param text text to comment with "--", may contain several lines -- @return commented text function comment (text) text = string.gsub(text, "\n", "\n-- ") return "-- " .. text end ------------------------------------------------------------------------------- -- Wrap a string into a paragraph. -- @param s string to wrap -- @param w width to wrap to [80] -- @param i1 indent of first line [0] -- @param i2 indent of subsequent lines [0] -- @return wrapped paragraph function wrap(s, w, i1, i2) w = w or 80 i1 = i1 or 0 i2 = i2 or 0 assert(i1 < w and i2 < w, "the indents must be less than the line width") s = string.rep(" ", i1) .. s local lstart, len = 1, string.len(s) while len - lstart > w do local i = lstart + w while i > lstart and string.sub(s, i, i) ~= " " do i = i - 1 end local j = i while j > lstart and string.sub(s, j, j) == " " do j = j - 1 end s = string.sub(s, 1, j) .. "\n" .. string.rep(" ", i2) .. string.sub(s, i + 1, -1) local change = i2 + 1 - (i - j) lstart = j + change len = len + change end return s end ------------------------------------------------------------------------------- -- Opens a file, creating the directories if necessary -- @param filename full path of the file to open (or create) -- @param mode mode of opening -- @return file handle function posix.open (filename, mode) local f = io.open(filename, mode) if f == nil then filename = string.gsub(filename, "\\", "/") local dir = "" for d in string.gfind(filename, ".-/") do dir = dir .. d posix.mkdir(dir) end f = io.open(filename, mode) end return f end ---------------------------------------------------------------------------------- -- Creates a Logger with LuaLogging, if present. Otherwise, creates a mock logger. -- @param options a table with options for the logging mechanism -- @return logger object that will implement log methods function loadlogengine(options) local logenabled = pcall(function() require "logging" require "logging.console" end) local logging = logenabled and logging if logenabled then if options.filelog then logger = logging.file("luadoc.log") -- use this to get a file log else logger = logging.console("[%level] %message\n") end if options.verbose then logger:setLevel(logging.INFO) else logger:setLevel(logging.WARN) end else noop = {__index=function(...) return function(...) -- noop end end} logger = {} setmetatable(logger, noop) end return logger end
apache-2.0
telebombang2018/energy
bot/bot.lua
1
12018
-- #@ENERGY_TEAM -----my_name_is_ehsan*#@mafia_boy -----@ENERGY_TEAM FOR UPDATE -----لطفا پیام بالا رو پاک نکنید tdcli = dofile('./tg/tdcli.lua') serpent = (loadfile "./libs/serpent.lua")() feedparser = (loadfile "./libs/feedparser.lua")() require('./bot/utils') require('./libs/lua-redis') URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() local lgi = require ('lgi') local notify = lgi.require('Notify') notify.init ("Telegram updates") chats = {} plugins = {} helper_id = 323046540 --Put Your Helper Bot ID Here function do_notify (user, msg) local n = notify.Notification.new(user, msg) n:show () end function dl_cb (arg, data) -- vardump(data) end function vardump(value) print(serpent.block(value, {comment=false})) end function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end function whoami() local usr = io.popen("whoami"):read('*a') usr = string.gsub(usr, '^%s+', '') usr = string.gsub(usr, '%s+$', '') usr = string.gsub(usr, '[\n\r]+', ' ') if usr:match("^root$") then tcpath = '/root/.telegram-cli' elseif not usr:match("^root$") then tcpath = '/home/'..usr..'/.telegram-cli' end print('>> Download Path = '..tcpath) end function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end function create_config( ) io.write('\n\27[1;33m>> Input your Telegram ID for set Sudo : \27[0;39;49m') local sudo_id = tonumber(io.read()) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "PL (1)", "PL (2)", "PL (3)", "PL (4)", "PL (5)", "PL (6)", "PL (7)", "PL (8)", "PL (9)", "PL (10)", "PL (11)", "PL (12)", "PL (13)", "PL (14)", "PL (15)", "PL (16)", "PL (17)", "PL (18)", "PL (19)", }, sudo_users = {323046540, 417589898, sudo_id}, admins = {}, disabled_channels = {}, moderation = {data = './data/moderation.json'}, info_text = [[》Beyond Reborn v6.0 An advanced administration bot based on https://valtman.name/telegram-cli 》https://github.com/telebombang2018/tele_bom_bang_new 》Special thanks to : 》beyond_permag_bombang 》Our channel : 》@RICHENERGY%%@energy_team 》Our website : 》http://telebombang.blogfa.com ]], } serialize_to_file(config, './data/config.lua') print ('saved config into config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: ./data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("SUDO USER: " .. user) end return config end whoami() _config = load_config() function load_plugins() local config = loadfile ("./data/config.lua")() for k, v in pairs(config.enabled_plugins) do print("Loaded Plugin ", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugins '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end print('\n'..#config.enabled_plugins..' Plugins Are Active\n\nStarting ENERGY Robot...\n') end load_plugins() function msg_valid(msg) if tonumber(msg.date_) < (tonumber(os.time()) - 60) then print('\27[36m>>-- OLD MESSAGE --<<\27[39m') return false end if is_silent_user(msg.sender_user_id_, msg.chat_id_) then del_msg(msg.chat_id_, msg.id_) return false end if is_banned(msg.sender_user_id_, msg.chat_id_) then del_msg(msg.chat_id_, tonumber(msg.id_)) kick_user(msg.sender_user_id_, msg.chat_id_) return false end if is_gbanned(msg.sender_user_id_) then del_msg(msg.chat_id_, tonumber(msg.id_)) kick_user(msg.sender_user_id_, msg.chat_id_) return false end return true end 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 end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = '_Plugin_ *'..check_markdown(disabled_plugin)..'* _is disabled on this chat_' print(warning) tdcli.sendMessage(receiver, "", 0, warning, 0, "md") return true end end end return false end function match_plugin(plugin, plugin_name, msg) if plugin.pre_process then --If plugin is for privileged users only local result = plugin.pre_process(msg) if result then print("pre process: ", plugin_name) -- tdcli.sendMessage(msg.chat_id_, "", 0, result, 0, "md") end end for k, pattern in pairs(plugin.patterns) do matches = match_pattern(pattern, msg.content_.text_ or msg.content_.caption_) if matches then if is_plugin_disabled_on_chat(plugin_name, msg.chat_id_) then return nil end print("Message matches: ", pattern..' | Plugin: '..plugin_name) if plugin.run then if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then tdcli.sendMessage(msg.chat_id_, msg.id_, 0, result, 0, "md") end end end return end end end function file_cb(msg) if msg.content_.ID == "MessagePhoto" then photo_id = '' local function get_cb(arg, data) if data.content_.photo_.sizes_[2] then photo_id = data.content_.photo_.sizes_[2].photo_.id_ else photo_id = data.content_.photo_.sizes_[1].photo_.id_ end tdcli.downloadFile(photo_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageVideo" then video_id = '' local function get_cb(arg, data) video_id = data.content_.video_.video_.id_ tdcli.downloadFile(video_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageAnimation" then anim_id, anim_name = '', '' local function get_cb(arg, data) anim_id = data.content_.animation_.animation_.id_ anim_name = data.content_.animation_.file_name_ tdcli.downloadFile(anim_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageVoice" then voice_id = '' local function get_cb(arg, data) voice_id = data.content_.voice_.voice_.id_ tdcli.downloadFile(voice_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageAudio" then audio_id, audio_name, audio_title = '', '', '' local function get_cb(arg, data) audio_id = data.content_.audio_.audio_.id_ audio_name = data.content_.audio_.file_name_ audio_title = data.content_.audio_.title_ tdcli.downloadFile(audio_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageSticker" then sticker_id = '' local function get_cb(arg, data) sticker_id = data.content_.sticker_.sticker_.id_ tdcli.downloadFile(sticker_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageDocument" then document_id, document_name = '', '' local function get_cb(arg, data) document_id = data.content_.document_.document_.id_ document_name = data.content_.document_.file_name_ tdcli.downloadFile(document_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) end end function tdcli_update_callback (data) if data.message_ then if msg_caption ~= get_text_msg() then msg_caption = get_text_msg() end end if (data.ID == "UpdateNewMessage") then local msg = data.message_ local d = data.disable_notification_ local chat = chats[msg.chat_id_] local hash = 'msgs:'..msg.sender_user_id_..':'..msg.chat_id_ redis:incr(hash) if redis:get('markread') == 'on' then tdcli.viewMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil) end if ((not d) and chat) then if msg.content_.ID == "MessageText" then do_notify (chat.title_, msg.content_.text_) else do_notify (chat.title_, msg.content_.ID) end end if msg_valid(msg) then var_cb(msg, msg) file_cb(msg) if msg.content_.ID == "MessageText" then msg.text = msg.content_.text_ msg.edited = false msg.pinned = false elseif msg.content_.ID == "MessagePinMessage" then msg.pinned = true elseif msg.content_.ID == "MessagePhoto" then msg.photo_ = true elseif msg.content_.ID == "MessageVideo" then msg.video_ = true elseif msg.content_.ID == "MessageAnimation" then msg.animation_ = true elseif msg.content_.ID == "MessageVoice" then msg.voice_ = true elseif msg.content_.ID == "MessageAudio" then msg.audio_ = true elseif msg.content_.ID == "MessageForwardedFromUser" then msg.forward_info_ = true elseif msg.content_.ID == "MessageSticker" then msg.sticker_ = true elseif msg.content_.ID == "MessageContact" then msg.contact_ = true elseif msg.content_.ID == "MessageDocument" then msg.document_ = true elseif msg.content_.ID == "MessageLocation" then msg.location_ = true elseif msg.content_.ID == "MessageGame" then msg.game_ = true elseif msg.content_.ID == "MessageChatAddMembers" then for i=0,#msg.content_.members_ do msg.adduser = msg.content_.members_[i].id_ end elseif msg.content_.ID == "MessageChatJoinByLink" then msg.joinuser = msg.sender_user_id_ elseif msg.content_.ID == "MessageChatDeleteMember" then msg.deluser = true end end elseif data.ID == "UpdateMessageContent" then cmsg = data local function edited_cb(arg, data) msg = data msg.media = {} if cmsg.new_content_.text_ then msg.text = cmsg.new_content_.text_ end if cmsg.new_content_.caption_ then msg.media.caption = cmsg.new_content_.caption_ end msg.edited = true if msg_valid(msg) then var_cb(msg, msg) end end tdcli_function ({ ID = "GetMessage", chat_id_ = data.chat_id_, message_id_ = data.message_id_ }, edited_cb, nil) elseif data.ID == "UpdateFile" then file_id = data.file_.id_ elseif (data.ID == "UpdateChat") then chat = data.chat_ chats[chat.id_] = chat elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then tdcli_function ({ID="GetChats", offset_order_="9223372036854775807", offset_chat_id_=0, limit_=20}, dl_cb, nil) end end -----my_name_is_ehsan*#@mafia_boy -----@ENERGY_TEAM FOR UPDATE -----لطفا پیام بالا رو پاک نکنید
gpl-3.0
boundary/boundary-plugin-riak
init.lua
2
3837
-- Copyright 2015 Boundary, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local framework = require('framework') local Plugin = framework.Plugin local WebRequestDataSource = framework.WebRequestDataSource local parseJson = framework.util.parseJson local url = require('url') local isHttpSuccess = framework.util.isHttpSuccess local notEmpty = framework.string.notEmpty local trim = framework.string.trim local params = framework.params params.url = trim(notEmpty(params.url, 'http://127.0.0.1:8098/stats')) local options = url.parse(params.url) local ds = WebRequestDataSource:new(options) local plugin = Plugin:new(params, ds) function plugin:onParseValues(data, extra) if not isHttpSuccess(extra.status_code) then self:emitEvent('error', ('Http request returned status code %s instead of OK. Please verify Riak stats endpoint configuration.'):format(extra.status_code)) return end local success, parsed = parseJson(data) if not success then self:emitEvent('error', 'Can not parse metrics. Please verify Riak stats endpoint configuration.') return end local result = { ['RIAK_RINGS_RECONCILED'] = parsed.rings_reconciled, ['RIAK_GOSSIP_RECEIVED'] = parsed.gossip_received, ['RIAK_CONVERGE_DELAY_MEAN'] = parsed.converge_delay_mean, ['RIAK_REBALANCE_DELAY_MEAN'] = parsed.rebalance_delay_mean, ['RIAK_KV_VNODES_RUNNING' ] = parsed.riak_kv_vnodes_running, ['RIAK_KV_VNODEQ_MEDIAN' ] = parsed.riak_kv_vnodeq_median, ['RIAK_KV_VNODEQ_TOTAL' ] = parsed.riak_kv_vnodeq_total, ['RIAK_PIPE_VNODES_RUNNING' ] = parsed.riak_pipe_vnodes_running, ['RIAK_PIPE_VNODEQ_MEDIAN' ] = parsed.riak_pipe_vnodeq_median, ['RIAK_PIPE_VNODEQ_TOTAL' ] = parsed.riak_pipe_vnodeq_total, ['RIAK_NODE_GET_FSM_IN_RATE' ] = parsed.node_get_fsm_in_rate, ['RIAK_NODE_GET_FSM_OUT_RATE' ] = parsed.node_get_fsm_out_rate, ['RIAK_NODE_PUT_FSM_IN_RATE' ] = parsed.node_put_fsm_in_rate, ['RIAK_NODE_PUT_FSM_OUT_RATE' ] = parsed.node_put_fsm_out_rate, ['RIAK_NODE_GETS' ] = parsed.node_gets, ['RIAK_NODE_PUTS' ] = parsed.node_puts, ['RIAK_PBC_CONNECTS' ] = parsed.pbc_connects, ['RIAK_READ_REPAIRS' ] = parsed.read_repairs, ['RIAK_NODE_GET_FSM_TIME_MEAN' ] = parsed.node_get_fsm_time_mean, ['RIAK_NODE_PUT_FSM_TIME_MEAN' ] = parsed.node_put_fsm_time_mean, ['RIAK_NODE_GET_FSM_SIBLINGS_MEAN' ] = parsed.node_get_fsm_siblings_mean, ['RIAK_NODE_GET_FSM_OBJSIZE_MEAN' ] = parsed.node_get_fsm_objsize_mean, ['RIAK_MEMORY_TOTAL' ] = parsed.memory_total, ['RIAK_PIPELINE_ACTIVE' ] = parsed.pipeline_active, ['RIAK_PIPELINE_CREATE_ONE' ] = parsed.pipeline_create_one, ['RIAK_SEARCH_VNODEQ_MEAN' ] = parsed.riak_search_vnodeq_mean, ['RIAK_SEARCH_VNODEQ_TOTAL' ] = parsed.riak_search_vnodeq_total, ['RIAK_SEARCH_VNODES_RUNNING' ] = parsed.riak_search_vnodes_running, ['RIAK_CONSISTENT_GETS' ] = parsed.consistent_gets, ['RIAK_CONSISTENT_GET_OBJSIZE_MEAN' ] = parsed.consistent_get_objsize_mean, ['RIAK_CONSISTENT_GET_TIME_MEAN' ] = parsed.consistent_get_time_mean, ['RIAK_CONSISTENT_PUTS' ] = parsed.consistent_puts, ['RIAK_CONSISTENT_PUT_OBJSIZE_MEAN' ] = parsed.consistent_put_objsize_mean, ['RIAK_CONSISTENT_PUT_TIME_MEAN' ] = parsed.consistent_put_time_mean } return result end plugin:run()
apache-2.0
ZerothAngel/FtDScripts
main/yawtest.lua
1
1901
--! yawtest --@ commons control firstrun eventdriver sixdof ytdefaults MyHeading = -90 LastTurn = nil ThrottleIndex = 0 YawTest = EventDriver.new() function YawTest_FirstRun(_) YawTest:Schedule(0, YawTest_Throttle) end AddFirstRun(YawTest_FirstRun) function YawTest_Throttle(I) if VaryThrottle then ThrottleIndex = ThrottleIndex + 1 local Throttle = ThrottleSettings[ThrottleIndex] ThrottleIndex = ThrottleIndex % #ThrottleSettings I:LogToHud(string.format("New throttle! %.0f%%", Throttle * 100)) V.SetThrottle(Throttle) -- Get up to speed before changing heading YawTest:Schedule(ThrottleDelay, YawTest_Heading) else V.ResetThrottle() YawTest:Schedule(0, YawTest_Heading) end end function YawTest_Heading(I) MyHeading = (MyHeading + 90) % 360 I:LogToHud(string.format("New heading! %f degrees", MyHeading)) V.SetHeading(MyHeading) LastTurn = { C:Now(), C:CoM() } YawTest:Schedule(HeadingDelay, YawTest_Throttle) end SelectHeadingImpl(SixDoF) SelectThrottleImpl(SixDoF) function Update(I) -- luacheck: ignore 131 C = Commons.new(I) FirstRun(I) if not C:IsDocked() then if ActivateWhen[C:MovementMode()] then if LastTurn and math.abs(Mathf.DeltaAngle(C:Yaw(), MyHeading)) < 0.1 then local DeltaTime = C:Now() - LastTurn[1] local SqrDistance = (C:CoM() - LastTurn[2]).sqrMagnitude local Radius = math.sqrt(SqrDistance / 2) local Message = string.format("Time: %.2f s, Radius: %.2f m", DeltaTime, Radius) I:Log(Message) I:LogToHud(Message) LastTurn = nil end YawTest:Tick(I) -- Suppress default AI I:TellAiThatWeAreTakingControl() else V.Reset() SixDoF.Release(I) end SixDoF.Update(I) else SixDoF.Disable(I) end end
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/base/entities/weapons/weapon_base/sh_anim.lua
2
2973
local ActIndex = { [ "pistol" ] = ACT_HL2MP_IDLE_PISTOL, [ "smg" ] = ACT_HL2MP_IDLE_SMG1, [ "grenade" ] = ACT_HL2MP_IDLE_GRENADE, [ "ar2" ] = ACT_HL2MP_IDLE_AR2, [ "shotgun" ] = ACT_HL2MP_IDLE_SHOTGUN, [ "rpg" ] = ACT_HL2MP_IDLE_RPG, [ "physgun" ] = ACT_HL2MP_IDLE_PHYSGUN, [ "crossbow" ] = ACT_HL2MP_IDLE_CROSSBOW, [ "melee" ] = ACT_HL2MP_IDLE_MELEE, [ "slam" ] = ACT_HL2MP_IDLE_SLAM, [ "normal" ] = ACT_HL2MP_IDLE, [ "fist" ] = ACT_HL2MP_IDLE_FIST, [ "melee2" ] = ACT_HL2MP_IDLE_MELEE2, [ "passive" ] = ACT_HL2MP_IDLE_PASSIVE, [ "knife" ] = ACT_HL2MP_IDLE_KNIFE, [ "duel" ] = ACT_HL2MP_IDLE_DUEL, [ "camera" ] = ACT_HL2MP_IDLE_CAMERA, [ "revolver" ] = ACT_HL2MP_IDLE_REVOLVER } --[[--------------------------------------------------------- Name: SetWeaponHoldType Desc: Sets up the translation table, to translate from normal standing idle pose, to holding weapon pose. -----------------------------------------------------------]] function SWEP:SetWeaponHoldType( t ) t = string.lower( t ) local index = ActIndex[ t ] if ( index == nil ) then Msg( "SWEP:SetWeaponHoldType - ActIndex[ \""..t.."\" ] isn't set! (defaulting to normal)\n" ) t = "normal" index = ActIndex[ t ] end self.ActivityTranslate = {} self.ActivityTranslate [ ACT_MP_STAND_IDLE ] = index self.ActivityTranslate [ ACT_MP_WALK ] = index+1 self.ActivityTranslate [ ACT_MP_RUN ] = index+2 self.ActivityTranslate [ ACT_MP_CROUCH_IDLE ] = index+3 self.ActivityTranslate [ ACT_MP_CROUCHWALK ] = index+4 self.ActivityTranslate [ ACT_MP_ATTACK_STAND_PRIMARYFIRE ] = index+5 self.ActivityTranslate [ ACT_MP_ATTACK_CROUCH_PRIMARYFIRE ] = index+5 self.ActivityTranslate [ ACT_MP_RELOAD_STAND ] = index+6 self.ActivityTranslate [ ACT_MP_RELOAD_CROUCH ] = index+6 self.ActivityTranslate [ ACT_MP_JUMP ] = index+7 self.ActivityTranslate [ ACT_RANGE_ATTACK1 ] = index+8 self.ActivityTranslate [ ACT_MP_SWIM_IDLE ] = index+8 self.ActivityTranslate [ ACT_MP_SWIM ] = index+9 -- "normal" jump animation doesn't exist if t == "normal" then self.ActivityTranslate [ ACT_MP_JUMP ] = ACT_HL2MP_JUMP_SLAM end self:SetupWeaponHoldTypeForAI( t ) end -- Default hold pos is the pistol SWEP:SetWeaponHoldType( "pistol" ) --[[--------------------------------------------------------- Name: weapon:TranslateActivity( ) Desc: Translate a player's Activity into a weapon's activity So for example, ACT_HL2MP_RUN becomes ACT_HL2MP_RUN_PISTOL Depending on how you want the player to be holding the weapon -----------------------------------------------------------]] function SWEP:TranslateActivity( act ) if ( self.Owner:IsNPC() ) then if ( self.ActivityTranslateAI[ act ] ) then return self.ActivityTranslateAI[ act ] end return -1 end if ( self.ActivityTranslate[ act ] != nil ) then return self.ActivityTranslate[ act ] end return -1 end
mit
yanarsin/arina
plugins/invite.lua
47
1193
do local function callbackres(extra, success, result) -- Callback for res_user in line 27 local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then -- Ignore bans send_large_msg(chat, 'User is banned.') elseif is_gbanned(result.id) then -- Ignore globall bans send_large_msg(chat, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) -- Add user on chat end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end --if not is_admin(msg) then -- For admins only ! --return 'Only admins can invite.' --end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^دعوت (.*)$" }, run = run } end
gpl-2.0
notestudio/shall-I-kill-her
assets/scripts/arrows.lua
1
2082
local arrows = {} local padding = 10 function arrows.load(game, stage, camera) arrows.img_left = love.graphics.newImage('assets/sprites/arrows/left.png') arrows.left_x = padding arrows.left_y = (game.canvas.height / 2) - (arrows.img_left:getHeight() /2) arrows.img_right = love.graphics.newImage('assets/sprites/arrows/right.png') arrows.right_x = (game.canvas.width - arrows.img_right:getWidth()) - padding arrows.right_y = (game.canvas.height / 2) - (arrows.img_left:getHeight() /2) arrows.game = game end function arrows.update(dt, game) end function arrows.draw() if arrows.game.level > 1 then love.graphics.draw(arrows.img_left, arrows.left_x, arrows.left_y) end if arrows.game.level < arrows.game.end_level then love.graphics.draw(arrows.img_right, arrows.right_x, arrows.right_y) end if arrows.game.level == arrows.game.end_level then arrows.game.var_end = true end end function arrows.mousepressed(mx, my, button) x1,y1,x2,y2,x3,y3,x4,y4 = camera.gcam:getVisibleCorners() wl, wt, ww, wh = camera.gcam:getWorld() if button == 1 then if x1 <= arrows.left_x + arrows.img_left:getWidth() then if mx >= arrows.left_x and mx < arrows.left_x + arrows.img_left:getWidth() then if my >= arrows.left_y and my < arrows.left_y + arrows.img_left:getHeight() then arrows.game:prevLevel() end end end if x2 >= (ww - arrows.img_right:getWidth()) then same_size = false if ww == arrows.game.canvas.width and x1 == 0 then -- Verify canvas == world same_size = true end if same_size then -- canvas == world if mx >= arrows.right_x then if my >= arrows.left_y and my < arrows.left_y + arrows.img_left:getHeight() then arrows.game:nextLevel() end end else -- large world - scroll cam if mx >= (ww - x1 - arrows.img_right:getWidth()) and mx <= (ww - arrows.img_right:getWidth()) or same_size then if my >= arrows.right_y and my < arrows.right_y + arrows.img_right:getHeight() then arrows.game:nextLevel() end end end end end end return arrows
apache-2.0
xiaowa183/Atlas
lib/ro-balance.lua
40
6646
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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 St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --- -- slave aware load-balancer -- -- * take slaves which are too far behind out of the rotation -- * when we bring back the slave make sure it doesn't get -- behind again too early (slow start) -- * fallback to the master of all slaves are too far behind -- * check if the backends are really configures as slave -- * check if the io-thread is running at all -- -- it is unclear how to -- - handle requests sent to a backend with a io-thread off -- - should we just close the connection to the client -- and let it retry ? -- - how to activate the backend again ? -- - if a slave is lagging, we don't send queries to it -- how do we figure out it is back again ? require("proxy.auto-config") local commands = require("proxy.commands") if not proxy.global.config.ro_balance then proxy.global.config.ro_balance = { max_seconds_lag = 10, -- 10 seconds max_bytes_lag = 10 * 1024, -- 10k check_timeout = 2, is_debug = true } end if not proxy.global.lag then proxy.global.lag = { } end local config = proxy.global.config.ro_balance local backend_lag = proxy.global.lag --- -- pick a backend server -- -- we take the lag into account -- * ignore backends which aren't configured -- * ignore backends which don't have a io-thread running -- * ignore backends that are too far behind function connect_server() local fallback_ndx local slave_ndx local unknown_slave_ndx local slave_bytes_lag for b_ndx = 1, #proxy.global.backends do local backend = proxy.global.backends[b_ndx] if backend.state ~= proxy.BACKEND_STATE_DOWN then if backend.type == proxy.BACKEND_TYPE_RW then -- the fallback fallback_ndx = b_ndx else --- -- connect to the backends first we don't know yet if not backend_lag[backend.dst.name] then unknown_slave_ndx = b_ndx elseif backend_lag[backend.dst.name].state == "running" then if not slave_bytes_lag then slave_ndx = b_ndx slave_bytes_lag = backend_lag[backend.dst.name].slave_bytes_lag elseif backend_lag[backend.dst.name].slave_bytes_lag < slave_bytes_lag then slave_ndx = b_ndx slave_bytes_lag = backend_lag[backend.dst.name].slave_bytes_lag end end end end end proxy.connection.backend_ndx = unknown_slave_ndx or slave_ndx or fallback_ndx if config.is_debug then print("(connect-server) using backend: " .. proxy.global.backends[proxy.connection.backend_ndx].dst.name) end end function read_query(packet) local cmd = commands.parse(packet) local ret = proxy.global.config:handle(cmd) if ret then return ret end -- -- check the backend periodicly for its lag -- -- translate the backend_ndx into its address local backend_addr = proxy.global.backends[proxy.connection.backend_ndx].dst.name backend_lag[backend_addr] = backend_lag[backend_addr] or { state = "unchecked" } local now = os.time() if config.is_debug then print("(read_query) we are on backend: ".. backend_addr .. " in state: " .. backend_lag[backend_addr].state) end if backend_lag[backend_addr].state == "unchecked" or (backend_lag[backend_addr].state == "running" and now - backend_lag[backend_addr].check_ts > config.check_timeout) then if config.is_debug then print("(read-query) unchecked, injecting a SHOW SLAVE STATUS") end proxy.queries:append(2, string.char(proxy.COM_QUERY) .. "SHOW SLAVE STATUS") proxy.queries:append(1, packet) return proxy.PROXY_SEND_QUERY elseif proxy.global.backends[proxy.connection.backend_ndx].type == proxy.BACKEND_TYPE_RW or -- master backend_lag[backend_addr].state == "running" then -- good slave -- pass through return else -- looks like this is a bad backend -- let's get the client to connect to another backend -- -- ... by closing the connection proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = "slave-state is " .. backend_lag[backend_addr].state, sqlstate = "08S01" } proxy.queries:reset() -- and now we have to tell the proxy to close the connection -- proxy.connection.connection_close = true return proxy.PROXY_SEND_RESULT end end function read_query_result(inj) -- pass through the client query if inj.id == 1 then return end --- -- parse the SHOW SLAVE STATUS -- -- what can happen ? -- * no permissions (ERR) -- * if not slave, result is empty local res = inj.resultset local fields = res.fields local show_slave_status = {} -- turn the resultset into local hash for row in res.rows do for field_id, field in pairs(row) do show_slave_status[fields[field_id].name] = tostring(field) if config.is_debug then print(("[%d] '%s' = '%s'"):format(field_id, fields[field_id].name, tostring(field))) end end end local backend_addr = proxy.global.backends[proxy.connection.backend_ndx].dst.name backend_lag[backend_addr].check_ts = os.time() backend_lag[backend_addr].state = nil if not show_slave_status["Master_Host"] then -- this backend is not a slave backend_lag[backend_addr].state = "noslave" return proxy.PROXY_IGNORE_RESULT end if show_slave_status["Master_Log_File"] == show_slave_status["Relay_Master_Log_File"] then -- ok, we use the same relay-log for reading and writing backend_lag[backend_addr].slave_bytes_lag = tonumber(show_slave_status["Exec_Master_Log_Pos"]) - tonumber(show_slave_status["Read_Master_Log_Pos"]) else backend_lag[backend_addr].slave_bytes_lag = nil end if show_slave_status["Seconds_Behind_Master"] then backend_lag[backend_addr].seconds_lag = tonumber(show_slave_status["Seconds_Behind_Master"]) else backend_lag[backend_addr].seconds_lag = nil end if show_slave_status["Slave_IO_Running"] == "No" then backend_lag[backend_addr].state = "noiothread" end backend_lag[backend_addr].state = backend_lag[backend_addr].state or "running" return proxy.PROXY_IGNORE_RESULT end
gpl-2.0
sdgdsffdsfff/nginx-openresty-windows
lua-resty-upload-0.09/lib/resty/upload.lua
10
5155
-- Copyright (C) Yichun Zhang (agentzh) local sub = string.sub local req_socket = ngx.req.socket local null = ngx.null local match = string.match local setmetatable = setmetatable local error = error local get_headers = ngx.req.get_headers local type = type -- local print = print local _M = { _VERSION = '0.08' } local MAX_LINE_SIZE = 512 local STATE_BEGIN = 1 local STATE_READING_HEADER = 2 local STATE_READING_BODY = 3 local STATE_EOF = 4 local mt = { __index = _M } local state_handlers local function get_boundary() local header = get_headers()["content-type"] if not header then return nil end if type(header) == "table" then header = header[1] end local m = match(header, ";%s*boundary=\"([^\"]+)\"") if m then return m end return match(header, ";%s*boundary=([^\",;]+)") end function _M.new(self, chunk_size) local boundary = get_boundary() -- print("boundary: ", boundary) if not boundary then return nil, "no boundary defined in Content-Type" end -- print('boundary: "', boundary, '"') local sock, err = req_socket() if not sock then return nil, err end local read2boundary, err = sock:receiveuntil("--" .. boundary) if not read2boundary then return nil, err end local read_line, err = sock:receiveuntil("\r\n") if not read_line then return nil, err end return setmetatable({ sock = sock, size = chunk_size or 4096, read2boundary = read2boundary, read_line = read_line, boundary = boundary, state = STATE_BEGIN }, mt) end function _M.set_timeout(self, timeout) local sock = self.sock if not sock then return nil, "not initialized" end return sock:settimeout(timeout) end local function discard_line(self) local read_line = self.read_line local line, err = self.read_line(MAX_LINE_SIZE) if not line then return nil, err end local dummy, err = self.read_line(1) if dummy then return nil, "line too long: " .. line .. dummy .. "..." end if err then return nil, err end return 1 end local function discard_rest(self) local sock = self.sock local size = self.size while true do local dummy, err = sock:receive(size) if err and err ~= 'closed' then return nil, err end if not dummy then return 1 end end end local function read_body_part(self) local read2boundary = self.read2boundary local chunk, err = read2boundary(self.size) if err then return nil, nil, err end if not chunk then local sock = self.sock local data = sock:receive(2) if data == "--" then local ok, err = discard_rest(self) if not ok then return nil, nil, err end self.state = STATE_EOF return "part_end" end if data ~= "\r\n" then local ok, err = discard_line(self) if not ok then return nil, nil, err end end self.state = STATE_READING_HEADER return "part_end" end return "body", chunk end local function read_header(self) local read_line = self.read_line local line, err = read_line(MAX_LINE_SIZE) if err then return nil, nil, err end local dummy, err = read_line(1) if dummy then return nil, nil, "line too long: " .. line .. dummy .. "..." end if err then return nil, nil, err end -- print("read line: ", line) if line == "" then -- after the last header self.state = STATE_READING_BODY return read_body_part(self) end local key, value = match(line, "([^: \t]+)%s*:%s*(.+)") if not key then return 'header', line end return 'header', {key, value, line} end local function eof() return "eof", nil end function _M.read(self) local size = self.size local handler = state_handlers[self.state] if handler then return handler(self) end return nil, nil, "bad state: " .. self.state end local function read_preamble(self) local sock = self.sock if not sock then return nil, nil, "not initialized" end local size = self.size local read2boundary = self.read2boundary while true do local preamble, err = read2boundary(size) if not preamble then break end -- discard the preamble data chunk -- print("read preamble: ", preamble) end local ok, err = discard_line(self) if not ok then return nil, nil, err end local read2boundary, err = sock:receiveuntil("\r\n--" .. self.boundary) if not read2boundary then return nil, nil, err end self.read2boundary = read2boundary self.state = STATE_READING_HEADER return read_header(self) end state_handlers = { read_preamble, read_header, read_body_part, eof } return _M
bsd-2-clause
pazos/koreader
frontend/ui/widget/doublespinwidget.lua
1
10097
local Blitbuffer = require("ffi/blitbuffer") local ButtonTable = require("ui/widget/buttontable") local CenterContainer = require("ui/widget/container/centercontainer") local CloseButton = require("ui/widget/closebutton") local Device = require("device") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local Font = require("ui/font") local HorizontalGroup = require("ui/widget/horizontalgroup") local InputContainer = require("ui/widget/container/inputcontainer") local LineWidget = require("ui/widget/linewidget") local MovableContainer = require("ui/widget/container/movablecontainer") local OverlapGroup = require("ui/widget/overlapgroup") local NumberPickerWidget = require("ui/widget/numberpickerwidget") local Size = require("ui/size") local TextBoxWidget = require("ui/widget/textboxwidget") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") local WidgetContainer = require("ui/widget/container/widgetcontainer") local _ = require("gettext") local Screen = Device.screen local DoubleSpinWidget = InputContainer:new{ title_text = "", title_face = Font:getFace("x_smalltfont"), info_text = nil, width = nil, height = nil, left_min = 1, left_max = 20, left_value = 1, left_default = nil, left_text = _("Left"), right_min = 1, right_max = 20, right_value = 1, right_default = nil, right_text = _("Right"), cancel_text = _("Close"), ok_text = _("Apply"), cancel_callback = nil, callback = nil, close_callback = nil, keep_shown_on_apply = false, -- Set this to add default button that restores numbers to their default values default_values = nil, default_text = _("Use defaults"), -- Optional extra button on bottom extra_text = nil, extra_callback = nil, } function DoubleSpinWidget:init() self.medium_font_face = Font:getFace("ffont") self.screen_width = Screen:getWidth() self.screen_height = Screen:getHeight() self.width = self.width or math.floor(self.screen_width * 0.8) self.picker_width = math.floor(self.screen_width * 0.25) if Device:hasKeys() then self.key_events = { Close = { {"Back"}, doc = "close time widget" } } end if Device:isTouchDevice() then self.ges_events = { TapClose = { GestureRange:new{ ges = "tap", range = Geom:new{ w = self.screen_width, h = self.screen_height, } }, }, } end -- Actually the widget layout self:update() end function DoubleSpinWidget:update() local left_widget = NumberPickerWidget:new{ show_parent = self, width = self.picker_width, value = self.left_value, value_min = self.left_min, value_max = self.left_max, value_step = self.left_step, value_hold_step = self.left_hold_step, wrap = false, } local right_widget = NumberPickerWidget:new{ show_parent = self, width = self.picker_width, value = self.right_value, value_min = self.right_min, value_max = self.right_max, value_step = self.right_step, value_hold_step = self.right_hold_step, wrap = false, } local left_vertical_group = VerticalGroup:new{ align = "center", VerticalSpan:new{ width = Size.span.vertical_large }, TextWidget:new{ text = self.left_text, face = self.title_face, max_width = 0.95 * self.width / 2, }, left_widget, } local right_vertical_group = VerticalGroup:new{ align = "center", VerticalSpan:new{ width = Size.span.vertical_large }, TextWidget:new{ text = self.right_text, face = self.title_face, max_width = 0.95 * self.width / 2, }, right_widget, } local widget_group = HorizontalGroup:new{ align = "center", CenterContainer:new{ dimen = Geom:new{ w = self.width / 2, h = left_vertical_group:getSize().h, }, left_vertical_group }, CenterContainer:new{ dimen = Geom:new{ w = self.width / 2, h = right_vertical_group:getSize().h, }, right_vertical_group } } local widget_title = FrameContainer:new{ padding = Size.padding.default, margin = Size.margin.title, bordersize = 0, TextWidget:new{ text = self.title_text, face = self.title_face, bold = true, width = self.width, }, } local widget_line = LineWidget:new{ dimen = Geom:new{ w = self.width, h = Size.line.thick, } } local widget_bar = OverlapGroup:new{ dimen = { w = self.width, h = widget_title:getSize().h }, widget_title, CloseButton:new{ window = self, padding_top = Size.margin.title, }, } local widget_info if self.info_text then widget_info = FrameContainer:new{ padding = Size.padding.default, margin = Size.margin.small, bordersize = 0, TextBoxWidget:new{ text = self.info_text, face = Font:getFace("x_smallinfofont"), width = math.floor(self.width * 0.9), } } else widget_info = VerticalSpan:new{ width = 0 } end local buttons = { { { text = self.cancel_text, callback = function() if self.cancel_callback then self.cancel_callback() end self:onClose() end, }, { text = self.ok_text, callback = function() if self.callback then self.callback(left_widget:getValue(), right_widget:getValue()) end if not self.keep_shown_on_apply then self:onClose() end end, }, }, } if self.default_values then table.insert(buttons,{ { text = self.default_text, callback = function() left_widget.value = self.left_default right_widget.value = self.right_default left_widget:update() right_widget:update() self.callback(nil, nil) end, } }) end if self.extra_text then table.insert(buttons,{ { text = self.extra_text, callback = function() if self.extra_callback then self.extra_callback(left_widget:getValue(), right_widget:getValue()) end if not self.keep_shown_on_apply then -- assume extra wants it same as ok self:onClose() end end, }, }) end local button_table = ButtonTable:new{ width = self.width - 2*Size.padding.default, buttons = buttons, zero_sep = true, show_parent = self, } self.widget_frame = FrameContainer:new{ radius = Size.radius.window, padding = 0, margin = 0, background = Blitbuffer.COLOR_WHITE, VerticalGroup:new{ align = "left", widget_bar, widget_line, widget_info, VerticalSpan:new{ width = Size.span.vertical_large }, CenterContainer:new{ dimen = Geom:new{ w = self.width, h = widget_group:getSize().h, }, widget_group }, VerticalSpan:new{ width = Size.span.vertical_large }, CenterContainer:new{ dimen = Geom:new{ w = self.width, h = button_table:getSize().h, }, button_table } } } self.movable = MovableContainer:new{ self.widget_frame, } self[1] = WidgetContainer:new{ align = "center", dimen = Geom:new{ x = 0, y = 0, w = self.screen_width, h = self.screen_height, }, self.movable, } -- If we're translucent, Button itself will handle that post-callback, in order to preserve alpha without flickering. if not self.movable.alpha then UIManager:setDirty(self, function() return "ui", self.widget_frame.dimen end) end end function DoubleSpinWidget:hasMoved() local offset = self.movable:getMovedOffset() return offset.x ~= 0 or offset.y ~= 0 end function DoubleSpinWidget:onCloseWidget() UIManager:setDirty(nil, function() return "ui", self.widget_frame.dimen end) return true end function DoubleSpinWidget:onShow() UIManager:setDirty(self, function() return "ui", self.widget_frame.dimen end) return true end function DoubleSpinWidget:onAnyKeyPressed() self:onClose() return true end function DoubleSpinWidget:onTapClose(arg, ges_ev) if ges_ev.pos:notIntersectWith(self.widget_frame.dimen) then self:onClose() end return true end function DoubleSpinWidget:onClose() UIManager:close(self) if self.close_callback then self.close_callback() end return true end return DoubleSpinWidget
agpl-3.0
openLuat/Luat
lib/patch.lua
1
2374
--- AM2320 系统补丁 -- @license MIT -- @copyright openLuat.com -- @release 2017.10.19 --[[ 模块名称:Lua自带接口补丁 模块功能:补丁某些Lua自带的接口,规避调用异常时死机 模块最后修改时间:2017.02.14 ]] --保存Lua自带的os.time接口 local oldostime = os.time --[[ 函数名:safeostime 功能 :封装自定义的os.time接口 参数 : t:日期表,如果没有传入,使用系统当前时间 返回值:t时间距离1970年1月1日0时0分0秒所经过的秒数 ]] function safeostime(t) return oldostime(t) or 0 end --Lua自带的os.time接口指向自定义的safeostime接口 os.time = safeostime --保存Lua自带的os.date接口 local oldosdate = os.date --[[ 函数名:safeosdate 功能 :封装自定义的os.date接口 参数 : s:输出格式 t:距离1970年1月1日0时0分0秒所经过的秒数 返回值:参考Lua自带的os.date接口说明 ]] function safeosdate(s, t) if s == "*t" then return oldosdate(s, t) or {year = 2012, month = 12, day = 11, hour = 10, min = 9, sec = 0} else return oldosdate(s, t) end end --Lua自带的os.date接口指向自定义的safeosdate接口 os.date = safeosdate -- 对coroutine.resume加一个修饰器用于捕获协程错误 local rawcoresume = coroutine.resume coroutine.resume = function(...) function wrapper(...) if not arg[1] then log.error("coroutine.resume", arg[2]) end return unpack(arg) end return wrapper(rawcoresume(unpack(arg))) end --保存Lua自带的json.decode接口 if json and json.decode then oldjsondecode = json.decode end --- 封装自定义的json.decode接口 -- @string s,json格式的字符串 -- @return table,第一个返回值为解析json字符串后的table -- @return boole,第二个返回值为解析结果(true表示成功,false失败) -- @return string,第三个返回值可选(只有第二个返回值为false时,才有意义),表示出错信息 function safejsondecode(s) local result, info = pcall(oldjsondecode, s) if result then return info, true else return {}, false, info end end --Lua自带的json.decode接口指向自定义的safejsondecode接口 if json and json.decode then json.decode = safejsondecode end
mit
sdgdsffdsfff/nginx-openresty-windows
lua-cjson-2.1.0.2/tests/bench.lua
145
3247
#!/usr/bin/env lua -- This benchmark script measures wall clock time and should be -- run on an unloaded system. -- -- Your Mileage May Vary. -- -- Mark Pulford <mark@kyne.com.au> local json_module = os.getenv("JSON_MODULE") or "cjson" require "socket" local json = require(json_module) local util = require "cjson.util" local function find_func(mod, funcnames) for _, v in ipairs(funcnames) do if mod[v] then return mod[v] end end return nil end local json_encode = find_func(json, { "encode", "Encode", "to_string", "stringify", "json" }) local json_decode = find_func(json, { "decode", "Decode", "to_value", "parse" }) local function average(t) local total = 0 for _, v in ipairs(t) do total = total + v end return total / #t end function benchmark(tests, seconds, rep) local function bench(func, iter) -- Use socket.gettime() to measure microsecond resolution -- wall clock time. local t = socket.gettime() for i = 1, iter do func(i) end t = socket.gettime() - t -- Don't trust any results when the run lasted for less than a -- millisecond - return nil. if t < 0.001 then return nil end return (iter / t) end -- Roughly calculate the number of interations required -- to obtain a particular time period. local function calc_iter(func, seconds) local iter = 1 local rate -- Warm up the bench function first. func() while not rate do rate = bench(func, iter) iter = iter * 10 end return math.ceil(seconds * rate) end local test_results = {} for name, func in pairs(tests) do -- k(number), v(string) -- k(string), v(function) -- k(number), v(function) if type(func) == "string" then name = func func = _G[name] end local iter = calc_iter(func, seconds) local result = {} for i = 1, rep do result[i] = bench(func, iter) end -- Remove the slowest half (round down) of the result set table.sort(result) for i = 1, math.floor(#result / 2) do table.remove(result, 1) end test_results[name] = average(result) end return test_results end function bench_file(filename) local data_json = util.file_load(filename) local data_obj = json_decode(data_json) local function test_encode() json_encode(data_obj) end local function test_decode() json_decode(data_json) end local tests = {} if json_encode then tests.encode = test_encode end if json_decode then tests.decode = test_decode end return benchmark(tests, 0.1, 5) end -- Optionally load any custom configuration required for this module local success, data = pcall(util.file_load, ("bench-%s.lua"):format(json_module)) if success then util.run_script(data, _G) configure(json) end for i = 1, #arg do local results = bench_file(arg[i]) for k, v in pairs(results) do print(("%s\t%s\t%d"):format(arg[i], k, v)) end end -- vi:ai et sw=4 ts=4:
bsd-2-clause
JRTXGaming/GuildDing_RIFT
libs/LibVersionCheck/ApiBrowser.lua
1
1912
if(not ApiBrowser) then return -- Don't process the remaining file if ApiBrowser is not installed end local symbols = { } symbols["LibVersionCheck.register"] = { summary = [[ Registers an addon and its current version with the library. This should be called from Addon initialization code, typically in a handler for Event.Addon.Load.End. It may be put into Event.Addon.Startup.End as well, but beware: version registration needs to take place before the Event.Addon.Startup.End handler of LibVersionCheck is called, which is done with a priority of -99. So, if you have reason to use Startup.End instead of Load.End, make sure you register the event with default priority, or at least a priority greater than -99.]], signatures = { "LibVersionCheck.register(addonName, addonVersion)", }, parameter = { ["addonName"] = "The Name of your Addon, like MyGreatAddon", ["addonVersion"] = "The Version of your Addon, like 2.0 or V2alpha3", }, result = { }, type = "function", } local summary = [[ A library that tries to detect when addons are outdated, by sharing used versions between players. Whenever a player encounters someone else (by grouping with them, or moving the mouse cursor over them; technically: when Event.Unit.Available.Full fires, the library asks the other player for their addon versions, saving the responses to persistent storage. When the player logs in next time, and any of the saved versions is greater than the one the player's addons registered with, the player will get an information screen. The player can then decide when to show the warning again, with several options between "next login" and "next year", so players who are interested in getting informed will, and players who aren't won't be bothered again. ]] local Addon = ... ApiBrowser.AddLibraryWithRiftLikeCatalogIndex(Addon.identifier, Addon.toc.Name, summary, symbols)
gpl-2.0
falsechicken/chickens_riddim_plugins
plugins/command_random.lua
1
2653
--[[ Command_Random Allows users to generate random things. Like numbers, picking a random user in muc room, etc. Licensed Under the GPLv2 --]] local tableUtils = require("riddim/ai_utils/tableutils"); local textUtils = require("riddim/ai_utils/textutils"); local jid_tool = require("riddim/ai_utils/jid_tool"); local permissions = require("riddim/ai_utils/permissions"); local stanzaUtils = require("riddim/ai_utils/stanzautils"); local BOT; local helpMessage = "\n"..[[ - Generates Random Stuff - Usage: @random <argument> # Arguments # - user - Picks a random user in a muc room. - number <min> <max> - Picks a random number between two numbers (Inclusive). - roll <sides> - Simulates a dice roll with specified number of sides. ]]; local invalidArgumentMessage = "Invalid argument. Run @random for help."; local onlyGroupChatMessage = "This argument only works in group chat."; local CheckPermissions = function(_command) if _command.stanza.attr.type == "groupchat" then if permissions.HasPermission(_command.sender["jid"], "command_random", BOT.config.permissions) == false then return false; end return true; else if permissions.HasPermission(jid_tool.StripResourceFromJID(_command.sender["jid"]), "command_random", BOT.config.permissions) == false then return false; end return true; end end local GenerateRandomNumberFromString= function(_min, _max) math.randomseed(os.time()); local n1 = tonumber(_min); local n2 = tonumber(_max); if (type(n1) == "number" and type(n2) == "number") then if (n1 <= 0 or n2 <= 0 or n1 > 2147483647 or n2 > 2147483647) then return "Number cannot be negitive or too large. Max size is 2,147,483,647."; end if n2 < n1 then return "Max number cannot be smaller than the min number."; end return tostring(math.random(n1, n2)); else return invalidArgumentMessage; end end function riddim.plugins.command_random(_bot) _bot:hook("commands/random", ProcessRandomCommand); BOT = _bot; end function ProcessRandomCommand(_command) if CheckPermissions(_command) then local params = textUtils.Split(_command.param); if _command.param == nil then return helpMessage; end if params[1] == "user" then if stanzaUtils.IsGroupChat(_command) == false then return onlyGroupChatMessage; end return tableUtils.GetRandomKey(_command.room.occupants); elseif params[1] == "number" then return GenerateRandomNumberFromString(params[2], params[3]); elseif params[1] == "roll" then return GenerateRandomNumberFromString(1, params[2]); else return invalidArgumentMessage; end else return "You are not authorized to run this command."; end end
gpl-2.0
vitaliylag/waifu2x
lib/cleanup_model.lua
2
1327
-- ref: https://github.com/torch/nn/issues/112#issuecomment-64427049 local function zeroDataSize(data) if type(data) == 'table' then for i = 1, #data do data[i] = zeroDataSize(data[i]) end elseif type(data) == 'userdata' then data = torch.Tensor():typeAs(data) end return data end -- Resize the output, gradInput, etc temporary tensors to zero (so that the -- on disk size is smaller) local function cleanupModel(node) if node.output ~= nil then node.output = zeroDataSize(node.output) end if node.gradInput ~= nil then node.gradInput = zeroDataSize(node.gradInput) end if node.finput ~= nil then node.finput = zeroDataSize(node.finput) end if tostring(node) == "nn.LeakyReLU" or tostring(node) == "w2nn.LeakyReLU" then if node.negative ~= nil then node.negative = zeroDataSize(node.negative) end end if tostring(node) == "nn.Dropout" then if node.noise ~= nil then node.noise = zeroDataSize(node.noise) end end -- Recurse on nodes with 'modules' if (node.modules ~= nil) then if (type(node.modules) == 'table') then for i = 1, #node.modules do local child = node.modules[i] cleanupModel(child) end end end end function w2nn.cleanup_model(model) cleanupModel(model) return model end
mit
pazos/koreader
spec/unit/luasettings_spec.lua
7
2854
describe("luasettings module", function() local Settings setup(function() require("commonrequire") Settings = require("frontend/luasettings"):open("this-is-not-a-valid-file") end) it("should handle undefined keys", function() Settings:delSetting("abc") assert.True(Settings:hasNot("abc")) assert.True(Settings:nilOrTrue("abc")) assert.False(Settings:isTrue("abc")) Settings:saveSetting("abc", true) assert.True(Settings:has("abc")) assert.True(Settings:nilOrTrue("abc")) assert.True(Settings:isTrue("abc")) end) it("should flip bool values", function() Settings:delSetting("abc") assert.True(Settings:hasNot("abc")) Settings:flipNilOrTrue("abc") assert.False(Settings:nilOrTrue("abc")) assert.True(Settings:has("abc")) assert.False(Settings:isTrue("abc")) Settings:flipNilOrTrue("abc") assert.True(Settings:nilOrTrue("abc")) assert.True(Settings:hasNot("abc")) assert.False(Settings:isTrue("abc")) Settings:flipTrue("abc") assert.True(Settings:has("abc")) assert.True(Settings:isTrue("abc")) assert.True(Settings:nilOrTrue("abc")) Settings:flipTrue("abc") assert.False(Settings:has("abc")) assert.False(Settings:isTrue("abc")) assert.True(Settings:nilOrTrue("abc")) end) it("should create child settings", function() Settings:delSetting("key") Settings:saveSetting("key", { a = "b", c = "true", d = false, }) local child = Settings:child("key") assert.is_not_nil(child) assert.True(child:has("a")) assert.are.equal(child:readSetting("a"), "b") assert.True(child:has("c")) assert.True(child:isTrue("c")) assert.True(child:has("d")) assert.True(child:isFalse("d")) assert.False(child:isTrue("e")) child:flipTrue("e") child:close() child = Settings:child("key") assert.True(child:isTrue("e")) end) describe("table wrapper", function() Settings:delSetting("key") it("should add item to table", function() Settings:addTableItem("key", 1) Settings:addTableItem("key", 2) Settings:addTableItem("key", 3) assert.are.equal(1, Settings:readSetting("key")[1]) assert.are.equal(2, Settings:readSetting("key")[2]) assert.are.equal(3, Settings:readSetting("key")[3]) end) it("should remove item from table", function() Settings:removeTableItem("key", 1) assert.are.equal(2, Settings:readSetting("key")[1]) assert.are.equal(3, Settings:readSetting("key")[2]) end) end) end)
agpl-3.0
philsiff/Red-Vs-Blue
Very Basic TDM [Gamemode]/gamemodes/vbtdm/gamemode/scoreboard/scoreboard.lua
1
9236
include( "player_row.lua" ) include( "player_frame.lua" ) surface.CreateFont( "suiscoreboardheader" , {font="coolvetica", size=28, weight=100, antialiasing=true}) surface.CreateFont( "suiscoreboardsubtitle", {font="coolvetica", size=20, weight=100, antialiasing=true}) surface.CreateFont( "suiscoreboardlogotext", {font="coolvetica", size=75, weight=100, antialiasing=true}) surface.CreateFont( "suiscoreboardsuisctext", {font="verdana" , size=12, weight=100, antialiasing=true}) surface.CreateFont( "suiscoreboardplayername", {font = "verdana", size = 16, weight = 5, antialiasing = true}) local texGradient = surface.GetTextureID( "gui/center_gradient" ) local function ColorCmp( c1, c2 ) if( !c1 || !c2 ) then return false end return (c1.r == c2.r) && (c1.g == c2.g) && (c1.b == c2.b) && (c1.a == c2.a) end local PANEL = {} /*--------------------------------------------------------- Name: Paint ---------------------------------------------------------*/ function PANEL:Init() SCOREBOARD = self self.Hostname = vgui.Create( "DLabel", self ) self.Hostname:SetText( GetHostName() ) self.Logog = vgui.Create( "DLabel", self ) self.Logog:SetText( "TDM" ) self.SuiSc = vgui.Create( "DLabel", self ) self.SuiSc:SetText( "Very Basic Team Deathmatch Scoreboard!" ) self.Description = vgui.Create( "DLabel", self ) self.Description:SetText( GAMEMODE.Name .. " - " .. GAMEMODE.Author ) self.PlayerFrame = vgui.Create( "suiplayerframe", self ) self.PlayerRows = {} self:UpdateScoreboard() // Update the scoreboard every 1 second timer.Create( "SuiScoreboardUpdater", 1, 0, self.UpdateScoreboard ) self.lblPing = vgui.Create( "DLabel", self ) self.lblPing:SetText( "Ping" ) self.lblKills = vgui.Create( "DLabel", self ) self.lblKills:SetText( "Kills" ) self.lblDeaths = vgui.Create( "DLabel", self ) self.lblDeaths:SetText( "Deaths" ) self.lblRatio = vgui.Create( "DLabel", self ) self.lblRatio:SetText( "Ratio" ) self.lblHealth = vgui.Create( "DLabel", self ) self.lblHealth:SetText( "Health" ) self.lblTeam = vgui.Create( "DLabel", self ) self.lblTeam:SetText( "Team" ) end /*--------------------------------------------------------- Name: Paint ---------------------------------------------------------*/ function PANEL:AddPlayerRow( ply ) local button = vgui.Create( "suiscoreplayerrow", self.PlayerFrame:GetCanvas() ) button:SetPlayer( ply ) self.PlayerRows[ ply ] = button end /*--------------------------------------------------------- Name: Paint ---------------------------------------------------------*/ function PANEL:GetPlayerRow( ply ) return self.PlayerRows[ ply ] end /*--------------------------------------------------------- Name: Paint ---------------------------------------------------------*/ function PANEL:Paint(w,h) draw.RoundedBox( 10, 0, 0, self:GetWide(), self:GetTall(), Color( 50, 50, 50, 205 ) ) surface.SetTexture( texGradient ) surface.SetDrawColor( 100, 100, 100, 155 ) surface.DrawTexturedRect( 0, 0, self:GetWide(), self:GetTall() ) // White Inner Box draw.RoundedBox( 6, 15, self.Description.y - 8, self:GetWide() - 30, self:GetTall() - self.Description.y - 6, Color( 230, 230, 230, 100 ) ) surface.SetTexture( texGradient ) surface.SetDrawColor( 255, 255, 255, 50 ) surface.DrawTexturedRect( 15, self.Description.y - 8, self:GetWide() - 30, self:GetTall() - self.Description.y - 8 ) // Sub Header draw.RoundedBox( 6, 178, self.Description.y - 4, self:GetWide() - 197, self.Description:GetTall() + 8, Color( 100, 100, 100, 155 ) ) surface.SetTexture( texGradient ) surface.SetDrawColor( 255, 255, 255, 50 ) surface.DrawTexturedRect( 178, self.Description.y - 4, self:GetWide() - 197, self.Description:GetTall() + 8 ) // Logo! if( ColorCmp( team.GetColor(21), Color( 255, 255, 100, 255 ) ) ) then tColor = Color( 255, 155, 0, 255 ) else tColor = team.GetColor(21) end if (tColor.r < 255) then tColorGradientR = tColor.r + 15 else tColorGradientR = tColor.r end if (tColor.g < 255) then tColorGradientG = tColor.g + 15 else tColorGradientG = tColor.g end if (tColor.b < 255) then tColorGradientB = tColor.b + 15 else tColorGradientB = tColor.b end draw.RoundedBox( 8, 24, 12, 150, 80, Color( tColor.r, tColor.g, tColor.b, 255 ) ) surface.SetTexture( texGradient ) surface.SetDrawColor( tColorGradientR, tColorGradientG, tColorGradientB, 225 ) surface.DrawTexturedRect( 24, 12, 80, 80 ) //draw.RoundedBox( 4, 10, self.Description.y + self.Description:GetTall() + 6, self:GetWide() - 20, 12, Color( 0, 0, 0, 50 ) ) end /*--------------------------------------------------------- Name: PerformLayout ---------------------------------------------------------*/ function PANEL:PerformLayout() self:SetSize( ScrW() * .75, ScrH() * 0.65 ) self:SetPos( (ScrW() - self:GetWide()) / 2, (ScrH() - self:GetTall()) / 2 ) self.Hostname:SizeToContents() self.Hostname:SetPos( 185, 17 ) self.Logog:SetSize( 150, 80 ) self.Logog:SetPos( 37, 18 ) self.Logog:SetColor( Color(30, 30, 30, 255) ) self.SuiSc:SetSize( 400, 15 ) self.SuiSc:SetPos( (self:GetWide() - 400), (self:GetTall() - 15) ) self.Description:SizeToContents() self.Description:SetPos( 185, 60 ) self.Description:SetColor( Color(30, 30, 30, 255) ) self.PlayerFrame:SetPos( 5, self.Description.y + self.Description:GetTall() + 20 ) self.PlayerFrame:SetSize( self:GetWide() - 10, self:GetTall() - self.PlayerFrame.y - 20 ) local y = 0 local PlayerSorted = {} for k, v in pairs( self.PlayerRows ) do table.insert( PlayerSorted, v ) end table.sort( PlayerSorted, function ( a , b) return a:HigherOrLower( b ) end ) for k, v in ipairs( PlayerSorted ) do v:SetPos( 0, y ) v:SetSize( self.PlayerFrame:GetWide(), v:GetTall() ) self.PlayerFrame:GetCanvas():SetSize( self.PlayerFrame:GetCanvas():GetWide(), y + v:GetTall() ) y = y + v:GetTall() + 1 end self.Hostname:SetText( GetGlobalString( "ServerName","Garry's Mod 13" ) ) self.lblPing:SizeToContents() self.lblKills:SizeToContents() self.lblRatio:SizeToContents() self.lblDeaths:SizeToContents() self.lblHealth:SizeToContents() self.lblTeam:SizeToContents() self.lblPing:SetPos( self:GetWide() - 45 - self.lblPing:GetWide()/2, self.PlayerFrame.y - self.lblPing:GetTall() - 3 ) self.lblRatio:SetPos( self:GetWide() - 45*2.4 - self.lblDeaths:GetWide()/2, self.PlayerFrame.y - self.lblPing:GetTall() - 3 ) self.lblDeaths:SetPos( self:GetWide() - 45*3.4 - self.lblDeaths:GetWide()/2, self.PlayerFrame.y - self.lblPing:GetTall() - 3 ) self.lblKills:SetPos( self:GetWide() - 45*4.4 - self.lblKills:GetWide()/2, self.PlayerFrame.y - self.lblPing:GetTall() - 3 ) self.lblHealth:SetPos( self:GetWide() - 45*5.4 - self.lblKills:GetWide()/2, self.PlayerFrame.y - self.lblPing:GetTall() - 3 ) self.lblTeam:SetPos( self:GetWide() - 45*10.2 - self.lblKills:GetWide()/2, self.PlayerFrame.y - self.lblPing:GetTall() - 3 ) //self.lblKills:SetFont( "DefaultSmall" ) //self.lblDeaths:SetFont( "DefaultSmall" ) end /*--------------------------------------------------------- Name: ApplySchemeSettings ---------------------------------------------------------*/ function PANEL:ApplySchemeSettings() self.Hostname:SetFont( "suiscoreboardheader" ) self.Description:SetFont( "suiscoreboardsubtitle" ) self.Logog:SetFont( "suiscoreboardlogotext" ) self.SuiSc:SetFont( "suiscoreboardsuisctext" ) if (ColorCmp( team.GetColor(21), Color( 255, 255, 100, 255 ))) then tColor = Color( 255, 155, 0, 255 ) else tColor = team.GetColor(21) end self.Hostname:SetFGColor( Color( tColor.r, tColor.g, tColor.b, 255 ) ) self.Description:SetFGColor( Color( 55, 55, 55, 255 ) ) self.Logog:SetFGColor( Color( 0, 0, 0, 255 ) ) self.SuiSc:SetFGColor( Color( 200, 200, 200, 200 ) ) self.lblPing:SetFont( "Default" ) self.lblKills:SetFont( "Default" ) self.lblDeaths:SetFont( "Default" ) self.lblTeam:SetFont( "Default" ) self.lblHealth:SetFont( "Default" ) self.lblRatio:SetFont( "Default" ) self.lblPing:SetColor( Color( 0, 0, 0, 255 ) ) self.lblKills:SetColor( Color( 0, 0, 0, 255 ) ) self.lblDeaths:SetColor( Color( 0, 0, 0, 255 ) ) self.lblTeam:SetColor( Color( 0, 0, 0, 255 ) ) self.lblHealth:SetColor( Color( 0, 0, 0, 255 ) ) self.lblRatio:SetColor( Color( 0, 0, 0, 255 ) ) self.lblPing:SetFGColor( Color( 0, 0, 0, 255 ) ) self.lblKills:SetFGColor( Color( 0, 0, 0, 255 ) ) self.lblDeaths:SetFGColor( Color( 0, 0, 0, 255 ) ) self.lblTeam:SetFGColor( Color( 0, 0, 0, 255 ) ) self.lblHealth:SetFGColor( Color( 0, 0, 0, 255 ) ) self.lblRatio:SetFGColor( Color( 0, 0, 0, 255 ) ) end function PANEL:UpdateScoreboard( force ) if self then if ( !force and !self:IsVisible() ) then return end for k, v in pairs( self.PlayerRows ) do if ( !k:IsValid() ) then v:Remove() self.PlayerRows[ k ] = nil end end local PlayerList = player.GetAll() for id, pl in pairs( PlayerList ) do if ( !self:GetPlayerRow( pl ) ) then self:AddPlayerRow( pl ) end end // Always invalidate the layout so the order gets updated self:InvalidateLayout() end end vgui.Register( "suiscoreboard", PANEL, "Panel" )
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/sandbox/gamemode/init.lua
2
5193
--[[--------------------------------------------------------- Sandbox Gamemode This is GMod's default gamemode -----------------------------------------------------------]] -- These files get sent to the client AddCSLuaFile( "cl_hints.lua" ) AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "cl_notice.lua" ) AddCSLuaFile( "cl_search_models.lua" ) AddCSLuaFile( "cl_spawnmenu.lua" ) AddCSLuaFile( "cl_worldtips.lua" ) AddCSLuaFile( "persistence.lua" ) AddCSLuaFile( "player_extension.lua" ) AddCSLuaFile( "save_load.lua" ) AddCSLuaFile( "shared.lua" ) AddCSLuaFile( "gui/IconEditor.lua" ) include( 'shared.lua' ) include( 'commands.lua' ) include( 'player.lua' ) include( 'spawnmenu/init.lua' ) -- -- Make BaseClass available -- DEFINE_BASECLASS( "gamemode_base" ) --[[--------------------------------------------------------- Name: gamemode:PlayerSpawn( ) Desc: Called when a player spawns -----------------------------------------------------------]] function GM:PlayerSpawn( pl ) player_manager.SetPlayerClass( pl, "player_sandbox" ) BaseClass.PlayerSpawn( self, pl ) end --[[--------------------------------------------------------- Name: gamemode:OnPhysgunFreeze( weapon, phys, ent, player ) Desc: The physgun wants to freeze a prop -----------------------------------------------------------]] function GM:OnPhysgunFreeze( weapon, phys, ent, ply ) -- Don't freeze persistent props (should already be froze) if ( ent:GetPersistent() ) then return false end BaseClass.OnPhysgunFreeze( self, weapon, phys, ent, ply ) ply:SendHint( "PhysgunUnfreeze", 0.3 ) ply:SuppressHint( "PhysgunFreeze" ) end --[[--------------------------------------------------------- Name: gamemode:OnPhysgunReload( weapon, player ) Desc: The physgun wants to unfreeze -----------------------------------------------------------]] function GM:OnPhysgunReload( weapon, ply ) local num = ply:PhysgunUnfreeze() if ( num > 0 ) then ply:SendLua( "GAMEMODE:UnfrozeObjects("..num..")" ) end ply:SuppressHint( "PhysgunReload" ) end --[[--------------------------------------------------------- Name: gamemode:PlayerShouldTakeDamage Return true if this player should take damage from this attacker Note: This is a shared function - the client will think they can damage the players even though they can't. This just means the prediction will show blood. -----------------------------------------------------------]] function GM:PlayerShouldTakeDamage( ply, attacker ) -- The player should always take damage in single player.. if ( game.SinglePlayer() ) then return true end -- Global godmode, players can't be damaged in any way if ( cvars.Bool( "sbox_godmode", false ) ) then return false end -- No player vs player damage if ( attacker:IsValid() && attacker:IsPlayer() ) then return cvars.Bool( "sbox_playershurtplayers", true ) end -- Default, let the player be hurt return true end --[[--------------------------------------------------------- Show the search when f1 is pressed -----------------------------------------------------------]] function GM:ShowHelp( ply ) ply:SendLua( "hook.Run( 'StartSearch' )" ); end --[[--------------------------------------------------------- Called once on the player's first spawn -----------------------------------------------------------]] function GM:PlayerInitialSpawn( ply ) BaseClass.PlayerInitialSpawn( self, ply ) end --[[--------------------------------------------------------- Desc: A ragdoll of an entity has been created -----------------------------------------------------------]] function GM:CreateEntityRagdoll( entity, ragdoll ) -- Replace the entity with the ragdoll in cleanups etc undo.ReplaceEntity( entity, ragdoll ) cleanup.ReplaceEntity( entity, ragdoll ) end --[[--------------------------------------------------------- Name: gamemode:PlayerUnfrozeObject( ) -----------------------------------------------------------]] function GM:PlayerUnfrozeObject( ply, entity, physobject ) local effectdata = EffectData() effectdata:SetOrigin( physobject:GetPos() ) effectdata:SetEntity( entity ) util.Effect( "phys_unfreeze", effectdata, true, true ) end --[[--------------------------------------------------------- Name: gamemode:PlayerFrozeObject( ) -----------------------------------------------------------]] function GM:PlayerFrozeObject( ply, entity, physobject ) if ( DisablePropCreateEffect ) then return end local effectdata = EffectData() effectdata:SetOrigin( physobject:GetPos() ) effectdata:SetEntity( entity ) util.Effect( "phys_freeze", effectdata, true, true ) end -- -- Who can edit variables? -- If you're writing prop protection or something, you'll -- probably want to hook or override this function. -- function GM:CanEditVariable( ent, ply, key, val, editor ) -- Only allow admins to edit admin only variables! if ( editor.AdminOnly ) then return ply:IsAdmin() end -- This entity decides who can edit its variables if ( isfunction( ent.CanEditVariables ) ) then return ent:CanEditVariables( ply ) end -- default in sandbox is.. anyone can edit anything. return true end
mit
bradchesney79/2015BeastRouterProject
openwrt/unsquash/squashfs-root/usr/lib/lua/luci/dispatcher.lua
31
19783
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local sys = require "luci.sys" local util = require "luci.util" local http = require "luci.http" local nixio = require "nixio", require "nixio.util" module("luci.dispatcher", package.seeall) context = util.threadlocal() uci = require "luci.model.uci" i18n = require "luci.i18n" _M.fs = fs authenticator = {} -- Index table local index = nil -- Fastindex local fi function build_url(...) local path = {...} local url = { http.getenv("SCRIPT_NAME") or "" } local k, v for k, v in pairs(context.urltoken) do url[#url+1] = "/;" url[#url+1] = http.urlencode(k) url[#url+1] = "=" url[#url+1] = http.urlencode(v) end local p for _, p in ipairs(path) do if p:match("^[a-zA-Z0-9_%-%.%%/,;]+$") then url[#url+1] = "/" url[#url+1] = p end end return table.concat(url, "") end function node_visible(node) if node then return not ( (not node.title or #node.title == 0) or (not node.target or node.hidden == true) or (type(node.target) == "table" and node.target.type == "firstchild" and (type(node.nodes) ~= "table" or not next(node.nodes))) ) end return false end function node_childs(node) local rv = { } if node then local k, v for k, v in util.spairs(node.nodes, function(a, b) return (node.nodes[a].order or 100) < (node.nodes[b].order or 100) end) do if node_visible(v) then rv[#rv+1] = k end end end return rv end function error404(message) http.status(404, "Not Found") message = message or "Not Found" require("luci.template") if not util.copcall(luci.template.render, "error404") then http.prepare_content("text/plain") http.write(message) end return false end function error500(message) util.perror(message) if not context.template_header_sent then http.status(500, "Internal Server Error") http.prepare_content("text/plain") http.write(message) else require("luci.template") if not util.copcall(luci.template.render, "error500", {message=message}) then http.prepare_content("text/plain") http.write(message) end end return false end function authenticator.htmlauth(validator, accs, default) local user = http.formvalue("luci_username") local pass = http.formvalue("luci_password") if user and validator(user, pass) then return user end if context.urltoken.stok then context.urltoken.stok = nil local cookie = 'sysauth=%s; expires=%s; path=%s/' %{ http.getcookie('sysauth') or 'x', 'Thu, 01 Jan 1970 01:00:00 GMT', build_url() } http.header("Set-Cookie", cookie) http.redirect(build_url()) else require("luci.i18n") require("luci.template") context.path = {} http.status(403, "Forbidden") luci.template.render("sysauth", {duser=default, fuser=user}) end return false end function httpdispatch(request, prefix) http.context.request = request local r = {} context.request = r context.urltoken = {} local pathinfo = http.urldecode(request:getenv("PATH_INFO") or "", true) if prefix then for _, node in ipairs(prefix) do r[#r+1] = node end end local tokensok = true for node in pathinfo:gmatch("[^/]+") do local tkey, tval if tokensok then tkey, tval = node:match(";(%w+)=([a-fA-F0-9]*)") end if tkey then context.urltoken[tkey] = tval else tokensok = false r[#r+1] = node end end local stat, err = util.coxpcall(function() dispatch(context.request) end, error500) http.close() --context._disable_memtrace() end function dispatch(request) --context._disable_memtrace = require "luci.debug".trap_memtrace("l") local ctx = context ctx.path = request local conf = require "luci.config" assert(conf.main, "/etc/config/luci seems to be corrupt, unable to find section 'main'") local lang = conf.main.lang or "auto" if lang == "auto" then local aclang = http.getenv("HTTP_ACCEPT_LANGUAGE") or "" for lpat in aclang:gmatch("[%w-]+") do lpat = lpat and lpat:gsub("-", "_") if conf.languages[lpat] then lang = lpat break end end end require "luci.i18n".setlanguage(lang) local c = ctx.tree local stat if not c then c = createtree() end local track = {} local args = {} ctx.args = args ctx.requestargs = ctx.requestargs or args local n local token = ctx.urltoken local preq = {} local freq = {} for i, s in ipairs(request) do preq[#preq+1] = s freq[#freq+1] = s c = c.nodes[s] n = i if not c then break end util.update(track, c) if c.leaf then break end end if c and c.leaf then for j=n+1, #request do args[#args+1] = request[j] freq[#freq+1] = request[j] end end ctx.requestpath = ctx.requestpath or freq ctx.path = preq if track.i18n then i18n.loadc(track.i18n) end -- Init template engine if (c and c.index) or not track.notemplate then local tpl = require("luci.template") local media = track.mediaurlbase or luci.config.main.mediaurlbase if not pcall(tpl.Template, "themes/%s/header" % fs.basename(media)) then media = nil for name, theme in pairs(luci.config.themes) do if name:sub(1,1) ~= "." and pcall(tpl.Template, "themes/%s/header" % fs.basename(theme)) then media = theme end end assert(media, "No valid theme found") end local function _ifattr(cond, key, val) if cond then local env = getfenv(3) local scope = (type(env.self) == "table") and env.self return string.format( ' %s="%s"', tostring(key), util.pcdata(tostring( val or (type(env[key]) ~= "function" and env[key]) or (scope and type(scope[key]) ~= "function" and scope[key]) or "" )) ) else return '' end end tpl.context.viewns = setmetatable({ write = http.write; include = function(name) tpl.Template(name):render(getfenv(2)) end; translate = i18n.translate; translatef = i18n.translatef; export = function(k, v) if tpl.context.viewns[k] == nil then tpl.context.viewns[k] = v end end; striptags = util.striptags; pcdata = util.pcdata; media = media; theme = fs.basename(media); resource = luci.config.main.resourcebase; ifattr = function(...) return _ifattr(...) end; attr = function(...) return _ifattr(true, ...) end; }, {__index=function(table, key) if key == "controller" then return build_url() elseif key == "REQUEST_URI" then return build_url(unpack(ctx.requestpath)) else return rawget(table, key) or _G[key] end end}) end track.dependent = (track.dependent ~= false) assert(not track.dependent or not track.auto, "Access Violation\nThe page at '" .. table.concat(request, "/") .. "/' " .. "has no parent node so the access to this location has been denied.\n" .. "This is a software bug, please report this message at " .. "http://luci.subsignal.org/trac/newticket" ) if track.sysauth then local authen = type(track.sysauth_authenticator) == "function" and track.sysauth_authenticator or authenticator[track.sysauth_authenticator] local def = (type(track.sysauth) == "string") and track.sysauth local accs = def and {track.sysauth} or track.sysauth local sess = ctx.authsession local verifytoken = false if not sess then sess = http.getcookie("sysauth") sess = sess and sess:match("^[a-f0-9]*$") verifytoken = true end local sdat = (util.ubus("session", "get", { ubus_rpc_session = sess }) or { }).values local user if sdat then if not verifytoken or ctx.urltoken.stok == sdat.token then user = sdat.user end else local eu = http.getenv("HTTP_AUTH_USER") local ep = http.getenv("HTTP_AUTH_PASS") if eu and ep and sys.user.checkpasswd(eu, ep) then authen = function() return eu end end end if not util.contains(accs, user) then if authen then local user, sess = authen(sys.user.checkpasswd, accs, def) local token if not user or not util.contains(accs, user) then return else if not sess then local sdat = util.ubus("session", "create", { timeout = tonumber(luci.config.sauth.sessiontime) }) if sdat then token = sys.uniqueid(16) util.ubus("session", "set", { ubus_rpc_session = sdat.ubus_rpc_session, values = { user = user, token = token, section = sys.uniqueid(16) } }) sess = sdat.ubus_rpc_session end end if sess and token then http.header("Set-Cookie", 'sysauth=%s; path=%s/' %{ sess, build_url() }) ctx.urltoken.stok = token ctx.authsession = sess ctx.authuser = user http.redirect(build_url(unpack(ctx.requestpath))) end end else http.status(403, "Forbidden") return end else ctx.authsession = sess ctx.authuser = user end end if track.setgroup then sys.process.setgroup(track.setgroup) end if track.setuser then -- trigger ubus connection before dropping root privs util.ubus() sys.process.setuser(track.setuser) end local target = nil if c then if type(c.target) == "function" then target = c.target elseif type(c.target) == "table" then target = c.target.target end end if c and (c.index or type(target) == "function") then ctx.dispatched = c ctx.requested = ctx.requested or ctx.dispatched end if c and c.index then local tpl = require "luci.template" if util.copcall(tpl.render, "indexer", {}) then return true end end if type(target) == "function" then util.copcall(function() local oldenv = getfenv(target) local module = require(c.module) local env = setmetatable({}, {__index= function(tbl, key) return rawget(tbl, key) or module[key] or oldenv[key] end}) setfenv(target, env) end) local ok, err if type(c.target) == "table" then ok, err = util.copcall(target, c.target, unpack(args)) else ok, err = util.copcall(target, unpack(args)) end assert(ok, "Failed to execute " .. (type(c.target) == "function" and "function" or c.target.type or "unknown") .. " dispatcher target for entry '/" .. table.concat(request, "/") .. "'.\n" .. "The called action terminated with an exception:\n" .. tostring(err or "(unknown)")) else local root = node() if not root or not root.target then error404("No root node was registered, this usually happens if no module was installed.\n" .. "Install luci-mod-admin-full and retry. " .. "If the module is already installed, try removing the /tmp/luci-indexcache file.") else error404("No page is registered at '/" .. table.concat(request, "/") .. "'.\n" .. "If this url belongs to an extension, make sure it is properly installed.\n" .. "If the extension was recently installed, try removing the /tmp/luci-indexcache file.") end end end function createindex() local controllers = { } local base = "%s/controller/" % util.libpath() local _, path for path in (fs.glob("%s*.lua" % base) or function() end) do controllers[#controllers+1] = path end for path in (fs.glob("%s*/*.lua" % base) or function() end) do controllers[#controllers+1] = path end if indexcache then local cachedate = fs.stat(indexcache, "mtime") if cachedate then local realdate = 0 for _, obj in ipairs(controllers) do local omtime = fs.stat(obj, "mtime") realdate = (omtime and omtime > realdate) and omtime or realdate end if cachedate > realdate and sys.process.info("uid") == 0 then assert( sys.process.info("uid") == fs.stat(indexcache, "uid") and fs.stat(indexcache, "modestr") == "rw-------", "Fatal: Indexcache is not sane!" ) index = loadfile(indexcache)() return index end end end index = {} for _, path in ipairs(controllers) do local modname = "luci.controller." .. path:sub(#base+1, #path-4):gsub("/", ".") local mod = require(modname) assert(mod ~= true, "Invalid controller file found\n" .. "The file '" .. path .. "' contains an invalid module line.\n" .. "Please verify whether the module name is set to '" .. modname .. "' - It must correspond to the file path!") local idx = mod.index assert(type(idx) == "function", "Invalid controller file found\n" .. "The file '" .. path .. "' contains no index() function.\n" .. "Please make sure that the controller contains a valid " .. "index function and verify the spelling!") index[modname] = idx end if indexcache then local f = nixio.open(indexcache, "w", 600) f:writeall(util.get_bytecode(index)) f:close() end end -- Build the index before if it does not exist yet. function createtree() if not index then createindex() end local ctx = context local tree = {nodes={}, inreq=true} local modi = {} ctx.treecache = setmetatable({}, {__mode="v"}) ctx.tree = tree ctx.modifiers = modi -- Load default translation require "luci.i18n".loadc("base") local scope = setmetatable({}, {__index = luci.dispatcher}) for k, v in pairs(index) do scope._NAME = k setfenv(v, scope) v() end local function modisort(a,b) return modi[a].order < modi[b].order end for _, v in util.spairs(modi, modisort) do scope._NAME = v.module setfenv(v.func, scope) v.func() end return tree end function modifier(func, order) context.modifiers[#context.modifiers+1] = { func = func, order = order or 0, module = getfenv(2)._NAME } end function assign(path, clone, title, order) local obj = node(unpack(path)) obj.nodes = nil obj.module = nil obj.title = title obj.order = order setmetatable(obj, {__index = _create_node(clone)}) return obj end function entry(path, target, title, order) local c = node(unpack(path)) c.target = target c.title = title c.order = order c.module = getfenv(2)._NAME return c end -- enabling the node. function get(...) return _create_node({...}) end function node(...) local c = _create_node({...}) c.module = getfenv(2)._NAME c.auto = nil return c end function _create_node(path) if #path == 0 then return context.tree end local name = table.concat(path, ".") local c = context.treecache[name] if not c then local last = table.remove(path) local parent = _create_node(path) c = {nodes={}, auto=true} -- the node is "in request" if the request path matches -- at least up to the length of the node path if parent.inreq and context.path[#path+1] == last then c.inreq = true end parent.nodes[last] = c context.treecache[name] = c end return c end -- Subdispatchers -- function _firstchild() local path = { unpack(context.path) } local name = table.concat(path, ".") local node = context.treecache[name] local lowest if node and node.nodes and next(node.nodes) then local k, v for k, v in pairs(node.nodes) do if not lowest or (v.order or 100) < (node.nodes[lowest].order or 100) then lowest = k end end end assert(lowest ~= nil, "The requested node contains no childs, unable to redispatch") path[#path+1] = lowest dispatch(path) end function firstchild() return { type = "firstchild", target = _firstchild } end function alias(...) local req = {...} return function(...) for _, r in ipairs({...}) do req[#req+1] = r end dispatch(req) end end function rewrite(n, ...) local req = {...} return function(...) local dispatched = util.clone(context.dispatched) for i=1,n do table.remove(dispatched, 1) end for i, r in ipairs(req) do table.insert(dispatched, i, r) end for _, r in ipairs({...}) do dispatched[#dispatched+1] = r end dispatch(dispatched) end end local function _call(self, ...) local func = getfenv()[self.name] assert(func ~= nil, 'Cannot resolve function "' .. self.name .. '". Is it misspelled or local?') assert(type(func) == "function", 'The symbol "' .. self.name .. '" does not refer to a function but data ' .. 'of type "' .. type(func) .. '".') if #self.argv > 0 then return func(unpack(self.argv), ...) else return func(...) end end function call(name, ...) return {type = "call", argv = {...}, name = name, target = _call} end local _template = function(self, ...) require "luci.template".render(self.view) end function template(name) return {type = "template", view = name, target = _template} end local function _cbi(self, ...) local cbi = require "luci.cbi" local tpl = require "luci.template" local http = require "luci.http" local config = self.config or {} local maps = cbi.load(self.model, ...) local state = nil for i, res in ipairs(maps) do res.flow = config local cstate = res:parse() if cstate and (not state or cstate < state) then state = cstate end end local function _resolve_path(path) return type(path) == "table" and build_url(unpack(path)) or path end if config.on_valid_to and state and state > 0 and state < 2 then http.redirect(_resolve_path(config.on_valid_to)) return end if config.on_changed_to and state and state > 1 then http.redirect(_resolve_path(config.on_changed_to)) return end if config.on_success_to and state and state > 0 then http.redirect(_resolve_path(config.on_success_to)) return end if config.state_handler then if not config.state_handler(state, maps) then return end end http.header("X-CBI-State", state or 0) if not config.noheader then tpl.render("cbi/header", {state = state}) end local redirect local messages local applymap = false local pageaction = true local parsechain = { } for i, res in ipairs(maps) do if res.apply_needed and res.parsechain then local c for _, c in ipairs(res.parsechain) do parsechain[#parsechain+1] = c end applymap = true end if res.redirect then redirect = redirect or res.redirect end if res.pageaction == false then pageaction = false end if res.message then messages = messages or { } messages[#messages+1] = res.message end end for i, res in ipairs(maps) do res:render({ firstmap = (i == 1), applymap = applymap, redirect = redirect, messages = messages, pageaction = pageaction, parsechain = parsechain }) end if not config.nofooter then tpl.render("cbi/footer", { flow = config, pageaction = pageaction, redirect = redirect, state = state, autoapply = config.autoapply }) end end function cbi(model, config) return {type = "cbi", config = config, model = model, target = _cbi} end local function _arcombine(self, ...) local argv = {...} local target = #argv > 0 and self.targets[2] or self.targets[1] setfenv(target.target, self.env) target:target(unpack(argv)) end function arcombine(trg1, trg2) return {type = "arcombine", env = getfenv(), target = _arcombine, targets = {trg1, trg2}} end local function _form(self, ...) local cbi = require "luci.cbi" local tpl = require "luci.template" local http = require "luci.http" local maps = luci.cbi.load(self.model, ...) local state = nil for i, res in ipairs(maps) do local cstate = res:parse() if cstate and (not state or cstate < state) then state = cstate end end http.header("X-CBI-State", state or 0) tpl.render("header") for i, res in ipairs(maps) do res:render() end tpl.render("footer") end function form(model) return {type = "cbi", model = model, target = _form} end translate = i18n.translate -- This function does not actually translate the given argument but -- is used by build/i18n-scan.pl to find translatable entries. function _(text) return text end
cc0-1.0
pazos/koreader
spec/unit/readerrolling_spec.lua
4
8880
describe("Readerrolling module", function() local DocumentRegistry, ReaderUI, Event, Screen local readerui, rolling setup(function() require("commonrequire") DocumentRegistry = require("document/documentregistry") ReaderUI = require("apps/reader/readerui") Event = require("ui/event") Screen = require("device").screen local sample_epub = "spec/front/unit/data/juliet.epub" readerui = ReaderUI:new{ dimen = Screen:getSize(), document = DocumentRegistry:openDocument(sample_epub), } rolling = readerui.rolling end) describe("test in portrait screen mode", function() it("should goto portrait screen mode", function() readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_PORTRAIT)) end) it("should goto certain page", function() for i = 1, 10, 5 do rolling:onGotoPage(i) assert.are.same(i, rolling.current_page) end end) it("should goto relative page", function() for i = 20, 40, 5 do rolling:onGotoPage(i) rolling:onGotoViewRel(1) assert.are.same(i + 1, rolling.current_page) rolling:onGotoViewRel(-1) assert.are.same(i, rolling.current_page) end end) it("should goto next chapter", function() local toc = readerui.toc for i = 30, 50, 5 do rolling:onGotoPage(i) rolling:onGotoNextChapter() assert.are.same(toc:getNextChapter(i, 0), rolling.current_page) end end) it("should goto previous chapter", function() local toc = readerui.toc for i = 60, 80, 5 do rolling:onGotoPage(i) rolling:onGotoPrevChapter() assert.are.same(toc:getPreviousChapter(i, 0), rolling.current_page) end end) it("should emit EndOfBook event at the end of sample epub", function() local called = false readerui.onEndOfBook = function() called = true end -- check beginning of the book rolling:onGotoPage(1) assert.is.falsy(called) rolling:onGotoViewRel(-1) rolling:onGotoViewRel(-1) assert.is.falsy(called) -- check end of the book rolling:onGotoPage(readerui.document:getPageCount()) assert.is.falsy(called) rolling:onGotoViewRel(1) assert.is.truthy(called) rolling:onGotoViewRel(1) assert.is.truthy(called) readerui.onEndOfBook = nil end) it("should emit EndOfBook event at the end sample txt", function() local sample_txt = "spec/front/unit/data/sample.txt" local txt_readerui = ReaderUI:new{ dimen = Screen:getSize(), document = DocumentRegistry:openDocument(sample_txt), } local called = false txt_readerui.onEndOfBook = function() called = true end local txt_rolling = txt_readerui.rolling -- check beginning of the book txt_rolling:onGotoPage(1) assert.is.falsy(called) txt_rolling:onGotoViewRel(-1) txt_rolling:onGotoViewRel(-1) assert.is.falsy(called) -- not at the end of the book txt_rolling:onGotoPage(3) assert.is.falsy(called) txt_rolling:onGotoViewRel(1) assert.is.falsy(called) -- at the end of the book txt_rolling:onGotoPage(txt_readerui.document:getPageCount()) assert.is.falsy(called) txt_rolling:onGotoViewRel(1) assert.is.truthy(called) readerui.onEndOfBook = nil txt_readerui:closeDocument() txt_readerui:onClose() end) end) describe("test in landscape screen mode", function() it("should go to landscape screen mode", function() readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_LANDSCAPE)) end) it("should goto certain page", function() for i = 1, 10, 5 do rolling:onGotoPage(i) assert.are.same(i, rolling.current_page) end end) it("should goto relative page", function() for i = 20, 40, 5 do rolling:onGotoPage(i) rolling:onGotoViewRel(1) assert.are.same(i + 1, rolling.current_page) rolling:onGotoViewRel(-1) assert.are.same(i, rolling.current_page) end end) it("should goto next chapter", function() local toc = readerui.toc for i = 30, 50, 5 do rolling:onGotoPage(i) rolling:onGotoNextChapter() assert.are.same(toc:getNextChapter(i, 0), rolling.current_page) end end) it("should goto previous chapter", function() local toc = readerui.toc for i = 60, 80, 5 do rolling:onGotoPage(i) rolling:onGotoPrevChapter() assert.are.same(toc:getPreviousChapter(i, 0), rolling.current_page) end end) it("should emit EndOfBook event at the end", function() rolling:onGotoPage(readerui.document:getPageCount()) local called = false readerui.onEndOfBook = function() called = true end rolling:onGotoViewRel(1) rolling:onGotoViewRel(1) assert.is.truthy(called) readerui.onEndOfBook = nil end) end) describe("switching screen mode should not change current page number", function() teardown(function() readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_PORTRAIT)) end) it("for portrait-landscape-portrait switching", function() for i = 80, 100, 10 do readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_PORTRAIT)) rolling:onGotoPage(i) assert.are.same(i, rolling.current_page) readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_LANDSCAPE)) assert.are_not.same(i, rolling.current_page) readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_PORTRAIT)) assert.are.same(i, rolling.current_page) end end) it("for landscape-portrait-landscape switching", function() for i = 110, 130, 10 do readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_LANDSCAPE)) rolling:onGotoPage(i) assert.are.same(i, rolling.current_page) readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_PORTRAIT)) assert.are_not.same(i, rolling.current_page) readerui:handleEvent(Event:new("SetRotationMode", Screen.ORIENTATION_LANDSCAPE)) assert.are.same(i, rolling.current_page) end end) end) describe("test changing word gap - space condensing", function() it("should show pages for different word gap", function() readerui:handleEvent(Event:new("SetWordSpacing", {100, 90})) assert.are.same(252, readerui.document:getPageCount()) readerui:handleEvent(Event:new("SetWordSpacing", {95, 75})) assert.are.same(241, readerui.document:getPageCount()) readerui:handleEvent(Event:new("SetWordSpacing", {75, 50})) assert.are.same(231, readerui.document:getPageCount()) end) end) describe("test initialization", function() it("should emit PageUpdate event after book is rendered", function() local ReaderView = require("apps/reader/modules/readerview") local saved_handler = ReaderView.onPageUpdate ReaderView.onPageUpdate = function(_self) assert.are.same(6, _self.ui.document:getPageCount()) end local test_book = "spec/front/unit/data/sample.txt" require("docsettings"):open(test_book):purge() local tmp_readerui = ReaderUI:new{ document = DocumentRegistry:openDocument(test_book), } ReaderView.onPageUpdate = saved_handler tmp_readerui:closeDocument() tmp_readerui:onClose() readerui:closeDocument() readerui:onClose() end) end) end)
agpl-3.0
philsiff/Red-Vs-Blue
Red Vs. Blue Files/lua/vgui/dcombobox.lua
2
4730
--[[ _ ( ) _| | __ _ __ ___ ___ _ _ /'_` | /'__`\( '__)/' _ ` _ `\ /'_` ) ( (_| |( ___/| | | ( ) ( ) |( (_| | `\__,_)`\____)(_) (_) (_) (_)`\__,_) DComboBox --]] PANEL = {} Derma_Hook( PANEL, "Paint", "Paint", "ComboBox" ) Derma_Install_Convar_Functions( PANEL ) --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:Init() self.DropButton = vgui.Create( "DPanel", self ) self.DropButton.Paint = function( panel, w, h ) derma.SkinHook( "Paint", "ComboDownArrow", panel, w, h ) end self.DropButton:SetMouseInputEnabled( false ) self.DropButton.ComboBox = self self:SetTall( 22 ) self:Clear() self:SetContentAlignment( 4 ) self:SetTextInset( 8, 0 ) self:SetIsMenu( true ) end --[[--------------------------------------------------------- Name: Clear -----------------------------------------------------------]] function PANEL:Clear() self:SetText( "" ) self.Choices = {} self.Data = {} if ( self.Menu ) then self.Menu:Remove() self.Menu = nil end end --[[--------------------------------------------------------- Name: GetOptionText -----------------------------------------------------------]] function PANEL:GetOptionText( id ) return self.Choices[ id ] end --[[--------------------------------------------------------- Name: PerformLayout -----------------------------------------------------------]] function PANEL:PerformLayout() self.DropButton:SetSize( 15, 15 ) self.DropButton:AlignRight( 4 ) self.DropButton:CenterVertical() end --[[--------------------------------------------------------- Name: ChooseOption -----------------------------------------------------------]] function PANEL:ChooseOption( value, index ) if ( self.Menu ) then self.Menu:Remove() self.Menu = nil end self:SetText( value ) self:OnSelect( index, value, self.Data[index] ) end --[[--------------------------------------------------------- Name: ChooseOptionID -----------------------------------------------------------]] function PANEL:ChooseOptionID( index ) if ( self.Menu ) then self.Menu:Remove() self.Menu = nil end local value = self:GetOptionText( index ) self:SetText( value ) self:OnSelect( index, value, self.Data[index] ) end --[[--------------------------------------------------------- Name: OnSelect -----------------------------------------------------------]] function PANEL:OnSelect( index, value, data ) -- For override end --[[--------------------------------------------------------- Name: AddChoice -----------------------------------------------------------]] function PANEL:AddChoice( value, data, select ) local i = table.insert( self.Choices, value ) if ( data ) then self.Data[ i ] = data end if ( select ) then self:ChooseOption( value, i ) end return i end function PANEL:IsMenuOpen() return IsValid( self.Menu ) && self.Menu:IsVisible() end --[[--------------------------------------------------------- Name: OpenMenu -----------------------------------------------------------]] function PANEL:OpenMenu( pControlOpener ) if ( pControlOpener ) then if ( pControlOpener == self.TextEntry ) then return end end -- Don't do anything if there aren't any options.. if ( #self.Choices == 0 ) then return end -- If the menu still exists and hasn't been deleted -- then just close it and don't open a new one. if ( IsValid( self.Menu ) ) then self.Menu:Remove() self.Menu = nil end self.Menu = DermaMenu() for k, v in pairs( self.Choices ) do self.Menu:AddOption( v, function() self:ChooseOption( v, k ) end ) end local x, y = self:LocalToScreen( 0, self:GetTall() ) self.Menu:SetMinimumWidth( self:GetWide() ) self.Menu:Open( x, y, false, self ) end function PANEL:CloseMenu() if ( IsValid( self.Menu ) ) then self.Menu:Remove() end end function PANEL:Think() self:ConVarNumberThink() end function PANEL:SetValue( strValue ) self:SetText( strValue ) end function PANEL:DoClick() if ( self:IsMenuOpen() ) then return self:CloseMenu() end self:OpenMenu() end --[[--------------------------------------------------------- Name: GenerateExample -----------------------------------------------------------]] function PANEL:GenerateExample( ClassName, PropertySheet, Width, Height ) local ctrl = vgui.Create( ClassName ) ctrl:AddChoice( "Some Choice" ) ctrl:AddChoice( "Another Choice" ) ctrl:SetWide( 150 ) PropertySheet:AddSheet( ClassName, ctrl, nil, true, true ) end derma.DefineControl( "DComboBox", "", PANEL, "DButton" )
mit
breakds/corpus-accu
cnn-sentence/testing.lua
1
1834
require 'torch' require 'nn' require 'os' ---------- Command Line Options ---------- local cmd = torch.CmdLine() cmd:option('-dictionary', '/home/breakds/tmp/bilibili/input/word_vecs.bin', 'path to the word2vec binary dictionary.') cmd:option('-model', '', 'Specifies the folder where trained model resides.') cmd:option('-input', '', 'Path to the input file') cmd:option('-sentence_size', 20, 'Max allowed length of sentences.') local arguments = cmd:parse(arg) function Testing() local Dictionary = require 'DataHandler.Dictionary' local DataSet = require 'DataHandler.DataSet' local SimpleCNN = require 'Model.SimpleCNN' assert(arguments.dictionary) assert(arguments.model) assert(arguments.input) -- Load Dictionary local dictionary = Dictionary(arguments.dictionary) -- Load Model local model = SimpleCNN {load_path = arguments.model} -- Options local options = {} options.sentence_size = arguments.sentence_size options.dictionary = dictionary -- Load Input local input = DataSet.Load(arguments.input, options) -- Testing local input_file = assert(torch.DiskFile(arguments.input, 'r')) for i = 1, input:size(1) do local input_vector = torch.Tensor(arguments.sentence_size, dictionary.dimension) for j = 1, arguments.sentence_size do if 0 < input[i][j] then input_vector[j] = dictionary.vectors[input[i][j]] else input_vector[j]:fill(0) end end local result = torch.exp(model.network:forward(input_vector)) print(result) result = result / (result[1] + result[2]) local text = input_file:readString('*l') print(string.format('%.4f - %s', result[1], text)) end input_file:close() end Testing()
mit
drmingdrmer/lua-paxos
lib/acid/impl/http.lua
2
9603
local strutil = require( "acid.strutil" ) local tableutil = require( "acid.tableutil" ) --example, how to use -- local h = s2http:new( ip, port, timeout ) -- h:request( uri, {method='GET', headers={}, body=''} ) -- status = h.status -- headers = h.headers -- buf = h:read_body( size ) --or -- local h = s2http:new( ip, port, timeout ) -- h:send_request( uri, {method='GET', headers={}, body=''} ) -- h:send_body( body ) -- h:finish_request() -- status = h.status -- headers = h.headers -- buf = h:read_body( size ) local DEF_PORT = 80 local DEF_METHOD = 'GET' local DEF_TIMEOUT = 60000 local NO_CONTENT = 204 local NOT_MODIFIED = 304 local _M = { _VERSION = '1.0' } local mt = { __index = _M } local function to_str(...) local argsv = {...} for i=1, select('#', ...) do argsv[i] = tableutil.str(argsv[i]) end return table.concat( argsv ) end local function _trim( s ) if type( s ) ~= 'string' then return s end return ( s:gsub( "^%s*(.-)%s*$", "%1" ) ) end local function _read_line( self ) return self.sock:receiveuntil('\r\n')() end local function _read( self, size ) if size <= 0 then return '', nil end return self.sock:receive( size ) end local function discard_lines_until( self, sequence ) local skip, err_msg sequence = sequence or '' while skip ~= sequence do skip, err_msg = _read_line( self ) if err_msg ~= nil then return 'SocketError', err_msg end end return nil, nil end local function _load_resp_status( self ) local status local line local err_code local err_msg local elems while true do line, err_msg = _read_line( self ) if err_msg ~= nil then return 'SocketError', to_str('read status line:', err_msg) end elems = strutil.split( line, ' ' ) if table.getn(elems) < 3 then return 'BadStatus', to_str('invalid status line:', line) end status = tonumber( elems[2] ) if status == nil or status < 100 or status > 999 then return 'BadStatus', to_str('invalid status value:', status) elseif 100 <= status and status < 200 then err_code, err_msg = discard_lines_until( self, '' ) if err_code ~= nil then return err_code, to_str('read header:', err_msg ) end else self.status = status break end end return nil, nil end local function _load_resp_headers( self ) local elems local err_msg local line local hname, hvalue self.ori_headers = {} self.headers = {} while true do line, err_msg = _read_line( self ) if err_msg ~= nil then return 'SocketError', to_str('read header:', err_msg) end if line == '' then break end elems = strutil.split( line, ':' ) if table.getn(elems) < 2 then return 'BadHeader', to_str('invalid header:', line) end hname = string.lower( _trim( elems[1] ) ) hvalue = _trim( line:sub(string.len(elems[1]) + 2) ) self.ori_headers[_trim(elems[1])] = hvalue self.headers[hname] = hvalue end if self.status == NO_CONTENT or self.status == NOT_MODIFIED or self.method == 'HEAD' then return nil, nil end if self.headers['transfer-encoding'] == 'chunked' then self.chunked = true return nil, nil end local cont_len = self.headers['content-length'] if cont_len ~= nil then cont_len = tonumber( cont_len ) if cont_len == nil then return 'BadHeader', to_str('invalid content-length header:', self.headers['content-length']) end self.cont_len = cont_len return nil, nil end return nil, nil end local function _norm_headers( headers ) local hs = {} for h, v in pairs( headers ) do if type( v ) ~= 'table' then v = { v } end for _, header_val in ipairs( v ) do table.insert( hs, to_str( h, ': ', header_val ) ) end end return hs end local function _read_chunk_size( self ) local line, err_msg = _read_line( self ) if err_msg ~= nil then return nil, 'SocketError', to_str('read chunk size:', err_msg) end local idx = line:find(';') if idx ~= nil then line = line:sub(1,idx-1) end local size = tonumber(line, 16) if size == nil then return nil, 'BadChunkCoding', to_str('invalid chunk size:', line) end return size, nil, nil end local function _next_chunk( self ) local size, err_code, err_msg = _read_chunk_size( self ) if err_code ~= nil then return err_code, err_msg end self.chunk_size = size self.chunk_pos = 0 if size == 0 then self.body_end = true --discard trailer local err_code, err_msg = discard_lines_until( self, '' ) if err_code ~= nil then return err_code, to_str('read trailer:', err_msg ) end end return nil, nil end local function _read_chunk( self, size ) local buf local err_code local err_msg local bufs = {} while size > 0 do if self.chunk_size == nil then err_code, err_msg = _next_chunk( self ) if err_code ~= nil then return nil, err_code, err_msg end if self.body_end then break end end buf, err_msg = _read( self, math.min(size, self.chunk_size - self.chunk_pos)) if err_msg ~= nil then return nil, 'SocketError', to_str('read chunked:', err_msg) end table.insert( bufs, buf ) size = size - #buf self.chunk_pos = self.chunk_pos + #buf self.has_read = self.has_read + #buf -- chunk end, ignore '\r\n' if self.chunk_pos == self.chunk_size then buf, err_msg = _read( self, #'\r\n') if err_msg ~= nil then return nil, 'SocketError', to_str('read chunked:', err_msg) end self.chunk_size = nil self.chunk_pos = nil end end return table.concat( bufs ), nil, nil end function _M.new( _, ip, port, timeout ) timeout = timeout or DEF_TIMEOUT local sock= ngx.socket.tcp() sock:settimeout( timeout ) local h = { ip = ip, port = port or DEF_PORT, timeout = timeout, sock = sock, has_read = 0, cont_len = 0, body_end = false, chunked = false } return setmetatable( h, mt ) end function _M.request( self, uri, opts ) local err_code, err_msg = self:send_request( uri, opts ) if err_code ~= nil then return err_code, err_msg end return self:finish_request() end function _M.send_request( self, uri, opts ) opts = opts or {} self.uri = uri self.method = opts.method or DEF_METHOD local body = opts.body or '' local headers = opts.headers or {} headers.Host = headers.Host or self.ip if #body > 0 and headers['Content-Length'] == nil then headers['Content-Length'] = #body end local sbuf = {to_str(self.method, ' ', self.uri, ' HTTP/1.1'), unpack( _norm_headers( headers ) ) } table.insert( sbuf, '' ) table.insert( sbuf, body ) sbuf = table.concat( sbuf, '\r\n' ) local ret, err_msg = self.sock:connect( self.ip, self.port ) if err_msg ~= nil then return 'SocketError', to_str('connect:', err_msg) end ret, err_msg = self.sock:send( sbuf ) if err_msg ~= nil then return 'SocketError', to_str('request:', err_msg) end return nil, nil end function _M.send_body( self, body ) local bytes = 0 local err_msg if body ~= nil then bytes, err_msg = self.sock:send( body ) if err_msg ~= nil then return nil, 'SocketError', to_str('send body:', err_msg) end end return bytes, nil, nil end function _M.finish_request( self ) local err_code local err_msg err_code, err_msg = _load_resp_status( self ) if err_code ~= nil then return err_code, err_msg end err_code, err_msg = _load_resp_headers( self ) if err_code ~= nil then return err_code, err_msg end return nil, nil end function _M.read_body( self, size ) if self.body_end then return '', nil, nil end if self.chunked then return _read_chunk( self, size ) end local rest_len = self.cont_len - self.has_read local buf, err_msg = _read( self, math.min(size, rest_len)) if err_msg ~= nil then return nil, 'SocketError', to_str('read body:', err_msg) end self.has_read = self.has_read + #buf if self.has_read == self.cont_len then self.body_end = true end return buf, nil, nil end function _M.set_keepalive( self, timeout, size ) local rst, err_msg = self.sock:setkeepalive( timeout, size ) if err_msg ~= nil then return 'SocketError', to_str('set keepalive:', err_msg) end return nil, nil end function _M.set_timeout( self, time ) self.sock:settimeout( time ) end function _M.close( self ) local rst, err_msg = self.sock:close() if err_msg ~= nil then return 'SocketError', to_str('close:', err_msg) end return nil, nil end return _M
mit
breezechen/sumatrapdf
luatest/t00.lua
7
1101
require'setupluafiles' local winapi = require'winapi' require'mywin' require'winapi.messageloop' local c = winapi.MyWindow{title = 'Main', help_button = false, maximize_button = true, minimize_button = true, autoquit = true, w = 500, h = 300, visible = false} c:show() function c:WM_GETDLGCODE() return DLGC_WANTALLKEYS end function c:on_key_down(vk, flags) print('WM_KEYDOWN', vk, flags) end function c:on_paint(hdc) print(string.format("on_paint(hdc=%p)", hdc)) local brWhite = winapi.GetStockObject(winapi.WHITE_BRUSH) local brBlack = winapi.GetStockObject(winapi.BLACK_BRUSH) --print(string.format("whiteBrush: %p", whiteBrush)) --local prev1 = winapi.SelectObject(hdc, white) --local r = winapi.RECT(0, 0, 40, 40) local r = c:get_client_rect() print(r) winapi.FillRect(hdc, r, brWhite) local newDx = r.w / 2 local newDy = r.h / 2 local x = (r.w - newDx) / 2 local y = (r.h - newDy) / 2 r = winapi.RECT(x, y, x + newDx, y + newDy) winapi.FillRect(hdc, r, brBlack) --winapi.SelectObject(hdc, prev1) print(r) end winapi.MessageLoop()
gpl-3.0
pazos/koreader
frontend/apps/cloudstorage/webdav.lua
3
5507
local BD = require("ui/bidi") local ConfirmBox = require("ui/widget/confirmbox") local DocumentRegistry = require("document/documentregistry") local InfoMessage = require("ui/widget/infomessage") local MultiInputDialog = require("ui/widget/multiinputdialog") local UIManager = require("ui/uimanager") local ReaderUI = require("apps/reader/readerui") local WebDavApi = require("apps/cloudstorage/webdavapi") local util = require("util") local _ = require("gettext") local Screen = require("device").screen local T = require("ffi/util").template local WebDav = {} function WebDav:run(address, user, pass, path) return WebDavApi:listFolder(address, user, pass, path) end function WebDav:downloadFile(item, address, username, password, local_path, close) local code_response = WebDavApi:downloadFile(address .. WebDavApi:urlEncode( item.url ), username, password, local_path) if code_response == 200 then local __, filename = util.splitFilePathName(local_path) if G_reader_settings:isTrue("show_unsupported") and not DocumentRegistry:hasProvider(filename) then UIManager:show(InfoMessage:new{ text = T(_("File saved to:\n%1"), BD.filepath(local_path)), }) else UIManager:show(ConfirmBox:new{ text = T(_("File saved to:\n%1\nWould you like to read the downloaded book now?"), BD.filepath(local_path)), ok_callback = function() close() ReaderUI:showReader(local_path) end }) end else UIManager:show(InfoMessage:new{ text = T(_("Could not save file to:\n%1"), BD.filepath(local_path)), timeout = 3, }) end end function WebDav:config(item, callback) local text_info = _([[Server address must be of the form http(s)://domain.name/path This can point to a sub-directory of the WebDAV server. The start folder is appended to the server path.]]) local hint_name = _("Server display name") local text_name = "" local hint_address = _("WebDAV address, for example https://example.com/dav") local text_address = "" local hint_username = _("Username") local text_username = "" local hint_password = _("Password") local text_password = "" local hint_folder = _("Start folder") local text_folder = "" local title local text_button_ok = _("Add") if item then title = _("Edit WebDAV account") text_button_ok = _("Apply") text_name = item.text text_address = item.address text_username = item.username text_password = item.password text_folder = item.url else title = _("Add WebDAV account") end self.settings_dialog = MultiInputDialog:new { title = title, fields = { { text = text_name, input_type = "string", hint = hint_name , }, { text = text_address, input_type = "string", hint = hint_address , }, { text = text_username, input_type = "string", hint = hint_username, }, { text = text_password, input_type = "string", text_type = "password", hint = hint_password, }, { text = text_folder, input_type = "string", hint = hint_folder, }, }, buttons = { { { text = _("Cancel"), callback = function() self.settings_dialog:onClose() UIManager:close(self.settings_dialog) end }, { text = _("Info"), callback = function() UIManager:show(InfoMessage:new{ text = text_info }) end }, { text = text_button_ok, callback = function() local fields = MultiInputDialog:getFields() if fields[1] ~= "" and fields[2] ~= "" then if item then -- edit callback(item, fields) else -- add new callback(fields) end self.settings_dialog:onClose() UIManager:close(self.settings_dialog) else UIManager:show(InfoMessage:new{ text = _("Please fill in all fields.") }) end end }, }, }, width = math.floor(Screen:getWidth() * 0.95), height = math.floor(Screen:getHeight() * 0.2), input_type = "text", } UIManager:show(self.settings_dialog) self.settings_dialog:onShowKeyboard() end function WebDav:info(item) local info_text = T(_"Type: %1\nName: %2\nAddress: %3", "WebDAV", item.text, item.address) UIManager:show(InfoMessage:new{text = info_text}) end return WebDav
agpl-3.0
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/base/entities/entities/base_point.lua
3
1127
ENT.Base = "base_entity" ENT.Type = "point" --[[--------------------------------------------------------- Name: Initialize Desc: First function called. Use to set up your entity -----------------------------------------------------------]] function ENT:Initialize() end --[[--------------------------------------------------------- Name: KeyValue Desc: Called when a keyvalue is added to us -----------------------------------------------------------]] function ENT:KeyValue( key, value ) end --[[--------------------------------------------------------- Name: Think Desc: Entity's think function. -----------------------------------------------------------]] function ENT:Think() end -- -- Name: OnRemove -- Desc: Called just before entity is deleted -- function ENT:OnRemove() end -- -- UpdateTransmitState -- function ENT:UpdateTransmitState() -- -- The default behaviour for point entities is to not be networked. -- If you're deriving an entity and want it to appear clientside, override this -- TRANSMIT_ALWAYS = always send, TRANSMIT_PVS = send if in PVS -- return TRANSMIT_NEVER end
mit
sdgdsffdsfff/nginx-openresty-windows
lua-cjson-2.1.0.2/lua/cjson/util.lua
170
6837
local json = require "cjson" -- Various common routines used by the Lua CJSON package -- -- Mark Pulford <mark@kyne.com.au> -- Determine with a Lua table can be treated as an array. -- Explicitly returns "not an array" for very sparse arrays. -- Returns: -- -1 Not an array -- 0 Empty table -- >0 Highest index in the array local function is_array(table) local max = 0 local count = 0 for k, v in pairs(table) do if type(k) == "number" then if k > max then max = k end count = count + 1 else return -1 end end if max > count * 2 then return -1 end return max end local serialise_value local function serialise_table(value, indent, depth) local spacing, spacing2, indent2 if indent then spacing = "\n" .. indent spacing2 = spacing .. " " indent2 = indent .. " " else spacing, spacing2, indent2 = " ", " ", false end depth = depth + 1 if depth > 50 then return "Cannot serialise any further: too many nested tables" end local max = is_array(value) local comma = false local fragment = { "{" .. spacing2 } if max > 0 then -- Serialise array for i = 1, max do if comma then table.insert(fragment, "," .. spacing2) end table.insert(fragment, serialise_value(value[i], indent2, depth)) comma = true end elseif max < 0 then -- Serialise table for k, v in pairs(value) do if comma then table.insert(fragment, "," .. spacing2) end table.insert(fragment, ("[%s] = %s"):format(serialise_value(k, indent2, depth), serialise_value(v, indent2, depth))) comma = true end end table.insert(fragment, spacing .. "}") return table.concat(fragment) end function serialise_value(value, indent, depth) if indent == nil then indent = "" end if depth == nil then depth = 0 end if value == json.null then return "json.null" elseif type(value) == "string" then return ("%q"):format(value) elseif type(value) == "nil" or type(value) == "number" or type(value) == "boolean" then return tostring(value) elseif type(value) == "table" then return serialise_table(value, indent, depth) else return "\"<" .. type(value) .. ">\"" end end local function file_load(filename) local file if filename == nil then file = io.stdin else local err file, err = io.open(filename, "rb") if file == nil then error(("Unable to read '%s': %s"):format(filename, err)) end end local data = file:read("*a") if filename ~= nil then file:close() end if data == nil then error("Failed to read " .. filename) end return data end local function file_save(filename, data) local file if filename == nil then file = io.stdout else local err file, err = io.open(filename, "wb") if file == nil then error(("Unable to write '%s': %s"):format(filename, err)) end end file:write(data) if filename ~= nil then file:close() end end local function compare_values(val1, val2) local type1 = type(val1) local type2 = type(val2) if type1 ~= type2 then return false end -- Check for NaN if type1 == "number" and val1 ~= val1 and val2 ~= val2 then return true end if type1 ~= "table" then return val1 == val2 end -- check_keys stores all the keys that must be checked in val2 local check_keys = {} for k, _ in pairs(val1) do check_keys[k] = true end for k, v in pairs(val2) do if not check_keys[k] then return false end if not compare_values(val1[k], val2[k]) then return false end check_keys[k] = nil end for k, _ in pairs(check_keys) do -- Not the same if any keys from val1 were not found in val2 return false end return true end local test_count_pass = 0 local test_count_total = 0 local function run_test_summary() return test_count_pass, test_count_total end local function run_test(testname, func, input, should_work, output) local function status_line(name, status, value) local statusmap = { [true] = ":success", [false] = ":error" } if status ~= nil then name = name .. statusmap[status] end print(("[%s] %s"):format(name, serialise_value(value, false))) end local result = { pcall(func, unpack(input)) } local success = table.remove(result, 1) local correct = false if success == should_work and compare_values(result, output) then correct = true test_count_pass = test_count_pass + 1 end test_count_total = test_count_total + 1 local teststatus = { [true] = "PASS", [false] = "FAIL" } print(("==> Test [%d] %s: %s"):format(test_count_total, testname, teststatus[correct])) status_line("Input", nil, input) if not correct then status_line("Expected", should_work, output) end status_line("Received", success, result) print() return correct, result end local function run_test_group(tests) local function run_helper(name, func, input) if type(name) == "string" and #name > 0 then print("==> " .. name) end -- Not a protected call, these functions should never generate errors. func(unpack(input or {})) print() end for _, v in ipairs(tests) do -- Run the helper if "should_work" is missing if v[4] == nil then run_helper(unpack(v)) else run_test(unpack(v)) end end end -- Run a Lua script in a separate environment local function run_script(script, env) local env = env or {} local func -- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists if _G.setfenv then func = loadstring(script) if func then setfenv(func, env) end else func = load(script, nil, nil, env) end if func == nil then error("Invalid syntax.") end func() return env end -- Export functions return { serialise_value = serialise_value, file_load = file_load, file_save = file_save, compare_values = compare_values, run_test_summary = run_test_summary, run_test = run_test, run_test_group = run_test_group, run_script = run_script } -- vi:ai et sw=4 ts=4:
bsd-2-clause
pazos/koreader
frontend/ui/widget/keyvaluepage.lua
1
22739
--[[-- Widget that presents a multi-page to show key value pairs. Example: local Foo = KeyValuePage:new{ title = "Statistics", kv_pairs = { {"Current period", "00:00:00"}, -- single or more "-" will generate a solid line "----------------------------", {"Page to read", "5"}, {"Time to read", "00:01:00"}, {"Press me", "will invoke the callback", callback = function() print("hello") end }, }, } UIManager:show(Foo) ]] local BD = require("ui/bidi") local Blitbuffer = require("ffi/blitbuffer") local BottomContainer = require("ui/widget/container/bottomcontainer") local Button = require("ui/widget/button") local CloseButton = require("ui/widget/closebutton") local Device = require("device") local Font = require("ui/font") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local HorizontalGroup = require("ui/widget/horizontalgroup") local HorizontalSpan = require("ui/widget/horizontalspan") local InputContainer = require("ui/widget/container/inputcontainer") local LeftContainer = require("ui/widget/container/leftcontainer") local LineWidget = require("ui/widget/linewidget") local OverlapGroup = require("ui/widget/overlapgroup") local Size = require("ui/size") local TextViewer = require("ui/widget/textviewer") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") local Input = Device.input local Screen = Device.screen local T = require("ffi/util").template local _ = require("gettext") local KeyValueTitle = VerticalGroup:new{ kv_page = nil, title = "", tface = Font:getFace("tfont"), align = "left", use_top_page_count = false, } function KeyValueTitle:init() self.close_button = CloseButton:new{ window = self } local btn_width = self.close_button:getSize().w -- title and close button table.insert(self, OverlapGroup:new{ dimen = { w = self.width }, TextWidget:new{ text = self.title, max_width = self.width - btn_width, face = self.tface, }, self.close_button, }) -- page count and separation line self.title_bottom = OverlapGroup:new{ dimen = { w = self.width, h = Size.line.thick }, LineWidget:new{ dimen = Geom:new{ w = self.width, h = Size.line.thick }, background = Blitbuffer.COLOR_DARK_GRAY, style = "solid", }, } if self.use_top_page_count then self.page_cnt = FrameContainer:new{ padding = Size.padding.default, margin = 0, bordersize = 0, background = Blitbuffer.COLOR_WHITE, -- overlap offset x will be updated in setPageCount method overlap_offset = {0, -15}, TextWidget:new{ text = "", -- page count fgcolor = Blitbuffer.COLOR_DARK_GRAY, face = Font:getFace("smallffont"), }, } table.insert(self.title_bottom, self.page_cnt) end table.insert(self, self.title_bottom) table.insert(self, VerticalSpan:new{ width = Size.span.vertical_large }) end function KeyValueTitle:setPageCount(curr, total) if total == 1 then -- remove page count if there is only one page table.remove(self.title_bottom, 2) return end self.page_cnt[1]:setText(curr .. "/" .. total) self.page_cnt.overlap_offset[1] = (self.width - self.page_cnt:getSize().w - 10) self.title_bottom[2] = self.page_cnt end function KeyValueTitle:onClose() self.kv_page:onClose() return true end local KeyValueItem = InputContainer:new{ key = nil, value = nil, value_lang = nil, cface = Font:getFace("smallinfofont"), tface = Font:getFace("smallinfofontbold"), width = nil, height = nil, textviewer_width = nil, textviewer_height = nil, value_overflow_align = "left", -- "right": only align right if value overflow 1/2 width -- "right_always": align value right even when small and -- only key overflows 1/2 width } function KeyValueItem:init() self.dimen = Geom:new{w = self.width, h = self.height} -- self.value may contain some control characters (\n \t...) that would -- be rendered as a square. Replace them with a shorter and nicer '|'. -- (Let self.value untouched, as with Hold, the original value can be -- displayed correctly in TextViewer.) local tvalue = tostring(self.value) tvalue = tvalue:gsub("[\n\t]", "|") local frame_padding = Size.padding.default local frame_internal_width = self.width - frame_padding * 2 local middle_padding = Size.padding.default -- min enforced padding between key and value local available_width = frame_internal_width - middle_padding -- Default widths (and position of value widget) if each text fits in 1/2 screen width local key_w = frame_internal_width / 2 - middle_padding local value_w = frame_internal_width / 2 local key_widget = TextWidget:new{ text = self.key, max_width = available_width, face = self.tface, } local value_widget = TextWidget:new{ text = tvalue, max_width = available_width, face = self.cface, lang = self.value_lang, } local key_w_rendered = key_widget:getWidth() local value_w_rendered = value_widget:getWidth() -- As both key_widget and value_width will be in a HorizontalGroup, -- and key is always left aligned, we can just tweak the key width -- to position the value_widget local value_align_right = false local fit_right_align = true -- by default, really right align if key_w_rendered > key_w or value_w_rendered > value_w then -- One (or both) does not fit in 1/2 width if key_w_rendered + value_w_rendered > available_width then -- Both do not fit: one has to be truncated so they fit if key_w_rendered >= value_w_rendered then -- Rare case: key larger than value. -- We should have kept our keys small, smaller than 1/2 width. -- If it is larger than value, it's that value is kinda small, -- so keep the whole value, and truncate the key key_w = available_width - value_w_rendered else -- Usual case: value larger than key. -- Keep our small key, fit the value in the remaining width. key_w = key_w_rendered end value_align_right = true -- so the ellipsis touches the screen right border if self.value_align ~= "right" and self.value_overflow_align ~= "right" and self.value_overflow_align ~= "right_always" then -- Don't adjust the ellipsis to the screen right border, -- so the left of text is aligned with other truncated texts fit_right_align = false end -- Allow for displaying the non-truncated text with Hold if Device:isTouchDevice() then self.ges_events.Hold = { GestureRange:new{ ges = "hold", range = self.dimen, } } -- If no tap callback, allow for displaying the non-truncated -- text with Tap too if not self.callback then self.callback = function() self:onHold() end end end else -- Both can fit: break the 1/2 widths if self.value_align == "right" or self.value_overflow_align == "right_always" or (self.value_overflow_align == "right" and value_w_rendered > value_w) then key_w = available_width - value_w_rendered value_align_right = true else key_w = key_w_rendered end end -- In all the above case, we set the right key_w to include any -- needed additional in-between padding: value_w is what's left. value_w = available_width - key_w else if self.value_align == "right" then key_w = available_width - value_w_rendered value_w = value_w_rendered value_align_right = true end end -- Adjust widgets' max widths if needed value_widget:setMaxWidth(value_w) if fit_right_align and value_align_right and value_widget:getWidth() < value_w then -- Because of truncation at glyph boundaries, value_widget -- may be a tad smaller than the specified value_w: -- add some padding to key_w so value is pushed to the screen right border key_w = key_w + ( value_w - value_widget:getWidth() ) end key_widget:setMaxWidth(key_w) -- For debugging positioning: -- value_widget = FrameContainer:new{ padding=0, margin=0, bordersize=1, value_widget } if self.callback and Device:isTouchDevice() then self.ges_events.Tap = { GestureRange:new{ ges = "tap", range = self.dimen, } } end self[1] = FrameContainer:new{ padding = frame_padding, bordersize = 0, background = Blitbuffer.COLOR_WHITE, HorizontalGroup:new{ dimen = self.dimen:copy(), LeftContainer:new{ dimen = { w = key_w, h = self.height }, key_widget, }, HorizontalSpan:new{ width = middle_padding, }, LeftContainer:new{ dimen = { w = value_w, h = self.height }, value_widget, } } } end function KeyValueItem:onTap() if self.callback then if G_reader_settings:isFalse("flash_ui") then self.callback() else self[1].invert = true UIManager:widgetInvert(self[1], self[1].dimen.x, self[1].dimen.y) UIManager:setDirty(nil, function() return "fast", self[1].dimen end) -- Force the repaint *now*, so we don't have to delay the callback to see the invert... UIManager:forceRePaint() self.callback() UIManager:forceRePaint() --UIManager:waitForVSync() -- Has to be scheduled *after* the dict delays for the lookup history pages... UIManager:scheduleIn(0.75, function() self[1].invert = false -- If we've ended up below something, things get trickier. local top_widget = UIManager:getTopWidget() if top_widget ~= self.show_parent then -- It's generally tricky to get accurate dimensions out of whatever was painted above us, -- so cheat by comparing against the previous refresh region... if self[1].dimen:intersectWith(UIManager:getPreviousRefreshRegion()) then -- If that something is a modal (e.g., dictionary D/L), repaint the whole stack if top_widget.modal then UIManager:setDirty(self.show_parent, function() return "ui", self[1].dimen end) return true else -- Otherwise, skip the repaint return true end end end UIManager:widgetInvert(self[1], self[1].dimen.x, self[1].dimen.y) UIManager:setDirty(nil, function() return "ui", self[1].dimen end) --UIManager:forceRePaint() end) end end return true end function KeyValueItem:onHold() local textviewer = TextViewer:new{ title = self.key, text = self.value, lang = self.value_lang, width = self.textviewer_width, height = self.textviewer_height, } UIManager:show(textviewer) return true end local KeyValuePage = InputContainer:new{ title = "", width = nil, height = nil, values_lang = nil, -- index for the first item to show show_page = 1, use_top_page_count = false, -- aligment of value when key or value overflows its reserved width (for -- now: 50%): "left" (stick to key), "right" (stick to scren right border) value_overflow_align = "left", } function KeyValuePage:init() self.dimen = Geom:new{ w = self.width or Screen:getWidth(), h = self.height or Screen:getHeight(), } if self.dimen.w == Screen:getWidth() and self.dimen.h == Screen:getHeight() then self.covers_fullscreen = true -- hint for UIManager:_repaint() end if Device:hasKeys() then self.key_events = { Close = { {"Back"}, doc = "close page" }, NextPage = {{Input.group.PgFwd}, doc = "next page"}, PrevPage = {{Input.group.PgBack}, doc = "prev page"}, } end if Device:isTouchDevice() then self.ges_events.Swipe = { GestureRange:new{ ges = "swipe", range = self.dimen, } } end -- return button --- @todo: alternative icon if BD.mirroredUILayout() self.page_return_arrow = self.page_return_arrow or Button:new{ icon = "back.top", callback = function() self:onReturn() end, bordersize = 0, show_parent = self, } -- group for page info local chevron_left = "chevron.left" local chevron_right = "chevron.right" local chevron_first = "chevron.first" local chevron_last = "chevron.last" if BD.mirroredUILayout() then chevron_left, chevron_right = chevron_right, chevron_left chevron_first, chevron_last = chevron_last, chevron_first end self.page_info_left_chev = self.page_info_left_chev or Button:new{ icon = chevron_left, callback = function() self:prevPage() end, bordersize = 0, show_parent = self, } self.page_info_right_chev = self.page_info_right_chev or Button:new{ icon = chevron_right, callback = function() self:nextPage() end, bordersize = 0, show_parent = self, } self.page_info_first_chev = self.page_info_first_chev or Button:new{ icon = chevron_first, callback = function() self:goToPage(1) end, bordersize = 0, show_parent = self, } self.page_info_last_chev = self.page_info_last_chev or Button:new{ icon = chevron_last, callback = function() self:goToPage(self.pages) end, bordersize = 0, show_parent = self, } self.page_info_spacer = HorizontalSpan:new{ width = Screen:scaleBySize(32), } self.page_return_spacer = HorizontalSpan:new{ width = self.page_return_arrow:getSize().w } if self.callback_return == nil and self.return_button == nil then self.page_return_arrow:hide() elseif self.callback_return == nil then self.page_return_arrow:disable() end self.page_info_left_chev:hide() self.page_info_right_chev:hide() self.page_info_first_chev:hide() self.page_info_last_chev:hide() self.page_info_text = self.page_info_text or Button:new{ text = "", hold_input = { title = _("Enter page number"), type = "number", hint_func = function() return "(" .. "1 - " .. self.pages .. ")" end, callback = function(input) local page = tonumber(input) if page and page >= 1 and page <= self.pages then self:goToPage(page) end end, }, bordersize = 0, margin = Screen:scaleBySize(20), text_font_face = "pgfont", text_font_bold = false, } self.page_info = HorizontalGroup:new{ self.page_return_arrow, self.page_info_first_chev, self.page_info_spacer, self.page_info_left_chev, self.page_info_text, self.page_info_right_chev, self.page_info_spacer, self.page_info_last_chev, self.page_return_spacer, } local footer = BottomContainer:new{ dimen = self.dimen:copy(), self.page_info, } local padding = Size.padding.large self.item_width = self.dimen.w - 2 * padding self.item_height = Size.item.height_default -- setup title bar self.title_bar = KeyValueTitle:new{ title = self.title, width = self.item_width, height = self.item_height, use_top_page_count = self.use_top_page_count, kv_page = self, } -- setup main content self.item_margin = self.item_height / 4 local line_height = self.item_height + 2 * self.item_margin local content_height = self.dimen.h - self.title_bar:getSize().h - self.page_info:getSize().h self.items_per_page = math.floor(content_height / line_height) self.pages = math.ceil(#self.kv_pairs / self.items_per_page) self.main_content = VerticalGroup:new{} -- set textviewer height to let our title fully visible self.textviewer_width = self.item_width self.textviewer_height = self.dimen.h - 2*self.title_bar:getSize().h self:_populateItems() local content = OverlapGroup:new{ dimen = self.dimen:copy(), allow_mirroring = false, VerticalGroup:new{ align = "left", self.title_bar, self.main_content, }, footer, } -- assemble page self[1] = FrameContainer:new{ height = self.dimen.h, padding = padding, bordersize = 0, background = Blitbuffer.COLOR_WHITE, content } end function KeyValuePage:nextPage() local new_page = math.min(self.show_page+1, self.pages) if new_page > self.show_page then self.show_page = new_page self:_populateItems() end end function KeyValuePage:prevPage() local new_page = math.max(self.show_page-1, 1) if new_page < self.show_page then self.show_page = new_page self:_populateItems() end end function KeyValuePage:goToPage(page) self.show_page = page self:_populateItems() end -- make sure self.item_margin and self.item_height are set before calling this function KeyValuePage:_populateItems() self.page_info:resetLayout() self.main_content:clear() local idx_offset = (self.show_page - 1) * self.items_per_page for idx = 1, self.items_per_page do local entry = self.kv_pairs[idx_offset + idx] if entry == nil then break end table.insert(self.main_content, VerticalSpan:new{ width = self.item_margin }) if type(entry) == "table" then table.insert( self.main_content, KeyValueItem:new{ height = self.item_height, width = self.item_width, key = entry[1], value = entry[2], value_lang = self.values_lang, callback = entry.callback, callback_back = entry.callback_back, textviewer_width = self.textviewer_width, textviewer_height = self.textviewer_height, value_overflow_align = self.value_overflow_align, value_align = self.value_align, show_parent = self, } ) elseif type(entry) == "string" then local c = string.sub(entry, 1, 1) if c == "-" then table.insert(self.main_content, VerticalSpan:new{ width = self.item_margin }) table.insert(self.main_content, LineWidget:new{ background = Blitbuffer.COLOR_LIGHT_GRAY, dimen = Geom:new{ w = self.item_width, h = Size.line.thick }, style = "solid", }) end end table.insert(self.main_content, VerticalSpan:new{ width = self.item_margin }) end self.page_info_text:setText(T(_("Page %1 of %2"), self.show_page, self.pages)) self.page_info_left_chev:showHide(self.pages > 1) self.page_info_right_chev:showHide(self.pages > 1) self.page_info_first_chev:showHide(self.pages > 2) self.page_info_last_chev:showHide(self.pages > 2) self.page_info_left_chev:enableDisable(self.show_page > 1) self.page_info_right_chev:enableDisable(self.show_page < self.pages) self.page_info_first_chev:enableDisable(self.show_page > 1) self.page_info_last_chev:enableDisable(self.show_page < self.pages) UIManager:setDirty(self, function() return "ui", self.dimen end) end function KeyValuePage:onNextPage() self:nextPage() return true end function KeyValuePage:onPrevPage() self:prevPage() return true end function KeyValuePage:onSwipe(arg, ges_ev) local direction = BD.flipDirectionIfMirroredUILayout(ges_ev.direction) if direction == "west" then self:nextPage() return true elseif direction == "east" then self:prevPage() return true elseif direction == "south" then -- Allow easier closing with swipe down self:onClose() elseif direction == "north" then -- no use for now do end -- luacheck: ignore 541 else -- diagonal swipe -- trigger full refresh UIManager:setDirty(nil, "full") -- a long diagonal swipe may also be used for taking a screenshot, -- so let it propagate return false end end function KeyValuePage:onClose() UIManager:close(self) return true end function KeyValuePage:onReturn() if self.callback_return then self:callback_return() UIManager:close(self) UIManager:setDirty(nil, "ui") end end return KeyValuePage
agpl-3.0
rstudio/redx
lua/src/lib/plugins/stickiness.lua
1
2053
local url = require('socket.url') local base64 = require('base64') local M = { } M.get_cookie = function(request, settings) local cookie = request.cookies[settings.COOKIE] if cookie ~= nil then return base64.decode(cookie) else return nil end end M.set_cookie = function(request, server, frontend, settings) local name = settings.COOKIE local value = base64.encode(server) local path = M.extract_path(frontend) local cookie = tostring(url.escape(name)) .. "=" .. tostring(url.escape(value)) .. "; Path=" .. tostring(path) .. "; HttpOnly; SameSite=None; Secure" ngx.log(ngx.DEBUG, "Setting sticky server: " .. tostring(server) .. " (Path=" .. tostring(path) .. ")") ngx.header['Set-Cookie'] = cookie end M.clear_cookie = function(request, settings) request.cookies[settings.COOKIE] = nil end M.balance = function(request, session, settings) local sticky_server = M.get_cookie(request, settings) if sticky_server ~= nil then local _list_0 = session.servers for _index_0 = 1, #_list_0 do local server = _list_0[_index_0] if sticky_server == M.extract_domain(server.address) then return server end end ngx.log(ngx.WARN, "Server not found matching address: " .. tostring(sticky_server)) M.clear_cookie(request, settings) end return session['servers'] end M.post = function(request, session, settings) local sticky_server = M.get_cookie(request, settings) if session.server ~= nil then local current_server = M.extract_domain(session.server) if sticky_server ~= current_server then return M.set_cookie(request, current_server, session.frontend, settings) end end end M.extract_domain = function(url) if not string.match(url, '/') then return url else local location_index = string.find(url, '/') local domain = string.sub(url, 1, (location_index - 1)) return domain end end M.extract_path = function(url) local i = string.find(url, '/') if i ~= nil then return string.sub(url, i) else return '/' end end return M
bsd-2-clause
InfiniteRain/CS2D-AmplifiedScripting
classes/dynObject.lua
1
11676
-- Initializing dynamic object class. cas.dynObject = cas.class() -------------------- -- Static methods -- -------------------- -- Checks if the dynamic object under the passed ID exists. function cas.dynObject.idExists(objectID) if type(objectID) ~= "number" then error("Passed \"objectID\" parameter is not valid. Number expected, ".. type(objectID) .." passed.", 2) end return cas._cs2dCommands.object(objectID, "exists") end -- Returns the dynamic object instance from the passed onject ID. function cas.dynObject.getInstance(dynObjectID) if type(dynObjectID) ~= "number" then error("Passed \"dynObjectID\" parameter is not valid. Number expected, ".. type(dynObjectID) .." passed.", 2) elseif not cas._cs2dCommands.object(dynObjectID, 'exists') then error("Passed \"dynObjectID\" parameter represents a non-existent object.", 2) end for key, value in pairs(cas.dynObject._instances) do if value._id == dynObjectID then cas.dynObject._debug:log("Dynamic object \"".. tostring(value) .."\" was found in \"_instances\" table and returned.") return value end end cas.dynObject._allowCreation = true local dynObject = cas.dynObject.new(dynObjectID) cas.dynObject._allowCreation = false return dynObject end -- Returns a table of all the dynamic objects. function cas.dynObject.dynamicObjects() local dynamicObjects = {} for key, value in pairs(cas._cs2dCommands.object(0, 'table')) do table.insert(dynamicObjects, cas.dynObject.getInstance(value)) end return dynObject end -- Returns a dynamic object on the position. function cas.dynObject.getDynamicObjectAt(x, y, dynObjectType) if type(x) ~= "number" then error("Passed \"x\" parameter is not valid. Number expected, ".. type(x) .." passed.", 2) elseif type(y) ~= "number" then error("Passed \"y\" parameter is not valid. Number expected, ".. type(y) .." passed.", 2) end if dynObjectType then if getmetatable(dynObjectType) ~= cas.dynObject.type then error("Passed \"dynObjectType\" parameter is not an instance of the \"cas.dynObject.type\" class.", 2) end end local dynObject = cas._cs2dCommands.objectat(x, y, dynObjectType and dynObjectType._objectTypeID or nil) return dynObject ~= 0 and cas.dynObject.getInstance(dynObject) or false end ---------------------- -- Instance methods -- ---------------------- -- Constructor. Creates a dynamic object instance with corresponding ID. function cas.dynObject:constructor(dynObjectID) if type(dynObjectID) ~= "number" then error("Passed \"dynObjectID\" parameter is not valid. Number expected, ".. type(dynObjectID) .." passed.", 2) elseif not cas._cs2dCommands.object(dynObjectID, 'exists') then error("Passed \"dynObjectID\" parameter represents a non-existent object.", 2) end if not cas.dynObject._allowCreation then error("Instantiation of this class is not allowed.", 2) end for key, value in pairs(cas.dynObject._instances) do if value._id == dynObjectID then error("Instance with the same object ID already exists.", 2) end end self._id = dynObjectID self._killed = false table.insert(cas.dynObject._instances, self) cas.dynObject._debug:log("Dynamic object \"".. tostring(self) .."\" was instantiated.") end -- Destructor function cas.dynObject:destructor() if not self._killed then self._killed = true end for key, value in pairs(cas.dynObject._instances) do if value._id == self._id then -- Removes the dynamic object from the cas.dynObject._instances table. cas.dynObject._instances[key] = nil end end cas.dynObject._debug:log("Dynamic object \"".. tostring(self) .."\" was garbage collected.") end --== Getters ==-- -- Gets the ID of the dynamic object. function cas.dynObject:getID() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return self._id end -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- The following is self explanatory, I based it on "object" function of cs2d -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- function cas.dynObject:getTypeName() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'typename') end function cas.dynObject:getType() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas.dynObject.type.getInstance(cas._cs2dCommands.object(self._id, 'type')) end function cas.dynObject:getHealth() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'health') end function cas.dynObject:getMode() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'mode') end function cas.dynObject:getTeam() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'team') end function cas.dynObject:getPlayer() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end if self:getType() == 30 then error("This dynamic object is an npc, thus does not have an owner.", 2) end return cas._cs2dCommands.object(self._id, 'player') end function cas.dynObject:getNPCType() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end if self:getType() ~= 30 then error("This dynamic object is not an npc, thus does not have an NPC type.", 2) end return cas._cs2dCommands.object(self._id, 'player') end function cas.dynObject:getPosition() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'x'), cas._cs2dCommands.object(self._id, 'y') end function cas.dynObject:getX() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'x') end function cas.dynObject:getY() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'y') end function cas.dynObject:getAngle() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'rot') end function cas.dynObject:getTilePosition() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'tilex'), cas._cs2dCommands.object(self._id, 'tiley') end function cas.dynObject:getTileX() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'tilex') end function cas.dynObject:getTileY() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'tiley') end function cas.dynObject:getCountdown() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'countdown') end function cas.dynObject:getOriginalAngle() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'rootrot') end function cas.dynObject:getTarget() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end local target = cas._cs2dCommands.object(self._id, 'target') return target ~= 0 and cas.player.getInstance(target) or false end function cas.dynObject:getUpgradeVal() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'upgrade') end function cas.dynObject:isSpawnedByEntity() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end return cas._cs2dCommands.object(self._id, 'entity') end function cas.dynObject:getSpawnEntityPosition() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end if not cas.dynObject:isSpawnedByEntity() then error("This dynamic object wasn't spawned by an entity.", 2) end return cas._cs2dCommands.object(self._id, 'entityx'), cas._cs2dCommands.object(self._id, 'entityy') end function cas.dynObject:getSpawnEntityX() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end if not cas.dynObject:isSpawnedByEntity() then error("This dynamic object wasn't spawned by an entity.", 2) end return cas._cs2dCommands.object(self._id, 'entityx') end function cas.dynObject:getSpawnEntityY() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end if not cas.dynObject:isSpawnedByEntity() then error("This dynamic object wasn't spawned by an entity.", 2) end return cas._cs2dCommands.object(self._id, 'entityy') end --== Setters/control ==-- function cas.dynObject:damage(damage, player) if type(damage) ~= "number" then error("Passed \"damage\" parameter is not valid. Number expected, ".. type(damage) .." passed.", 2) end if player then if getmetatable(player) ~= cas.player then error("Passed \"player\" parameter is not an instance of the \"cas.player\" class.", 2) end end if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end if self:getType() == cas.dynObject.type.image then error("This object is an image, thus it cannot be damaged.", 2) end local player = player or 0 cas.console.parse("damageobject", self._id, damage, player) end function cas.dynObject:kill() if self._killed then error("The dynamic object of this instance was already killed. It's better if you dispose of this instance.", 2) end if self:getType() == cas.dynObject.type.image then cas._image.getInstance(self._id):free() else cas.console.parse("killobject", self._id) end end ------------------- -- Static fields -- ------------------- cas.dynObject._allowCreation = false -- Defines if instantiation of this class is allowed. cas.dynObject._instances = setmetatable({}, {__mode = "kv"}) -- A table of instances of this class. cas.dynObject._debug = cas.debug.new(cas.color.yellow, "CAS Dynamic Object") -- Debug for dynamic objects. --cas.dynObject._debug:setActive(true)
mit
leMaik/RpgPlus
docs/lua-api/inventorywrapper.lua
1
1794
--- An inventory. -- @classmod Inventory --- Sets the items in this inventory. -- @param items table of items in the inventory, with slots as keys -- @param[opt=true] clear whether the inventory should be cleared before adding the items -- function setItems(items, clear) end --- Sets the item in the given slot of this inventory. -- @param slot slot -- @param item item to put into the slot -- function setItem(slot, item) end --- Opens this inventory for a player. -- @param player player -- function open(player) end --- Closes this inventory for all viewers. -- function close() end --- Add a callback for the given event. -- @param event event to add a handler to, possible events are: -- -- * `"click"` - [InventoryClickEvent](https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/event/inventory/InventoryClickEvent.html) -- * `"close"` - [InventoryCloseEvent](https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/event/inventory/InventoryCloseEvent.html) -- -- @param handler a handler function that is invoked whenever the event happens, gets the event as first parameter -- function on(event, handler) end --- Register an event handler that is only called once. -- @param event event to add a one-time handler to -- @param handler a handler function that is invoked whenever the event happens, gets the event as first parameter -- function once(event, handler) end --- Remove an event handler. -- @param[opt] event event to remove an event handler from; if not specified, all event handlers of this inventory will be removed -- @param[optchain] handler the handler function to remove as previously added with @{on}; if not specified, all handlers of this event will be removed -- @return `true` if any event handler was removed, `false` if not -- function off(event, handler) end
mit
lopezloo/mta-csrw
csrw/client/render/radar.lua
1
4085
local radar = { showing = false, -- background and border colors background = {51, 162, 37, 160}, disc = {0, 0, 0, 240}, -- position and size x = sY * 0.028, y = sY * 0.75, height = sY * 0.200, range = 100, blips = {} } radar.centerleft = radar.x + radar.height / 2 radar.centerTop = radar.y + radar.height / 2 radar.blipSize = radar.height / 16 radar.lpsize = radar.height / 8 function csCreateBlip(pos, img, size) table.insert(radar.blips, { pos = pos, attachedTo = nil, img = img, size = size }) end function csCreateBlipAttachedTo(attachedTo, img, size) table.insert(radar.blips, { pos = nil, attachedTo = attachedTo, img = img, size = size }) end function csClearBlips() radar.blips = {} end local function renderRadar() local target = getCameraTarget() if not radar.showing or (not target and not g_player.spectator) then return end if target and target.type == "vehicle" and localPlayer.vehicle == target then target = localPlayer end if not g_player.spectator and target then px, py, pz = getElementPosition(target) pr = getPedRotation(target) else px, py, pz = getCameraMatrix() pr = 0 end local cx, cy, _, tx, ty = getCameraMatrix() local north = findRotation(cx, cy, tx, ty) dxDrawImage(radar.x, radar.y, radar.height, radar.height, ":csrw-media/images/radar/background.png", 0, 0, 0, tocolor(radar.background[1], radar.background[2], radar.background[3], radar.background[4]), false) dxDrawImage(radar.x, radar.y, radar.height, radar.height, ":csrw-media/images/radar/disc.png", 0, 0, 0, tocolor(radar.disc[1], radar.disc[2], radar.disc[3], radar.disc[4]), false) for _, v in ipairs(getElementsByType("player")) do if (g_player.spectator or (getElementData(v, "alive") and v.team == localPlayer.team)) and target ~= v then local _, _, rot = getElementRotation(v) local ex, ey, ez = getElementPosition(v) local dist = getDistanceBetweenPoints2D(px, py, ex, ey) if dist > radar.range then dist = tonumber(radar.range) end local rot = 180-north + findRotation(px, py, ex, ey) local cblipx, cblipy = getPointFromDistanceRotation(0, 0, radar.height * (dist/radar.range)/2, rot) local blipx = radar.centerleft + cblipx - radar.blipSize/2 local blipy = radar.centerTop + cblipy - radar.blipSize/2 if v.team == g_team[1] then dxDrawImage(blipx, blipy, radar.blipSize, radar.blipSize, ":csrw-media/images/radar/tt.png", north-rot+45) else dxDrawImage(blipx, blipy, radar.blipSize, radar.blipSize, ":csrw-media/images/radar/ct.png", north-rot+45) end end end for _, v in ipairs(radar.blips) do local ex, ey, ez if v.pos then ex, ey, ez = v.pos.x, v.pos.y, v.pos.z elseif isElement(v.attachedTo) then ex, ey, ez = v.attachedTo.position.x, v.attachedTo.position.y, v.attachedTo.position.z end if ex and ey and ez then local dist = getDistanceBetweenPoints2D(px, py, ex, ey) if dist > radar.range then dist = tonumber(radar.range) end local size = radar.height / v.size local rot = 180 - north + findRotation(px, py, ex, ey) local cblipx, cblipy = getPointFromDistanceRotation(0, 0, radar.height * (dist/radar.range)/2, rot) local blipx = radar.centerleft + cblipx - size/2 local blipy = radar.centerTop + cblipy - size/2 dxDrawImage(blipx, blipy, size, size, ":csrw-media/images/radar/" .. v.img .. ".png") end end if g_player.spectator and not target then dxDrawImage(radar.centerleft - radar.lpsize/2, radar.centerTop - radar.lpsize/2, radar.lpsize, radar.lpsize, ":csrw-media/images/radar/camera.png", north - pr) else dxDrawImage(radar.centerleft - radar.lpsize/2, radar.centerTop - radar.lpsize/2, radar.lpsize, radar.lpsize, ":csrw-media/images/radar/centre.png", north - pr) end end function showRadar(show) if not show then show = not radar.showing end if radar.showing and show == false then removeEventHandler("onClientRender", root, renderRadar) elseif not radar.showing and show == true then addEventHandler("onClientRender", root, renderRadar) end radar.showing = show end
gpl-3.0
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/base/entities/entities/base_nextbot/sv_nextbot.lua
3
7703
-- -- Name: NEXTBOT:BehaveStart -- Desc: Called to initialize the behaviour.\n\n You shouldn't override this - it's used to kick off the coroutine that runs the bot's behaviour. \n\nThis is called automatically when the NPC is created, there should be no need to call it manually. -- Arg1: -- Ret1: -- function ENT:BehaveStart() local s = self self.BehaveThread = coroutine.create( function() self:RunBehaviour() end ) end -- -- Name: NEXTBOT:BehaveUpdate -- Desc: Called to update the bot's behaviour -- Arg1: number|interval|How long since the last update -- Ret1: -- function ENT:BehaveUpdate( fInterval ) if ( !self.BehaveThread ) then return end local ok, message = coroutine.resume( self.BehaveThread ) if ( ok == false ) then self.BehaveThread = nil Msg( self, "error: ", message, "\n" ); end end -- -- Name: NEXTBOT:BodyUpdate -- Desc: Called to update the bot's animation -- Arg1: -- Ret1: -- function ENT:BodyUpdate() local act = self:GetActivity() -- -- This helper function does a lot of useful stuff for us. -- It sets the bot's move_x move_y pose parameters, sets their animation speed relative to the ground speed, and calls FrameAdvance. -- -- if ( act == ACT_RUN || act == ACT_WALK ) then self:BodyMoveXY() end -- -- If we're not walking or running we probably just want to update the anim system -- self:FrameAdvance() end -- -- Name: NEXTBOT:OnLeaveGround -- Desc: Called when the bot's feet leave the ground - for whatever reason -- Arg1: -- Ret1: -- function ENT:OnLeaveGround() --MsgN( "OnLeaveGround" ) end -- -- Name: NEXTBOT:OnLeaveGround -- Desc: Called when the bot's feet return to the ground -- Arg1: -- Ret1: -- function ENT:OnLandOnGround() --MsgN( "OnLandOnGround" ) end -- -- Name: NEXTBOT:OnStuck -- Desc: Called when the bot thinks it is stuck -- Arg1: -- Ret1: -- function ENT:OnStuck() --MsgN( "OnStuck" ) end -- -- Name: NEXTBOT:OnUnStuck -- Desc: Called when the bot thinks it is un-stuck -- Arg1: -- Ret1: -- function ENT:OnUnStuck() --MsgN( "OnUnStuck" ) end -- -- Name: NEXTBOT:OnInjured -- Desc: Called when the bot gets hurt -- Arg1: CTakeDamageInfo|info|damage info -- Ret1: -- function ENT:OnInjured( damageinfo ) end -- -- Name: NEXTBOT:OnKilled -- Desc: Called when the bot gets killed -- Arg1: CTakeDamageInfo|info|damage info -- Ret1: -- function ENT:OnKilled( damageinfo ) self:BecomeRagdoll( damageinfo ) end -- -- Name: NEXTBOT:OnOtherKilled -- Desc: Called when someone else or something else has been killed -- Arg1: -- Ret1: -- function ENT:OnOtherKilled() --MsgN( "OnOtherKilled" ) end -- -- Name: NextBot:FindSpots -- Desc: Returns a table of hiding spots. -- Arg1: table|specs|This table should contain the search info.\n\n * 'type' - the type (either 'hiding')\n * 'pos' - the position to search.\n * 'radius' - the radius to search.\n * 'stepup' - the highest step to step up.\n * 'stepdown' - the highest we can step down without being hurt. -- Ret1: table|An unsorted table of tables containing\n * 'vector' - the position of the hiding spot\n * 'distance' - the distance to that position -- function ENT:FindSpots( tbl ) local tbl = tbl or {} tbl.pos = tbl.pos or self:WorldSpaceCenter() tbl.radius = tbl.radius or 1000 tbl.stepdown = tbl.stepdown or 20 tbl.stepup = tbl.stepup or 20 tbl.type = tbl.type or 'hiding' -- Use a path to find the length local path = Path( "Follow" ) -- Find a bunch of areas within this distance local areas = navmesh.Find( tbl.pos, tbl.radius, tbl.stepdown, tbl.stepup ) local found = {} -- In each area for _, area in pairs( areas ) do -- get the spots local spots if ( tbl.type == 'hiding' ) then spots = area:GetHidingSpots() end for k, vec in pairs( spots ) do -- Work out the length, and add them to a table path:Invalidate() path:Compute( self, vec, 1 ) -- TODO: This is bullshit - it's using 'self.pos' not tbl.pos table.insert( found, { vector = vec, distance = path:GetLength() } ) end end return found end -- -- Name: NextBot:FindSpot -- Desc: Like FindSpots but only returns a vector -- Arg1: string|type|Either "random", "near", "far" -- Arg2: table|options|A table containing a bunch of tweakable options. See the function definition for more details -- Ret1: vector|If it finds a spot it will return a vector. If not it will return nil. -- function ENT:FindSpot( type, options ) local spots = self:FindSpots( options ) if ( !spots || #spots == 0 ) then return end if ( type == "near" ) then table.SortByMember( spots, "distance", true ) return spots[1].vector end if ( type == "far" ) then table.SortByMember( spots, "distance", false ) return spots[1].vector end -- random return spots[ math.random( 1, #spots ) ].vector end -- -- Name: NextBot:HandleStuck -- Desc: Called from Lua when the NPC is stuck. This should only be called from the behaviour coroutine - so if you want to override this function and do something special that yields - then go for it.\n\nYou should always call self.loco:ClearStuck() in this function to reset the stuck status - so it knows it's unstuck. -- Arg1: -- Ret1: -- function ENT:HandleStuck() -- -- Clear the stuck status -- self.loco:ClearStuck(); end -- -- Name: NextBot:MoveToPos -- Desc: To be called in the behaviour coroutine only! Will yield until the bot has reached the goal or is stuck -- Arg1: Vector|pos|The position we want to get to -- Arg2: table|options|A table containing a bunch of tweakable options. See the function definition for more details -- Ret1: string|Either "failed", "stuck", "timeout" or "ok" - depending on how the NPC got on -- function ENT:MoveToPos( pos, options ) local options = options or {} local path = Path( "Follow" ) path:SetMinLookAheadDistance( options.lookahead or 300 ) path:SetGoalTolerance( options.tolerance or 20 ) path:Compute( self, pos ) if ( !path:IsValid() ) then return "failed" end while ( path:IsValid() ) do path:Update( self ) -- Draw the path (only visible on listen servers or single player) if ( options.draw ) then path:Draw() end -- If we're stuck then call the HandleStuck function and abandon if ( self.loco:IsStuck() ) then self:HandleStuck(); return "stuck" end -- -- If they set maxage on options then make sure the path is younger than it -- if ( options.maxage ) then if ( path:GetAge() > options.maxage ) then return "timeout" end end -- -- If they set repath then rebuild the path every x seconds -- if ( options.repath ) then if ( path:GetAge() > options.repath ) then path:Compute( self, pos ) end end coroutine.yield() end return "ok" end -- -- Name: NextBot:PlaySequenceAndWait -- Desc: To be called in the behaviour coroutine only! Plays an animation sequence and waits for it to end before returning. -- Arg1: string|name|The sequence name -- Arg2: number|the speed (default 1) -- Ret1: -- function ENT:PlaySequenceAndWait( name, speed ) local len = self:SetSequence( name ) speed = speed or 1 self:ResetSequenceInfo() self:SetCycle( 0 ) self:SetPlaybackRate( speed ); -- wait for it to finish coroutine.wait( len / speed ) end -- -- Name: NEXTBOT:Use -- Desc: Called when a player 'uses' the entity -- Arg1: entity|activator|The entity that activated the use -- Arg2: entity|called|The entity that called the use -- Arg3: number|type|The type of use (USE_ON, USE_OFF, USE_TOGGLE, USE_SET) -- Arg4: number|value|Any passed value -- Ret1: -- function ENT:Use( activator, caller, type, value ) end -- -- Name: NEXTBOT:Think -- Desc: Called periodically -- Arg1: -- Ret1: -- function ENT:Think() end
mit