content
stringlengths
5
1.05M
--[[ This is modified version of https://github.com/wube/factorio-data/blob/master/core/lualib/event_handler.lua Modified by ZwerOxotnik ]] ---@type table<string, table> local libraries = {} local setup_ran = false local register_remote_interfaces = function() --Sometimes, in special cases, on_init and on_load can be run at the same time. Only register events once in this case. if setup_ran then return end setup_ran = true for _, lib in pairs(libraries) do if lib.add_remote_interface then lib.add_remote_interface() end if lib.add_commands then lib.add_commands() end end end local register_events = function() local all_events = {} local on_nth_tick = {} for lib_name, lib in pairs(libraries) do if lib.events then for k, handler in pairs(lib.events) do all_events[k] = all_events[k] or {} all_events[k][lib_name] = handler end end if lib.on_nth_tick then for n, handler in pairs(lib.on_nth_tick) do on_nth_tick[n] = on_nth_tick[n] or {} on_nth_tick[n][lib_name] = handler end end end for event, handlers in pairs(all_events) do local count = 0 for _ in pairs(handlers) do count = count + 1 end if count == 1 then local _, func = next(handlers) script.on_event(event, func) else -- TODO: improve local action = function(_event) for _, handler in pairs(handlers) do handler(_event) end end script.on_event(event, action) end end for n, handlers in pairs(on_nth_tick) do local count = 0 for _ in pairs(handlers) do count = count + 1 end if count == 1 then local _, func = next(handlers) script.on_nth_tick(n, func) else -- TODO: improve local action = function(event) for _, handler in pairs(handlers) do handler(event) end end script.on_nth_tick(n, action) end end end script.on_init(function() register_remote_interfaces() register_events() for _, lib in pairs(libraries) do if lib.on_init then lib.on_init() end end end) script.on_load(function() register_remote_interfaces() register_events() for _, lib in pairs(libraries) do if lib.on_load then lib.on_load() end end end) script.on_configuration_changed(function(data) for _, lib in pairs(libraries) do if lib.on_configuration_changed then lib.on_configuration_changed(data) end end end) local handler = {} handler.add_lib = function(lib) for _, current in pairs(libraries) do if current == lib then error("Trying to register same lib twice") end end table.insert(libraries, lib) end handler.add_libraries = function(libs) for _, lib in pairs(libs) do handler.add_lib(lib) end end return handler
local AUTOEQUIP_NAME local AUTOEQUIP_SAVE_INFO,AUTOEQUIP_DEL_INFO,AUTOEQUIP_SAVE_FINFO,AUTOEQUIP_ERROR_INFO,AUTOEQUIP_DEL_TEXT,AUTOEQUIP_TEXT_SAVED local AUTOEQUIP_TEXT_RENAME,AUTOEQUIP_HELP_SAVE_BTN_TITLE,AUTOEQUIP_HELP_SAVE_BTN_DESC,AUTOEQUIP_HELP_SET_BTN_COMMENT1,AUTOEQUIP_NEW_INFO local AUTOEQUIP_MOVE_TOOLTIP,AUTOEQUIP_TEXT_SWITCH,AUTOEQUIP_TEXT_SWITCH_LOSTSET,AUTOEQUIP_RAID_TIP,AUTOEQUIP_TEXT_SWITCH_InCombat local AUTOEQUIP_HELP_SET_DROPDOWN_COMMENT,M_REPAIR_COST local _ if ( GetLocale() == "zhCN" ) then AUTOEQUIP_NAME = "自动换装"; BINDING_HEADER_AUTOEQUIP_TITLE = "自动换装按键"; BINDING_NAME_AUTOEQUIP_SET1 = "套装 1"; BINDING_NAME_AUTOEQUIP_SET2 = "套装 2"; BINDING_NAME_AUTOEQUIP_SET3 = "套装 3"; BINDING_NAME_AUTOEQUIP_SET4 = "套装 4"; BINDING_NAME_AUTOEQUIP_SET5 = "套装 5"; BINDING_NAME_AUTOEQUIP_SET6 = "套装 6"; BINDING_NAME_AUTOEQUIP_SET7 = "套装 7"; BINDING_NAME_AUTOEQUIP_SET8 = "套装 8"; BINDING_NAME_AUTOEQUIP_NEXT = "切换到下一套装备"; BINDING_NAME_AUTOEQUIP_PREV = "切换到上一套装备"; AUTOEQUIP_SAVE_INFO = "执行该操作将覆盖方案 %s 以前的设置,您是否真的想这么做?"; AUTOEQUIP_DEL_INFO = "确定要删除此方案吗?"; AUTOEQUIP_SAVE_FINFO ="该方案未保存任何配置,是否新建一个装备方案?"; AUTOEQUIP_ERROR_INFO ="请检查是否与其他方案名称冲突!"; AUTOEQUIP_DEL_TEXT = "套装方案 %s 已删除"; AUTOEQUIP_TEXT_SAVED = "套装方案 %s 已保存"; AUTOEQUIP_TEXT_RENAME = "已将方案 %s 重命名为 %s "; AUTOEQUIP_HELP_SAVE_BTN_TITLE = "保存装备配置"; AUTOEQUIP_HELP_SAVE_BTN_DESC = "左键单击覆盖或添加套裝方案,右键单击卸除所有装备。"; AUTOEQUIP_NEW_INFO = "点击快捷新建一个套装方案"; AUTOEQUIP_HELP_SET_BTN_COMMENT1 = "左键单击切换到此方案"; AUTOEQUIP_HELP_SET_DROPDOWN_COMMENT = "右键调出详细菜单" AUTOEQUIP_MOVE_TOOLTIP = "按住Shift和鼠标左键可拖动框体。"; AUTOEQUIP_TEXT_SWITCH = "|cff00adef<自动换装>|r 当前装备的套装方案为 %s。"; AUTOEQUIP_TEXT_SWITCH_InCombat = "|cff00adef<自动换装>|r 战斗状态无法切换套装方案!"; AUTOEQUIP_TEXT_SWITCH_LOSTSET = "|cff00adef<自动换装>|r 无法完全切换到方案 %s。缺少%d件装备,请检查。"; AUTOEQUIP_RAID_TIP = "你现在处于团队中,自动换装界面自动隐藏。为了切换装备套装,请移动鼠标到自己头像上,界面将会显示。"; M_REPAIR_COST = "维修费用" elseif ( GetLocale() == "zhTW" ) then AUTOEQUIP_NAME = "自動換裝"; BINDING_HEADER_AUTOEQUIP_TITLE = "自動換裝按鍵"; BINDING_NAME_AUTOEQUIP_SET1 = "套裝 1"; BINDING_NAME_AUTOEQUIP_SET2 = "套裝 2"; BINDING_NAME_AUTOEQUIP_SET3 = "套裝 3"; BINDING_NAME_AUTOEQUIP_SET4 = "套裝 4"; BINDING_NAME_AUTOEQUIP_SET5 = "套裝 5"; BINDING_NAME_AUTOEQUIP_SET6 = "套裝 6"; BINDING_NAME_AUTOEQUIP_SET7 = "套裝 7"; BINDING_NAME_AUTOEQUIP_SET8 = "套裝 8"; BINDING_NAME_AUTOEQUIP_NEXT = "切換到下一套裝備"; BINDING_NAME_AUTOEQUIP_PREV = "切換到上一套裝備"; AUTOEQUIP_SAVE_INFO = "執行該操作將覆蓋方案 %s 以前的設置,您是否真的想這麼做?"; AUTOEQUIP_DEL_INFO = "確定要刪除此號方案嗎?"; AUTOEQUIP_SAVE_FINFO ="該方案未保存任何配置,是否新建一個裝備方案?"; AUTOEQUIP_ERROR_INFO ="請檢查是否與其他方案名稱衝突!"; AUTOEQUIP_DEL_TEXT = "套裝方案 %s 已刪除"; AUTOEQUIP_TEXT_SAVED = "套裝方案 %s 已保存"; AUTOEQUIP_TEXT_RENAME = "已將方案 %s 重命名為 %s "; AUTOEQUIP_HELP_SAVE_BTN_TITLE = "保存裝備配置"; AUTOEQUIP_HELP_SAVE_BTN_DESC = "左鍵單擊覆蓋或添加套装方案,右鍵單擊卸除所有裝備。"; AUTOEQUIP_NEW_INFO = "點擊快捷新建一個套裝方案"; AUTOEQUIP_HELP_SET_BTN_COMMENT1 = "左鍵單擊切換到此方案"; AUTOEQUIP_HELP_SET_DROPDOWN_COMMENT = "右鍵調出詳細菜單" AUTOEQUIP_MOVE_TOOLTIP = "按住Shift和滑鼠左鍵可拖動框體。"; AUTOEQUIP_TEXT_SWITCH = "|cff00adef<自動換裝>|r 當前裝備的套裝方案為 %s。"; AUTOEQUIP_TEXT_SWITCH_InCombat = "|cff00adef<自動換裝>|r 戰鬥狀態無法切換套裝方案!"; AUTOEQUIP_TEXT_SWITCH_LOSTSET = "|cff00adef<自動換裝>|r 無法完全切換到方案 %s。缺少%d件裝備,請檢查。"; AUTOEQUIP_RAID_TIP = "你現在處於團隊中,自動換裝介面自動隱藏。為了切換裝備套裝,請移動滑鼠到自己頭像上,介面將會顯示。"; M_REPAIR_COST = "維修費用" else AUTOEQUIP_NAME = "Auto Equip"; BINDING_HEADER_AUTOEQUIP_TITLE = "Auto Equip"; BINDING_NAME_AUTOEQUIP_SET1 = "Set 1"; BINDING_NAME_AUTOEQUIP_SET2 = "Set 2"; BINDING_NAME_AUTOEQUIP_SET3 = "Set 3"; BINDING_NAME_AUTOEQUIP_SET4 = "Set 4"; BINDING_NAME_AUTOEQUIP_SET5 = "Set 5"; BINDING_NAME_AUTOEQUIP_SET6 = "Set 6"; BINDING_NAME_AUTOEQUIP_SET7 = "Set 7"; BINDING_NAME_AUTOEQUIP_SET8 = "Set 8"; BINDING_NAME_AUTOEQUIP_NEXT = "Switch to next set"; BINDING_NAME_AUTOEQUIP_PREV = "Switch to previous set"; AUTOEQUIP_SAVE_INFO = "Settings %s will be replaced, do you really want to do?"; AUTOEQUIP_DEL_INFO = "Are you sure to delete this plan?"; AUTOEQUIP_SAVE_FINFO ="The scheme not save any configuration, whether a new equipment plan?"; AUTOEQUIP_ERROR_INFO ="Please check whether the name conflicts with other schemes!"; AUTOEQUIP_DEL_TEXT = "Suit scheme %s The deleted"; AUTOEQUIP_TEXT_SAVED = "Suit scheme %s Has preserved"; AUTOEQUIP_TEXT_RENAME = "Has suit scheme %s Renamed %s "; AUTOEQUIP_HELP_SAVE_BTN_TITLE = "Save settings"; AUTOEQUIP_HELP_SAVE_BTN_DESC = "Left-click on cover or add suit scheme, right-click the unloading all equipment."; AUTOEQUIP_NEW_INFO = "Click to create a new Set"; AUTOEQUIP_HELP_SET_BTN_COMMENT1 = "Left-click switching suit scheme"; AUTOEQUIP_HELP_SET_DROPDOWN_COMMENT = "Right-click call the detail drop down list" AUTOEQUIP_MOVE_TOOLTIP = "Hold shift key and Left button to drag frame."; AUTOEQUIP_TEXT_SWITCH = "|cff00adef<AutoEquip>|r Current equipped set: %s ."; AUTOEQUIP_TEXT_SWITCH_InCombat = "|cff00adef<AutoEquip>|r Can't change Set InCombat."; AUTOEQUIP_TEXT_SWITCH_LOSTSET = "|cff00adef<AutoEquip>|r Set %s Miss %d Equipment,Please Check."; AUTOEQUIP_RAID_TIP = "You are now in raid, the AutoEquip interface will be hide automatically. To switch your equipment set, move your mouse on your portrait, the interface will be shown."; M_REPAIR_COST = "Repair Cost" end local AutoEquip_a4ed2c6153d1a73ae298b67f0bcbabce = BLibrary("BInfo", "chat", AUTOEQUIP_NAME); local AutoEquip_b5afb1939b42d2489f5d7985e2839133 = { 16, 17, 5, 7, 1, 3, 8, 10, 9, 6, 2, 15, 11, 12, 13, 14, 4, 19, }; local AutoEquip_6781199f633c5d9ede0aa8c0a5a346d0,AutoEquip_352a74c60685e01427cbef1c647d5199,AutoEquip_642022feafc2fd091c1bc9b53b20e8d1; local AutoEquip_500a8ad122d34cab3e445c13c86044e5; local function MoveIcons() PlayerLeaderIcon:ClearAllPoints(); PlayerLeaderIcon:SetPoint("TOPLEFT", "PlayerFrame", "TOPLEFT", 55, -12); PlayerMasterIcon:ClearAllPoints(); PlayerMasterIcon:SetPoint("TOPLEFT", "PlayerFrame", "TOPLEFT", 80, -12); end local function ResetIcons() PlayerLeaderIcon:ClearAllPoints(); PlayerLeaderIcon:SetPoint("TOPLEFT", "PlayerFrame", "TOPLEFT", 40, -12); PlayerMasterIcon:ClearAllPoints(); PlayerMasterIcon:SetPoint("TOPLEFT", "PlayerFrame", "TOPLEFT", 80, -10); end function AutoEquipFrame_OnMouseDown(self) if (AutoEquip_352a74c60685e01427cbef1c647d5199 and IsShiftKeyDown()) then self:StartMoving(); self.moving = true; end end function AutoEquipFrame_OnMouseUp(self) if (self.moving) then self:StopMovingOrSizing(); self.moving = false; end end function AutoEquipFrame_OnEnter(self) AutoEquipFrameBackground:SetTexCoord(unpack(AutoEquipFrameBackground.hilight_coords)); GameTooltip:SetOwner(self, "ANCHOR_BOTTOM",0,-50); GameTooltip:SetText(AUTOEQUIP_NAME, 1.0, 1.0, 1.0); GameTooltip:AddLine(AUTOEQUIP_MOVE_TOOLTIP, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1.0, 1); GameTooltip:Show(); end function AutoEquipFrame_OnLeave(self) AutoEquipFrameBackground:SetTexCoord(unpack(AutoEquipFrameBackground.normal_coords)); GameTooltip:Hide(); end local function AutoEquip_PlayerFrame_OnEnter() if (AutoEquip_6781199f633c5d9ede0aa8c0a5a346d0 and not AutoEquipFrame:IsShown()) then AutoEquipFrame:Show(); end end local function AutoEquip_PlayerFrame_OnUpdate() if (AutoEquip_6781199f633c5d9ede0aa8c0a5a346d0 and AutoEquip_642022feafc2fd091c1bc9b53b20e8d1) then if (AutoEquipFrame:IsVisible() and PlayerFrameGroupIndicator:IsVisible()) then local AutoEquip_7242cf1b41caa7510cf530297a011730, AutoEquip_cf709faa4d1d5a25a70ffb7820ac3c77 = GetCursorPosition(); if ( AutoEquip_cf709faa4d1d5a25a70ffb7820ac3c77 < 600) then AutoEquipFrame:Hide(); end end end end local function AutoEquip_c990e192b1d042b676a4ee0ffff5d729() if (AutoEquip_6781199f633c5d9ede0aa8c0a5a346d0 and AutoEquip_642022feafc2fd091c1bc9b53b20e8d1) then if not IsInRaid() then AutoEquipFrame:Show(); else if AutoEquipFrame:IsShown() then AutoEquipFrame:Hide(); AutoEquip_a4ed2c6153d1a73ae298b67f0bcbabce:Print(AUTOEQUIP_RAID_TIP); end end end end function AutoEquipFrame_OnLoad(self) hooksecurefunc("PlayerFrame_UpdateGroupIndicator", AutoEquip_c990e192b1d042b676a4ee0ffff5d729); PlayerFrame:HookScript("OnEnter", AutoEquip_PlayerFrame_OnEnter); PlayerFrame:HookScript("OnUpdate", AutoEquip_PlayerFrame_OnUpdate); self:RegisterEvent("ADDON_LOADED"); self:RegisterEvent("EQUIPMENT_SETS_CHANGED"); self:RegisterEvent("PLAYER_EQUIPMENT_CHANGED"); for AutoEquip_e914904fab9d05d3f54d52bfc31a0f3f = 1, 8, 1 do local AutoEquip_99f3cf2c6f1fdfadb0fd4ab6e0843bf5 = _G["AutoEquipSetButton"..AutoEquip_e914904fab9d05d3f54d52bfc31a0f3f]; local AutoEquip_5b142532ca616f4ae4690d782a43675e = _G["AutoEquipSetButton"..(AutoEquip_e914904fab9d05d3f54d52bfc31a0f3f - 1)]; AutoEquip_99f3cf2c6f1fdfadb0fd4ab6e0843bf5:GetNormalTexture():SetTexCoord(0 + (AutoEquip_e914904fab9d05d3f54d52bfc31a0f3f - 1) * 0.07421875, 0.07421875 + (AutoEquip_e914904fab9d05d3f54d52bfc31a0f3f - 1) * 0.07421875, 0.6484375, 0.78125); AutoEquip_99f3cf2c6f1fdfadb0fd4ab6e0843bf5:GetPushedTexture():SetTexCoord(0 + (AutoEquip_e914904fab9d05d3f54d52bfc31a0f3f - 1) * 0.07421875, 0.07421875 + (AutoEquip_e914904fab9d05d3f54d52bfc31a0f3f - 1) * 0.07421875, 0.7890625, 0.921875); if AutoEquip_e914904fab9d05d3f54d52bfc31a0f3f == 1 then AutoEquip_99f3cf2c6f1fdfadb0fd4ab6e0843bf5:SetPoint("LEFT", AutoEquipSaveButton, "RIGHT", 3, 0); elseif AutoEquip_5b142532ca616f4ae4690d782a43675e then AutoEquip_99f3cf2c6f1fdfadb0fd4ab6e0843bf5:SetPoint("LEFT", AutoEquip_5b142532ca616f4ae4690d782a43675e, "RIGHT", 3, 0); end end end local function AutoEquip_76c6488cc84b5b8179cfa77d4fd56eaa(AutoEquip_8d0febf2348ea712b2b375ae95601d5f) local AutoEquip_3decdcd698c5cf72604c8703b513eb41 = C_EquipmentSet.GetEquipmentSetIDs(); return AutoEquip_3decdcd698c5cf72604c8703b513eb41[AutoEquip_8d0febf2348ea712b2b375ae95601d5f]; end local function AutoEquip_4028c7da12ff52455abb865b298ff7e2(AutoEquip_8d0febf2348ea712b2b375ae95601d5f) local AutoEquip_ff1b4022732c44ba86eae6bf2228a25a = AutoEquip_76c6488cc84b5b8179cfa77d4fd56eaa(AutoEquip_8d0febf2348ea712b2b375ae95601d5f); if AutoEquip_ff1b4022732c44ba86eae6bf2228a25a then return C_EquipmentSet.GetEquipmentSetInfo(AutoEquip_ff1b4022732c44ba86eae6bf2228a25a); end end local function AutoEquip_7fa14bf1c4f9fdb64a455dfd719908d8() for i = 1, 8 do _G["AutoEquipSetButton"..i]:SetChecked(false); end local isEquipped; local AutoEquip_3decdcd698c5cf72604c8703b513eb41 = C_EquipmentSet.GetEquipmentSetIDs(); local num = #AutoEquip_3decdcd698c5cf72604c8703b513eb41; num = num > 8 and 8 or num; for index = 1, num do _a,_b,_c,isEquipped = C_EquipmentSet.GetEquipmentSetInfo(AutoEquip_3decdcd698c5cf72604c8703b513eb41[index]); if isEquipped then _G["AutoEquipSetButton"..index]:SetChecked(true); end if not AutoEquip_500a8ad122d34cab3e445c13c86044e5 and (PaperDollEquipmentManagerPane.selectedSetID == AutoEquip_3decdcd698c5cf72604c8703b513eb41[index]) then AutoEquip_500a8ad122d34cab3e445c13c86044e5 = index; end end end local function AutoEquip_edde6b9defd14002a775b763b5f565e3(AutoEquip_8d0febf2348ea712b2b375ae95601d5f) if not InCombatLockdown() then local setName,_,_,_,_,_,_,numLost = AutoEquip_4028c7da12ff52455abb865b298ff7e2(AutoEquip_8d0febf2348ea712b2b375ae95601d5f) if setName then local AutoEquip_ff1b4022732c44ba86eae6bf2228a25a = AutoEquip_76c6488cc84b5b8179cfa77d4fd56eaa(AutoEquip_8d0febf2348ea712b2b375ae95601d5f); EquipmentManager_EquipSet(AutoEquip_ff1b4022732c44ba86eae6bf2228a25a) local str; if numLost == 0 then str = string.format(AUTOEQUIP_TEXT_SWITCH, setName); else str = string.format(AUTOEQUIP_TEXT_SWITCH_LOSTSET, setName,numLost); end BigFoot_Report("info", str); PlaySound(SOUNDKIT.IG_CHARACTER_INFO_OPEN); end else BigFoot_Report("info", AUTOEQUIP_TEXT_SWITCH_InCombat); end AutoEquip_7fa14bf1c4f9fdb64a455dfd719908d8(); end local function AutoEquip_bf737188f1f5a0018780565eaf91afc0(AutoEquip_8d0febf2348ea712b2b375ae95601d5f) local AutoEquip_ff1b4022732c44ba86eae6bf2228a25a = AutoEquip_76c6488cc84b5b8179cfa77d4fd56eaa(AutoEquip_8d0febf2348ea712b2b375ae95601d5f); if AutoEquip_ff1b4022732c44ba86eae6bf2228a25a then local AutoEquip_34123c02f75da83a2df856cf83cac9c1 = AutoEquip_4028c7da12ff52455abb865b298ff7e2(AutoEquip_8d0febf2348ea712b2b375ae95601d5f); C_EquipmentSet.DeleteEquipmentSet(AutoEquip_ff1b4022732c44ba86eae6bf2228a25a); local str = string.format(AUTOEQUIP_DEL_TEXT, AutoEquip_34123c02f75da83a2df856cf83cac9c1); BigFoot_Report("info", str); end end local function AutoEquip_224246a2aec3ecad61ed8d03e82f9cb2(AutoEquip_34123c02f75da83a2df856cf83cac9c1,AutoEquip_ff1b4022732c44ba86eae6bf2228a25a) if AutoEquip_ff1b4022732c44ba86eae6bf2228a25a then SaveEquipmentSet(AutoEquip_34123c02f75da83a2df856cf83cac9c1); else C_EquipmentSet.CreateEquipmentSet(AutoEquip_34123c02f75da83a2df856cf83cac9c1); end local str = string.format(AUTOEQUIP_TEXT_SAVED, AutoEquip_34123c02f75da83a2df856cf83cac9c1); BigFoot_Report("info", str); end local function AutoEquip_5eb24152420f2e356247c122dfb5cdbc(AutoEquip_ff1b4022732c44ba86eae6bf2228a25a,AutoEquip_1d3e52f32b5592fd24f689bf25fef888) StaticPopupDialogs["SAVE_SET"].switch = nil; if C_EquipmentSet.GetEquipmentSetID(AutoEquip_1d3e52f32b5592fd24f689bf25fef888) then BigFoot_Report("info", AUTOEQUIP_ERROR_INFO); return; end local AutoEquip_8d0febf2348ea712b2b375ae95601d5f = AutoEquip_76c6488cc84b5b8179cfa77d4fd56eaa(AutoEquip_ff1b4022732c44ba86eae6bf2228a25a); if AutoEquip_8d0febf2348ea712b2b375ae95601d5f then local AutoEquip_34123c02f75da83a2df856cf83cac9c1 = AutoEquip_4028c7da12ff52455abb865b298ff7e2(AutoEquip_ff1b4022732c44ba86eae6bf2228a25a); C_EquipmentSet.ModifyEquipmentSet(AutoEquip_8d0febf2348ea712b2b375ae95601d5f,AutoEquip_1d3e52f32b5592fd24f689bf25fef888); local str = string.format(AUTOEQUIP_TEXT_RENAME, AutoEquip_34123c02f75da83a2df856cf83cac9c1,AutoEquip_1d3e52f32b5592fd24f689bf25fef888); BigFoot_Report("info", str); end end local function IsEquippableSlot(slot) return not InCombatLockdown() or (slot == 16 or slot == 17) end local function GetAvailableBags() local bags = {} for i = 0, 4 do local slots, family = GetContainerNumFreeSlots(i) bags[i] = (family == 0) and slots or 0 end return bags end local function GetFirstAvailableBag(bags) for i = 0, 4 do if bags[i] > 0 then return i end end end local function StripOff() local bags = GetAvailableBags() for i,v in pairs(AutoEquip_b5afb1939b42d2489f5d7985e2839133) do local lnk = GetInventoryItemLink("player", v) if lnk and IsEquippableSlot(v) then local bag = GetFirstAvailableBag(bags) if bag then PickupInventoryItem(v) if CursorHasItem() then if bag == 0 then PutItemInBackpack() else PutItemInBag(19 + bag) end end bags[bag] = bags[bag] - 1 else BigFoot_Report("info", ERR_INV_FULL); return; end end end end function AutoEquipSaveButton_OnClick(self, button) if ( button and button == "RightButton" ) then StripOff(); else if AutoEquip_500a8ad122d34cab3e445c13c86044e5 then local setName = AutoEquip_4028c7da12ff52455abb865b298ff7e2(AutoEquip_500a8ad122d34cab3e445c13c86044e5) if setName then StaticPopup_Show("SAVE_RESAVE", setName) else StaticPopup_Show("SAVE_SET"); end else StaticPopup_Show("SAVE_SET"); end end end function AutoEquipSetButton_OnClick(self, __index, AutoEquip_99f3cf2c6f1fdfadb0fd4ab6e0843bf5) if CursorHasItem() then return end AutoEquip_500a8ad122d34cab3e445c13c86044e5 = __index; local AutoEquip_34123c02f75da83a2df856cf83cac9c1 = AutoEquip_4028c7da12ff52455abb865b298ff7e2(__index); if not AutoEquip_34123c02f75da83a2df856cf83cac9c1 then StaticPopup_Show("SAVE_FSET"); return; end if (AutoEquip_99f3cf2c6f1fdfadb0fd4ab6e0843bf5 and AutoEquip_99f3cf2c6f1fdfadb0fd4ab6e0843bf5 == "RightButton") then ToggleDropDownMenu(nil, nil, bf_AeDropDownMenu, AutoEquipFrame, 32, 10); else AutoEquip_edde6b9defd14002a775b763b5f565e3(__index); end end function AutoEquipFrame_OnEvent(self, AutoEquip_d0708241b607c9a9dd1953c812fadfb7, ...) if AutoEquip_d0708241b607c9a9dd1953c812fadfb7 == "ADDON_LOADED" then local AutoEquip_1652701c940a7445a6e43b954d36ec9b = ...; if AutoEquip_1652701c940a7445a6e43b954d36ec9b == "AutoEquip" then self:UnregisterEvent("ADDON_LOADED"); AutoEquip_7fa14bf1c4f9fdb64a455dfd719908d8(); end return; end AutoEquip_7fa14bf1c4f9fdb64a455dfd719908d8(); end function AutoEquip_SwitchToNext() local AutoEquip_3decdcd698c5cf72604c8703b513eb41 = C_EquipmentSet.GetEquipmentSetIDs(); local num = #AutoEquip_3decdcd698c5cf72604c8703b513eb41; num = num > 8 and 8 or num; if num < 1 then return end if not AutoEquip_500a8ad122d34cab3e445c13c86044e5 then AutoEquipSetButton_OnClick(nil, 1); return; end local AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f; for i = 1, num do if i == AutoEquip_500a8ad122d34cab3e445c13c86044e5 then AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f = i + 1; break; end end if ( not AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f or AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f > num ) then AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f = 1; end AutoEquipSetButton_OnClick(nil, AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f); end function AutoEquip_SwitchToPrev() local AutoEquip_3decdcd698c5cf72604c8703b513eb41 = C_EquipmentSet.GetEquipmentSetIDs(); local num = #AutoEquip_3decdcd698c5cf72604c8703b513eb41; num = num > 8 and 8 or num; if num < 1 then return end if not AutoEquip_500a8ad122d34cab3e445c13c86044e5 then AutoEquipSetButton_OnClick(nil, 1); return; end local AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f; for i = 1, num do if i == AutoEquip_500a8ad122d34cab3e445c13c86044e5 then AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f = i - 1; break; end end if ( not AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f or AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f < 1 ) then AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f = num; end AutoEquipSetButton_OnClick(nil, AutoEquip_8f81cccca434aa7ae8e147d0fcfb685f); end function AutoEquipSaveButton_OnEnter(self) GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT",-50,-50); GameTooltip:SetText(AUTOEQUIP_HELP_SAVE_BTN_TITLE, 1.0, 1.0, 1.0); GameTooltip:AddLine(AUTOEQUIP_HELP_SAVE_BTN_DESC, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1.0, 1); GameTooltip:Show(); end function AutoEquipSetButton_OnEnter(self, AutoEquip_8d0febf2348ea712b2b375ae95601d5f) GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT",-50,-50); local AutoEquip_34123c02f75da83a2df856cf83cac9c1 = AutoEquip_4028c7da12ff52455abb865b298ff7e2(AutoEquip_8d0febf2348ea712b2b375ae95601d5f); if AutoEquip_34123c02f75da83a2df856cf83cac9c1 then GameTooltip:SetText(AutoEquip_34123c02f75da83a2df856cf83cac9c1, 1.0, 1.0, 1.0); GameTooltip:AddLine(AUTOEQUIP_HELP_SET_BTN_COMMENT1, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1.0, 1); GameTooltip:AddLine(AUTOEQUIP_HELP_SET_DROPDOWN_COMMENT, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1.0, 1); else GameTooltip:SetText(PAPERDOLL_NEWEQUIPMENTSET, 1.0, 1.0, 1.0); GameTooltip:AddLine(AUTOEQUIP_NEW_INFO, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1.0, 1); end GameTooltip:Show(); end local function DropDownMenu_DeleteSet() StaticPopup_Show("DELETE_SET"); end local function DropDownMenu_RenameSet() StaticPopupDialogs["SAVE_SET"].switch = 1; StaticPopup_Show("SAVE_SET"); end function bf_AeDropDownMenu_OnLoad() info = {}; info.text = "删除该方案"; info.notCheckable = true info.func = DropDownMenu_DeleteSet; UIDropDownMenu_AddButton(info); info.text = "重命名该方案"; info.notCheckable = true info.func = DropDownMenu_RenameSet; UIDropDownMenu_AddButton(info); end StaticPopupDialogs["DELETE_SET"] = { text = AUTOEQUIP_DEL_INFO, button1 = TEXT(YES), button2 = TEXT(NO), OnAccept = function(self) AutoEquip_bf737188f1f5a0018780565eaf91afc0(AutoEquip_500a8ad122d34cab3e445c13c86044e5) end, OnCancel = function(self) AutoEquip_7fa14bf1c4f9fdb64a455dfd719908d8(); end, showAlert = 1, timeout = 0, }; StaticPopupDialogs["SAVE_SET"] = { text = GEARSETS_POPUP_TEXT, button1 = ACCEPT, button2 = CANCEL, hasEditBox = 1, maxLetters = 16, OnAccept = function(self) local editBox = _G[self:GetName().."EditBox"]; if StaticPopupDialogs["SAVE_SET"].switch then AutoEquip_5eb24152420f2e356247c122dfb5cdbc(AutoEquip_500a8ad122d34cab3e445c13c86044e5,editBox:GetText()); else AutoEquip_224246a2aec3ecad61ed8d03e82f9cb2(editBox:GetText()); end end, OnShow = function(self) local AutoEquip_34123c02f75da83a2df856cf83cac9c1 = AutoEquip_4028c7da12ff52455abb865b298ff7e2(AutoEquip_500a8ad122d34cab3e445c13c86044e5); if AutoEquip_34123c02f75da83a2df856cf83cac9c1 then _G[self:GetName().."EditBox"]:SetText(AutoEquip_34123c02f75da83a2df856cf83cac9c1); _G[self:GetName().."EditBox"]:HighlightText(); end end, OnHide = function(self) _G[self:GetName().."EditBox"]:SetText(""); end, OnCancel = function(self) AutoEquip_7fa14bf1c4f9fdb64a455dfd719908d8(); end, EditBoxOnEnterPressed = function(self) local editBox = _G[self:GetName()]; if StaticPopupDialogs["SAVE_SET"].switch then AutoEquip_5eb24152420f2e356247c122dfb5cdbc(AutoEquip_500a8ad122d34cab3e445c13c86044e5,editBox:GetText()); else AutoEquip_224246a2aec3ecad61ed8d03e82f9cb2(editBox:GetText()); end self:GetParent():Hide(); end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide(); end, timeout = 0, exclusive = 1, whileDead = 1, hideOnEscape = 1 }; StaticPopupDialogs["SAVE_FSET"] = { text = AUTOEQUIP_SAVE_FINFO, button1 = TEXT(YES), button2 = TEXT(NO), OnAccept = function(self) StaticPopup_Show("SAVE_SET"); end, OnCancel = function(self) AutoEquip_7fa14bf1c4f9fdb64a455dfd719908d8() end, showAlert = 1, timeout = 0, }; StaticPopupDialogs["SAVE_RESAVE"] = { text = AUTOEQUIP_SAVE_INFO, button1 = TEXT(YES), button2 = TEXT(NO), OnAccept = function(self) local name = AutoEquip_4028c7da12ff52455abb865b298ff7e2(AutoEquip_500a8ad122d34cab3e445c13c86044e5) AutoEquip_224246a2aec3ecad61ed8d03e82f9cb2(name,AutoEquip_500a8ad122d34cab3e445c13c86044e5) end, showAlert = 1, timeout = 0, }; function AutoEquip_Toggle(switch) if (switch) then AutoEquip_6781199f633c5d9ede0aa8c0a5a346d0 = true; AutoEquipFrame:Show(); else AutoEquip_6781199f633c5d9ede0aa8c0a5a346d0 = false; AutoEquipFrame:Hide(); end end function AutoEquip_ToggleMode(mode) if (mode == "normal") then AutoEquip_352a74c60685e01427cbef1c647d5199 = false; AutoEquipFrame:SetMovable(false); AutoEquipFrame:SetClampedToScreen(false); AutoEquipFrame:SetParent(PlayerFrame); AutoEquipFrame:SetWidth(120); AutoEquipFrame:SetHeight(23); AutoEquipFrame:EnableMouse(false); AutoEquipFrame:SetHitRectInsets(0, 0, 119, 22); AutoEquipFrame:ClearAllPoints(); AutoEquipFrame:SetPoint("TOPLEFT", "PlayerFrame", "TOPLEFT", 90, -1); AutoEquipFrame:SetFrameLevel(AutoEquipFrame:GetParent():GetFrameLevel()+2); AutoEquipFrameBackground.normal_coords = {0, 0.46484375, 0, 0.171875}; AutoEquipFrameBackground.hilight_coords = {0, 0.46484375, 0, 0.171875}; AutoEquipFrameBackground:SetTexCoord(unpack(AutoEquipFrameBackground.normal_coords)); AutoEquipSaveButton:SetPoint("TOPLEFT", AutoEquipFrame, "TOPLEFT", 6, -2); AutoEquipSetButton5:Hide(); AutoEquipSetButton6:Hide(); AutoEquipSetButton7:Hide(); AutoEquipSetButton8:Hide(); MoveIcons(); elseif (mode == "advance") then AutoEquip_352a74c60685e01427cbef1c647d5199 = true; AutoEquipFrame:SetMovable(true); AutoEquipFrame:SetClampedToScreen(true); AutoEquipFrame:SetParent(UIParent); AutoEquipFrame:SetWidth(240); AutoEquipFrame:SetHeight(30); AutoEquipFrame:EnableMouse(true); AutoEquipFrame:SetHitRectInsets(0, 204, 0, 0); AutoEquipFrame:ClearAllPoints(); AutoEquipFrame:SetPoint("CENTER", "UIParent", "CENTER", 0, 0); AutoEquipFrame:SetFrameLevel(AutoEquipFrame:GetParent():GetFrameLevel()+2) AutoEquipFrameBackground.normal_coords = {0, 0.93359375, 0.1796875, 0.40625}; AutoEquipFrameBackground.hilight_coords = {0, 0.93359375, 0.4140625, 0.640625}; AutoEquipFrameBackground:SetTexCoord(unpack(AutoEquipFrameBackground.normal_coords)); AutoEquipSaveButton:SetPoint("TOPLEFT", AutoEquipFrame, "TOPLEFT", 37, -5); AutoEquipSetButton5:Show(); AutoEquipSetButton6:Show(); AutoEquipSetButton7:Show(); AutoEquipSetButton8:Show(); ResetIcons(); RegisterForSaveFrame(AutoEquipFrame, "AutoEquipFrame"); end end function AutoEquip_EnableAutoHide(switch) if (switch) then AutoEquip_642022feafc2fd091c1bc9b53b20e8d1 = true; AutoEquip_c990e192b1d042b676a4ee0ffff5d729(); else AutoEquip_642022feafc2fd091c1bc9b53b20e8d1 = false; AutoEquipFrame:Show(); end end function AutoEquip_KeyBinding() BigFoot_ShowKeyBindingFrame("HEADER_AUTOEQUIP_TITLE"); end local MerSwitch,havedone,MerDurabilityTooltip local InventorySlots = { "HeadSlot:d", "NeckSlot:n", "ShoulderSlot:d", "BackSlot:n", "ChestSlot:d", "ShirtSlot:n", "TabardSlot:n", "WristSlot:d", "HandsSlot:d", "WaistSlot:d", "LegsSlot:d", "FeetSlot:d", "Finger0Slot:n", "Finger1Slot:n", "Trinket0Slot:n", "Trinket1Slot:n", "MainHandSlot:d", "SecondaryHandSlot:d", }; local function CreateRepairCostFrame() if MerRepairMoneyFrame then return end local moneyFrame = CreateFrame("Frame", "MerRepairMoneyFrame", PaperDollFrame, "SmallMoneyFrameTemplate"); moneyFrame:SetPoint("BOTTOMLEFT", CharacterModelFrame, "BOTTOMLEFT", 5, 20); moneyFrame.title = moneyFrame:CreateFontString(nil, "ARTWORK", "GameFontNormal"); moneyFrame.title:SetPoint("BOTTOMLEFT", moneyFrame, "TOPLEFT", -2, 2); moneyFrame.title:SetText(M_REPAIR_COST); moneyFrame:SetScript("OnShow", function(self) MoneyFrame_SetType(self,"STATIC"); end); end local function CreateInventorySlots(frame) if havedone then return end local s for _, v in pairs(InventorySlots) do s = strsplit(":", v); local button = _G[frame .. s]; count = button.Count; count:ClearAllPoints(); count:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 2, 3); end havedone = true; end local function DisplayInventoryInfo() MerDurabilityTooltip = MerDurabilityTooltip or CreateFrame("GameTooltip", "MerDurabilityTooltip", UIParent, "GameTooltipTemplate"); local button, count, c, m, p, hasItem, itemLink, repairCos, totalCos, suffix, scan; for i, v in ipairs(InventorySlots) do suffix, scan = strsplit(":", v,2); button = _G["Character" .. suffix]; count = button.Count; count:Hide(); MerDurabilityTooltip:SetOwner(UIParent, "ANCHOR_NONE"); MerDurabilityTooltip:ClearLines(); hasItem, _, repairCos = MerDurabilityTooltip:SetInventoryItem("player", button:GetID()); itemLink = select(2, MerDurabilityTooltip:GetItem()); if MerSwitch and hasItem and itemLink then if (scan == "d") then totalCos = (totalCos or 0) + repairCos; c, m = GetInventoryItemDurability(button:GetID()); if (c and m and m > 0) then p = c / m; count:SetFormattedText("%d%%", floor(p * 100)); if (p > 0.5) then count:SetTextColor(0.133, 0.78, 0.133); elseif (p > 0.25) then count:SetTextColor(1, 0.7 ,0.2); else count:SetTextColor(1, 0, 0); end count:Show() end end end end if not MerSwitch or totalCos == 0 then MerRepairMoneyFrame:Hide() else MoneyFrame_Update("MerRepairMoneyFrame", totalCos or 0); MerRepairMoneyFrame:Show() end end local function UpdateInventoryItemDurability() local button, count, c, m, p, suffix, scan; for i, v in ipairs(InventorySlots) do suffix,scan = strsplit(":", v,2); button = _G["Character" .. suffix]; count = button.Count; count:Hide() if MerSwitch then if (scan == "d") then c, m = GetInventoryItemDurability(button:GetID()); if (c and m and m > 0) then p = c / m; count:SetFormattedText("%d%%", floor(p * 100)); if (p > 0.5) then count:SetTextColor(0.133, 0.78, 0.133); elseif (p > 0.25) then count:SetTextColor(1, 0.7 ,0.2); else count:SetTextColor(1, 0, 0); end count:Show() end end end end end hooksecurefunc("PaperDollItemSlotButton_OnEvent",function(self, event, ...) if ( event == "PLAYER_EQUIPMENT_CHANGED") then local arg1, arg2 = ...; if ( self:GetID() == arg1 ) then if MerSwitch then DisplayInventoryInfo() end end elseif event == "BAG_UPDATE_COOLDOWN" then UpdateInventoryItemDurability() end end); PaperDollFrame:HookScript("OnShow", DisplayInventoryInfo); function MerInspect_ToogleD(switch) if (switch) then MerSwitch = true; CreateRepairCostFrame(); CreateInventorySlots("Character") else MerSwitch = false; end DisplayInventoryInfo() end
function onStart(target, buff) add_buff_parameter(target, buff, 1) end function onPostTick(target, buff) if buff.not_go_round > 0 then return end buff.remaining_round = buff.remaining_round - 1; if buff.remaining_round <= 0 then UnitRemoveBuff(buff); end end function onEnd(target, buff) local move_type = buff.cfg_property[2] if move_type then local all, partners, enemies = FindAllRoles() if move_type == 1 then for i = 1, #all do local index = RAND(1, #all) if all[index].uuid ~= target.uuid then Common_UnitAddBuff(target, all[index], buff.id, 1, { parameter_99 = buff.parameter_99 }) break else table.remove(all, index) end end elseif move_type == 2 then if #partners == 1 then Common_UnitAddBuff(target, partners[index], buff.id, 1, { parameter_99 = buff.parameter_99 }) else for i = 1, #partners do local index = RAND(1, #partners) if partners[index].uuid ~= target.uuid then Common_UnitAddBuff(target, partners[index], buff.id, 1, { parameter_99 = buff.parameter_99 }) break else table.remove(partners, index) end end end elseif move_type == 3 then for i = 1, #enemies do local index = RAND(1, #enemies) Common_UnitAddBuff(target, enemies[index], buff.id, 1, { parameter_99 = buff.parameter_99 }) end end end add_buff_parameter(target, buff, -1) end function targetAfterHit(target, buff, bullet) if buff.cfg_property[1] and Hurt_Effect_judge(bullet) and RAND(1,10000) <= buff.cfg_property[1] then UnitRemoveBuff(buff); end end
EtcdClient = EtcdClient or class("EtcdClient") function EtcdClient:ctor(host) self.host = string.rtrim(host, "/") end function EtcdClient:get_host() return self.host end function EtcdClient:example_cb(id, op, result) end function EtcdClient:set(key, value, ttl, is_dir, cb_fn) local op = EtcdClientOpSet:new() op[EtcdConst.Key] = key op[EtcdConst.Value] = value op[EtcdConst.Ttl] = ttl op[EtcdConst.Dir] = is_dir and "true" or nil op.cb_fn = cb_fn return self:execute(op) end function EtcdClient:refresh_ttl(key, ttl, is_dir, cb_fn) return self:set(key, nil, ttl, is_dir, cb_fn) end function EtcdClient:get(key, recursive, cb_fn) local op = EtcdClientOpGet:new() op[EtcdConst.Key] = key op[EtcdConst.Recursive] = recursive and "true" or nil op.cb_fn = cb_fn return self:execute(op) end function EtcdClient:delete(key, recursive, cb_fn) local op = EtcdClientOpDelete:new() op[EtcdConst.Key] = key op[EtcdConst.Recursive] = recursive and "true" or nil op.cb_fn = cb_fn return self:execute(op) end function EtcdClient:watch(key, recursive, waitIndex, cb_fn) local op = EtcdClientOpGet:new() op[EtcdConst.Key] = key op[EtcdConst.Wait] = "true" op[EtcdConst.WaitIndex] = waitIndex op[EtcdConst.Recursive] = recursive and "true" or nil op.cb_fn = cb_fn return self:execute(op) end function EtcdClient:cmp_swap(key, prev_index, prev_value, value, cb_fn) local op = EtcdClientOpSet:new() op[EtcdConst.Key] = key op[EtcdConst.Value] = value op[EtcdConst.PrevIndex] = prev_index op[EtcdConst.PrevValue] = prev_value op.cb_fn = cb_fn return self:execute(op) end function EtcdClient:cmp_delete(key, prev_index, prev_value, recursive, cb_fn) local op = EtcdClientOpDelete:new() op[EtcdConst.Key] = key op[EtcdConst.PrevIndex] = prev_index op[EtcdConst.PrevValue] = prev_value op[EtcdConst.Recursive] = recursive and "true" or nil op.cb_fn = cb_fn return self:execute(op) end function EtcdClient:execute(op) return op:execute(self) end function EtcdClient._Handle_event_cb(op, op_id, err_type_enum, err_num_int) log_debug("EtcdClient._Handle_event_cb %s", op_id) end function EtcdClient._handle_set_result_cb(op, op_id, url_str, heads_map, body_str, body_len) log_debug("EtcdClient._handle_set_result_cb %s", op_id) end function EtcdClient._handle_get_result_cb(op, op_id, url_str, heads_map, body_str, body_len) log_debug("EtcdClient._handle_get_result_cb %s", op_id) end function EtcdClient._handle_delete_result_cb(op, op_id, url_str, heads_map, body_str, body_len) log_debug("EtcdClient._handle_delete_result_cb %s", op_id) end
test_run = require('test_run').new() REPLICASET_1 = { 'box_1_a', 'box_1_b' } REPLICASET_2 = { 'box_2_a', 'box_2_b' } test_run:create_cluster(REPLICASET_1, 'rebalancer') test_run:create_cluster(REPLICASET_2, 'rebalancer') util = require('util') util.wait_master(test_run, REPLICASET_1, 'box_1_a') util.wait_master(test_run, REPLICASET_2, 'box_2_a') util.map_evals(test_run, {REPLICASET_1, REPLICASET_2}, 'bootstrap_storage(\'memtx\')') util.push_rs_filters(test_run) -- -- gh-113: during rebalancing the recoverer can make a bucket be -- ACTIVE on two replicasets. It is possible, if bucket_send -- during marking a bucket to be SENDING does too long WAL write. -- During the write the recovery fiber wakes up, checks that the -- bucket does not exist on the destination replicaset and makes -- it ACTIVE on the source. Then bucket_send finalizes WAL write -- and sends data. If the data is applied too long on the -- destination, bucket_send catches TIMEOUT error and exits. So -- now the bucket is ACTIVE both on the source and the -- destination. -- -- Since 113 was fixed, now recovery does not work with a bucket -- sending right now, so the issue is not so actual anymore. -- test_run:switch('box_1_a') _bucket = box.space._bucket vshard.storage.cfg(cfg, util.name_to_uuid.box_1_a) wait_rebalancer_state('Total active bucket count is not equal to total', test_run) vshard.storage.rebalancer_disable() for i = 1, 100 do _bucket:replace{i, vshard.consts.BUCKET.ACTIVE} end test_run:switch('box_2_a') _bucket = box.space._bucket for i = 101, 200 do _bucket:replace{i, vshard.consts.BUCKET.ACTIVE} end vshard.storage.internal.errinj.ERRINJ_LONG_RECEIVE = true test_run:switch('box_1_a') vshard.storage.rebalancer_enable() wait_rebalancer_state('The cluster is balanced ok', test_run) errinj = box.error.injection errinj.set('ERRINJ_WAL_DELAY', true) log.info(string.rep('a', 1000)) cfg.sharding[util.replicasets[1]].weight = 0.5 vshard.storage.cfg(cfg, util.name_to_uuid.box_1_a) -- -- The rebalancer tries to send a bucket. It made the bucket be -- SENDING and started to persist that in WAL. -- if not test_run:grep_log('box_1_a', 'Apply rebalancer routes', 1000) then wait_rebalancer_state('Apply rebalancer routes', test_run) end -- -- During that the recovery fiber wakes up, sees SENDING bucket, -- checks that it does not exist on the destination, and makes it -- ACTIVE. It is wrong - the recovery fiber must not recovery -- buckets that are beeing sent right now. -- fiber = require('fiber') for i = 1, 10 do vshard.storage.recovery_wakeup() fiber.sleep(0.1) end not test_run:grep_log('box_1_a', 'Finish bucket recovery step') errinj.set('ERRINJ_WAL_DELAY', false) -- -- WAL is working again. Bucket_send wakes up, and tries to send -- the bucket. On the destination the bucket is applied too long, -- and the bucket_send gets timeout error. -- while not test_run:grep_log('box_1_a', 'Error during rebalancer routes applying') do vshard.storage.rebalancer_wakeup() fiber.sleep(0.01) end test_run:grep_log('box_1_a', 'Timeout exceeded') ~= nil test_run:switch('box_2_a') vshard.storage.internal.errinj.ERRINJ_LONG_RECEIVE = false test_run:switch('box_1_a') wait_rebalancer_state('The cluster is balanced ok', test_run) _bucket.index.status:count{vshard.consts.BUCKET.ACTIVE} test_run:switch('box_2_a') _bucket.index.status:count{vshard.consts.BUCKET.ACTIVE} -- -- Test that it is possible to send multiple bucket at the same -- time, even using the public bucket_send function. -- box.error.injection.set('ERRINJ_WAL_DELAY', true) _ = test_run:switch('box_1_a') _bucket:get{35} _bucket:get{36} ret1 = nil ret2 = nil err1 = nil err2 = nil f1 = fiber.create(function() ret1, err1 = vshard.storage.bucket_send(35, util.replicasets[2]) end) f2 = fiber.create(function() ret2, err2 = vshard.storage.bucket_send(36, util.replicasets[2]) end) _ = test_run:switch('box_2_a') box.error.injection.set('ERRINJ_WAL_DELAY', false) _ = test_run:switch('box_1_a') while f1:status() ~= 'dead' or f2:status() ~= 'dead' do fiber.sleep(0.001) end ret1, err1 ret2, err2 wait_bucket_is_collected(35) wait_bucket_is_collected(36) _ = test_run:switch('box_2_a') _bucket:get{35} _bucket:get{36} -- -- Test that bucket_send is correctly handled by recovery. When -- bucket_send is in progress, the recovery should not touch its -- bucket. -- _ = test_run:switch('box_2_a') box.error.injection.set('ERRINJ_WAL_DELAY', true) _ = test_run:switch('box_1_a') f1 = fiber.create(function() ret1, err1 = vshard.storage.bucket_send(36, util.replicasets[2]) end) _ = test_run:switch('box_2_a') while not _bucket:get{36} do fiber.sleep(0.0001) end _ = test_run:switch('box_1_a') wait_bucket_is_collected(36) _bucket:get{36} _ = test_run:switch('box_2_a') _bucket:get{36} box.error.injection.set('ERRINJ_WAL_DELAY', false) test_run:switch('default') test_run:drop_cluster(REPLICASET_2) test_run:drop_cluster(REPLICASET_1)
module("util", package.seeall)
-- Use `digest` library http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/install.html local digest = require "bgcrypto.private.digest" return digest('ripemd160')
--[[ CLI Plugin -> Map Command (ServerSide) by Tassilo (@TASSIA710) Command for quickly changing map. --]] jet.AddCliCommand("map", function(args) if #args == 0 then print("Current Map: " .. game.GetMap()) elseif #args == 1 then RunConsoleCommand("changelevel", args[1]) else return false end end, "", "Change map.")
require("config") --Changes require("prototypes.changes") --Speed require("prototypes.speed-4") require("prototypes.speed-5") --Productivity require("prototypes.productivity-4") require("prototypes.productivity-5") --Effectivity require("prototypes.effectivity-4") require("prototypes.effectivity-5") --Pollution require("prototypes.pollution-1") require("prototypes.pollution-2") require("prototypes.pollution-3") require("prototypes.pollution-4") require("prototypes.pollution-5") --Mix MK4 require("prototypes.speed-effectivity-4") require("prototypes.speed-productivity-4") require("prototypes.speed-pollution-4") require("prototypes.pollution-effectivity-4") require("prototypes.pollution-productivity-4") require("prototypes.effectivity-productivity-4") --Mix MK5 require("prototypes.speed-effectivity-5") require("prototypes.speed-productivity-5") require("prototypes.speed-pollution-5") require("prototypes.pollution-effectivity-5") require("prototypes.pollution-productivity-5") require("prototypes.effectivity-productivity-5") --Welder require("prototypes.recipe-category") require("prototypes.welder") --Category require("prototypes.module-category") --Tech require("prototypes.tech")
local c = '' --env-types do local f = ASR(io.open(CEU.opts.env_types)) c = c..'\n\n/* ENV_HEADER */\n\n'..f:read'*a' f:close() end --env-threads do if CEU.opts.env_threads then local f = ASR(io.open(CEU.opts.env_threads)) c = c..'\n\n/* ENV_THREADS */\n\n'..f:read'*a' f:close() end end -- callbacks do c = c..[[ typedef union tceu_callback_arg { void* ptr; s32 num; usize size; } tceu_callback_arg; typedef struct tceu_callback_ret { bool is_handled; tceu_callback_arg value; } tceu_callback_ret; tceu_callback_ret ceu_callback (int cmd, tceu_callback_arg p1, tceu_callback_arg p2); #define ceu_callback_void_void(cmd) \ ceu_callback(cmd, (tceu_callback_arg){}, \ (tceu_callback_arg){}) #define ceu_callback_num_void(cmd,p1) \ ceu_callback(cmd, (tceu_callback_arg){.num=p1}, \ (tceu_callback_arg){}) #define ceu_callback_num_ptr(cmd,p1,p2) \ ceu_callback(cmd, (tceu_callback_arg){.num=p1}, \ (tceu_callback_arg){.ptr=p2}) #define ceu_callback_num_num(cmd,p1,p2) \ ceu_callback(cmd, (tceu_callback_arg){.num=p1}, \ (tceu_callback_arg){.num=p2}) #define ceu_callback_ptr_num(cmd,p1,p2) \ ceu_callback(cmd, (tceu_callback_arg){.ptr=p1}, \ (tceu_callback_arg){.num=p2}) #define ceu_callback_ptr_ptr(cmd,p1,p2) \ ceu_callback(cmd, (tceu_callback_arg){.ptr=p1}, \ (tceu_callback_arg){.ptr=p2}) #define ceu_callback_ptr_size(cmd,p1,p2) \ ceu_callback(cmd, (tceu_callback_arg){.ptr=p1}, \ (tceu_callback_arg){.size=p2}) #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #ifndef ceu_callback_assert_msg_ex #define ceu_callback_assert_msg_ex(v,msg,file,line) \ if (!(v)) { \ if ((msg)!=NULL) { \ ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)"["); \ ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)(file)); \ ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)":"); \ ceu_callback_num_num(CEU_CALLBACK_LOG, 2, line); \ ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)"] "); \ ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)"runtime error: "); \ ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)(msg)); \ ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)"\n"); \ } \ ceu_callback_num_ptr(CEU_CALLBACK_ABORT, 0, NULL); \ } #endif #define ceu_callback_assert_msg(v,msg) ceu_callback_assert_msg_ex((v),(msg),__FILE__,__LINE__) #define ceu_dbg_assert(v) ceu_callback_assert_msg(v,"bug found") #define ceu_dbg_log(msg) { ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)(msg)); \ ceu_callback_num_ptr(CEU_CALLBACK_LOG, 0, (void*)"\n"); } enum { CEU_CALLBACK_START, CEU_CALLBACK_STOP, CEU_CALLBACK_STEP, CEU_CALLBACK_ABORT, CEU_CALLBACK_LOG, CEU_CALLBACK_TERMINATING, CEU_CALLBACK_ASYNC_PENDING, CEU_CALLBACK_THREAD_TERMINATING, CEU_CALLBACK_ISR_ENABLE, CEU_CALLBACK_ISR_ATTACH, CEU_CALLBACK_ISR_DETACH, CEU_CALLBACK_ISR_EMIT, CEU_CALLBACK_WCLOCK_MIN, CEU_CALLBACK_WCLOCK_DT, CEU_CALLBACK_OUTPUT, CEU_CALLBACK_REALLOC, }; ]] end if TESTS then c = c .. [[ u32 _ceu_tests_trails_visited_ = 0; ]] end --env-ceu do local f = ASR(io.open(CEU.opts.env_ceu)) c = c..'\n\n/* ENV_CEU */\n\n'..f:read'*a' f:close() end --env-main do if CEU.opts.env_main then local f = ASR(io.open(CEU.opts.env_main)) c = c..'\n\n/* ENV_MAIN */\n\n'..f:read'*a' f:close() end end --env-output do local out = [[ /* * This file is automatically generated. * http://www.ceu-lang.org/ * http://github.com/fsantanna/ceu/ * * Céu is distributed under the MIT License: * Copyright (C) 2012-2016 Francisco Sant'Anna Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ ]] .. c if CEU.opts.env_output == '-' then print(out) else local f = ASR(io.open(CEU.opts.env_output,'w')) f:write(out) f:close() end end
loadfile("/tmp/metrics.lua") local https = require "ssl.https" local ltn12 = require "ltn12" local json = require 'lunajson' local redis = require "resty.redis" local arg = ngx.req.get_uri_args() local incr = 0 function read_all(file) local f = assert(io.open(file, "rb")) local content = f:read("*all") f:close() return content end local http = require("socket.http") math.randomseed(os.clock()*100000000000) local rand = math.random(999, 9999) local arg = ngx.req.get_uri_args() if os.getenv("KUBERNETES_SERVICE_HOST") then k8s_url = "https://" .. os.getenv("KUBERNETES_SERVICE_HOST") .. ":" .. os.getenv("KUBERNETES_SERVICE_PORT_HTTPS") else k8s_url = os.getenv("ENDPOINT") end local token = os.getenv("TOKEN") local namespace = arg['namespace'] local node_name = arg['nodename'] local url = k8s_url .. "/apis/batch/v1/namespaces/" .. namespace .. "/jobs" local resp = {} if ngx.var.request_method == "GET" then local red = redis:new() local okredis, errredis = red:connect("unix:/tmp/redis.sock") if okredis then ngx.log(ngx.ERR, "Connection to Redis is ok") else ngx.log(ngx.ERR, "Connection to Redis is not ok") ngx.log(ngx.ERR, errredis) end -- Count the total of chaos jobs launched against nodes local chaos_node_res, err = red:get("chaos_node_jobs_total") if chaos_node_res == ngx.null then ngx.say(err) red:set("chaos_node_jobs_total", 0) else local incr = chaos_node_res + 1 local res, err = red:set("chaos_node_jobs_total",incr) end -- Count the total of chaos jobs launched against nodes per node local node_name = arg['nodename'] local chaos_node_res, err = red:get("chaos_node_jobs_total_on_" .. node_name) if chaos_node_res == ngx.null then ngx.say(err) red:set("chaos_node_jobs_total_on_" .. node_name, 1) else local incr = chaos_node_res + 1 local res, err = red:set("chaos_node_jobs_total_on_" .. node_name,incr) end end ngx.header['Access-Control-Allow-Origin'] = '*' ngx.header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' ngx.header['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' ngx.header['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range'; headers = { ["Accept"] = "application/json", ["Content-Type"] = "application/json", ["Authorization"] = "Bearer " .. token, } body = [[ { "apiVersion": "batch/v1", "kind": "Job", "metadata": { "name": "kubeinvaders-chaos-]] .. rand .. [[", "labels": { "app": "kubeinvaders", "approle": "chaosnode" } }, "spec": { "template": { "metadata": { "labels": { "app": "kubeinvaders", "approle": "chaosnode" } }, "spec": { "containers": [ { "name": "kubeinvaders-chaos-node", "image": "docker.io/luckysideburn/kubeinvaders-stress-ng:latest", "command": [ "stress-ng", "--cpu", "4", "--io", "2", "--vm", "1", "--vm-bytes", "1G", "--timeout", "10s", "--metrics-brief" ] } ], "restartPolicy": "Never", "nodeSelector": { "kubernetes.io/hostname": "wrk5-oc" } } }, "backoffLimit": null } } ]] local headers2 = { ["Accept"] = "application/json", ["Content-Type"] = "application/json", ["Authorization"] = "Bearer " .. token, ["Content-Length"] = string.len(body) } url = k8s_url .. "/apis/batch/v1/namespaces/" .. namespace .. "/jobs" ngx.log(ngx.ERR, "Creating chaos_node job kubeinvaders-chaos-" ..rand) local ok, statusCode, headers, statusText = https.request{ url = url, headers = headers2, method = "POST", sink = ltn12.sink.table(resp), source = ltn12.source.string(body) } ngx.log(ngx.ERR, ok) ngx.log(ngx.ERR, statusCode) ngx.log(ngx.ERR, statusText) local url = k8s_url.. "/apis/batch/v1/namespaces/" .. namespace .. "/jobs" ngx.log(ngx.ERR, "Getting JobList" .. rand) local ok, statusCode, headers, statusText = https.request{ url = url, headers = headers, method = "GET", sink = ltn12.sink.table(resp) } ngx.log(ngx.ERR, ok) ngx.log(ngx.ERR, statusCode) ngx.log(ngx.ERR, statusText) for k,v in ipairs(resp) do decoded = json.decode(v) if decoded["kind"] == "JobList" then for k2,v2 in ipairs(decoded["items"]) do if v2["status"]["succeeded"] == 1 and v2["metadata"]["labels"]["approle"] == "chaosnode" then delete_job = "kubectl delete job " .. v2["metadata"]["name"] .. " --token=" .. token .. " --server=" .. k8s_url .. " --insecure-skip-tls-verify=true -n " .. namespace ngx.log(ngx.ERR, delete_pod) end end end end local url = k8s_url.. "/api/v1/namespaces/" .. namespace .. "/pods" ngx.log(ngx.ERR, "Getting PodList" .. rand) local ok, statusCode, headers, statusText = https.request{ url = url, headers = headers, method = "GET", sink = ltn12.sink.table(resp) } ngx.log(ngx.ERR, ok) ngx.log(ngx.ERR, statusCode) ngx.log(ngx.ERR, statusText) for k,v in ipairs(resp) do decoded = json.decode(v) if decoded["kind"] == "PodList" then for k2,v2 in ipairs(decoded["items"]) do if v2["status"]["phase"] == "Succeeded" and v2["metadata"]["labels"]["approle"] == "chaosnode" then delete_pod = "kubectl delete pod " .. v2["metadata"]["name"] .. " --token=" .. token .. " --server=" .. k8s_url .. " --insecure-skip-tls-verify=true -n " .. namespace ngx.log(ngx.ERR, delete_pod) end end end end ngx.say("chaos node")
object_static_worldbuilding_structures_mun_nboo_building_chunk_destoyed_09 = object_static_worldbuilding_structures_shared_mun_nboo_building_chunk_destoyed_09:new { } ObjectTemplates:addTemplate(object_static_worldbuilding_structures_mun_nboo_building_chunk_destoyed_09, "object/static/worldbuilding/structures/mun_nboo_building_chunk_destoyed_09.iff")
object_tangible_furniture_nym_themepark_nym_themepark_rug = object_tangible_furniture_nym_themepark_shared_nym_themepark_rug:new { } ObjectTemplates:addTemplate(object_tangible_furniture_nym_themepark_nym_themepark_rug, "object/tangible/furniture/nym_themepark/nym_themepark_rug.iff")
-- The MIT License (MIT) -- Copyright (c) 2016 Ruairidh Carmichael - ruairidhcarmichael@live.co.uk -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. local config = require 'moontastic.config' local glyph = {} glyph.DIVIDER_RIGHT_PATCHED = '' glyph.DIVIDER_RIGHT_SOFT_PATCHED = '' glyph.DIVIDER_LEFT_PATCHED = '' glyph.DIVIDER_LEFT_SOFT_PATCHED = '' glyph.BRANCH1_PATCHED = '' glyph.BRANCH2 = '⭃' glyph.TIME = '⌚' glyph.VIRTUAL_ENV = 'ⓥ' glyph.TIME = '⌚' glyph.HOURGLASS = '⌛' glyph.CROSS = '✖' glyph.ESCLAMATION = '❕' glyph.LOCK = '' glyph.N1 = '➊' glyph.N2 = '➋' glyph.N3 = '➌' glyph.N4 = '➍' glyph.N5 = '➎' glyph.N6 = '➏' glyph.N7 = '➐' glyph.N8 = '➑' glyph.N9 = '➒' glyph.N10 = '➓' glyph.LEFT_ARROW = '⤎' glyph.RIGHT_ARROW = '⤏' glyph.PEN = '' glyph.SUNNY = '☀' glyph.CLOUDY = '☁' glyph.RAINY = '☂' -- Branch and divider glyphs are different depending on whether the current theme is using -- patched fonts or not. if config.PATCHED_FONTS then glyph.BRANCH = glyph.BRANCH1_PATCHED glyph.DIVIDER = glyph.DIVIDER_RIGHT_PATCHED glyph.WRITE_ONLY = glyph.LOCK else glyph.BRANCH = glyph.BRANCH2 glyph.DIVIDER = '' glyph.WRITE_ONLY = glyph.PEN end return glyph
local local0 = 0.3 local local1 = 1 - local0 local local2 = 1 - local0 local local3 = 1 - local0 local local4 = 1 - local0 local local5 = 0 - local0 local local6 = 1 - local0 local local7 = 30 - local0 local local8 = 1 - local0 local local9 = 30 - local0 local local10 = 1 - local0 local local11 = 10 - local0 local local12 = 1 - local0 local local13 = 10 - local0 local local14 = 1 - local0 local local15 = 1 - local0 local local16 = 1 - local0 local local17 = 15 - local0 local local18 = 1 - local0 local local19 = 1 - local0 local local20 = 1 - local0 local local21 = 9 - local0 local local22 = 12.2 - local0 local local23 = 0.5 - local0 local local24 = 5 - local0 local local25 = 0.5 - local0 local local26 = 2 - local0 local local27 = 3.5 - local0 local local28 = 3.5 - local0 local local29 = 1 - local0 local local30 = 1 - local0 local local31 = 99.9 - local0 local local32 = 1 - local0 local local33 = 99.9 - local0 function OnIf_306001(arg0, arg1, arg2) if arg2 == 0 then DungeonResident_bride_fetus_306001_ActAfter(arg0, arg1) end if arg2 == 2 then DungeonResident_bride_fetus_306001_combofinish(arg0, arg1) end return end local0 = 1 function DungeonResident_bride_fetus_306001Battle_Activate(arg0, arg1) local local0 = {} local local1 = {} local local2 = {} Common_Clear_Param(local0, local1, local2) local local3 = arg0:GetHpRate(TARGET_SELF) local local4 = arg0:GetDist(TARGET_ENE_0) local local5 = arg0:GetRandam_Int(1, 100) local local6 = arg0:GetEventRequest(0) local local7 = arg0:GetEventRequest(1) local local8 = arg0:GetNumber(1) if local8 == 22 or arg0:GetNumber(0) == 0 then local local9 = 1 SETUPVAL 11 0 0 elseif arg0:GetNumber(2) == 1 then local local9 = UPVAL0 * 1.75 SETUPVAL 11 0 0 else local local9 = UPVAL0 * 1.25 SETUPVAL 11 0 0 end if local3 <= 0.8 and arg0:GetNumber(0) == 0 then local0[21] = 100 elseif local3 <= 0.5 and arg0:GetNumber(0) == 1 then local0[11] = 100 elseif arg0:HasSpecialEffectId(TARGET_SELF, 5401) and arg0:IsFinishTimer(0) == true and arg0:GetNumber(3) == 0 then local0[22] = 100 elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 240) then local0[20] = 100 elseif arg0:GetNumber(0) == 2 then if local8 == 12 and 10 <= local4 then if 13 <= local4 then local0[1] = 100 else local0[7] = 100 end elseif 12 <= local4 then local0[1] = 100 elseif 9 <= local4 then local0[1] = 25 local0[2] = 0 local0[4] = 5 local0[5] = 15 local0[7] = 20 local0[12] = 20 local0[13] = 15 local0[22] = UPVAL0 elseif 6 <= local4 then local0[2] = 10 local0[4] = 10 local0[5] = 15 local0[7] = 20 local0[12] = 25 local0[13] = 20 local0[22] = UPVAL0 elseif 3 <= local4 then local0[2] = 0 local0[4] = 15 local0[5] = 15 local0[6] = 5 local0[9] = 5 local0[10] = 10 local0[12] = 30 local0[13] = 10 local0[22] = UPVAL0 else local0[2] = 0 local0[6] = 10 local0[8] = 15 local0[9] = 25 local0[10] = 10 local0[12] = 40 local0[13] = 0 local0[22] = UPVAL0 end elseif arg0:GetNumber(0) == 1 then if 12 <= local4 then local0[1] = 75 local0[4] = 25 local0[13] = 0 local0[22] = UPVAL0 elseif 9 <= local4 then local0[1] = 25 local0[2] = 0 local0[4] = 20 local0[5] = 15 local0[7] = 30 local0[13] = 10 local0[22] = UPVAL0 elseif 6 <= local4 then local0[2] = 20 local0[4] = 25 local0[5] = 20 local0[7] = 20 local0[13] = 15 local0[22] = UPVAL0 elseif 3 <= local4 then local0[2] = 20 local0[5] = 30 local0[6] = 10 local0[9] = 10 local0[10] = 10 local0[13] = 20 local0[22] = UPVAL0 else local0[2] = 0 local0[6] = 20 local0[8] = 20 local0[9] = 20 local0[10] = 20 local0[13] = 20 local0[22] = UPVAL0 end elseif 12 <= local4 then local0[1] = 100 local0[2] = 0 local0[3] = 0 elseif 9 <= local4 then local0[1] = 80 local0[2] = 20 local0[3] = 0 elseif 6 <= local4 then local0[1] = 15 local0[2] = 55 local0[3] = 30 else local0[1] = 0 local0[2] = 50 local0[3] = 50 end if local8 == 1 and 0 < local0[1] then local0[1] = 1 end if local8 == 2 and 0 < local0[2] then local0[2] = 1 end if local8 == 3 and 0 < local0[3] then local0[3] = 1 end if local8 == 4 and 0 < local0[4] then local0[4] = 1 end if local8 == 5 and 0 < local0[5] then local0[5] = 1 end if local8 == 6 and 0 < local0[6] then local0[6] = 1 end if local8 == 7 and 0 < local0[7] then local0[7] = 1 end if local8 == 8 and 0 < local0[8] then local0[8] = 1 end if local8 == 9 and 0 < local0[9] then local0[9] = 1 end if local8 == 10 and 0 < local0[10] then local0[10] = 1 end if local8 == 11 and 0 < local0[11] then local0[11] = 1 end if local8 == 12 and 0 < local0[12] then local0[12] = 1 end if local8 == 13 and 0 < local0[13] then local0[13] = 1 end if local8 == 22 and 0 < local0[22] then local0[22] = 1 end local1[1] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act01) local1[2] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act02) local1[3] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act03) local1[4] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act04) local1[5] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act05) local1[6] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act06) local1[7] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act07) local1[8] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act08) local1[9] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act09) local1[10] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act10) local1[11] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act11) local1[12] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act12) local1[13] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act13) local1[20] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act20) local1[21] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act21) local1[22] = REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_Act22) Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, DungeonResident_bride_fetus_306001_ActAfter_AdjustSpace), local2) return end local0 = 30 - local0 local0 = 30 - local0 function DungeonResident_bride_fetus_306001_Act01(arg0, arg1, arg2) local local0 = UPVAL0 + 1 local local1 = UPVAL1 + 1 local local2 = arg0:GetRandam_Int(1, 100) if arg0:GetNumber(0) == 0 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local0, 0, 0) if local2 <= 50 then arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, local1, 0) end arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3001, TARGET_ENE_0, local1, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3025, TARGET_ENE_0, local0, 0, 0) if local2 <= 50 then arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3026, TARGET_ENE_0, local1, 0) end arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3026, TARGET_ENE_0, local1, 0) end arg0:SetNumber(1, 1) arg0:SetNumber(2, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 10 - local0 local0 = 10 - local0 function DungeonResident_bride_fetus_306001_Act02(arg0, arg1, arg2) local local0 = UPVAL0 + 1 local local1 = UPVAL1 + 1 if arg0:GetNumber(0) == 2 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3027, TARGET_ENE_0, local0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3028, TARGET_ENE_0, local1, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3002, TARGET_ENE_0, local0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3003, TARGET_ENE_0, local1, 0) end arg0:SetNumber(1, 2) arg0:SetNumber(2, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 8 - local0 function DungeonResident_bride_fetus_306001_Act03(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3004, TARGET_ENE_0, UPVAL0 + 1, 0, 0) arg0:SetNumber(1, 3) arg0:SetNumber(2, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 15 - local0 function DungeonResident_bride_fetus_306001_Act04(arg0, arg1, arg2) local local0 = UPVAL0 + 1 if 2 <= arg0:GetNumber(0) then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3004, TARGET_ENE_0, local0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3006, TARGET_ENE_0, local0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3008, TARGET_ENE_0, local0, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3004, TARGET_ENE_0, local0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3007, TARGET_ENE_0, local0, 0) end arg0:SetNumber(1, 4) arg0:SetNumber(2, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 5 - local0 function DungeonResident_bride_fetus_306001_Act05(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, UPVAL0, 0, -1) arg0:SetNumber(1, 5) arg0:SetNumber(2, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 2.5 - local0 local0 = 2.7 - local0 function DungeonResident_bride_fetus_306001_Act06(arg0, arg1, arg2) Approach_Act(arg0, arg1, UPVAL1, 999, 0) arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3010, TARGET_ENE_0, UPVAL0 + 2, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3011, TARGET_ENE_0, 12, 0) arg0:SetNumber(1, 6) arg0:SetNumber(2, 1) arg1:AddSubGoal(GOAL_COMMON_If, 10, 2) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 2.2 - local0 local0 = 6.7 - local0 local0 = local22 function DungeonResident_bride_fetus_306001_combofinish(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = UPVAL1 + 1 if local0 <= 2 then arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3012, TARGET_ENE_0, UPVAL0 + 1, 0) elseif local0 <= 5 then arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3015, TARGET_ENE_0, UPVAL2 + 1, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3013, TARGET_ENE_0, AttDist3, 0) end return end local0 = local22 function DungeonResident_bride_fetus_306001_Act07(arg0, arg1, arg2) Approach_Act(arg0, arg1, UPVAL0, 999, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3013, TARGET_ENE_0, UPVAL0, 0, 0) arg0:SetNumber(1, 7) arg0:SetNumber(2, 1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 3 - local0 function DungeonResident_bride_fetus_306001_Act08(arg0, arg1, arg2) Approach_Act(arg0, arg1, UPVAL0, 999, 0, 3) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3014, TARGET_ENE_0, UPVAL0 + 1, 0, 0) arg0:SetNumber(1, 8) arg0:SetNumber(2, 1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 1.7 - local0 function DungeonResident_bride_fetus_306001_Act09(arg0, arg1, arg2) Approach_Act(arg0, arg1, UPVAL0, 999, 0, 3) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3016, TARGET_ENE_0, UPVAL0 + 1, 0, 0) arg0:SetNumber(1, 9) arg0:SetNumber(2, 1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = 5.1 - local0 local0 = 4.5 - local0 function DungeonResident_bride_fetus_306001_Act10(arg0, arg1, arg2) local local0 = UPVAL0 + 1 Approach_Act(arg0, arg1, UPVAL1, 999, 0) arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3017, TARGET_ENE_0, local0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3018, TARGET_ENE_0, local0, 0) arg0:SetNumber(1, 10) arg0:SetNumber(2, 1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end function DungeonResident_bride_fetus_306001_Act11(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3023, TARGET_ENE_0, DIST_None, 0, 0) arg0:AddObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5516) GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = 15.1 - local0 function DungeonResident_bride_fetus_306001_Act12(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3024, TARGET_ENE_0, UPVAL0 + 1, 0, 0) arg0:SetNumber(1, 12) arg0:SetNumber(2, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end function DungeonResident_bride_fetus_306001_Act13(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3036, TARGET_ENE_0, DIST_None, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3037, TARGET_ENE_0, DIST_None, 0) arg0:SetNumber(1, 13) arg0:SetNumber(2, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end function DungeonResident_bride_fetus_306001_Act20(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(1, 100) local local3 = arg0:GetRandam_Float(1, 2) if arg0:GetNumber(0) == 1 then if local0 <= 3 then if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 180) then if local1 <= 40 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 0) elseif local1 <= 40 then DungeonResident_bride_fetus_306001_Act05(arg0, arg1, arg2) else DungeonResident_bride_fetus_306001_Act06(arg0, arg1, arg2) end elseif local1 <= 50 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 0) elseif local1 <= 40 then DungeonResident_bride_fetus_306001_Act05(arg0, arg1, arg2) else DungeonResident_bride_fetus_306001_Act06(arg0, arg1, arg2) end elseif local0 <= 10 then if local2 <= 35 then if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 180) then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 0) else arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 0) end elseif local2 <= 70 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local3, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(30, 45), false, true, -1) else DungeonResident_bride_fetus_306001_Act05(arg0, arg1, arg2) end else arg1:AddSubGoal(GOAL_COMMON_Turn, 3, TARGET_ENE_0, 0, 0, 0) end elseif local0 <= 3 then if arg0:GetRandam_Int(1, 100) <= 50 then if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 180) then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local3, TARGET_ENE_0, 1, arg0:GetRandam_Int(30, 45), false, true, -1) else arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local3, TARGET_ENE_0, 0, arg0:GetRandam_Int(30, 45), false, true, -1) end else DungeonResident_bride_fetus_306001_Act03(arg0, arg1, arg2) end elseif local0 <= 8 then DungeonResident_bride_fetus_306001_Act02(arg0, arg1, arg2) else arg1:AddSubGoal(GOAL_COMMON_Turn, 3, TARGET_ENE_0, 0, 0, 0) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end function DungeonResident_bride_fetus_306001_Act21(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3030, TARGET_ENE_0, DIST_None, 0, 0) arg0:AddObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5401) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function DungeonResident_bride_fetus_306001_Act22(arg0, arg1, arg2) if arg0:GetNumber(0) == 2 then arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3020, TARGET_ENE_0, DIST_None, 0, 0) else arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3019, TARGET_ENE_0, DIST_None, 0, 0) end arg0:SetNumber(1, 22) arg0:SetNumber(3, 1) GetWellSpace_Odds = 0 return GetWellSpace_Odds end function DungeonResident_bride_fetus_306001_ActAfter_AdjustSpace(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_If, 10, 0) return end function DungeonResident_bride_fetus_306001_ActAfter(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(0, 1) if local0 > 5 then if local0 <= 7.5 then if local1 <= 40 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, arg0:GetRandam_Float(2.5, 3.5), TARGET_ENE_0, local2, arg0:GetRandam_Int(120, 120), true, true, -1) end elseif local0 <= 10 then if local1 <= 70 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, arg0:GetRandam_Float(3.5, 4.5), TARGET_ENE_0, local2, arg0:GetRandam_Int(120, 120), true, true, -1) end else arg1:AddSubGoal(GOAL_COMMON_SidewayMove, arg0:GetRandam_Float(4.5, 5.5), TARGET_ENE_0, local2, arg0:GetRandam_Int(120, 120), true, true, -1) end end return end function DungeonResident_bride_fetus_306001Battle_Update(arg0, arg1) return GOAL_RESULT_Continue end function DungeonResident_bride_fetus_306001Battle_Terminate(arg0, arg1) return end local0 = 99.9 - local0 function DungeonResident_bride_fetus_306001Battle_Interupt(arg0, arg1) local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(1, 100) local local3 = arg0:GetDist(TARGET_ENE_0) local local4 = UPVAL0 + 1 if arg0:IsInterupt(INTERUPT_FLAG_ActivateSpecialEffect) then if arg0:IsActivateSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5401) then arg1:ClearSubGoal() arg0:SetNumber(0, 1) arg0:SetTimer(0, arg0:GetRandam_Int(10, 15)) arg0:DeleteObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5401) arg0:Replaning() elseif arg0:IsActivateSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5516) then arg1:ClearSubGoal() arg0:SetNumber(0, 2) arg0:DeleteObserveSpecialEffect(TARGET_SELF, AI_SPEFFOBSERVE_SpEffId, 5516) arg0:Replaning() end return true else return false end end return
--- --- De-obfuscated bootloader --- The initial boot script has standardised path and filename (/boot) so it must not be altered --- Working directory must be the (virtual) filesystem root --- --- Created by torvald. --- DateTime: 2019-11-03 02:30 --- dofile("etc/init.lua")
function dumpDirectory(filelist, directory) flist = System.listDirectory(directory) for idx, file in ipairs(flist) do if file.name ~= "." and file.name ~= ".." and file.name ~= "filelist.txt" then fullFile = directory .. "/" .. file.name if file.directory then dumpDirectory(filelist, fullFile) else fullFileHandle = io.open(fullFile, "r") if fullFileHandle then md5sum = System.md5sum(fullFileHandle:read("*a")) fullFileHandle:close() filelist:write(fullFile .. ", size: " .. file.size .. ", md5: " .. md5sum .. "\r\n") end end end end end flist = System.listDirectory() dofiles = { 0, 0, 0 } for idx, file in ipairs(flist) do if file.name ~= "." and file.name ~= ".." then if string.lower(file.name) == "script.lua" then -- luaplayer/script.lua dofiles[1] = file.name end if file.directory then fflist = System.listDirectory(file.name) for fidx, ffile in ipairs(fflist) do if string.lower(ffile.name) == "script.lua" then -- app bundle dofiles[2] = file.name.."/"..ffile.name System.currentDirectory(file.name) end if string.lower(ffile.name) == "index.lua" then -- app bundle dofiles[2] = file.name.."/"..ffile.name System.currentDirectory(file.name) end if string.lower(ffile.name) == "system.lua" then -- luaplayer/System dofiles[3] = file.name.."/"..ffile.name end end end end end done = false for idx, runfile in ipairs(dofiles) do if runfile ~= 0 then dofile(runfile) done = true break end end if not done then print("Boot error: No boot script found, creating filelist.txt...") filelist = io.open("filelist.txt", "w") dumpDirectory(filelist, System.currentDirectory()) print("Send the filelist.txt to the Lua Player maintainer for bugfixing.") filelist:close() end
-- Hook dictating command permissions local Get = require(workspace.Get) local G = Get "Common.Globals" -- Can this owner command be run? function IsOwner(context) return G.IsOwner(context.Executor) end -- Can this admin command be run? function IsAdmin(context) return G.IsAdmin(context.Executor) end -- Can this debug command be run? function CanDebug(_) return IsOwner() end return function(registry) registry:RegisterHook("BeforeRun", function(context) -- Owner commands if context.Group == "Owner" and not IsOwner(context) then return "Only the owner can run this command" end -- Admin commands if context.Group == "DefaultAdmin" and not IsAdmin(context) then return "You do not have permission to run this command" end -- Debug commands if context.Group == "DefaultDebug" and not CanDebug(context) then return "Debug commands cannot currently be run" end end) end
local load = loadstring and loadstring or load local dump = string.dump local mtstates = require("mtstates") local mts = mtstates print("test01 started") print("mtstates._VERSION", mts._VERSION) print("mtstates._INFO", mts._INFO) local function line() return debug.getinfo(2).currentline end local function PRINT(s) print(s.." ("..debug.getinfo(2).currentline..")") end local function msgh(err) return debug.traceback(err, 2) end local function pcall(f, ...) return xpcall(f, msgh, ...) end PRINT("==================================================================================") do local _, err = pcall(function() mts.newstate("foo") end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match("bad argument #1")) local _, err = pcall(function() mts.newstate("foo", [[xxx]]) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match("bad argument #2")) local _, err = pcall(function() mts.newstate("foo", true, [[xxx]]) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match("bad argument #3")) local _, err = pcall(function() mts.newstate("foo", true, [[xxx]], "foo2") end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match("bad argument #3")) local _, err = pcall(function() mts.newstate("foo", true, 2, "foo2") end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match("bad argument #3")) local _, err = pcall(function() mts.newstate("foo", true, mts.newstate, "foo2") end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match("bad argument #3")) end PRINT("==================================================================================") do local function f1() local a = 1 local b = 2 return function(x) return x + 1 end end local s1 = mts.newstate("s1", f1) print(s1, s1:id()) assert(s1:name() == "s1") assert(s1:call(10) == 11) s1 = nil collectgarbage() local s1 = mts.newstate("s1", function() local x = 1 local y = 2 return function(x) return x + 2 end end) local s2 = mts.newstate("s2", [[return function() return x + 1 end]]) assert(s2:isowner()) local s3, x, y = mts.newstate([[return function(x) return x + 2 end, 4, 5]]) assert(s3:isowner()) assert(x == 4 and y == 5) print(s1, s1:id()) print(s2, s2:id()) local _, err = pcall(function() s2:call("fooarg", 2, {}) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match("bad argument #3")) local _, err = pcall(function() s2:call() end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mts.error.invoking_state)) print(s3, s3:id()) assert(s1:name() == "s1") assert(s2:name() == "s2") assert(s3:name() == nil) local s1a = mts.state("s1") print(s1a) assert(s1a:id() == s1:id()) assert(s1a:name() == s1:name()) assert(not s1a:isowner()) local s2a = mts.state(s2:id()) print(s2a) assert(s2a:id() == s2:id()) assert(s2a:name() == s2:name()) local _, err = pcall(function() mts.state("foo") end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mts.error.unknown_object)) local s1a = mts.newstate("s1", f1) local _, err = pcall(function() mts.state("s1") end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mts.error.ambiguous_name)) end PRINT("==================================================================================") do local s = mts.newstate("return function(x) return x + 3 end") assert(s:call(10) == 13) assert(s:name() == nil) local n = "foo"..line() local s = mts.newstate(n, "return function(x) return x + 4 end") assert(s:call(10) == 14) assert(s:name() == n) local s = mts.newstate(nil, "return function(x) return x + 5 end") assert(s:call(10) == 15) assert(s:name() == nil) end PRINT("==================================================================================") do local s = mts.newstate(function() local function m2(x) error("error xxx") end local function m(x) return m2(x) + 5 end return function(x) return m(x) + 3 end end) local function a2() return s:call(42) end local function a() return a2() + 1 end local _, err = pcall(a) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mts.error.invoking_state)) end PRINT("==================================================================================") do local function invokeNew() mts.newstate(function(x) local function m2(x) error("error yyy") end local function m(x) return m2(x) + 5 end return m(x) + 3 end) end local _, err = pcall(function() invokeNew() end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mts.error.invoking_state)) end PRINT("==================================================================================") do local x1 = 0 local _, err = pcall(function () mts.newstate(function() return x1 end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") end do local x2 = 0 local _, err = pcall(function () mts.newstate(function() print(x2) return x2 end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") end PRINT("==================================================================================") do local _, err = pcall(function() mts.newstate(function() local e = {} error(e) end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mts.error.invoking_state)) end PRINT("==================================================================================") do local _, err = pcall(function() mts.newstate(function() local e = {} local s = tostring(e) setmetatable(e, { __tostring = function(self) return "XXXX {"..s.."}" end}) error(e) end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mts.error.invoking_state)) end PRINT("==================================================================================") do GLOBAL_VAR = 1 local _, err = pcall(function() mts.newstate(function() local x = GLOBAL_VAR + 1 return function() return x end end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mts.error.invoking_state)) end PRINT("==================================================================================") do local function testcase() local _, err = pcall(function() mts.newstate(function() return function() end, "", {} end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mtstates.error.state_result)) end testcase() end PRINT("==================================================================================") do local _, err = pcall(function() mts.newstate(function() return require"mtstates".newstate(function() return {} end) end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mtstates.error.invoking_state)) assert(err:match(mtstates.error.state_result)) end PRINT("==================================================================================") do local _, err = pcall(function() mts.newstate(function() return 1 end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert( err:match(mtstates.error.state_result)) assert(not err:match(mtstates.error.invoking_state)) end PRINT("==================================================================================") do local s = mts.newstate(function() return function() end, "a", "b" end) local _, err = pcall(function() s:call(1, 2, function() end) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") end PRINT("==================================================================================") do local s, a, b = mts.newstate(function() local mts = require"mtstates" local s = mts.newstate(function() return (function() end) end) return function() return s:id(), s; end, "a", "b" end) assert(a == "a" and b == "b") local _, err = pcall(function() s:call(1) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mtstates.error.state_result)) end PRINT("==================================================================================") do local s = mts.newstate(function() return function() return 42; end end) assert(s:call() == 42) s:close() local _, err = pcall(function() s:call() end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mtstates.error.object_closed)) end PRINT("==================================================================================") do local s = mts.newstate(function() assert(type(table) == "table") assert(type(debug) == "table") return function() end end) assert(s:name() == nil) local s = mts.newstate(true, function() assert(type(table) == "table") assert(type(debug) == "table") return function() end end) assert(s:name() == nil) local n = "foo"..line() local s = mts.newstate(n, true, function() assert(type(table) == "table") assert(type(string) == "table") assert(type(debug) == "table") return function() end end) assert(s:name() == n) local n = "foo"..line() local s = mts.newstate(n, false, function() assert(type(package) == "table") assert(type(string) == "nil") assert(type(debug) == "nil") return function() end end) assert(s:name() == n) local s = mts.newstate(nil, false, function() assert(type(package) == "table") assert(type(string) == "nil") assert(type(debug) == "nil") return function() end end) assert(s:name() == nil) local s = mts.newstate(false, function() assert(type(package) == "table") assert(type(table) == "nil") assert(type(string) == "nil") table = require("table") assert("a b" == table.concat({"a", "b"}, " ")) string = require("string") assert(string.len("123") == 3) assert(debug == nil) debug = require("debug") assert(type(debug.traceback) == "function") if _VERSION == "Lua 5.2" then assert(bit32 == nil) local bit32 = require("bit32") assert(type(bit32.bnot) == "function") end if _VERSION ~= "Lua 5.1" then assert(coroutine == nil) coroutine = require("coroutine") end assert(type(coroutine) == "table") assert(type(coroutine.yield) == "function") assert(type(require("mtstates").newstate) == "function") return function() end end) assert(s:name() == nil) end PRINT("==================================================================================") do local s = mts.newstate(function() return function(arg) return arg + 5 end end) local _, err = pcall(function() s:interrupt("") end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") s:interrupt(nil) local _, err = pcall(function() s:call(100) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(err:match(mtstates.error.invoking_state)) assert(err:match(mtstates.error.interrupted)) assert(s:call(200) == 205) s:interrupt() local _, err = pcall(function() s:call(100) end) assert(err:match(mtstates.error.invoking_state)) assert(err:match(mtstates.error.interrupted)) assert(s:call(300) == 305) s:interrupt(true) for i = 1, 4 do local _, err = pcall(function() s:call(100) end) print("-- Expected error:", err) assert(err:match(mtstates.error.invoking_state)) assert(err:match(mtstates.error.interrupted)) end s:interrupt(false) assert(s:call(400) == 405) end PRINT("==================================================================================") do local ok, err = pcall(function() mtstates.newstate(mtstates.newstate) end) print("-------------------------------------") PRINT("-- Expected error:") print(err) print("-------------------------------------") assert(not ok and err:match("lua function expected")) end PRINT("==================================================================================") do local s = mtstates.newstate(function() local x = 0 return function(y) x = x + 1 return x + (y and y or 0), y end end) assert(s:call() == 1) local ok , rslt1, rslt2 = s:tcall(0) assert(ok and rslt1 == 2 and rslt2 == nil) print(ok, rslt1, rslt2) local ok , rslt1, rslt2 = s:tcall(1, 100) print(ok, rslt1, rslt2) assert(ok and rslt1 == 103 and rslt2 == 100) end PRINT("==================================================================================") do local stateSetup = function() return function(x) return 100 + x end end local _, err = pcall(function() mtstates.state("foo") end) assert(err:match(mtstates.error.unknown_object)) local s1 = mtstates.singleton("foo", stateSetup) local s2 = mtstates.singleton("foo", stateSetup) assert(s1:isowner()) assert(s2:isowner()) assert(s1:id() == s2:id()) assert(s2:call(3) == 103) local s3 = mtstates.state("foo") assert(s1:id() == s3:id()) end collectgarbage() PRINT("==================================================================================") do local s1 = mtstates.newstate("foo", "return function() return 3 end") local id1 = s1:id() assert(s1:call() == 3) local s2 = mtstates.newstate("foo", "return function() return 4 end") local id2 = s2:id() assert(s2:call() == 4) local _, err = pcall(function() mtstates.state("foo") end) assert(err:match(mtstates.error.ambiguous_name)) local _, err = pcall(function() mtstates.singleton("foo", "return function() return 4 end") end) assert(err:match(mtstates.error.ambiguous_name)) s1:close() s3 = mtstates.singleton("foo", "return function() return 5 end") assert(s3:id() == id2) assert(s3:call() == 4) s2:close() s3:close() local _, err = pcall(function() return mtstates.state("foo") end) assert(err:match(mtstates.error.unknown_object)) local _, err = pcall(function() return mtstates.state(id2) end) assert(err:match(mtstates.error.unknown_object)) local s3 = mtstates.singleton("foo", "return function() return 6 end") assert(s3:call() == 6) end PRINT("==================================================================================") print("OK.")
return { Logger = require('./logger'), TableUtils = require('./tableUtils'), Loader = require('./loader'), Process = require('./process') }
-------------------------------- -- @module Director -- @parent_module cc ---@class cc.Director local Director = {} cc.Director = Director -------------------------------- --- Pauses the running scene. --- The running scene will be _drawed_ but all scheduled timers will be paused. --- While paused, the draw rate will be 4 FPS to reduce CPU consumption. ---@return cc.Director function Director:pause() end -------------------------------- --- Sets the EventDispatcher associated with this director. --- since v3.0 --- js NA ---@param dispatcher cc.EventDispatcher ---@return cc.Director function Director:setEventDispatcher(dispatcher) end -------------------------------- --- The size in pixels of the surface. It could be different than the screen size. --- High-res devices might have a higher surface size than the screen size. --- Only available when compiled using SDK >= 4.0. --- since v0.99.4 ---@param scaleFactor number ---@return cc.Director function Director:setContentScaleFactor(scaleFactor) end -------------------------------- --- ---@return number function Director:getDeltaTime() end -------------------------------- --- Gets content scale factor. --- see Director::setContentScaleFactor() ---@return number function Director:getContentScaleFactor() end -------------------------------- --- Returns the size of the OpenGL view in pixels. ---@return size_table function Director:getWinSizeInPixels() end -------------------------------- --- Returns safe area rectangle of the OpenGL view in points. ---@return rect_table function Director:getSafeAreaRect() end -------------------------------- --- Sets the OpenGL default values. --- It will enable alpha blending, disable depth test. --- js NA ---@return cc.Director function Director:setGLDefaultValues() end -------------------------------- --- Sets the ActionManager associated with this director. --- since v2.0 ---@param actionManager cc.ActionManager ---@return cc.Director function Director:setActionManager(actionManager) end -------------------------------- --- Pops out all scenes from the stack until the root scene in the queue. --- This scene will replace the running one. --- Internally it will call `popToSceneStackLevel(1)`. ---@return cc.Director function Director:popToRootScene() end -------------------------------- --- Adds a matrix to the top of specified type of matrix stack. --- param type Matrix type. --- param mat The matrix that to be added. --- js NA ---@param type number ---@param mat mat4_table ---@return cc.Director function Director:loadMatrix(type, mat) end -------------------------------- --- This object will be visited after the main scene is visited. --- This object MUST implement the "visit" function. --- Useful to hook a notification object, like Notifications (http:github.com/manucorporat/CCNotifications) --- since v0.99.5 ---@return cc.Node function Director:getNotificationNode() end -------------------------------- --- Returns the size of the OpenGL view in points. ---@return size_table function Director:getWinSize() end -------------------------------- --- ---@return cc.TextureCache function Director:getTextureCache() end -------------------------------- --- Whether or not the replaced scene will receive the cleanup message. --- If the new scene is pushed, then the old scene won't receive the "cleanup" message. --- If the new scene replaces the old one, the it will receive the "cleanup" message. --- since v0.99.0 ---@return boolean function Director:isSendCleanupToScene() end -------------------------------- --- Returns visible origin coordinate of the OpenGL view in points. ---@return vec2_table function Director:getVisibleOrigin() end -------------------------------- --- Invoke main loop with delta time. Then `calculateDeltaTime` can just use the delta time directly.<br> -- The delta time paseed may include vsync time. See issue #17806<br> -- since 3.16 ---@param dt number ---@return cc.Director ---@overload fun(self:cc.Director):cc.Director function Director:mainLoop(dt) end -------------------------------- --- Gets Frame Rate. --- js NA ---@return number function Director:getFrameRate() end -------------------------------- --- Get seconds per frame. ---@return number function Director:getSecondsPerFrame() end -------------------------------- --- Clear all types of matrix stack, and add identity matrix to these matrix stacks. --- js NA ---@return cc.Director function Director:resetMatrixStack() end -------------------------------- --- Converts an OpenGL coordinate to a screen coordinate. --- Useful to convert node points to window points for calls such as glScissor. ---@param point vec2_table ---@return vec2_table function Director:convertToUI(point) end -------------------------------- --- Clones a specified type matrix and put it to the top of specified type of matrix stack. --- js NA ---@param type number ---@return cc.Director function Director:pushMatrix(type) end -------------------------------- --- Sets the default values based on the Configuration info. ---@return cc.Director function Director:setDefaultValues() end -------------------------------- --- ---@return boolean function Director:init() end -------------------------------- --- Sets the Scheduler associated with this director. --- since v2.0 ---@param scheduler cc.Scheduler ---@return cc.Director function Director:setScheduler(scheduler) end -------------------------------- --- Gets the top matrix of specified type of matrix stack. --- js NA ---@param type number ---@return mat4_table function Director:getMatrix(type) end -------------------------------- --- returns whether or not the Director is in a valid state ---@return boolean function Director:isValid() end -------------------------------- --- The main loop is triggered again. --- Call this function only if [stopAnimation] was called earlier. --- warning Don't call this function to start the main loop. To run the main loop call runWithScene. ---@return cc.Director function Director:startAnimation() end -------------------------------- --- Returns the Renderer associated with this director. --- since v3.0 ---@return cc.Renderer function Director:getRenderer() end -------------------------------- --- Get the GLView. --- lua NA ---@return cc.GLView function Director:getOpenGLView() end -------------------------------- --- Gets current running Scene. Director can only run one Scene at a time. ---@return cc.Scene function Director:getRunningScene() end -------------------------------- --- Sets the glViewport. ---@return cc.Director function Director:setViewport() end -------------------------------- --- Stops the animation. Nothing will be drawn. The main loop won't be triggered anymore. --- If you don't want to pause your animation call [pause] instead. ---@return cc.Director function Director:stopAnimation() end -------------------------------- --- Pops out all scenes from the stack until it reaches `level`. --- If level is 0, it will end the director. --- If level is 1, it will pop all scenes until it reaches to root scene. --- If level is <= than the current stack level, it won't do anything. ---@param level number ---@return cc.Director function Director:popToSceneStackLevel(level) end -------------------------------- --- Resumes the paused scene. --- The scheduled timers will be activated again. --- The "delta time" will be 0 (as if the game wasn't paused). ---@return cc.Director function Director:resume() end -------------------------------- --- Whether or not `_nextDeltaTimeZero` is set to 0. ---@return boolean function Director:isNextDeltaTimeZero() end -------------------------------- --- Sets clear values for the color buffers, --- value range of each element is [0.0, 1.0]. --- js NA ---@param clearColor color4f_table ---@return cc.Director function Director:setClearColor(clearColor) end -------------------------------- --- Ends the execution, releases the running scene. --- lua endToLua ---@return cc.Director function Director:endToLua() end -------------------------------- --- Sets the GLView. --- lua NA ---@param openGLView cc.GLView ---@return cc.Director function Director:setOpenGLView(openGLView) end -------------------------------- --- Converts a screen coordinate to an OpenGL coordinate. --- Useful to convert (multi) touch coordinates to the current layout (portrait or landscape). ---@param point vec2_table ---@return vec2_table function Director:convertToGL(point) end -------------------------------- --- Removes all cocos2d cached data. --- It will purge the TextureCache, SpriteFrameCache, LabelBMFont cache --- since v0.99.3 ---@return cc.Director function Director:purgeCachedData() end -------------------------------- --- How many frames were called since the director started ---@return number function Director:getTotalFrames() end -------------------------------- --- Enters the Director's main loop with the given Scene. --- Call it to run only your FIRST scene. --- Don't call it if there is already a running scene. --- It will call pushScene: and then it will call startAnimation --- js NA ---@param scene cc.Scene ---@return cc.Director function Director:runWithScene(scene) end -------------------------------- --- Sets the notification node. --- see Director::getNotificationNode() ---@param node cc.Node ---@return cc.Director function Director:setNotificationNode(node) end -------------------------------- --- Draw the scene. --- This method is called every frame. Don't call it manually. ---@return cc.Director function Director:drawScene() end -------------------------------- --- ---@return cc.Director function Director:restart() end -------------------------------- --- Pops out a scene from the stack. --- This scene will replace the running one. --- The running scene will be deleted. If there are no more scenes in the stack the execution is terminated. --- ONLY call it if there is a running scene. ---@return cc.Director function Director:popScene() end -------------------------------- --- Adds an identity matrix to the top of specified type of matrix stack. --- js NA ---@param type number ---@return cc.Director function Director:loadIdentityMatrix(type) end -------------------------------- --- Whether or not displaying the FPS on the bottom-left corner of the screen. ---@return boolean function Director:isDisplayStats() end -------------------------------- --- Sets OpenGL projection. ---@param projection number ---@return cc.Director function Director:setProjection(projection) end -------------------------------- --- Returns the Console associated with this director. --- since v3.0 --- js NA ---@return cc.Console function Director:getConsole() end -------------------------------- --- Multiplies a matrix to the top of specified type of matrix stack. --- param type Matrix type. --- param mat The matrix that to be multiplied. --- js NA ---@param type number ---@param mat mat4_table ---@return cc.Director function Director:multiplyMatrix(type, mat) end -------------------------------- --- Gets the distance between camera and near clipping frame. --- It is correct for default camera that near clipping frame is same as the screen. ---@return number function Director:getZEye() end -------------------------------- --- Sets the delta time between current frame and next frame is 0. --- This value will be used in Schedule, and will affect all functions that are using frame delta time, such as Actions. --- This value will take effect only one time. ---@param nextDeltaTimeZero boolean ---@return cc.Director function Director:setNextDeltaTimeZero(nextDeltaTimeZero) end -------------------------------- --- Pops the top matrix of the specified type of matrix stack. --- js NA ---@param type number ---@return cc.Director function Director:popMatrix(type) end -------------------------------- --- Returns visible size of the OpenGL view in points. --- The value is equal to `Director::getWinSize()` if don't invoke `GLView::setDesignResolutionSize()`. ---@return size_table function Director:getVisibleSize() end -------------------------------- --- Gets the Scheduler associated with this director. --- since v2.0 ---@return cc.Scheduler function Director:getScheduler() end -------------------------------- --- Suspends the execution of the running scene, pushing it on the stack of suspended scenes. --- The new scene will be executed. --- Try to avoid big stacks of pushed scenes to reduce memory allocation. --- ONLY call it if there is a running scene. ---@param scene cc.Scene ---@return cc.Director function Director:pushScene(scene) end -------------------------------- --- Gets the FPS value. ---@return number function Director:getAnimationInterval() end -------------------------------- --- Whether or not the Director is paused. ---@return boolean function Director:isPaused() end -------------------------------- --- Display the FPS on the bottom-left corner of the screen. ---@param displayStats boolean ---@return cc.Director function Director:setDisplayStats(displayStats) end -------------------------------- --- Gets the EventDispatcher associated with this director. --- since v3.0 --- js NA ---@return cc.EventDispatcher function Director:getEventDispatcher() end -------------------------------- --- Replaces the running scene with a new one. The running scene is terminated. --- ONLY call it if there is a running scene. --- js NA ---@param scene cc.Scene ---@return cc.Director function Director:replaceScene(scene) end -------------------------------- --- Sets the FPS value. FPS = 1/interval. ---@param interval number ---@return cc.Director function Director:setAnimationInterval(interval) end -------------------------------- --- Gets the ActionManager associated with this director. --- since v2.0 ---@return cc.ActionManager function Director:getActionManager() end -------------------------------- --- Returns a shared instance of the director. --- js _getInstance ---@return cc.Director function Director:getInstance() end return nil
-- Inject new raw definitions into the world --[====[ devel/inject-raws ================= WARNING: THIS SCRIPT CAN PERMANENLY DAMAGE YOUR SAVE. This script attempts to inject new raw objects into your world. If the injected references do not match the actual edited raws, your save will refuse to load, or load but crash. This script can handle reaction, item and building definitions. The savegame contains a list of the relevant definition tokens in the right order, but all details are read from raws every time. This allows just adding stub definitions, and simply saving and reloading the game. This is useful enough for modders and some users to justify the danger. Usage example:: devel/inject-raws trapcomp ITEM_TRAPCOMP_STEAM_PISTON workshop STEAM_ENGINE MAGMA_STEAM_ENGINE reaction STOKE_BOILER ]====] local utils = require 'utils' local raws = df.global.world.raws print[[ WARNING: THIS SCRIPT CAN PERMANENLY DAMAGE YOUR SAVE. This script attempts to inject new raw objects into your world. If the injected references do not match the actual edited raws, your save will refuse to load, or load but crash. ]] if not utils.prompt_yes_no('Did you make a backup?') then qerror('Not backed up.') end df.global.pause_state = true local changed = false function inject_reaction(name) for _,v in ipairs(raws.reactions) do if v.code == name then print('Reaction '..name..' already exists.') return end end print('Injecting reaction '..name) changed = true raws.reactions:insert('#', { new = true, code = name, name = 'Dummy reaction '..name, index = #raws.reactions, }) end local building_types = { workshop = { df.building_def_workshopst, raws.buildings.workshops }, furnace = { df.building_def_furnacest, raws.buildings.furnaces }, } function inject_building(btype, name) for _,v in ipairs(raws.buildings.all) do if v.code == name then print('Building '..name..' already exists.') return end end print('Injecting building '..name) changed = true local typeinfo = building_types[btype] local id = raws.buildings.next_id raws.buildings.next_id = id+1 raws.buildings.all:insert('#', { new = typeinfo[1], code = name, name = 'Dummy '..btype..' '..name, id = id, }) typeinfo[2]:insert('#', raws.buildings.all[#raws.buildings.all-1]) end local itemdefs = raws.itemdefs local item_types = { weapon = { df.itemdef_weaponst, itemdefs.weapons, 'weapon_type' }, trainweapon = { df.itemdef_weaponst, itemdefs.weapons, 'training_weapon_type' }, pick = { df.itemdef_weaponst, itemdefs.weapons, 'digger_type' }, trapcomp = { df.itemdef_trapcompst, itemdefs.trapcomps, 'trapcomp_type' }, toy = { df.itemdef_toyst, itemdefs.toys, 'toy_type' }, tool = { df.itemdef_toolst, itemdefs.tools, 'tool_type' }, instrument = { df.itemdef_instrumentst, itemdefs.instruments, 'instrument_type' }, armor = { df.itemdef_armorst, itemdefs.armor, 'armor_type' }, ammo = { df.itemdef_ammost, itemdefs.ammo, 'ammo_type' }, siegeammo = { df.itemdef_siegeammost, itemdefs.siege_ammo, 'siegeammo_type' }, gloves = { df.itemdef_glovest, itemdefs.gloves, 'gloves_type' }, shoes = { df.itemdef_shoest, itemdefs.shoes, 'shoes_type' }, shield = { df.itemdef_shieldst, itemdefs.shields, 'shield_type' }, helm = { df.itemdef_helmst, itemdefs.helms, 'helm_type' }, pants = { df.itemdef_pantsst, itemdefs.pants, 'pants_type' }, food = { df.itemdef_foodst, itemdefs.food }, } function add_to_civ(entity, bvec, id) for _,v in ipairs(entity.resources[bvec]) do if v == id then return end end entity.resources[bvec]:insert('#', id) end function add_to_dwarf_civs(btype, id) local typeinfo = item_types[btype] if not typeinfo[3] then print('Not adding to civs.') end for _,entity in ipairs(df.global.world.entities.all) do if entity.race == df.global.ui.race_id then add_to_civ(entity, typeinfo[3], id) end end end function inject_item(btype, name) for _,v in ipairs(itemdefs.all) do if v.id == name then print('Itemdef '..name..' already exists.') return end end print('Injecting item '..name) changed = true local typeinfo = item_types[btype] local vec = typeinfo[2] local id = #vec vec:insert('#', { new = typeinfo[1], id = name, subtype = id, name = name, name_plural = name, }) itemdefs.all:insert('#', vec[id]) add_to_dwarf_civs(btype, id) end local args = {...} local mode = nil local ops = {} for _,kv in ipairs(args) do if mode and string.match(kv, '^[%u_ ]+$') then table.insert(ops, curry(mode, kv)) elseif kv == 'reaction' then mode = inject_reaction elseif building_types[kv] then mode = curry(inject_building, kv) elseif item_types[kv] then mode = curry(inject_item, kv) else qerror('Invalid option: '..kv) end end if #ops > 0 then print('') for _,v in ipairs(ops) do v() end end if changed then print('\nNow without unpausing save and reload the game to re-read raws.') else print('\nNo changes made.') end
local _, CLM = ... local L = {} -- For Lazy creating localization during runtime throug CLM.L[string] setmetatable(L, { __index = function (table, key) return tostring(key) end }) CLM.L = L
AuctionatorTabDisplayModes = { Auctionator = { "AuctionatorConfigFrame" }, ShoppingLists = { "AuctionatorShoppingListFrame" }, Undercutting = { "AuctionatorUndercuttingFrame" } }
Unicorn = { version = 0.02, throttled = {}, } function Unicorn.throttle(key, frequency) current_ms = GetFrameTimeMilliseconds() / 1000.0 last_render_ms = Unicorn.throttled[key] or 0 if current_ms > (last_render_ms + frequency) then Unicorn.throttled[key] = current_ms return false end return true end
--[[ * The `Matter.Events` module contains methods to fire and listen to events on other objects. * * See the included usage [examples](https:--github.com/liabru/matter-js/tree/master/examples). * * @class Events ]]-- import 'matter/core/Common' Events = {} Events.__index = Events --[[ * Subscribes a callback function to the given object's `eventName`. * @method on * @param {} object * @param {string} eventNames * @param {function} callback ]]-- function Events.on(object, eventNames, callback) local names = eventNames:split(' ') local n = #names local name for i = 1, n do name = names[i] object.events = object.events or {} object.events[name] = object.events[name] or {} table.insert(object.events[name], callback) end return callback end --[[ * Removes the given event callback. If no callback, clears all callbacks in `eventNames`. If no `eventNames`, clears all events. * @method off * @param {} object * @param {string} eventNames * @param {function} callback ]]-- function Events.off(object, eventNames, callback) if (not eventNames) then object.events = {} return end -- handle Events.off(object, callback) if (type(eventNames) == 'function') then callback = eventNames eventNames = Common.keys(object.events) -- join table with space local s = '' local n = #eventNames for i=1, n do s = (s ~= '' and s .. ' ' .. eventNames[i] or eventNames[i]) end eventNames = s end local names = eventNames:split(' ') local n = #names for i = 1, n do local callbacks = object.events[names[i]] local newCallbacks = {} if (callback and callbacks) then local c = #callbacks for j = 1, c do if (callbacks[j] ~= callback) then table.insert(newCallbacks, callbacks[j]) end end end object.events[names[i]] = newCallbacks end end --[[ * Fires all the callbacks subscribed to the given object's `eventName`, in the order they subscribed, if any. * @method trigger * @param {} object * @param {string} eventNames * @param {} event ]]-- function Events.trigger(object, eventNames, event) local names, name, callbacks, eventClone local events = object.events local e = Common.keys(events) e = #e if (events and e > 0) then if (not event) then event = {} end names = eventNames:split(' ') local n = #names for i = 1, n do name = names[i] callbacks = events[name] if (callbacks) then eventClone = Common.clone(event, false) eventClone.name = name eventClone.source = object local c = #callbacks for j = 1, c do callbacks[j](object, table.unpack(eventClone)) end end end end end
-- file : config.lua local module = {} module.SSID = {} module.SSID["YOUR_SSID"] = "YOUR_WIFI_PASSWORD" module.HOST = "BROKER_IP" module.PORT = 1883 module.ID = "moisture" module.USER = "BROKER_USER" module.PASS = "BROKER_PASSWORD" module.ENDPOINT = "medusa" return module
class 'PlayerFoV' function PlayerFoV:__init() self.fov = MeshTriangle( LocalPlayer:GetPosition(), 20 ) self.fov:SetPosition( LocalPlayer:GetPosition() ) self.fov.width_multi = 3 self.last_yaw = 0 self.anti_spam = Timer() Events:Subscribe( 'PostTick', self, self.Update ) end function PlayerFoV:Update() if self.fov then local yaw = Camera:GetAngle().yaw local fyaw = math.floor(math.deg(yaw)) if fyaw ~= self.last_yaw then local angle = Angle( yaw, 0, 0 ) self.fov:UpdatePositionAndAngle( Camera:GetPosition(), angle ) local t = self.anti_spam if t:GetMilliseconds() > 250 then t:Restart() self.last_yaw = fyaw Network:Send( 'PlayerFoVUpdate', { position = Camera:GetPosition(), yaw = math.rad(fyaw) } ) end end end end LPFoV = nil Events:Subscribe( 'ModuleLoad', function() LPFoV = PlayerFoV() end )
-- Routine for NPC "Robert" in Velius' Dungeon velocity = 45 loadRoutine = function(R, W) if (W:isConditionFulfilled("boss", "BossVelius")) then R:setDisposed() return end R:setTilePosition(20,5) R:setReloadEnabled(false) R:setFacingDown() R:wait(4000) R:goToTile(19,5) R:setFacingUp() R:wait(1000) R:goToTile(20,5) R:setFacingLeft() R:wait(1400) R:goToTile(21,5) R:setFacingUp() R:wait(1400) R:goToTile(20,5) end
local tbug = SYSTEMS:GetSystem("merTorchbug") local cm = CALLBACK_MANAGER local abs = math.abs local floor = math.floor local strmatch = string.match local tonumber = tonumber local defaults = { interfaceColors = { tabWindowBackground = "hsla(60, 10, 20, 0.5)", tabWindowPanelBackground = "rgba(0, 0, 0, 0.6)", tabWindowTitleBackground_TOPLEFT = "rgba(0, 0, 0, 0.3)", tabWindowTitleBackground_TOPRIGHT = "rgba(0, 0, 0, 0.2)", tabWindowTitleBackground_BOTTOMLEFT = "rgba(0, 0, 0, 0.6)", tabWindowTitleBackground_BOTTOMRIGHT = "rgba(0, 0, 0, 0.5)", }, typeColors = { ["nil"] = "hsl(120, 50, 70)", ["boolean"] = "hsl(120, 50, 70)", ["event"] = "hsl(60, 90, 70)", ["number"] = "hsl(120, 50, 70)", ["string"] = "hsl(30, 90, 70)", ["function"] = "hsl(270, 90, 80)", ["table"] = "hsl(210, 90, 75)", ["userdata"] = "hsl(0, 0, 75)", }, } tbug.interfaceColorChanges = ZO_CallbackObject:New() tbug.makeColorDef = {} tbug.savedVars = {} function tbug.makeColorDef.hsl(h, s, l) return tbug.makeColorDef.hsla(h, s, l, 1) end function tbug.makeColorDef.hsla(h, s, l, a) -- https://en.wikipedia.org/wiki/HSL_and_HSV -- formulas adjusted to reduce the number of calculations local h = tonumber(h) / 30 -- equals 2*H' from wiki local s = tonumber(s) / 100 local l = tonumber(l) / 100 local c = s * (0.5 - abs(l - 0.5)) -- equals C/2 from wiki local r, g, b if h < 2 then r = l + c g = l + c * (h - 1) b = l - c elseif h < 4 then r = l + c * (3 - h) g = l + c b = l - c elseif h < 6 then r = l - c g = l + c b = l + c * (h - 5) elseif h < 8 then r = l - c g = l + c * (7 - h) b = l + c elseif h < 10 then r = l + c * (h - 9) g = l - c b = l + c else r = l + c g = l - c b = l + c * (11 - h) end return ZO_ColorDef:New(r, g, b, tonumber(a)) end function tbug.makeColorDef.hsv(h, s, v) return tbug.makeColorDef.hsva(h, s, v, 1) end function tbug.makeColorDef.hsva(h, s, v, a) -- https://en.wikipedia.org/wiki/HSL_and_HSV local h = tonumber(h) / 60 local s = tonumber(s) / 100 local v = tonumber(v) / 100 local r, g, b if h < 1 then r = v g = v * (1 - s * (1 - h)) b = v * (1 - s) elseif h < 2 then r = v * (1 - s * (h - 1)) g = v b = v * (1 - s) elseif h < 3 then r = v * (1 - s) g = v b = v * (1 - s * (3 - h)) elseif h < 4 then r = v * (1 - s) g = v * (1 - s * (h - 3)) b = v elseif h < 5 then r = v * (1 - s * (5 - h)) g = v * (1 - s) b = v else r = v g = v * (1 - s) b = v * (1 - s * (h - 5)) end return ZO_ColorDef:New(r, g, b, tonumber(a)) end function tbug.makeColorDef.rgb(r, g, b) local r = tonumber(r) / 255 local g = tonumber(g) / 255 local b = tonumber(b) / 255 return ZO_ColorDef:New(r, g, b) end function tbug.makeColorDef.rgba(r, g, b, a) local r = tonumber(r) / 255 local g = tonumber(g) / 255 local b = tonumber(b) / 255 return ZO_ColorDef:New(r, g, b, tonumber(a)) end local function copyDefaults(dst, src) for k, v in next, src do local dk = dst[k] local tv = type(v) if tv == "table" then if type(dk) == "table" then copyDefaults(dk, v) else dst[k] = copyDefaults({}, v) end elseif type(dk) ~= tv then dst[k] = v end end return dst end local function initColorTable(tableName, callbackName) -- this ensures that the first lookup of any not-yet-cached color -- creates a ZO_ColorDef object from saved color value and stores -- it in the cache for future lookups setmetatable(tbug.cache[tableName], { __index = function(tab, key) local val = tbug.savedVars[tableName][key] local color = tbug.parseColorDef(val) if not color then val = defaults[tableName][key] color = tbug.parseColorDef(val) or ZO_ColorDef:New() end rawset(tab, key, color) return color end, }) -- this ensures that when the user edits a color value through -- the TableInspector, a new ZO_ColorDef object will be stored -- in the cache and callbacks fired to notify listeners setmetatable(tbug.savedVars[tableName], { _tbug_gettype = function(tab, key) return "color" end, _tbug_setindex = function(tab, key, val) if val == nil then -- restore the default value instead val = defaults[tableName][key] end local color = tbug.parseColorDef(val) if not color then error("unable to parse color: " .. tostring(val), 0) end rawset(tab, key, val) rawset(tbug.cache[tableName], key, color) cm:FireCallbacks(callbackName, key, color) end, }) end do local function setControlColor(control, color) control:SetColor(color:UnpackRGBA()) end local setVertexColorFuncs = { ["_BOTTOMLEFT"] = function(control, color) control:SetVertexColors(VERTEX_POINTS_BOTTOMLEFT, color:UnpackRGBA()) end, ["_BOTTOMRIGHT"] = function(control, color) control:SetVertexColors(VERTEX_POINTS_BOTTOMRIGHT, color:UnpackRGBA()) end, ["_TOPLEFT"] = function(control, color) control:SetVertexColors(VERTEX_POINTS_TOPLEFT, color:UnpackRGBA()) end, ["_TOPRIGHT"] = function(control, color) control:SetVertexColors(VERTEX_POINTS_TOPRIGHT, color:UnpackRGBA()) end, } function tbug.confControlColor(control, childName--[[optional]], colorName) if colorName then control = control:GetNamedChild(childName) else colorName = childName end setControlColor(control, tbug.cache.interfaceColors[colorName]) tbug.interfaceColorChanges:RegisterCallback(colorName, setControlColor, control) end function tbug.confControlVertexColors(control, childName--[[optional]], colorPrefix) if colorPrefix then control = control:GetNamedChild(childName) else colorPrefix = childName end for suffix, setter in next, setVertexColorFuncs do local colorName = colorPrefix .. suffix setter(control, tbug.cache.interfaceColors[colorName]) tbug.interfaceColorChanges:RegisterCallback(colorName, setter, control) end end end function tbug.initSavedVars() if merTorchbugSavedVars then tbug.savedVars = merTorchbugSavedVars else merTorchbugSavedVars = tbug.savedVars end copyDefaults(tbug.savedVars, defaults) initColorTable("interfaceColors", "tbugChanged:interfaceColor") initColorTable("typeColors", "tbugChanged:typeColor") cm:RegisterCallback("tbugChanged:interfaceColor", function(key, color) tbug.interfaceColorChanges:FireCallbacks(key, color) end) end function tbug.parseColorDef(...) if type(...) ~= "string" then return ZO_ColorDef:New(...) end -- syntax inspired by CSS color specification -- http://www.w3.org/TR/css3-color/#numerical local scheme, args = strmatch(..., "^ *(%l+) *%((.*)%) *$") if scheme then local ctor = tbug.makeColorDef[scheme] local ok, color = pcall(ctor, zo_strsplit(",", args)) if ok then return color end else local hex = strmatch(..., "^ *#(%x+) *$") if hex then local val = tonumber(hex, 16) local a, r, g, b = 1 if #hex <= 4 then b = 17 * (val % 16) / 255 g = 17 * (floor(val / 16) % 16) / 255 r = 17 * (floor(val / 256) % 16) / 255 if #hex == 4 then a = 17 * (floor(val / 4096) % 16) / 255 end else b = (val % 256) / 255 g = (floor(val / 256) % 256) / 255 r = (floor(val / 65536) % 256) / 255 if #hex >= 8 then a = (floor(val / 2^24) % 256) / 255 end end return ZO_ColorDef:New(r, g, b, a) end end end function tbug.savedTable(...) return tbug.subtable(tbug.savedVars, ...) end
object_static_worldbuilding_vegitation_ptch_weedclump = object_static_worldbuilding_vegitation_shared_ptch_weedclump:new { } ObjectTemplates:addTemplate(object_static_worldbuilding_vegitation_ptch_weedclump, "object/static/worldbuilding/vegitation/ptch_weedclump.iff")
-- Copyright (c) 2018 Redfern, Trevor <trevorredfern@gmail.com> -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT describe("UnionFind", function() local UnionFind = require "moonpie.collections.unionfind" it("can union two objects together", function() local uf = UnionFind:new() uf:union(1, 2) uf:union(3, 4) end) it("can find the root of the tree", function() local uf = UnionFind:new() uf:union(1, 2) assert.equals(2, uf:find(1)) assert.equals(2, uf:find(2)) uf:union(2, 5) assert.equals(2, uf:find(5)) assert.equals(2, uf:find(5)) end) it("can detect whether objects are unioned together", function() local uf = UnionFind:new() uf:union(1, 2) uf:union(2, 3) assert.is_true(uf:connected(1, 3)) end) it("can work with any objects", function() local uf = UnionFind:new() uf:union("foo", "bar") uf:union("bar", "snafu") uf:union("foo", 5) assert.is_true(uf:connected("foo", 5)) assert.is_true(uf:connected(5, "snafu")) assert.is_true(uf:connected("bar", "foo")) end) it("tracks the size of the tree to ensure that it maintains the shortest tree possible", function() local uf = UnionFind:new() uf:union(2, 3) assert.equals(3, uf:find(2)) uf:union(2, 4) assert.equals(3, uf:find(4)) uf:union(7, 8) uf:union(6, 8) uf:union(9, 8) uf:union(10, 8) uf:union(8, 2) assert.equals(8, uf:find(2)) end) end)
--[[ Licensed under GNU General Public License v2 * (c) 2014, anticlockwise <http://github.com/anticlockwise> --]] local helpers = require("modules.lain.helpers") local async = require("modules.lain.asyncshell") local escape_f = require("awful.util").escape local naughty = require("naughty") local wibox = require("wibox") local io = { popen = io.popen } local os = { execute = os.execute, getenv = os.getenv } local string = { format = string.format, gmatch = string.gmatch } local setmetatable = setmetatable local moc = {} local function worker(args) local args = args or {} local timeout = args.timeout or 2 local music_dir = args.music_dir or os.getenv("HOME") .. "/Music" local cover_size = args.cover_size or 100 local default_art = args.default_art or "" local settings = args.settings or function() end local mpdcover = helpers.scripts_dir .. "mpdcover" moc.widget = wibox.widget.textbox('') moc_notification_preset = { title = "Now playing", timeout = 6 } helpers.set_map("current moc track", nil) function moc.update() -- mocp -i will produce output like: -- Artist: Travis -- Album: The Man Who -- etc. async.request("mocp -i", function(f) moc_now = { state = "N/A", file = "N/A", artist = "N/A", title = "N/A", album = "N/A", elapsed = "N/A", total = "N/A" } for line in f:lines() do for k, v in string.gmatch(line, "([%w]+):[%s](.*)$") do if k == "State" then moc_now.state = v elseif k == "File" then moc_now.file = v elseif k == "Artist" then moc_now.artist = escape_f(v) elseif k == "SongTitle" then moc_now.title = escape_f(v) elseif k == "Album" then moc_now.album = escape_f(v) elseif k == "CurrentTime" then moc_now.elapsed = escape_f(v) elseif k == "TotalTime" then moc_now.total = escape_f(v) end end end moc_notification_preset.text = string.format("%s (%s) - %s\n%s", moc_now.artist, moc_now.album, moc_now.total, moc_now.title) widget = moc.widget settings() if moc_now.state == "PLAY" then if moc_now.title ~= helpers.get_map("current moc track") then helpers.set_map("current moc track", moc_now.title) os.execute(string.format("%s %q %q %d %q", mpdcover, "", moc_now.file, cover_size, default_art)) moc.id = naughty.notify({ preset = moc_notification_preset, icon = "/tmp/mpdcover.png", replaces_id = moc.id, }).id end elseif moc_now.state ~= "PAUSE" then helpers.set_map("current moc track", nil) end end) end helpers.newtimer("moc", timeout, moc.update) return setmetatable(moc, { __index = moc.widget }) end return setmetatable(moc, { __call = function(_, ...) return worker(...) end })
require("lang.clojure").format() require("lang.clojure").lint() require("lang.clojure").lsp() require("lang.clojure").dap()
require("src.update.freezers") -- For freezers require("src.update.shields") -- For shields require("src.update.mirrors") -- For mirrors require("src.update.intakers") -- For intakers require("src.update.supgens") -- For super generators require("src.update.gens") -- For generators require("src.update.replicators") -- For generators require("src.update.molds") -- For molds require("src.update.flippers") -- For flippers require("src.update.rotators") -- For rotators require("src.update.gear") -- For gears require("src.update.redirectors") -- For redirectors require("src.update.impulsers") -- For impulsers require("src.update.repulsers") -- For repulsers require("src.update.supreps") -- For super repulsers require("src.update.drillers") -- For drillers require("src.update.advancer") -- For advancers require("src.update.pullers") -- For pullers require("src.update.movers") -- For movers require("src.update.gate") -- For movers
-- [[ Constants support in LUA ]] -- -- [[ Credits: Andrejs Cainikovs]] -- -- [[ Used as Safety measure ]] -- function CreateConstant(tbl) return setmetatable( {}, { __index = tbl, __newindex = function(t, key, value) error("attempting to change constant " .. tostring(key) .. " to " .. tostring(value), 2) end } ) end
object_tangible_wearables_cybernetic_s03_cybernetic_s03_arm_r = object_tangible_wearables_cybernetic_s03_shared_cybernetic_s03_arm_r:new { } ObjectTemplates:addTemplate(object_tangible_wearables_cybernetic_s03_cybernetic_s03_arm_r, "object/tangible/wearables/cybernetic/s03/cybernetic_s03_arm_r.iff")
--[[ Condition codes to translate OpenWeather weather info to Fibaro weather icon Read more https://openweathermap.org/weather-conditions#How-to-get-icon-URL @author ikubicki ]] class 'ConditionCodes' function ConditionCodes:get(id, icon) local key = id .. string.sub(icon, 3) return ConditionCodes.codes[key] end ConditionCodes.codes = { -- clear ["800d"] = 32, ["800n"] = 31, -- clouds ["801d"] = 28, ["802d"] = 28, ["803d"] = 26, ["804d"] = 26, ["801n"] = 27, ["802n"] = 27, ["803n"] = 26, ["804n"] = 26, -- atmosphere ["701d"] = 20, ["711d"] = 20, ["721d"] = 20, ["731d"] = 2, ["741d"] = 20, ["751d"] = 24, ["761d"] = 24, ["762d"] = 24, ["771d"] = 24, ["781d"] = 1, ["701n"] = 20, ["711n"] = 20, ["721n"] = 20, ["731n"] = 2, ["741n"] = 20, ["751n"] = 24, ["761n"] = 24, ["762n"] = 24, ["771n"] = 24, ["781n"] = 1, -- snow ["600d"] = 41,["601d"] = 16, ["602d"] = 13, ["611d"] = 7, ["612d"] = 7, ["613d"] = 7, ["615d"] = 7, ["616d"] = 7, ["620d"] = 7, ["621d"] = 7, ["622d"] = 7, ["600n"] = 41, ["601n"] = 16, ["602n"] = 13, ["611n"] = 7, ["612n"] = 7, ["613n"] = 7, ["615n"] = 7, ["616n"] = 7, ["620n"] = 7, ["621n"] = 7, ["622n"] = 7, -- rain ["500d"] = 11, ["501d"] = 11, ["502d"] = 11, ["503d"] = 11, ["504d"] = 11, ["511d"] = 7, ["520d"] = 11, ["521d"] = 11, ["522d"] = 11, ["531d"] = 11, ["500n"] = 11, ["501n"] = 11, ["502n"] = 11, ["503n"] = 11, ["504n"] = 11, ["511n"] = 7, ["520n"] = 11, ["521n"] = 11, ["522n"] = 11, ["531n"] = 11, -- drizzle ["300d"] = 9, ["301d"] = 9, ["302d"] = 9, ["310d"] = 9, ["311d"] = 9, ["312d"] = 9, ["313d"] = 9, ["314d"] = 9, ["321d"] = 9, ["300n"] = 9, ["301n"] = 9, ["302n"] = 9, ["310n"] = 9, ["311n"] = 9, ["312n"] = 9, ["313n"] = 9, ["314n"] = 9, ["321n"] = 9, -- thunderstorm ["200d"] = 6, ["201d"] = 6, ["202d"] = 6, ["210d"] = 4, ["211d"] = 4, ["212d"] = 37, ["221d"] = 37, ["230d"] = 35, ["231d"] = 35, ["232d"] = 35, ["200n"] = 6, ["201n"] = 6, ["202n"] = 6, ["210n"] = 4, ["211n"] = 4, ["212n"] = 37, ["221n"] = 37, ["230n"] = 35, ["231n"] = 35, ["232n"] = 35, }
local S = df_underworld_items.S local glowstone_def = { _doc_items_longdesc = df_underworld_items.doc.glowstone_desc, _doc_items_usagehelp = df_underworld_items.doc.glowstone_usage, light_source = minetest.LIGHT_MAX, description = S("Lightseam"), tiles = { { name = "dfcaverns_glowstone_anim.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 8, }, }, }, is_ground_content = false, groups = {cracky=3}, sounds = default.node_sound_glass_defaults(), paramtype = "light", drawtype = "glasslike", drop = "", sunlight_propagates = true, } if minetest.get_modpath("tnt") then glowstone_def.on_dig = function(pos, node, digger) tnt.boom(pos, {radius=3}) end end minetest.register_node("df_underworld_items:glowstone", glowstone_def)
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('StoryBit', { ActivationEffects = {}, Category = "ColdWaveStart", Delay = 60000, Effects = {}, Enables = { "BadMoxie_Tech", }, Image = "UI/Messages/Events/18_moxie.tga", InheritsObject = false, Prerequisites = { PlaceObj('PickFromLabel', { 'Label', "MOXIE", 'Conditions', {}, }), }, ScriptDone = true, Text = T(940021000465, --[[StoryBit BadMOXIE_ColdWave Text]] "MOXIEs use a form of electrolysis to produce Oxygen from carbon dioxide. However, the process requires relatively high (for Mars) temperatures.\n\nIt looks like a failure in one of our MOXIE units has highlighted a design flaw in the technology. We have to find a solution that works for all MOXIEs."), TextReadyForValidation = true, TextsDone = true, Trigger = "ColdWave", VoicedText = T(728411744190, --[[voice:narrator]] "As the frost outside settles, an urgent maintenance report flashes on your terminal. There’s a problem with a MOXIE unit."), group = "Disasters", id = "BadMOXIE_ColdWave", PlaceObj('StoryBitReply', { 'Text', T(899944302275, --[[StoryBit BadMOXIE_ColdWave Text]] "Install additional heaters."), 'OutcomeText', "custom", 'CustomOutcomeText', T(637039960544, --[[StoryBit BadMOXIE_ColdWave CustomOutcomeText]] "MOXIEs power consumption increased by <power(increased_consumption)>"), }), PlaceObj('StoryBitParamResource', { 'Name', "increased_consumption", 'Value', 5000, 'Resource', "power", }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Effects', { PlaceObj('ModifyLabel', { 'Label', "MOXIE", 'Prop', "electricity_consumption", 'Amount', "<increased_consumption>", 'ModifyId', "BadMoxie_ColdWave", }), }, }), PlaceObj('StoryBitReply', { 'Text', T(879385110893, --[[StoryBit BadMOXIE_ColdWave Text]] "Improve the insulation of the MOXIEs."), 'OutcomeText', "custom", 'CustomOutcomeText', T(929769322749, --[[StoryBit BadMOXIE_ColdWave CustomOutcomeText]] "<polymers(insulation)> extra construction cost for MOXIEs; existing MOXIEs will request <polymers(insulation)> maintenance"), 'Comment', "some effects don't have a param option", }), PlaceObj('StoryBitParamResource', { 'Name', "insulation", 'Value', 5000, 'Resource', "polymers", }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Effects', { PlaceObj('AddBuildingExtraCost', { 'BuildingClass', "MOXIE", 'Resource', "Polymers", 'Amount', 5000, }), PlaceObj('ForEachExecuteEffects', { 'Label', "MOXIE", 'Filters', {}, 'Effects', { PlaceObj('SetBuildingBreakdownState', { 'RepairResource', "Polymers", 'RepairAmount', "<insulation>", }), }, }), }, }), PlaceObj('StoryBitReply', { 'Text', T(570399353506, --[[StoryBit BadMOXIE_ColdWave Text]] "Leave the MOXIEs as they are."), 'OutcomeText', "custom", 'CustomOutcomeText', T(982145860164, --[[StoryBit BadMOXIE_ColdWave CustomOutcomeText]] "MOXIEs will require maintenance more often"), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Effects', { PlaceObj('ModifyLabel', { 'Label', "MOXIE", 'Prop', "maintenance_threshold_base", 'Percent', -25, 'ModifyId', "BadMoxie_ColdWave", }), }, }), })
-- DRV8825 driver -- Provides gpio init, enable, disable, direction, and pulse counting for steps -- The DVR8825 runs over normal GPIO local m = {} m.pinStep = 4 m.pinDir = 0 -- it is 0 cuz that is bootstrap pin which inconsequential on direction pin m.pinSleep = 16 -- Loopback pulse in from m.pinStep -- You need to connect a physical wire from m.pinStep 4 to pin 36 for step counting to work m.pinPulseIn = 36 -- 36 (sens_vp) -- Microsteps pins in case you want to manage microsteps from gpio m.pinM0 = 17 m.pinM1 = 18 m.pinM2 = 19 -- Min/max steps allowed 32768 + or - is allowed m.stepMax = 32000 m.stepMin = -32000 m.isDebug = false -- Pulse counter object m.pcnt = nil m._isInitted = false m._onLimit = nil -- Pass in a table of settings -- @param tbl.initStepDirEnPins Defaults to false -- @param tbl.pinStep Defaults to 4 -- @param tbl.pinDir Defaults to 0 -- @param tbl.pinEn Defaults to 16 -- @param tbl.isDebug Defaults to false. Turn on for extra logging. -- @param tbl.onLimit Callback when stepMax or stepMin is hit -- @param tbl.stepLimitMax Defaults to 32000 -- @param tbl.stepLimitMin Defaults to -32000 -- Example motor.init({initStepDirEnPins=true, }) function m.init(tbl) if m._isInitted then print("DRV8825 already initted") return end m._isInitted = true if tbl.pinStep ~= nil then m.pinStep = tbl.pinStep end if tbl.pinDir ~= nil then m.pinDir = tbl.pinDir end if tbl.pinEn ~= nil then m.pinSleep = tbl.pinEn end if tbl.isDebug == true then m.isDebug = true end if tbl.onLimit ~= nil then m._onLimit = tbl.onLimit end if tbl.stepLimitMax ~= nil then m.stepMax = tbl.stepLimitMax end if tbl.stepLimitMin ~= nil then m.stepMin = tbl.stepLimitMin end -- defaults to false if tbl.initStepDirEnPins == true then gpio.config({ gpio= { m.pinStep, m.pinSleep, m.pinDir, m.pinM0, m.pinM1, m.pinM2 }, dir=gpio.IN_OUT, }) gpio.write(m.pinStep, 0) m.disable() m.dirFwd() -- for full steps, all low -- for max micro-stepping, all high gpio.write(m.pinM0, 0) gpio.write(m.pinM1, 0) gpio.write(m.pinM2, 0) end -- Start counting pulses on the loopback signal m.initPulseCtr() print("initted pulse ctr") end function m.initPulseCtr() -- Setup the pulse counter to watch the steps -- Adhere to the direction pin as well to know automatically fwd/rev -- so our steps are accurate to where the motor is m.pcnt = pulsecnt.create(0, m.onPulseCnt, false) m.pcnt:chan0Config( m.pinPulseIn, -- 36 (sens_vp), 39 (sens_vn), m.pinStep, m.pinPulseIn, --pinPulseIn --pulse_gpio_num m.pinDir, --ctrl_gpio_num If no control is desired specify PCNT_PIN_NOT_USED pulsecnt.PCNT_COUNT_INC, --pos_mode PCNT positive edge count mode pulsecnt.PCNT_COUNT_DIS, --neg_mode PCNT negative edge count mode pulsecnt.PCNT_MODE_REVERSE, --lctrl_mode PCNT_MODE_KEEP, PCNT_MODE_REVERSE, PCNT_MODE_DISABLE pulsecnt.PCNT_MODE_KEEP, --hctrl_mode PCNT_MODE_KEEP, PCNT_MODE_REVERSE, PCNT_MODE_DISABLE -32768, --counter_l_lim 32767 --counter_h_lim ) m.pcnt:setThres(m.stepMin, m.stepMax) m.pcnt:clear() end function m.onPulseCnt(unit, isThr0, isThr1, isLLim, isHLim, isZero) print("Got pulse counter.") print("unit:", unit, "isThr0:", isThr0, "isThr1:", isThr1) print("isLLim:", isLLim, "isHLim:", isHLim, "isZero:", isZero) if isThr0 or isThr1 then m.disable() -- if callback from user, then call it if m.onLimit ~= nil then m.onLimit(isThr0, isThr1) end -- m.pause() -- m.stop() if isThr0 then print("Hit endstop in negative direction") else print("Hit endstop in positive direction") end end end m.DIR_FWD = 1 m.DIR_REV = 0 m._dir = nil function m.setDir(dir) if dir == m.DIR_FWD then if m._dir == m.DIR_FWD then -- already set. ignore. if m.isDebug then print("Dir fwd already set. Ignoring.") end return end gpio.write(m.pinDir,1) m._dir = m.DIR_FWD if m.isDebug then print("Set dir fwd") end else if m._dir == m.DIR_REV then -- already set. ignore. if m.isDebug then print("Dir rev already set. Ignoring.") end return end gpio.write(m.pinDir,0) m._dir = m.DIR_REV if m.isDebug then print("Set dir rev") end end end function m.dirFwd() m.setDir(m.DIR_FWD) end function m.dirRev() m.setDir(m.DIR_REV) end function m.dirToggle() if m._dir == m.DIR_FWD then m.dirRev() else m.dirFwd() end end function m.disable() -- drv8825 low makes sleep / high make active gpio.write(m.pinSleep, 0) if m.isDebug then print("Sleeping motor (disable)") end end function m.enable() -- drv8825 low makes sleep / high make active gpio.write(m.pinSleep, 1) if m.isDebug then print("Waking motor (enable)") end end return m
local Cell = require "src.cell" local Piece = require "src.piece" local kalis = require "lib.kalis" local class = require "lib.middleclass" --- @class Board --- @field new fun(self: Board, game: Game, width: integer, height: integer, cell_size: integer) local Board = class("Board") --- @param game Game @ The corresponding game object --- @param width integer @ The width of the board in cells --- @param height integer @ The height of the board in cells --- @param cell_size integer @ The size of a single cell on the board in pixels function Board:initialize(game, width, height, cell_size) self.game = game self.cell_size = cell_size self.width = width self.height = height self.pieces = {} self.next_piece = Piece.generate(self) -- initialise bounds self.bounds = { bottom = { coordinates = {} }, top = { coordinates = {} }, left = { coordinates = {} }, right = { coordinates = {} } } for i = 0, width - 1 do table.insert(self.bounds.bottom.coordinates, { x = i, y = height }) table.insert(self.bounds.top.coordinates, { x = i, y = -1 }) end for i = 0, height - 1 do table.insert(self.bounds.left.coordinates, { x = -1, y = i }) table.insert(self.bounds.right.coordinates, { x = width, y = i }) end -- Initialise cells for i = 0, height - 1 do self[i] = {} for j = 0, width - 1 do self[i][j] = Cell:new(j * cell_size, i * cell_size, cell_size) end end end --- Puts next_piece into the board. Generates a new random piece for next_piece. function Board:newPiece() table.insert(self.pieces, self.next_piece) self.next_piece = Piece.generate(self) end --- Returns the currently active (latest) piece --- @return Piece @ The currently active piece function Board:getActivePiece() return self.pieces[#self.pieces] end --- Returns an iterator over all cells in the board --- @return fun(t: table): number, Cell @ Iterator over all cells in the board function Board:cells() return coroutine.wrap( function() for _, row in kalis.ipairs(self) do for _, cell in kalis.ipairs(row) do coroutine.yield(cell) end end end) end --- Returns a cell found at board coordinates (`x`, `y`) --- @param x integer @ The x coordinate of the cell --- @param y integer @ The y coordinate of the cell --- @return Cell @ The found cell function Board:getCell(x, y) if not x or not y then return nil end if x < 0 or x > self.width or y < 0 or y > self.height then return nil end return self[y][x] end --- Returns a random cell --- @return Cell @ A random cell in the board function Board:getRandomCell() local random_row = self[math.random(0, #self)] return random_row[math.random(0, #random_row)] end --- Returns a cell found at pixel coordinates (`x`, `y`) --- @param x integer @ The pixel's x coordinate --- @param y integer @ The pixel's y coordinate --- @return Cell @ Cell found at pixel coordinates (`x`, `y`) function Board:pixelToCell(x, y) return self:getCell(self:pixelToBoard(x, y)) end --- Returns board coordinates for pixel coordinates (`x`, `y`) --- @param x integer @ The pixel's x coordinate --- @param y integer @ The pixel's y coordinate --- @return integer, integer @ Corresponding board coordinates function Board:pixelToBoard(x, y) if y >= self.width * self.cell_size then return nil end local board_y = math.floor(y / self.cell_size) local board_x = math.floor(x / self.cell_size) return board_x, board_y end --- Move the active piece along an axis --- @param axis AxisEnum @ The axis of the move --- @param delta integer @ The size and direction of the move function Board:move(axis, delta) local piece = self:getActivePiece() if piece then if not piece:willCollideAny(self.bounds, axis, delta) and not piece:willCollideAny(self.pieces, axis, delta) then piece:move(axis, delta) end end end --- Advances the active one step along the y axis. Generates a new piece when --- the active piece can't advance further. --- @return boolean @ true if the piece moved, false if not function Board:step() local has_moved = false local piece = self:getActivePiece() if piece then if not piece:willCollide(self.bounds.bottom, 'y', 1) and not piece:willCollideAny(self.pieces, 'y', 1) then piece:move('y', 1) has_moved = true end end if not has_moved then self:onPieceLanded() end return has_moved end --- Advances the active piece until it can't advance further function Board:skip() local has_moved = true while has_moved do has_moved = self:step() end end --- Returns all board coordinates that are currenlly occupied by a piece --- @return table[] @ List of all occupied coordinates function Board:getOccupiedCoords() local occupied_coords = {} for _, piece in ipairs(self.pieces) do for _, coord in ipairs(piece.coordinates) do table.insert(occupied_coords, coord) end end return occupied_coords end --- Called after a piece has landed. Clears and scores any filled lines, --- and generates the next piece function Board:onPieceLanded() local filled_lines = self:getFilledLines() self:clearLines(filled_lines) if (#filled_lines > 0) then self.game:onLinesCleared(#filled_lines) end self:newPiece() end --- Returns line numbers for all completely filled lines --- @return integer[] @ All line numbers that are completely filled function Board:getFilledLines() local occupied_coords = self:getOccupiedCoords() local filled_lines = {} -- Loop through all cells in all lines to check if they're occupied -- Add fully occupied lines to filled_lines for y = 0, self.height - 1 do local has_empty_cells = false for x = 0, self.width - 1 do if not kalis.contains(occupied_coords, { x = x, y = y }) then has_empty_cells = true break end end if not has_empty_cells then table.insert(filled_lines, y) end end return filled_lines end --- Clear all provided line numbers --- @param filled_lines integer[] @ A list of line numbers to be cleared function Board:clearLines(filled_lines) -- Try to remove all coordinates in finished lines from all pieces on the board -- If pieces have no coordinates left, they're cleaned for _, y in ipairs(filled_lines) do for x = 0, self.width - 1 do for i = #self.pieces, 1, -1 do local piece = self.pieces[i] piece:removeCoordinate(x, y) if #piece.coordinates == 0 then table.remove(self.pieces, i) end end end end -- Advance the remaining pieces to account for the removed lines for _, piece in ipairs(self.pieces) do for i, coord in ipairs(piece.coordinates) do for _, line_number in ipairs(filled_lines) do if coord.y < line_number then piece.coordinates[i].y = coord.y + 1 end end end end end --- Draws the board function Board:draw() for _, piece in ipairs(self.pieces) do piece:draw() end for cell in self:cells() do cell:draw() end end return Board
print("test2 starting") test2_var="foo" print(test1_var) print("test2 done")
--[[ Script that fetches the recent forum posts from forum and shows them in chat --]] local url = "https://mrgreengaming.com/forums/forum/31-multi-theft-auto.xml"; local showTopics = 4; local interval = 3 * 60 * 60 * 1000; local chatDelay = 10 * 1000; local fetchTimer, chatDelayTimer = nil; function onStart() fetchTimer = setTimer(getReadyForFetch, interval, 0); end addEventHandler ( 'onResourceStart', resourceRoot, onStart); function getReadyForFetch() chatDelayTimer = setTimer ( fetch, chatDelay, 1 ); end function delayFetch() if ( isTimer(chatDelayTimer) ) then resetTimer(chatDelayTimer); resetTimer(fetchTimer); end end addEventHandler('onPlayerChat', root, delayFetch); function fetch() fetchRemote ( url , fetchCallback ); end -- addCommandHandler('recent', fetch); function fetchCallback ( data, errno, ... ) if (errno ~= 0) then outputDebugString("fetchRemote error: " .. tostring(errno) .. ' (' .. type(errno) .. ')'); return error(); end outputChatBox("Recent MTA subforum topics on Mr.Green", root, 0, 255, 0 ); if data then local f = fileCreate'recent.xml' fileWrite(f, data) fileClose(f) local x = xmlLoadFile'recent.xml' if x then local c = xmlFindChild(x, 'channel', 0) if c then for i=1,showTopics do local item = xmlFindChild(c, 'item', i-1) if item then local title = xmlFindChild(item, 'title', 0) -- outputChatBox ( '* ' .. xmlNodeGetValue(title) .. ' (' .. author .. ')', root, 0, 255, 0 ); outputChatBox ( '* ' .. xmlNodeGetValue(title), root, 0, 255, 0 ); else break end end end xmlUnloadFile(x) end fileDelete'recent.xml' else outputDebugString'recent forum topics error' end end
-- Generated by CSharp.lua Compiler local System = System local SlipeMtaDefinitions local SlipeCollisionShapes System.import(function (out) SlipeMtaDefinitions = Slipe.MtaDefinitions SlipeCollisionShapes = Slipe.Shared.CollisionShapes end) System.namespace("Slipe.Shared.CollisionShapes", function (namespace) -- <summary> -- This is a shape that has a position and a width and a depth. -- </summary> namespace.class("CollisionRectangle", function (namespace) local __ctor1__, __ctor2__ __ctor1__ = function (this, element) SlipeCollisionShapes.CollisionShape.__ctor__(this, element) end -- <summary> -- Creates a rectangular collision shape. The position marks on the south west corner of the colshape. -- </summary> -- <param name="dimensions">The length and width</param> __ctor2__ = function (this, position, dimensions) __ctor1__(this, SlipeMtaDefinitions.MtaShared.CreateColRectangle(position.X, position.Y, dimensions.X, dimensions.Y)) end return { __inherits__ = function (out) return { out.Slipe.Shared.CollisionShapes.CollisionShape } end, __ctor__ = { __ctor1__, __ctor2__ }, __metadata__ = function (out) return { methods = { { ".ctor", 0x106, __ctor1__, out.Slipe.MtaDefinitions.MtaElement }, { ".ctor", 0x206, __ctor2__, System.Numerics.Vector2, System.Numerics.Vector2 } }, class = { 0x6 } } end } end) end)
print('core.contents.list.changeTokenLockTx'); local ContMe = ContentsMe; ChangeTokenLockTx = class(ContMe); local auObjs = {}; -- Change Token Lock Tx Objects ChangeTokenLockTx._myContentsObj = {}; -- local _myContentsObj = ChangeTokenLockTx._myContentsObj; ChangeTokenLockTx._myContentsName = 'changeTokenLockTx'; -- local _myContentsName = ChangeTokenLockTx._myContentsName; ChangeTokenLockTx._myContentsList = { 'tokenAction', 'lockTx', 'regSuperPrikey', 'regSuperPrikeyPw', 'regSuperPubkey' }; -- function ChangeTokenLockTx:init() auObjs[self] = self; ContMe.init(self); end function ChangeTokenLockTx:remove() auObjs[self] = nil; ContMe.remove(self); end
local function getData( theElement, key ) local key = tostring(key) if isElement(theElement) and (key) then return exports['[ars]anticheat-system']:callData( theElement, tostring(key) ) else return false end end local function setData( theElement, key, value, sync ) local key = tostring(key) local value = tonumber(value) or tostring(value) if isElement(theElement) and (key) and (value) then return exports['[ars]anticheat-system']:assignData( theElement, tostring(key), value, sync ) else return false end end local weathers = { { 0, "Sunny 1" }, { 1, "Sunny 2" }, { 2, "Sunny 3" }, { 3, "Sunny 4" }, { 7, "Sunny 5" }, { 40, "Sunny 6" }, { 8, "Rainy" }, { 10, "Clear" }, { 19, "Sand Storm" } } local theWeatherID = nil local theWeatherName = nil -- CHANGE WEATHER local nextWeather = nil function regulateWeather( ) if ( nextWeather ~= nil ) then theWeatherID = weathers[nextWeather][1] theWeatherName = weathers[nextWeather][2] local success = setNextWeather( ) if ( success ) then for key, value in ipairs( getElementsByType("player" ) ) do triggerClientEvent(value, "setPlayerWeather", value, theWeatherID) end end else local success = setNextWeather( ) if ( success ) then regulateWeather( ) end end end addEventHandler("onResourceStart", resourceRoot, regulateWeather) setTimer( regulateWeather, 3600000, 0 ) -- NEXT WEATHER function setNextWeather( ) nextWeather = math.random(1, 8) if ( nextWeather ) then return true else return false end end function getNextWeather( ) return nextWeather end -- CURRENT WEATHER function getCurrentWeather( clientCall ) if ( not clientCall ) then return theWeatherName, theWeatherID else triggerClientEvent(source, "setPlayerWeather", source, theWeatherID) end end addEvent("getCurrentWeather", true) addEventHandler("getCurrentWeather", root, getCurrentWeather) -- ADMIN COMMANDS function setWeather( thePlayer, commandName, givenWeatherID ) if getData(thePlayer, "loggedin") == 1 and exports['[ars]global']:isPlayerTrialModerator(thePlayer) then if (givenWeatherID) then local givenWeatherID = tonumber( givenWeatherID ) if ( givenWeatherID >= 1 and givenWeatherID <= 9 ) then theWeatherID = weathers[givenWeatherID][1] theWeatherName = weathers[givenWeatherID][2] getNextWeather( ) for key, value in ipairs( getElementsByType("player" ) ) do triggerClientEvent(value, "setPlayerWeather", value, theWeatherID) end outputChatBox("The weather was set to '".. tostring(theWeatherName) .."'.", thePlayer, 212, 156, 49) else for key, value in ipairs ( weathers ) do outputChatBox(tostring( key ) .." - ".. value[2], thePlayer, 212, 156, 49) end outputChatBox("Weather ID can only be between 1 and 9.", thePlayer, 212, 156, 49) end else outputChatBox("SYNTAX: /".. commandName .." [Weather ID]", thePlayer, 212, 156, 49) end end end addCommandHandler("setweather", setWeather, false, false)
-- All the net messages defined here util.AddNetworkString("Impound:UI:Impound") util.AddNetworkString("Impound:UI:Clamp") util.AddNetworkString("Impound:Unimpound") util.AddNetworkString("Impound:Unclamp")
local tabletools = {} -- Initialize an array of size *size* fill with *value* tabletools.init = function (size, value) local vector = {} for i = 1, size do vector[i] = value end return vector end -- Check if two arrays are equals tabletools.equal = function (v1, v2) if # v1 == # v2 then for i, v in ipairs(v1) do if v ~= v2[i] then return false end end return true else return false end end -- Slice a lua table between i1 and i2 tabletools.slice = function (values, i1, i2) local res = {} local n = #values -- default values for range i1 = i1 or 1 i2 = i2 or n if i2 < 0 then i2 = n + i2 + 1 elseif i2 > n then i2 = n end if i1 < 1 or i1 > n then return {} end local k = 1 for i = i1,i2 do res[k] = values[i] k = k + 1 end return res end -- Convert a dictionary into a flat array. For example {bla = 'foo', planet = 'mars'} -- becomes {'bla', 'foo', 'planet', 'mars'} tabletools.flat = function (tbl) local result = {} for name,value in pairs(tbl) do table.insert(result,name) table.insert(result,value) end return result end tabletools.asdict = function (tbl) local result, key = {} for i, value in ipairs(tbl) do if 2*math.floor(i/2) == i then result[key] = value else key = value end end return result end tabletools.load_code = function(code, environment) if setfenv and loadstring then local f = assert(loadstring(code)) setfenv(f, environment) return f else return assert(load(code, nil,"t",environment)) end end tabletools.json_clean = function (meta) local m, t = {} for k, v in pairs(meta) do t = type(v) -- json return null as a function while cjson as userdata. In both -- cases we don't want the values. if t ~= 'function' and t ~= 'userdata' then if t == 'table' then v = tabletools.json_clean(v) end m[k] = v end end return m end -- Return the module only when this module is not in REDIS if not (KEYS and ARGV) then return tabletools end
-- Titanium smelting local util = require("__bztitanium__.data-util"); if mods["FactorioExtended-Plus-Core"] then util.remove_raw("recipe", "titanium-ore") util.remove_raw("item", "titanium-alloy") util.remove_raw("recipe", "titanium-alloy") util.remove_raw("technology", "titanium-processing") end if mods["modmashsplinterresources"] then util.remove_raw("item", "titanium-plate") util.remove_raw("recipe", "titanium-extraction-process") end if (mods["bobrevamp"] and not mods["bobores"]) then util.remove_raw("technology", "titanium-processing") end if (not mods["pyrawores"] and not mods["bobplates"] and not mods["angelssmelting"]) then data:extend( { { type = "recipe", name = util.titanium_plate, category = "smelting", order = "d[titanium-plate]", icons = (mods["Krastorio2"] and { { icon = "__bztitanium__/graphics/icons/titanium-plate.png", icon_size = 64, icon_mipmaps = 3,}, { icon = "__bztitanium__/graphics/icons/titanium-ore.png", icon_size = 64, icon_mipmaps = 3, scale=0.25, shift= {-8, -8}}, } or nil), normal = (mods["Krastorio2"] and { enabled = false, energy_required = 16, ingredients = {{"titanium-ore", 10}}, results = {{type="item", name= util.titanium_plate, amount_min=2, amount_max=3}}, } or { enabled = false, energy_required = 8, ingredients = {{"titanium-ore", 5}}, result = util.titanium_plate }), expensive = { enabled = false, energy_required = 16, ingredients = {{"titanium-ore", 10}}, result = util.titanium_plate } }, { type = "item", name = util.titanium_plate, icon = "__bztitanium__/graphics/icons/titanium-plate.png", icon_size = 64, icon_mipmaps = 3, subgroup = "raw-material", order = "b[titanium-plate]", stack_size = util.get_stack_size(100) }, { type = "technology", name = "titanium-processing", icon_size = 256, icon_mipmaps = 4, icon = "__bztitanium__/graphics/technology/titanium-processing.png", effects = { { type = "unlock-recipe", recipe = util.titanium_plate }, mods["TheBigFurnace"] and { type = "unlock-recipe", recipe = "big-titanium-plate", } or nil, }, unit = { count = 75, ingredients = (mods["Pre0-17-60Oil"] and { {"automation-science-pack", 1}, {"logistic-science-pack", 1} } or { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1} }), time = 30 }, prerequisites = {"lubricant"}, order = "b-b" }, mods["TheBigFurnace"] and { type = "recipe", name = "big-titanium-plate", category = "big-smelting", order = "d[titanium-plate]", normal = { enabled = false, energy_required = 8.75, ingredients = {{"titanium-ore", 50}}, result = util.titanium_plate, result_count = 10, }, expensive = { enabled = false, energy_required = 16, ingredients = {{"titanium-ore", 100}}, result = util.titanium_plate, result_count = 10, } } or nil, } ) end
config = { var0 = { 'file/symlink_file' }, var1 = { '..', 'file/symlink_dir' }, var4 = { 'this_path_should_not_exist' } }
local determineOffsetX = function(self, child) if self.left ~= "fill" then return self.left elseif self.right ~= "fill" then return self:grantedWidth() - self.right - child:grantedWidth() else local spareWidth = self:grantedWidth() - child:grantedWidth() local totalookyhunks = (self.leftWeight or 1) + (self.rightWeight or 1) return spareWidth / totalookyhunks * (self.leftWeight or 1) end end local determineOffsetY = function(self, child) if self.top ~= "fill" then return self.top elseif self.bottom ~= "fill" then return self:grantedHeight() - self.bottom - child:grantedHeight() else local spareHeight = self:grantedHeight() - child:grantedHeight() local totalookyhunks = (self.topWeight or 1) + (self.bottomWeight or 1) return spareHeight / totalookyhunks * (self.topWeight or 1) end end local renderBordered = function(self) local child = self:getChild(1) if child then love.graphics.translate(determineOffsetX(self,child), determineOffsetY(self,child)) self:getChild(1):render() end end local function layout(self, children) local child = self:getChild(1) if child then local giveWidth = 0 local giveHeight = 0 local availableWidth = self:grantedWidth() if self.left ~= "fill" then availableWidth = availableWidth - self.left end if self.right ~= "fill" then availableWidth = availableWidth - self.right end if child:desiredWidth() == "fill" then giveWidth = availableWidth else giveWidth = math.min(child:desiredWidth(), availableWidth) end local availableHeight = self:grantedHeight() if self.top ~= "fill" then availableHeight = availableHeight - self.top end if self.bottom ~= "fill" then availableHeight = availableHeight - self.bottom end if child:desiredHeight() == "fill" then giveHeight = availableHeight else giveHeight = math.min(child:desiredHeight(), availableHeight) end self:getChild(1):setDimensions(giveWidth, giveHeight) self:getChild(1):layoutingPass() end end return function(looky) return { build = function(options) local base = looky:makeBaseLayout(options) -- set sizes and weights base.left = options.left or 0 base.right = options.right or 0 base.bottom = options.bottom or 0 base.top = options.top or 0 base.leftWeight = options.leftWeight or 1 base.rightWeight = options.rightWeight or 1 base.bottomWeight = options.bottomWeight or 1 base.topWeight = options.topWeight or 1 base.addListener = function(self, listener, method) table.insert(self.listeners, { target = listener, method = method }) end base.renderCustom = renderBordered base.oldAddChild = base.addChild base.offset = options.offset or { 0, 0 } base.layoutingPass = layout base.contentWidth = function(self) if self.left == "fill" or self.right == "fill" then return "fill" end if self:getChild(1) then if self:getChild(1):desiredWidth() == "fill" then return "fill" else return self:getChild(1):desiredWidth() + self.left + self.right end end return self.left + self.right end base.contentHeight = function(self) if self.top == "fill" or self.bottom == "fill" then return "fill" end if self:getChild(1) then if self:getChild(1):desiredHeight() == "fill" then return "fill" else return self:getChild(1):desiredHeight() + self.top + self.bottom end end return self.top + self.bottom end base.desiredWidth = function(self) if self.visibility == "gone" then return 0 end return self:contentWidth() end base.desiredHeight = function(self) if self.visibility == "gone" then return 0 end return self:contentHeight() end base.addChild = function(self, child) if #base:getChildren() >= 1 then error( "A borderer layout can only have 1 child." ) end base:oldAddChild(child) end base.translateCoordsToChild = function(self, child, x, y) return x - determineOffsetX(self,child), y - determineOffsetY(self,child) end base.translateCoordsFromChild = function(self, child, x, y) return x + determineOffsetX(self,child), y + determineOffsetY(self,child) end return base end, schema = looky:extendSchema("base", { width = false, height = false, left = { required = false, schemaType = "oneOf", possibilities = { { schemaType = "fromList", list = {"fill"} }, { schemaType = "number" } }}, leftWeight = { required = false, schemaType = "number" }, right = { required = false, schemaType = "oneOf", possibilities = { { schemaType = "fromList", list = {"fill"} }, { schemaType = "number" } }}, rightWeight = { required = false, schemaType = "number" }, top = { required = false, schemaType = "oneOf", possibilities = { { schemaType = "fromList", list = {"fill"} }, { schemaType = "number" } }}, topWeight = { required = false, schemaType = "number" }, bottom = { required = false, schemaType = "oneOf", possibilities = { { schemaType = "fromList", list = {"fill"} }, { schemaType = "number" } }}, bottomWeight = { required = false, schemaType = "number" } }) } end
local cjson = require("cjson") local dynamicd_build = require("core.dao.dynamicd_build_sql") local utils = require("core.utils.utils") local user_log = require("core.log.user_log") local _M = {} function _M.query_info_by_id(store,id) local flag, info= store:query({ sql = "select id,limit_count from c_host where id = ?", params ={ id } }) if info and #info >0 then return info[1] else return nil end end function _M.query_host_by_host_name(host, store) local _, results, err = store:query({ sql = "select * from c_host where host = ?", params = {host} }) if err then ngx.log(ngx.ERR, "Find data from storage when query host error:", err) return false, nil end if results and type(results) == "table" then return true, results end return false,nil end function _M.query_rate_limit_by_host(host, store) local _, results, err = store:query({ sql = "select a.id host_id,a.gateway_id,a.limit_count host_limit_count,a.limit_period host_limit_period,b.limit_count gateway_limit_count,b.limit_period gateway_limit_period,b.gateway_code from c_host a join c_gateway b on a.gateway_id=b.id where a.host=?", params = {host} }) if err then ngx.log(ngx.ERR, "Find data from storage when query rate limit by host error:", err) return false, nil end if results and type(results) == "table" then return true, results end return false,nil end function _M.query_host(req_host, store) local select_sql = [[ select a.*, b.gateway_code, b.gateway_desc, c.content_type, c.message, c.http_status from c_host a join c_gateway b on a.gateway_id = b.id ]]; local suffix = " left join c_err_resp_template c on a.id = c.biz_id and c.plugin_name = 'host'" -- 根据参数动态组装SQL local sql,params = dynamicd_build:build_and_condition_like_sql(select_sql,req_host) sql = sql .. suffix local _, results, err = store:query({ sql = sql, params = params }) if err then ngx.log(ngx.ERR, "Find data from storage when query gateway error:", err) return false, nil end if results and type(results) == "table" and #results > 0 then return true, results end return false,nil end function _M.insert_host(host_table, store) ngx.log(ngx.INFO,"insert_host...param【"..cjson.encode(host_table).."】") return store:insert({ sql = "insert into c_host(gateway_id, host, host_desc,enable, limit_count, limit_period) values(?,?,?,?,?,?)", params={ utils.trim(host_table.gateway_id), utils.trim(host_table.host), utils.trim(host_table.host_desc), utils.trim(host_table.enable or 0), utils.trim(host_table.limit_count ), utils.trim(host_table.limit_period or 1) } }) end function _M.delete_host(id, store) local res = store:delete({ sql = "delete from c_host where id = ?", params={id} }) return res; end function _M.update_host(host_table, store) ngx.log(ngx.INFO,"update_host...param【"..cjson.encode(host_table).."】") local res = store:update({ sql = "UPDATE c_host set gateway_id=?,host=?,host_desc=? where id = ?", params={ host_table.gateway_id, host_table.host, host_table.host_desc, host_table.id } }) return res; end function _M.update_host_limit_count(host_table, store) ngx.log(ngx.INFO,"update_host...param【"..cjson.encode(host_table).."】") user_log.print_log(store,user_log.module.host.. "-修改", "host_dao",host_table) local res = store:update({ sql = "UPDATE c_host set host_desc=?, limit_count=? where id = ?", params={ host_table.host_desc or "", host_table.limit_count, host_table.id } }) return res; end function _M.update_host_enable(host_table, store) ngx.log(ngx.INFO,"update_host...param【"..cjson.encode(host_table).."】") local res = store:update({ sql = "UPDATE c_host set enable=? where id = ?", params={ host_table.enable, host_table.id } }) return res; end return _M
local setmetatable = setmetatable local _M = require('apicast.policy').new('Example', '0.1') local mt = { __index = _M } local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' function dec(data) data = string.gsub(data, '[^'..b..'=]', '') return (data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(b:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string.char(c) end)) end function split(s, delimiter) result = {}; for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match); end return result; end function _M.new() print("---------------INSIDE _M.new()--------------") print("---------------END _M.new()--------------") return setmetatable({}, mt) end function _M:init() print("--------------- Inside _M:init()---------------") print("--------------- END _M:init()---------------") -- do work when nginx master process starts end function _M:init_worker() print("---------------Inside _M:init_worker()---------------") print("---------------END _M:init_worker()---------------") -- do work when nginx worker process is forked from master end function _M:rewrite(context) print("---------------Inside _M:rewrite()---------------") local headers = ngx.req.get_headers() or {} print("some stuff to print "..headers['Authorization'] ) auth_header_val = headers['Authorization'] -- print(auth_header_val .. ' and other stuff') -- basic_headers = split( auth_header_val , ' ')[2] result = {}; for match in (auth_header_val..' '):gmatch("(.-)"..' ') do table.insert(result, match); end result2 = result[2] print(result2) decoded_header = dec(result2) result3 = {}; for match1 in (decoded_header..':'):gmatch("(.-)"..':') do table.insert(result3, match1); end --userkey = split(decoded_headers,":")[1] userkey = result3[1] ngx.req.set_header('user-key', userkey) print("---------------END _M:rewrite()---------------") -- change the request before it reaches upstream end function _M:log() -- can do extra logging print("logging mt") end function _M:balancer() -- use for example require('resty.balancer.round_robin').call to do load balancing print("Hello World from _M:balancer()") end return _M
local opt = vim.opt local cmd = vim.cmd local fn = vim.fn local g = vim.g local api = vim.api cmd [[packadd packer.nvim]] require('packer').startup(function(use) use 'wbthomason/packer.nvim' -- functionalities use { 'nvim-telescope/telescope.nvim', requires = { {'nvim-lua/plenary.nvim'}, {'nvim-telescope/telescope-fzy-native.nvim'}, {'nvim-treesitter/nvim-treesitter'} } } use 'mbbill/undotree' use 'tpope/vim-fugitive' use 'tpope/vim-eunuch' use 'airblade/vim-gitgutter' use 'justinmk/vim-sneak' use 'unblevable/quick-scope' use 'tpope/vim-commentary' use 'ThePrimeagen/harpoon' -- languages stuff and lsp use 'sheerun/vim-polyglot' use 'neovim/nvim-lspconfig' use { 'hrsh7th/nvim-cmp', requires = { {'hrsh7th/cmp-nvim-lsp'}, {'hrsh7th/cmp-buffer'}, } } -- fluffy use 'EdenEast/nightfox.nvim' use 'hoob3rt/lualine.nvim' use 'folke/zen-mode.nvim' use 'szw/vim-maximizer' -- use 'gruvbox-community/gruvbox' -- -- this is used to try to fix missing LSP features -- -- of colorschemes, like LspReferenceText -- use 'folke/lsp-colors.nvim' end) -- GENERAL OPTIONS opt.exrc = true opt.mouse = 'a' opt.splitright = true opt.splitbelow = true opt.expandtab = true opt.tabstop = 2 opt.shiftwidth = 2 cmd('filetype plugin indent on') opt.number = true opt.hls = false opt.incsearch = true opt.hidden = true opt.cmdheight = 1 opt.updatetime = 500 opt.backup = false opt.swapfile = false opt.undofile = true opt.undolevels = 9999 opt.belloff = 'all' g.netrw_banner = 0 g.netrw_liststyle = 3 g.netrw_winsize = 25 -- MOVEMENT -- quickscope g.qs_highlight_on_keys = {'f', 'F', 't', 'T'} cmd([[ augroup qs_colors autocmd! autocmd ColorScheme * highlight QuickScopePrimary guifg='#458588' gui=underline ctermfg=155 cterm=underline autocmd ColorScheme * highlight QuickScopeSecondary guifg='#b16286' gui=underline ctermfg=81 cterm=underline augroup END ]]) -- sneak g['sneak#label'] = 1 g['sneak#use_ic_scs'] = 1 g['sneak#s_next'] = 1 -- FLUFFY -- opt.background = 'dark' -- g.gruvbox_contrast_dark = 'hard' -- cmd('colorscheme gruvbox') local nightfox = require('nightfox') nightfox.setup({ fox = "dayfox", -- change the colorscheme to use nordfox styles = { comments = "italic", -- change style of comments to be italic keywords = "bold", -- change style of keywords to be bold functions = "italic,bold" -- styles can be a comma separated list }, }) nightfox.load() opt.scrolloff = 8 opt.signcolumn = 'yes' opt.termguicolors = true opt.wrap = false require('lualine').setup({ options = { icons_enabled = false, theme = 'nightfox', component_separators = {'', ''}, section_separators = {'', ''}, disabled_filetypes = {} }, sections = { lualine_a = {'mode'}, lualine_b = {'branch'}, lualine_c = {'filename'}, lualine_x = {'encoding', 'fileformat', 'filetype'}, lualine_y = {'progress'}, lualine_z = {'location'} }, inactive_sections = { lualine_a = {}, lualine_b = {}, lualine_c = {'filename'}, lualine_x = {'location'}, lualine_y = {}, lualine_z = {} }, tabline = {}, extensions = {} }) opt.showmode = false local function map(mode, lhs, rhs, opts) local options = { noremap = true } if opts then options = vim.tbl_extend('force', options, opts) end api.nvim_set_keymap(mode, lhs, rhs, options) end require('telescope').setup{ defaults = { file_sorter = require('telescope.sorters').get_fzy_sorter, }, pickers = {}, extensions = { fzy_native = { override_generic_sorter = false, override_file_sorter = true, } } } -- TELESCOPE require('telescope').load_extension('fzy_native') _G.find_files_project = function() local utils = require('telescope.utils') local builtin = require('telescope.builtin') local _, res, _ = utils.get_os_command_output({ 'git', 'rev-parse', '--is-inside-work-tree' }) if res == 0 then builtin.git_files() else builtin.find_files({ hidden = true }) end end _G.cd_into_dir_project = function() local utils = require('telescope.utils') local builtin = require('telescope.builtin') cmd('cd %:p:h') local stdout, _, _ = utils.get_os_command_output({ 'git', 'rev-parse', '--git-dir' }) if next(stdout) ~= nil and stdout[1] ~= '.git' then local cleaned_path = string.gsub(stdout[1], '/.git', '') cmd('cd '.. cleaned_path) end end -- LSP local cmp = require('cmp') local nvim_lsp = require('lspconfig') cmp.setup({ mapping = { ['<C-j>'] = cmp.mapping.scroll_docs(-4), ['<C-k>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm({ select = true }), }, sources = { { name = 'nvim_lsp' }, { name = 'buffer' }, } }) -- on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) if client.name == 'tsserver' then if client.config.flags then client.config.flags.allow_incremental_sync = true end client.resolved_capabilities.document_formatting = false elseif client.name == 'efm' then client.resolved_capabilities.document_formatting = true client.resolved_capabilities.goto_definition = false end local function buf_set_keymap(...) api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) api.nvim_buf_set_option(bufnr, ...) end -- Enable completion triggered by <c-x><c-o> buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { noremap=true, silent=true } buf_set_keymap('n', 'gD', ':lua vim.lsp.buf.declaration()<CR>', opts) buf_set_keymap('n', 'gd', ':lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'gi', ':lua vim.lsp.buf.implementation()<CR>', opts) buf_set_keymap('n', 'K', ':lua vim.lsp.buf.hover()<CR>', opts) buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) -- used to highlight when the cursor doesn't move for period of time cmd([[autocmd ColorScheme * :lua require('vim.lsp.diagnostic')._define_default_signs_and_highlights()]]) cmd([[autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()]]) cmd([[autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight()]]) cmd([[autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()]]) -- format on save -- cmd([[autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()]]) -- format keymap buf_set_keymap('n', '<F9>', ':lua vim.lsp.buf.formatting_sync()<CR>', opts) -- buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) -- buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) -- buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) -- buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) -- buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) -- buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts) -- buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) -- buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts) -- buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts) -- buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts) end -- basic tsserver config nvim_lsp.tsserver.setup { on_attach = on_attach, flags = { debounce_text_changes = 150, }, capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()), } -- basic haskell ls config nvim_lsp.hls.setup{ on_attach = on_attach, } -- eslint config -- thanks to https://phelipetls.github.io/posts/configuring-eslint-to-work-with-neovim-lsp/ local function eslint_config_exists() local eslintrc = vim.fn.glob(".eslintrc*", 0, 1) if not vim.tbl_isempty(eslintrc) then return true end return false end local eslint = { lintCommand = "eslint_d -f unix --stdin --stdin-filename ${INPUT}", lintStdin = true, lintFormats = {"%f:%l:%c: %m"}, lintIgnoreExitCode = true, formatCommand = "eslint_d --fix-to-stdout --stdin --stdin-filename=${INPUT}", formatStdin = true } nvim_lsp.efm.setup { on_attach = on_attach, root_dir = function() if not eslint_config_exists() then return nil end return vim.fn.getcwd() end, settings = { languages = { javascript = {eslint}, javascriptreact = {eslint}, ["javascript.jsx"] = {eslint}, typescript = {eslint}, ["typescript.tsx"] = {eslint}, typescriptreact = {eslint} } }, filetypes = { "javascript", "javascriptreact", "javascript.jsx", "typescript", "typescript.tsx", "typescriptreact" }, flags = { debounce_text_changes = 150, }, capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()), } -- GLOBAL KEYMAPS g.mapleader = ' ' -- split to left map('n', '<leader>sl', ':vs<CR>') -- quit map('n', '<leader>wd', ':q<CR>') -- file save map('n', '<leader>fs', ':w<CR>') -- navigate left map('n', '<leader>wl', '<C-w>l') -- navidate right map('n', '<leader>wh', '<C-w>h') -- navigate up map('n', '<leader>wk', '<C-w>k') -- navidate down map('n', '<leader>wj', '<C-w>j') -- clear everything map('n', '<leader>wo', '<C-w>o') -- change to current directory of the file map('n', '<leader>cd', ':lua cd_into_dir_project()<CR>:pwd<CR>') -- maximize map('n', '<leader>wm', ':MaximizerToggle!<CR>') -- zen mode map('n', '<leader>mm', ':ZenMode<CR>') -- telescop -- find file map('n', '<leader><leader>', ':lua find_files_project()<CR>') -- search buffers map('n', '<leader>ss', [[:lua require('telescope.builtin').live_grep()<CR>]]) -- search history map('n', '<leader>sh', [[:lua require('telescope.builtin').search_history()<CR>]]) -- search buffersunder cursor map('n', '<leader>*', [[:lua require('telescope.builtin').grep_string()<CR>]]) -- open buffers map('n', '<leader>bb', [[:lua require('telescope.builtin').buffers()<CR>]]) -- open command history map('n', '<F1>', [[:lua require('telescope.builtin').command_history()<CR>]]) -- git branches map('n', '<leader>gb', [[:lua require('telescope.builtin').git_branches()<CR>]]) -- git commits map('n', '<leader>gc', [[:lua require('telescope.builtin').git_commits()<CR>]]) -- git status map('n', '<leader>gs', [[:lua require('telescope.builtin').git_status()<CR>]]) -- toggle between buffer map('n', '<leader>bl', '<C-^>') -- undo tree map('n', '<F5>', ':UndotreeToggle<CR>') -- git map('n', '<leader>gg', ':Git<CR>') -- source and packer sync map('n', '<F12>', ':so %<CR>:PackerSync<CR>') -- window tree map('n', '<leader>ff', ':Lex<CR>') -- stop sneak from hijacking , and ; map('', 'gs', '<Plug>Sneak_;') map('', 'gS', '<Plug>Sneak_,') -- harpoon map('n', '<leader>1', [[:lua require('harpoon.ui').nav_file(1)<CR>]]); map('n', '<leader>2', [[:lua require('harpoon.ui').nav_file(2)<CR>]]); map('n', '<leader>3', [[:lua require('harpoon.ui').nav_file(3)<CR>]]); map('n', '<leader>4', [[:lua require('harpoon.ui').nav_file(4)<CR>]]); map('n', '<leader>5', [[:lua require('harpoon.ui').nav_file(5)<CR>]]); map('n', '<leader>ha', [[:lua require('harpoon.mark').add_file()<CR>]]); map('n', '<leader>hh', [[:lua require('harpoon.ui').toggle_quick_menu()<CR>]]);
-- Copyright 2004-present Facebook. All Rights Reserved. -- Author: Michael Mathieu <myrhev@fb.com> require 'fb.luaunit' require 'nn' require 'fbcunn' local test_repeats = 100 local function testSequentialCriterion_run(input_size, n_classes, module, crit, targettype) module = module:clone() crit = crit:clone() local modcrit = nn.SequentialCriterion(module:clone(), crit:clone()) targettype = targettype or torch.Tensor():type() local batch_size = torch.random(100) local input = torch.rand(batch_size, input_size) local target = torch.rand(batch_size):mul(n_classes):add(1):floor():type(targettype) local output1 = modcrit:forward(input, target) local z2 = module:forward(input) local output2 = crit:forward(z2, target) assertTrue(math.abs(output1-output2) < 1e-5) local gradInput1 = modcrit:updateGradInput(input, target) local derr_do2 = crit:updateGradInput(z2, target) local gradInput2 = module:updateGradInput(input, derr_do2) assertTrue(gradInput1:clone():add(-1, gradInput2):abs():max() < 1e-5) modcrit:zeroGradParameters() module:zeroGradParameters() if crit.zeroGradParameters then crit:zeroGradParameters() end modcrit:accGradParameters(input, target) if crit.accGradParameters then crit:accGradParameters(z2, target) end module:accGradParameters(input, derr_do2) modcrit:updateParameters(1) if crit.updateParameters then crit:updateParameters(1) end module:updateParameters(1) local output1 = modcrit:forward(input, target) local z2 = module:forward(input) local output2 = crit:forward(z2, target) assertTrue(math.abs(output1-output2) < 1e-5) end local function make_HSM(n_clusters, n_class, input_size) local mapping = {} local n_class_in_cluster = {} for i = 1, n_class do local cluster = torch.random(n_clusters) n_class_in_cluster[cluster] = n_class_in_cluster[cluster] or 0 n_class_in_cluster[cluster] = n_class_in_cluster[cluster] + 1 mapping[i] = {cluster, n_class_in_cluster[cluster]} end for i = 1,n_clusters do if n_class_in_cluster[i] == nil then n_class_in_cluster[i] = 1 mapping[1+#mapping] = {i, 1} n_class = n_class + 1 end end return nn.HSM(mapping, input_size) end function testSequentialCriterion() for i = 1, test_repeats do -- try with NLL local input_size = torch.random(200) local n_classes = torch.random(200) local module = nn.Linear(input_size, n_classes) local crit = nn.ClassNLLCriterion() testSequentialCriterion_run(input_size, n_classes, module, crit) -- try with HSM local input1_size = torch.random(200) local input2_size = torch.random(200) local n_classes = torch.random(200) local module = nn.Sequential() module:add(nn.Linear(input1_size, input2_size)) module:add(nn.Threshold()) local crit = make_HSM(20, n_classes, input2_size) testSequentialCriterion_run(input1_size, n_classes, module, crit, 'torch.LongTensor') end end LuaUnit:main()
local has_telescope, telescope = pcall(require, "telescope") if not has_telescope then return end local finders = require "telescope.finders" local pickers = require "telescope.pickers" local config = require("telescope.config").values local actions = require "telescope.actions" local action_state = require "telescope.actions.state" local entry_display = require "telescope.pickers.entry_display" -- Defines the action to open the selection in the browser. local function open_in_browser(prompt_bufnr) local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) os.execute(('open "%s"'):format(selection.url)) end -- This extension will show the users GitHub stars with the repository -- description and provide an action to open it in the default browser. -- -- The information is cached using an asynchronous job which is started when -- this plugin is loaded. It is stored in a global variable -- (`_CachedGithubStars`) which contains the following two fields: -- - `stars`: List of tables each containing respository information: -- - `name`: Full repository name (user/repo) -- - `url`: GitHub url -- - `description`: Repository description -- - `max_length`: Maximum length of the `name` field from above -- -- Default action (<CR>) will open the GitHub URL in the default browser. ---@opts table ---@return nil local function github_stars(opts) opts = opts or {} if vim.tbl_isempty(_CachedGithubStars.stars) then return dm.notify("Telescope", "GitHub stars are not cached yet", 3) end local displayer = entry_display.create { separator = " ", items = { { width = _CachedGithubStars.max_length + 2 }, { remaining = true }, }, } local function make_display(entry) return displayer { entry.value, { entry.description, "Comment" }, } end pickers.new(opts, { prompt_title = "Search GitHub Stars", finder = finders.new_table { results = _CachedGithubStars.stars, entry_maker = function(entry) return { display = make_display, value = entry.name, description = entry.description, url = entry.url, ordinal = entry.name .. " " .. entry.description, } end, }, previewer = false, sorter = config.generic_sorter(opts), attach_mappings = function() actions.select_default:replace(open_in_browser) return true end, }):find() end return telescope.register_extension { exports = { github_stars = github_stars }, }
local _tl_compat; if (tonumber((_VERSION or ''):match('[%d.]*$')) or 0) < 5.3 then local p, m = true, require('compat53.module'); if p then _tl_compat = m end end; local ipairs = _tl_compat and _tl_compat.ipairs or ipairs; local table = _tl_compat and _tl_compat.table or table; local _tl_table_unpack = unpack or table.unpack local tl = require("tl") local argparse = require("argparse") local log = require("cyan.log") local config = require("cyan.config") local command = require("cyan.command") local common = require("cyan.tlcommon") local sandbox = require("cyan.sandbox") local function add_to_argparser(cmd) cmd:argument("script", "The Teal script to run."): args("+") end local function run(args, loaded_config) local env, env_err = common.init_env_from_config(loaded_config) if not env then log.err("Could not initialize Teal environment:\n", env_err) return 1 end local arg_list = args["script"] local neg_arg = {} local nargs = #arg_list local j = #arg local p = nargs local n = 1 while arg[j] do if arg[j] == arg_list[p] then p = p - 1 else neg_arg[n] = arg[j] n = n + 1 end j = j - 1 end for p2, a in ipairs(neg_arg) do arg[-p2] = a end for p2, a in ipairs(arg_list) do arg[p2 - 1] = a end n = nargs while arg[n] do arg[n] = nil n = n + 1 end local chunk, load_err = common.type_check_and_load_file(arg_list[1], env, loaded_config) if not chunk then log.err("Error loading file", load_err and "\n " .. load_err or "") return 1 end tl.loader() local box = sandbox.new(function() chunk(_tl_table_unpack(arg)) end) local ok, err = box:run(1000000000) if ok then return 0 else log.err("Error in script:\n", err) return 1 end end command.new({ name = "run", description = [[Run a Teal script.]], exec = run, argparse = add_to_argparser, })
require('unitevents.generic._table') require('stdlib.worldbounds') local onEnterMapFuncs = {} local function OnEnterMap() local enteringUnit = unit.wrap(GetFilterUnit()) for _,func in ipairs(onEnterMapFuncs) do local r,e = pcall(func, enteringUnit) if not r then print(e) end end return false end function unitevents.generic:onEnterMap(callback) table.insert(onEnterMapFuncs, callback) end ceres.addHook('main::after', function() TriggerRegisterEnterRegion(CreateTrigger(), worldbounds.REGION.handle, Filter(OnEnterMap)) end)
--!strict --[[ A symbol for representing nil values in contexts where nil is not usable. ]] local Package = script.Parent.Parent local Types = require(Package.Types) return { type = "Symbol", name = "None" } :: Types.None
LV = createColRectangle(901.67871, 601.66272, 2050, 2400) function isElementInLV(ele) if (not ele or not isElement(ele)) then return nil end if (isElementWithinColShape(ele, LV)) then return true end return false end
-- LuaTools需要PROJECT和VERSION这两个信息 PROJECT = "fatfs" VERSION = "1.0.0" -- sys库是标配 _G.sys = require("sys") --[[ 接线要求: SPI 使用常规4线解法 Air105开发板 TF模块 PC9 CS PB12(SPI0_CLK) CLK PB14(SPI0_MISO) MOSI PB15(SPI0_MISO) MISO 5V VCC GND GND ]] sys.taskInit(function() sys.wait(1000) -- 启动延时 local spiId = 0 local result = spi.setup( spiId,--串口id 255, -- 不使用默认CS脚 0,--CPHA 0,--CPOL 8,--数据宽度 400*1000 -- 初始化时使用较低的频率 ) local TF_CS = pin.PC9 gpio.setup(TF_CS, 1) --fatfs.debug(1) -- 若挂载失败,可以尝试打开调试信息,查找原因 fatfs.mount("SD", 0, TF_CS) local data, err = fatfs.getfree("SD") if data then log.info("fatfs", "getfree", json.encode(data)) else log.info("fatfs", "err", err) end -- 重新设置spi,使用更高速率 spi.close(0) sys.wait(100) spi.setup(spiId, 255, 0, 0, 8, 10*1000*1000) -- ################################################# -- 文件操作测试 -- ################################################# local f = io.open("/sd/boottime", "rb") local c = 0 if f then local data = f:read("*a") log.info("fs", "data", data, data:toHex()) c = tonumber(data) f:close() end log.info("fs", "boot count", c) c = c + 1 f = io.open("/sd/boottime", "wb") if f ~= nil then log.info("fs", "write c to file", c, tostring(c)) f:write(tostring(c)) f:close() else log.warn("sdio", "mount not good?!") end if fs then log.info("fsstat", fs.fsstat("/")) log.info("fsstat", fs.fsstat("/sd")) end -- 测试一下追加, fix in 2021.12.21 os.remove("/sd/test_a") sys.wait(50) f = io.open("/sd/test_a", "w") if f then f:write("ABC") f:close() end f = io.open("/sd/test_a", "a+") if f then f:write("def") f:close() end f = io.open("/sd/test_a", "r") if f then local data = f:read("*a") log.info("data", data, data == "ABCdef") f:close() end -- 测试一下按行读取, fix in 2022-01-16 f = io.open("/sd/testline", "w") if f then f:write("abc\n") f:write("123\n") f:write("wendal\n") f:close() end sys.wait(100) f = io.open("/sd/testline", "r") if f then log.info("sdio", "line1", f:read("*l")) log.info("sdio", "line2", f:read("*l")) log.info("sdio", "line3", f:read("*l")) f:close() end -- ################################################# end) -- 用户代码已结束--------------------------------------------- -- 结尾总是这一句 sys.run() -- sys.run()之后后面不要加任何语句!!!!!
local Plugin = script.Parent.Parent.Parent.Parent.Parent.Parent local Libs = Plugin.Libs local Roact = require(Libs.Roact) local RoactRodux = require(Libs.RoactRodux) local Utility = require(Plugin.Core.Util.Utility) local Constants = require(Plugin.Core.Util.Constants) local ContextGetter = require(Plugin.Core.Util.ContextGetter) local ContextHelper = require(Plugin.Core.Util.ContextHelper) local Funcs = require(Plugin.Core.Util.Funcs) local withTheme = ContextHelper.withTheme local withModal = ContextHelper.withModal local getModal = ContextGetter.getModal local Actions = Plugin.Core.Actions local SetStampSelected = require(Actions.SetStampSelected) local ClearStampSelected = require(Actions.ClearStampSelected) local SetStampDeleting = require(Actions.SetStampDeleting) local ClearStampDeleting = require(Actions.ClearStampDeleting) local DeleteStampObject = require(Actions.DeleteStampObject) local SetStampCurrentlyStamping = require(Actions.SetStampCurrentlyStamping) local ClearStampCurrentlyStamping = require(Actions.ClearStampCurrentlyStamping) local rotationFormatCallback = Funcs.rotationFormatCallback local rotationValidateCallback = Funcs.rotationValidateCallback local rotationFixedOnFocusLost = Funcs.rotationFixedOnFocusLost local rotationMinOnFocusLost = Funcs.rotationMinOnFocusLost local rotationMaxOnFocusLost = Funcs.rotationMaxOnFocusLost local scaleFormatCallback = Funcs.scaleFormatCallback local scaleValidateCallback = Funcs.scaleValidateCallback local scaleFixedOnFocusLost = Funcs.scaleFixedOnFocusLost local scaleMinOnFocusLost = Funcs.scaleMinOnFocusLost local scaleMaxOnFocusLost = Funcs.scaleMaxOnFocusLost local verticalOffsetFormatCallback = Funcs.verticalOffsetFormatCallback local verticalOffsetValidateCallback = Funcs.verticalOffsetValidateCallback local verticalOffsetFixedOnFocusLost = Funcs.verticalOffsetFixedOnFocusLost local verticalOffsetMinOnFocusLost = Funcs.verticalOffsetMinOnFocusLost local verticalOffsetMaxOnFocusLost = Funcs.verticalOffsetMaxOnFocusLost local formatVector3 = Funcs.formatVector3 local orientationFormatCallback = Funcs.orientationFormatCallback local orientationValidateCallback = Funcs.orientationValidateCallback local orientationCustomOnFocusLost = Funcs.orientationCustomOnFocusLost local Components = Plugin.Core.Components local Foundation = Components.Foundation local BorderedFrame = require(Foundation.BorderedFrame) local ThemedCheckbox = require(Foundation.ThemedCheckbox) local ObjectThumbnail = require(Foundation.ObjectThumbnail) local PreciseButton = require(Foundation.PreciseButton) local BorderedVerticalList = require(Foundation.BorderedVerticalList) local VerticalList = require(Foundation.VerticalList) local CollapsibleTitledSection = require(Foundation.CollapsibleTitledSection) local TextField = require(Foundation.TextField) local DropdownField = require(Foundation.DropdownField) local ThemedTextButton = require(Foundation.ThemedTextButton) local DeleteButton = require(script.DeleteButton) local RoundedBorderedFrame = require(Foundation.RoundedBorderedFrame) local RoundedBorderedVerticalList = require(Foundation.RoundedBorderedVerticalList) local StatefulButtonDetector = require(Foundation.StatefulButtonDetector) local StampObjectEntry = Roact.PureComponent:extend("StampObjectEntry") function StampObjectEntry:init() self:setState( { buttonState = "Default" } ) self.onStateChanged = function(buttonState) game:GetService("RunService").Heartbeat:Wait() self:setState{ buttonState = buttonState } end self.onClick = function() local props = self.props local currentlyStamping = props.currentlyStamping local guid = props.guid if not currentlyStamping then props.setCurrentlyStamping(guid) else props.clearCurrentlyStamping() end end end function StampObjectEntry:render() local props = self.props local stale = props.state if stale then -- this doesn't seem to do anything? return nil end local isHovered = self.state.isHovered local isPressed = self.state.isPressed local LayoutOrder = props.LayoutOrder local guid = props.guid local rbxObject = props.rbxObject local name = props.name local selected = props.selected local currentlyStamping = props.currentlyStamping local Visible = props.Visible local BorderTop = props.BorderTop ~= false local BorderBottom = props.BorderBottom ~= false local labelWidth = Constants.FIELD_LABEL_WIDTH local rotation = props.rotation local scale = props.scale local verticalOffset = props.verticalOffset local orientation = props.orientation local deleting = props.deleting local layoutOrder = 0 local function generateSequentialLayoutOrder() layoutOrder = layoutOrder+1 return layoutOrder end if props.stale then return end return withTheme(function(theme) local buttonTheme = theme.button local entryTheme = theme.objectGridEntry local entryHeight = 60 local entryPadding = 4 local rightButtonSize = 40 local buttonsOnRightSpace = rightButtonSize*1 local modal = getModal(self) local buttonHeight = Constants.BUTTON_HEIGHT local thumbnailSize = entryHeight-entryPadding*2 local buttonState = self.state.buttonState local boxState if currentlyStamping then local map = { Default = "Selected", Hovered = "SelectedHovered", PressedInside = "SelectedPressedInside", PressedOutside = "SelectedPressedOutside" } boxState = map[buttonState] else local map = { Default = "Default", Hovered = "Hovered", PressedInside = "PressedInside", PressedOutside = "PressedOutside" } boxState = map[buttonState] end local bgColors = entryTheme.backgroundColor local bgColor = bgColors[boxState] return Roact.createElement( RoundedBorderedVerticalList, { width = UDim.new(1, 0), LayoutOrder = props.LayoutOrder, BackgroundColor3 = theme.mainBackgroundColor, BorderColor3 = theme.borderColor, }, not deleting and { Wrap = Roact.createElement( "Frame", { Size = UDim2.new(1, 0, 0, entryHeight), BackgroundTransparency = 1, Visible = Visible, LayoutOrder = 1 }, { Border = Roact.createElement( RoundedBorderedFrame, { Size = UDim2.new(1, 0, 1, 0), BackgroundColor3 = bgColor, BorderColor3 = theme.borderColor, LayoutOrder = props.LayoutOrder, slice = selected and "Top" or "Center" } ), Detector = Roact.createElement( StatefulButtonDetector, { Size = UDim2.new(1, -buttonsOnRightSpace, 1, 0), BackgroundTransparency = 1, onClick = self.onClick, onStateChanged = self.onStateChanged } ), ImageFrame = Roact.createElement( BorderedFrame, { Size = UDim2.new(0, thumbnailSize, 0, thumbnailSize), Position = UDim2.new(0, entryPadding, 0, entryPadding), BackgroundColor3 = theme.mainBackgroundColor, BorderColor3 = theme.borderColor, ZIndex = 2 }, { Size = Roact.createElement( "Frame", { Size = UDim2.new(1, -2, 1, -2), Position = UDim2.new(0, 1, 0, 1), BackgroundTransparency = 1 }, { Image = Roact.createElement( ObjectThumbnail, { object = rbxObject, BackgroundColor3 = theme.mainBackgroundColor, ImageTransparency = currentlyStamping and 0 or 0.5, ImageColor3 = currentlyStamping and Color3.new(1, 1, 1) or Color3.new(0.5, 0.5, 0.5) } ) } ) } ), ContentFrame = Roact.createElement( "Frame", { BackgroundTransparency = 1, Size = UDim2.new(1, 0, 1, 0), Position = UDim2.new(0, 0, 0, 0), ZIndex = 2 }, { TextLabel = Roact.createElement( "TextLabel", { BackgroundTransparency = 1, Font = Constants.FONT_BOLD, TextColor3 = currentlyStamping and entryTheme.textColorEnabled or entryTheme.textColorDisabled, Size = UDim2.new(1, -thumbnailSize-entryPadding*2-buttonsOnRightSpace-entryPadding, 1, 0), Position = UDim2.new(0, thumbnailSize+entryPadding*2, 0, 0), Text = name, TextSize = Constants.FONT_SIZE_MEDIUM, TextXAlignment = Enum.TextXAlignment.Center, TextYAlignment = Enum.TextYAlignment.Center, TextTruncate = Enum.TextTruncate.AtEnd, ZIndex = 9 } ), DeleteButton = Roact.createElement( DeleteButton, { guid = guid, selected = selected } ) } ) } ) } or { Wrap = Roact.createElement( "Frame", { Size = UDim2.new(1, 0, 0, entryHeight), BackgroundTransparency = 1, Visible = Visible, LayoutOrder = 1 }, { Roact.createElement( RoundedBorderedFrame, { Size = UDim2.new(1, 0, 1, 0), BackgroundColor3 = entryTheme.backgroundColor.Default, BorderColor3 = theme.borderColor, LayoutOrder = props.LayoutOrder } ), DeleteText = Roact.createElement( "TextLabel", { BackgroundTransparency = 1, Font = Constants.FONT_BOLD, TextColor3 = entryTheme.textColorEnabled, Size = UDim2.new(1, -entryPadding*2, 0, Constants.FONT_SIZE_MEDIUM), Position = UDim2.new(0.5, 0, 0, 5), Text = string.format("Are you sure you want to delete %s?", name), AnchorPoint = Vector2.new(0.5, 0), TextSize = Constants.FONT_SIZE_MEDIUM, TextXAlignment = Enum.TextXAlignment.Center, TextTruncate = Enum.TextTruncate.AtEnd, ZIndex = 2 } ), DeleteButton = Roact.createElement( ThemedTextButton, { Text = "Delete", buttonStyle = "Delete", Size = UDim2.new(0, 100, 0, buttonHeight), AnchorPoint = Vector2.new(1, 1), Position = UDim2.new(0.5, -3, 1, -entryPadding), ZIndex = 2, onClick = function() props.clearCurrentlyStamping() props.deleteObject(guid) props.clearDeleting() end } ), CancelButton = Roact.createElement( ThemedTextButton, { Text = "Cancel", Size = UDim2.new(0, 100, 0, buttonHeight), AnchorPoint = Vector2.new(0, 1), Position = UDim2.new(0.5, 3, 1, -entryPadding), ZIndex = 2, onClick = function() props.clearDeleting() end } ) } ) } ) end) end local function mapStateToProps(state, props) -- we mark this as stale if the object was removed from the state. -- this is because this gets re-rendered before the grid unmounts it. local stamp = state.stamp local objects = state.stampObjects local guid = props.guid local object = objects[guid] if object then local rbxObject = object.rbxObject local currentlyStamping = stamp.currentlyStamping return { rbxObject = rbxObject, selected = stamp.selected == guid, currentlyStamping = currentlyStamping == guid, name = object.name, stale = false, guid = guid, deleting = stamp.deleting == guid, rotation = object.rotation, scale = object.scale, verticalOffset = object.verticalOffset, orientation = object.orientation, centerMode = object.stampCenterMode, hasPrimaryPart = rbxObject:IsA("Model") and rbxObject.PrimaryPart ~= nil } else return { stale = true } end end local function mapDispatchToProps(dispatch) return { setSelected = function(guid) dispatch(SetStampSelected(guid)) end, clearSelected = function() dispatch(ClearStampSelected()) end, setDeleting = function(guid) dispatch(SetStampDeleting(guid)) end, clearDeleting = function() dispatch(ClearStampDeleting()) end, deleteObject = function(guid) dispatch(DeleteStampObject(guid)) end, setCurrentlyStamping = function(guid) dispatch(SetStampCurrentlyStamping(guid)) end, clearCurrentlyStamping = function() dispatch(ClearStampCurrentlyStamping()) end, } end return RoactRodux.connect(mapStateToProps, mapDispatchToProps)(StampObjectEntry)
local FunctionNode = require'nodes.node'.Node:new() local function F(fn, args, ...) return FunctionNode:new{fn = fn, args = args, type = 2, markers = {},user_args = {...}} end function FunctionNode:get_args() local args = {} for i, node in ipairs(self.args) do args[i] = node:get_text() end args[#args+1] = self.parent return args end function FunctionNode:update() self.parent:set_text(self, self.fn(self:get_args(), unpack(self.user_args))) end return { F = F }
--[[ Copyright 2016 BloomReach, Inc. Copyright 2016 Ronak Kothari <ronak.kothari@gmail.com>. 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. --]] -- all the system specifc global modules cjson = require "cjson" -- all bb specific global modules shmem = require "bb.core.shmem" -- return code version -- <major version number>.<minior version number>.<sub version number> local _M = {} _M.version = "0.10.5" _M.path = ngx.config.prefix() .. "../bb/lualib/" return _M
-- luacheck: globals unpack vim local nvim = require'nvim' local stdpath = nvim.fn.stdpath local function system_name() local name = 'unknown' if nvim.has('win32unix') or nvim.has('win32') then name = 'windows' elseif nvim.has('mac') then name = 'mac' elseif nvim.has('unix') then name = 'linux' end return name end local function homedir() local var = system_name() == 'windows' and 'USERPROFILE' or 'HOME' local home = nvim.env[var] return home:gsub('\\', '/') end local function basedir() return stdpath('config'):gsub('\\', '/') end local function cachedir() return stdpath('cache'):gsub('\\', '/') end local function datadir() return stdpath('data'):gsub('\\', '/') end local function luajit_version() return vim.split(jit.version, ' ')[2] end local sys = { name = system_name(), home = homedir(), base = basedir(), data = datadir(), cache = cachedir(), luajit = luajit_version(), user = vim.loop.os_get_passwd() } sys.user.name = sys.user.username function sys.tmp(filename) local tmpdir = sys.name == 'windows' and 'c:/temp/' or '/tmp/' return tmpdir .. filename end return sys
function onSay(cid, words, param) if #getCreatureSummons(cid) == 0 then return doPlayerSendCancel(cid, "You don't have any pokemon.") end local summons = getCreatureSummons(cid)[1] local mon = getCreatureName(summons) if getCreatureSpeed(summons) >= 1 then doChangeSpeed(summons, -getCreatureSpeed(summons)) doCreatureSay(cid, ""..mon..", hold position!", TALKTYPE_SAY) else doRegainSpeed(summons) doCreatureSay(cid, ""..mon..", stop holding!", TALKTYPE_SAY) end return 0 end
--[[ - SKYNET SIMPLE ( https://github.com/viticm/skynet-simple ) - $Id object_type.lua - @link https://github.com/viticm/skynet-simple for the canonical source repository - @copyright Copyright (c) 2020 viticm( viticm.ti@gmail.com ) - @license - @user viticm( viticm.ti@gmail.com ) - @date 2020/09/17 14:47 - @uses The object type enum. --]] return { monster = 1, player = 2, npc = 3, }
-- teleport_beam return { ["teleport_beam"] = { usedefaultexplosions = true, GlowSpawner = { air = true, class = [[CExpGenSpawner]], count = 13, ground = true, water = false, properties = { delay = [[0 i4]], explosiongenerator = [[custom:Glow2]], pos = [[0, 0, 0]], }, }, }, ["Glow2"] = { glow = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.55 0.6 0.9 0.008 0.55 0.7 1 0.008 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 0, emitvector = [[0, 0, 0]], gravity = [[0, 0.00, 0]], numparticles = 1, particlelife = 11, particlelifespread = 0, particlesize = 50, particlesizespread = 10, particlespeed = 1, particlespeedspread = 0, pos = [[0, 2, 0]], sizegrowth = 35.0, sizemod = 1.0, texture = [[flare1]], }, }, }, ["teleport_beam_blue"] = { usedefaultexplosions = true, GlowSpawner = { air = true, class = [[CExpGenSpawner]], count = 13, ground = true, water = false, properties = { delay = [[0 i4]], explosiongenerator = [[custom:glow_blue]], pos = [[0, 0, 0]], }, }, }, ["glow_blue"] = { glow = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.01 0.01 0.9 0.008 0.12 0.12 1 0.008 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 0, emitvector = [[0, 0, 0]], gravity = [[0, 0.00, 0]], numparticles = 1, particlelife = 11, particlelifespread = 0, particlesize = 90, particlesizespread = 10, particlespeed = 1, particlespeedspread = 0, pos = [[0, 2, 0]], sizegrowth = 35.0, sizemod = 1.0, texture = [[flare1]], }, }, }, ["teleport_beam_yellow"] = { usedefaultexplosions = true, GlowSpawner = { air = true, class = [[CExpGenSpawner]], count = 13, ground = true, water = false, properties = { delay = [[0 i4]], explosiongenerator = [[custom:glow_yellow]], pos = [[0, 0, 0]], }, }, }, ["glow_yellow"] = { glow = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 1, colormap = [[1.0 0.9 0.0 0.008 0.95 0.85 0.1 0.008 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 0, emitvector = [[0, 0, 0]], gravity = [[0, 0.00, 0]], numparticles = 1, particlelife = 11, particlelifespread = 0, particlesize = 60, particlesizespread = 10, particlespeed = 1, particlespeedspread = 0, pos = [[0, 2, 0]], sizegrowth = 35.0, sizemod = 1.0, texture = [[flare1]], }, }, }, }
--DO NOT TOUCH CUSTOMTOOLGUN = {} CUSTOMTOOLGUN.data = { enabled = false, overridecustom = true, overridewithpic = true, color = Color(255,255,255), picture = "https://pm1.narvii.com/7349/20496af691a3f529d64bdffade368e123b204328r1-640-526v2_uhq.jpg", textcolor = Color(255,255,255), textheight = 210, textspeed=250, rainbowtext = true, textsize = 60, rainbowspeed=10, showdesc = true, descheight = 240, descsize = 30, descspeed = 200, } if SERVER then for i,v in ipairs(file.Find("custom_toolgun/*","LUA")) do if(string.StartWith(v,"cl_"))then AddCSLuaFile("custom_toolgun/"..v) end if(string.StartWith(v,"sh_"))then AddCSLuaFile("custom_toolgun/"..v) include("custom_toolgun/"..v) end if(string.StartWith(v,"sv_"))then include("custom_toolgun/"..v) end end else for i,v in ipairs(file.Find("custom_toolgun/*","LUA")) do if(string.StartWith(v,"cl_"))then include("custom_toolgun/"..v) end if(string.StartWith(v,"sh_"))then include("custom_toolgun/"..v) end end end
-- Model the loss of a 1 meter run of copper WR-12 waveguide, and check that -- the loss matches what we expect from theory. Check the wall and floor loss -- separately and together, for Ez and Exy models. test_number = tonumber(FLAGS.test_number) or Parameter{label='Test', min=1, max=6, default=1, integer=true} test_number_mod3 = ((test_number - 1) % 3) + 1 config = { unit = 'mm', mesh_edge_length = Parameter{label='Mesh edge length', min=0.1, max=2, default=0.3}, frequency = Parameter{label='Frequency (Hz)', min=60e9, max=90e9, default=75e9}, excited_port = 1, test = function(port_power, port_phase, field) -- For a 1 meter run of copper WR-12 waveguide, we expect -- 1.37244 dB of attenuation from the floor/ceiling. -- 0.57091 dB of attenuation from the walls. -- 1.94335 dB of attenuation in total. local loss = -10*math.log10(port_power[2]) local expected_loss if test_number == 1 or test_number == 5 then expected_loss = 1.37244 elseif test_number == 2 or test_number == 4 then expected_loss = 0.57091 elseif test_number_mod3 == 3 then expected_loss = 1.94335 end print('Test ', test_number, ', Loss =', loss, 'Expected loss =', expected_loss, 'Error =', loss - expected_loss) assert(math.abs(loss - expected_loss) < 0.02) end } if test_number <= 3 then config.type = 'Ez' W = 1000 -- Waveguide length H = 3.0988 -- WR-12 waveguide height (long dimension) config.depth = H / 2 else config.type = 'Exy' W = 1000 -- Waveguide length H = 3.0988 / 2 -- WR-12 waveguide height (short dimension) config.depth = H * 2 end cd = Rectangle(-W/2, -H/2, W/2, H/2) cd:Port(cd:Select(-W/2,0), 1) cd:Port(cd:Select(W/2,0), 2) -- The conductivity of copper. conductivity = 5.96e7 if test_number_mod3 == 1 or test_number_mod3 == 3 then local ep = util.PaintMetal(cd, Rectangle(-W/2, -H/2, W/2, H/2), 0xffff80, conductivity) print('Material epsilon =', ep.re, ep.im) end if test_number_mod3 == 2 or test_number_mod3 == 3 then util.PortMetal(cd, cd:Select(0, H/2), 3, conductivity) util.PortMetal(cd, cd:Select(0,-H/2), 4, conductivity) end config.cd = cd
class "TimerManager" function TimerManager:TimerManager(...) for k,v in pairs(arg) do if type(v) == "table" then if v.__ptr ~= nil then arg[k] = v.__ptr end end end if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then self.__ptr = Polycore.TimerManager(unpack(arg)) Polycore.__ptr_lookup[self.__ptr] = self end end function TimerManager:removeTimer(timer) local retVal = Polycore.TimerManager_removeTimer(self.__ptr, timer.__ptr) end function TimerManager:addTimer(timer) local retVal = Polycore.TimerManager_addTimer(self.__ptr, timer.__ptr) end function TimerManager:Update() local retVal = Polycore.TimerManager_Update(self.__ptr) end function TimerManager:__delete() Polycore.__ptr_lookup[self.__ptr] = nil Polycore.delete_TimerManager(self.__ptr) end
--[[ NetworkContract v1.1 [2020-12-02 14:30] Facilitates Client Server communication through Events. Has Encode, Decode, Diff, Patch and Message Knowledge This is a minified version of NetworkContract, to see the full source code visit https://github.com/nidorx/roblox-network-contract Discussions about this script are at https://devforum.roblox.com/t/900276 This code was minified using https://goonlinetools.com/lua-minifier/ ------------------------------------------------------------------------------ MIT License Copyright (c) 2020 Alex Rodin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local a=game:GetService('RunService')local b=bit32.band;local c=bit32.bor;local d=bit32.lshift;local e={}local f=0x0;for g=0,31 do table.insert(e,d(1,g))end;local h=0.2;local i=1-h;local j={}local k=0;local function l()end;local m=0.00001;local function n(o,p)if o==p then return true end;return math.abs(o-p)<m end;local function q(r,s)if r==s then return true end;if not r.Position:FuzzyEq(s.Position)then return false end;if not r.LookVector:FuzzyEq(s.LookVector)then return false end;if not r.RightVector:FuzzyEq(s.RightVector)then return false end;if not r.UpVector:FuzzyEq(s.UpVector)then return false end;return true end;local function t(u,v)local w=f;local x={true,w}for y,z in ipairs(v)do local A=u[z]if A~=nil then w=c(w,e[y])table.insert(x,A)end end;x[2]=w;return x end;local function B(u,v,C)if not u then return{}end;local x={}local D=table.getn(u)local w=u[2]local E=1;for g=3,D do for F=E,C do E=E+1;if b(w,e[F])~=f then x[v[F]]=u[g]break end end end;return x end;local function G(H,I,v)local J=f;local K=f;local x={K,J}for y,z in ipairs(v)do local L=H[z]local M=I[z]if L==nil then if M~=nil then J=c(J,e[y])table.insert(x,M)end elseif M==nil then K=c(K,e[y])else local N=typeof(L)local O=typeof(M)local P=false;if N==O then if N=='number'and not n(L,M)then P=true elseif N=='Vector3'and not L:FuzzyEq(M)then P=true elseif N=='CFrame'and not q(L,M)then P=true elseif L~=M then P=true end elseif L~=M then P=true end;if P then J=c(J,e[y])table.insert(x,M)end end end;x[1]=K;x[2]=J;return x end;local function Q(H,R,v,S,C)if not R then R={f,f}end;if not H then H={}end;local x={}local K=R[1]local J=R[2]local T={}local D=table.getn(R)local E=1;if J~=f then for g=3,D do for F=E,C do E=E+1;local U=e[F]if b(K,U)~=f then T[F]=true elseif b(J,U)~=f then T[F]=true;x[v[F]]=R[g]break end end end end;if K>=d(1,E-1)then for F=E,C do E=E+1;if b(K,e[F])~=f then T[F]=true end end end;for z,A in pairs(H)do local y=S[z]if y~=nil and A~=nil and not T[y]then x[z]=A end end;return x end;local function V(W,X,Y,Z,_)local S={}local v={}for y,z in ipairs(X)do S[z]=y;table.insert(v,z)end;local C=table.getn(v)local a0={Encode=function(u)return t(u,v)end,Decode=function(u)return B(u,v,C)end,Diff=function(H,I)return G(H,I,v)end,Patch=function(H,R)return Q(H,R,v,S,C)end}if Y==nil then a0.Send=l;a0.Acknowledge=l;a0.RTT=function()return 0 end else local a1;local a2='NCRCT_'..W;_=_~=false;if a:IsServer()then if game.ReplicatedStorage:FindFirstChild(a2)then error('There is already an event with the given ID ('..a2 ..')')end;a1=Instance.new('RemoteEvent')a1.Parent=game.ReplicatedStorage;a1.Name=a2;local a3={}local function a4(a5,a6)local a7=a6.UserId;if a3[a7]~=nil and a3[a7][a5]~=nil then if j[a7]==nil then j[a7]={LastRttTime=-math.huge,RTT=0}end;local a8=j[a7]local a9=a3[a7][a5]if a9>a8.LastRttTime then local aa=os.clock()-a9;if a8.RTT==0 then a8.RTT=aa else a8.RTT=h*aa+i*a8.RTT end;a8.LastRttTime=a9 end;a3[a7][a5]=nil end end;a1.OnServerEvent:Connect(function(a6,ab)local u=ab[1]local a5=ab[2]if u==true then if a5~=nil then if _ then a4(a5,a6)end;if Z~=nil then Z(a5,a6,a0)end end else if u~=nil then if _ and a5~=nil then a1:FireClient(a6,{true,a5})end;Y(u,a5,u[1]~=true,a6,a0)end end end)a0.Send=function(u,a5,a6)if u==nil then return end;if _ and a5~=nil then local a7=a6.UserId;if a3[a7]==nil then a3[a7]={}end;if a3[a7][a5]==nil then a3[a7][a5]=os.clock()end end;a1:FireClient(a6,{u,a5})end;a0.Acknowledge=function(ac,a6)a1:FireClient(a6,{true,ac})end;a0.RTT=function(a6)local a8=j[a6.UserId]if a8~=nil then return a8.RTT end;return 0 end else a1=game.ReplicatedStorage:WaitForChild(a2)local a3={}local ad=-math.huge;local function a4(a5)if a3[a5]~=nil then local a9=a3[a5]if a9>ad then local aa=os.clock()-a9;if k==0 then k=aa else k=h*aa+i*k end;ad=a9 end;a3[a5]=nil end end;a1.OnClientEvent:Connect(function(ab)local u=ab[1]local a5=ab[2]if u==true then if a5~=nil then if _ then a4(a5)end;if Z~=nil then Z(a5,nil,a0)end end else if u~=nil then if _ and a5~=nil then a1:FireServer({true,a5})end;Y(u,a5,u[1]~=true,nil,a0)end end end)a0.Send=function(u,a5)if u==nil then return end;if _ and a5~=nil then if a3[a5]==nil then a3[a5]=os.clock()end end;a1:FireServer({u,a5})end;a0.Acknowledge=function(ac)a1:FireServer({true,ac})end;a0.RTT=function()return k end end end;return a0 end;return V
--[[ The contents of this file are subject to the Common Public Attribution License Version 1.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://ultimate-empire-at-war.com/cpal. The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15 have been added to cover use of software over a computer network and provide for limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is Ultimate Empire at War. The Original Developer is the Initial Developer. The Initial Developer of the Original Code is the Ultimate Empire at War team. All portions of the code written by the Ultimate Empire at War team are Copyright (c) 2012. All Rights Reserved. ]] require("pgevents") function Definitions() DebugMessage("%s -- In Definitions", tostring(Script)) Category = "Advance_Tech_Dark_Side" IgnoreTarget = true TaskForce = { { "TechForce", "E2_AGREEMENT_BAKTOID | E2_DEVELOPMENT_HEAVY_FIGHTERS | E2_DEVELOPMENT_HEAVY_BOMBERS | E2_DEVELOPMENT_CORVETTES | E2_AGREEMENT_HOERSCH_KESSEL | E2_DEVELOPMENT_FRIGATES | E2_DEVELOPMENT_LIGHT_DESTROYERS | E2_RESTRUCTURING_DESTROYERS | E2_DEVELOPMENT_HEAVY_DESTROYERS | E2_DEVELOPMENT_SUPERIOR_BATTLESHIPS | E2_RESTRUCTURING_BATTLESHIPS | E2_ADVANCED_MATERIALS_CIS | E2_ADVANCED_DEFENCES_CIS | E2_ADVANCED_WEAPONS_SYSTEMS_CIS | E2_SUPERIOR_SYSTEMS_CIS= 1", "E3_ACQUIRATION_PATROL_CRAFT | E3_DEVELOPING_NEW_PATROL_CLASS | E3_DEVELOPING_NEW_GUNSHIPS | E3_DRAFT_CLONE_WARS_SHIPS | E3_REDESIGN_CLONE_WARS_DESIGNS | E3_CONTINUE_CLONE_WARS_SHIPS | E3_GET_INTERDICTOR_PLANS | E3_REDESIGN_VICTORY_I | E3_REDESIGN_VICTORY_CLASS | E3_DEVELOPING_NEW_FIGHTERS | E3_SUPERIOR_GUNBOATS | E3_DEVELOPMENT_SUPERIOR_BATTLESHIPS | E3_DEVELOPMENT_SUPERIOR_ASSAULT_FIGHTERS | E3_DEVELOPMENT_SUPERSHIPS | E3_REVISING_OLD_BATTLESTATION_PLANS | E3_BUILDING_PROTOTYPE | E3_PLANNING_BUILDING | E3_GATHER_RESSOURCES | E3_BUILDING_DEATH_STAR_I | E3_REDESIGN_DEATH_STAR_I | E3_BUILDING_DEATH_STAR_II | E3_ADVANCED_MATERIALS_EMPIRE | E3_ADVANCED_DEFENCES_EMPIRE | E3_ADVANCED_WEAPONS_SYSTEMS_EMPIRE | E3_SUPERIOR_SYSTEMS_EMPIRE= 1", "E4_RESEARCHING_CLOAKING_TECHNOLOGY | E4_AUTOMATED_COMBAT_SYSTEM | E4_ADV_AF_DEFENCE | E4_DEVELOPING_NEW_RAID_TECHNOLOGY | E4_COMBINING_SUPERLASER_SUPERSHIPS = 1" } } DebugMessage("%s -- Done Definitions", tostring(Script)) end function TechForce_Thread() DebugMessage("%s -- In TechForce_Thread.", tostring(Script)) -- Ensure that all goal feasability will be reevaluated based on the new production budgetting conditions -- (production underway that is already paid for and remains affordable under new budgets should continue) Purge_Goals(PlayerObject) TechForce.Set_As_Goal_System_Removable(false) Sleep(1) BlockOnCommand(TechForce.Produce_Force()) TechForce.Set_Plan_Result(true) DebugMessage("%s -- TechForce done!", tostring(Script)); ScriptExit() end function TechForce_Production_Failed(tf, failed_object_type) DebugMessage("%s -- Abandonning plan owing to production failure.", tostring(Script)) ScriptExit() end
--- -- Widget to select from a range of values. -- -- **Extends:** `kloveui.Widget` -- -- @classmod kloveui.Slider local graphics = love.graphics local Widget = require "kloveui.Widget" local Slider = Widget:extend("kloveui.Slider") --- -- Current value for the slider. -- -- Lies in the range 0-1 (inclusive). -- -- @tfield number value Default is 0. Slider.value = 0 --- -- Value increment. -- -- If a number, the value snaps to the nearest multiple of that value; -- if nil, the value resolution depends on the widget's size. -- -- @tfield nil|number increment Default is nil. Slider.increment = nil --- -- Anchor border. -- -- If it is `"l"`, the value increments left to right. -- If it is `"r"`, the value increments right to left. -- If it is `"t"`, the value increments top to bottom. -- If it is `"b"`, the value increments bottom to top. -- -- @tfield string anchor Default is "l". Slider.anchor = "l" --- -- Color for the handle while pressed. -- -- @tfield kloveui.Color handlecolorpressed Default is (.75, .75, .75). Slider.handlecolorpressed = ({ .75, .75, .75 }) --- -- Set the slider's value. -- -- This method calls `valuechanged` if the value is different. -- -- @tparam number v New value. Clamped to the range 0-1. -- @tparam ?boolean force Set new value even if unchanged. Default is false. -- @treturn number Old value. function Slider:setvalue(v, force) local old = self.value v = math.max(0, math.min(1, v)) if force or v ~= self.value then self.value = v self:valuechanged(old) end return old end --- -- Called to paint the handle. -- -- The handle is part of the "foreground". -- -- @tparam number x X position of the center of the handle. -- @tparam number y Y position of the center of the handle. -- @tparam boolean vert True if this is a vertical bar, false otherwise. -- @tparam boolean pressed True if the handle is currently pressed, -- false otherwise. -- @see kloveui.Widget:paintfg function Slider:painthandle(x, y, vert, pressed) local size = (vert and self.w or self.h)/4 local fg = (self.enabled and (pressed and self.handlecolorpressed or self.fgcolor) or self.fgcolordisabled) local bc = self.bordercolor graphics.push() graphics.translate(x, y) if vert then graphics.rotate(math.pi/2) end graphics.setColor(fg) graphics.polygon("fill", 0, -size, -size, -size*2, size, -size*2) graphics.polygon("fill", 0, size, -size, size*2, size, size*2) graphics.line(0, -size, 0, size) graphics.setColor(bc) graphics.polygon("line", 0, -size, -size, -size*2, size, -size*2) graphics.polygon("line", 0, size, -size, size*2, size, size*2) graphics.pop() end --- -- Called to paint the bar. -- -- The bar is part of the "background". -- -- @tparam number x X position of the center of the handle. -- @see kloveui.Widget:paintbg function Slider:paintbar() graphics.setColor(self.bgcolor) graphics.rectangle("fill", 0, 0, self.w, self.h) end --- -- Called when the value of the bar changes. -- -- @tparam number oldval Old value. -- @see value function Slider:valuechanged(oldval) end function Slider:calcminsize() if self.anchor == "t" or self.anchor == "b" then return 16, 32 else return 32, 16 end end function Slider:mousepressed(x, y, b) if b == 1 then self._pressed = true self:mousemoved(x, y) end end function Slider:mousereleased(_, _, b) if b == 1 then self._pressed = nil end end function Slider:mousemoved(x, y) if self._pressed then local anchor = self.anchor local v if anchor == "t" then v = y/self.h elseif anchor == "b" then v = 1-y/self.h elseif anchor == "r" then v = 1-x/self.w else v = x/self.w end if self.increment then v = math.floor(v/self.increment+.5)*self.increment end self:setvalue(v) end end function Slider:wheelmoved(_, y) local v = self.value + (self.increment or .1)*(-y) self:setvalue(v) end function Slider:paintfg() local anchor = self.anchor local vert = anchor == "t" or anchor == "b" local invert = anchor == "r" or anchor == "b" local x = vert and self.w/2 or self.w*self.value local y = vert and self.h*self.value or self.h/2 if invert then x, y = self.w-x, self.h-y end self:painthandle(x, y, vert, self._pressed) Widget.paintfg(self) end function Slider:paintbg() Widget.paintbg(self) self:paintbar() graphics.setColor(self.bordercolor) graphics.rectangle("line", 0, 0, self.w, self.h) end return Slider
module(..., package.seeall) require("lua_tda") require "lpeg" require "dialog_utilities" require "core" require "dialog_utilities" joProfile = require "OWLGrEd_UserFields.Profile" syncProfile = require "OWLGrEd_UserFields.syncProfile" styleMechanism = require "OWLGrEd_UserFields.styleMechanism" viewMechanism = require "OWLGrEd_UserFields.viewMechanism" serialize = require "serialize" local report = require("reporter.report") --atver formu ar visiem profiliem projektaa function profileMechanism() report.event("StylePaletteWindow_ManageViewsAndExtensions", { GraphDiagramType = "projectDiagram" }) local close_button = lQuery.create("D#Button", { caption = "Close" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.close()") }) local form = lQuery.create("D#Form", { id = "allProfiles" ,caption = "Profiles in project" ,minimumWidth = 300 ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = close_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.close()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#HorizontalBox" ,{ component = { lQuery.create("D#VerticalBox", { id = "VerticalBoxWithListBox" ,component = { lQuery.create("D#ListBox", { id = "ListWithProfiles" ,item = collectProfiles() }) } }) ,lQuery.create("D#VerticalBox", { component = { lQuery.create("D#Button", { caption = "Custom Fields" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.openProfileProperties()") }) ,lQuery.create("D#Button", { caption = "Views in profile" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.viewMechanism.viewMechanism()") }) ,lQuery.create("D#Button", { caption = "New profile" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.newProfile()") ,topMargin = 15 }) ,lQuery.create("D#Button", { caption = "Import (load) profile" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.import()") }) ,lQuery.create("D#Button", { caption = "Save profile" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noLoadForm()") }) -- ,lQuery.create("D#Button", { -- caption = "Default for views" -- ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.defaultForViews()") -- }) ,lQuery.create("D#Button", { caption = "Delete profile" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.deleteProfile()") ,topMargin = 15 }) ,lQuery.create("D#Button", { caption = "Advanced.." ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.advenced()") }) } }) }}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end function advenced() local close_button = lQuery.create("D#Button", { caption = "Close" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeAdvanced()") }) local form = lQuery.create("D#Form", { id = "AdvencedManegement" ,caption = "Advanced profile management" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = close_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeAdvanced()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#HorizontalBox" ,{ component = { lQuery.create("D#VerticalBox", { component = { lQuery.create("D#Row", { component = { lQuery.create("D#Button", { caption = "Save profile snapshot" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.saveProfileSnapshot()") }) ,lQuery.create("D#Label", {caption="Export all profile definitions to OWLGrEd_UserFields/snapshot folder"}) } }) ,lQuery.create("D#Row", { component = { lQuery.create("D#Button", { caption = "Restore from snapshot" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.restoreFromSnapshot()") }) ,lQuery.create("D#Label", {caption="Import all profile definitions from OWLGrEd_UserFields/snapshot folder"}) } }) ,lQuery.create("D#Row", { component = { lQuery.create("D#Button", { caption = "Manage configuration" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.configuration.configurationProperty()") }) ,lQuery.create("D#Label", {caption="Open form for field context and profile tag management"}) } }) } }) }}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end function MakeDir(path) lfs = require("lfs") lfs.mkdir(path) end function restoreFromSnapshot() local start_folder if tda.isWeb then start_folder = tda.FindPath(tda.GetToolPath() .. "/AllPlugins", "OWLGrEd_UserFields") .. "/snapshot/" else start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\snapshot\\" end local path = start_folder .. "snapshot.txt" serialize.import_from_file(path) local configuration = lQuery("AA#Configuration"):first() lQuery("AA#ContextType"):each(function(obj) obj:remove_link("configuration", obj:find("/configuration")) end) lQuery("AA#ContextType"):link("configuration", configuration) lQuery("AA#TagType"):each(function(obj) obj:remove_link("configuration", obj:find("/configuration")) end) lQuery("AA#TagType"):link("configuration", configuration) lQuery("AA#Configuration"):filter(function(obj) return obj:id() ~= configuration:id() end):delete() lQuery("AA#Profile"):remove_link("configuration", lQuery("AA#Profile/configuration")) lQuery("AA#Profile"):link("configuration", lQuery("AA#Configuration")) -- izmest dublikatus -- atrast visus AA#ContextType -- iziet cauri visiem. Ja ir vairki ar viendu id, tad izdzest to, kam nav AA#Field lQuery("AA#ContextType"):each(function(obj) local id = obj:attr("id") local eq = lQuery("AA#ContextType[id = '" .. id .."']") if eq:size()>1 then if obj:find("/fieldInContext"):is_empty() then obj:delete() else eq:filter(function(ct) return ct:attr("id") ~= obj:attr("id") end):delete() end end end) lQuery("AA#TagType"):each(function(obj) local tt = lQuery("AA#TagType[key='" .. obj:attr("key") .. "'][notation='" .. obj:attr("notation") .. "'][rowType='" .. obj:attr("rowType") .. "']") if tt:size()>1 then obj:delete() end end) --jaatrod profila vards --jaatrod tas profils, kam nav saderibas local profileName lQuery("AA#Profile"):each(function(obj) if lQuery("Extension[id='" .. obj:attr("name") .. "'][type='aa#Profile']"):is_empty() then profileName = obj:attr("name") local ext = lQuery.create("Extension", {id = profileName, type = "aa#Profile"})--:link("aa#owner", lQuery("Extension[id = 'OWL_Fields']")) lQuery("Extension[id = 'OWL_Fields']"):link("aa#subExtension", ext) lQuery("AA#Profile[name='" .. profileName .. "']/view"):each(function(prof) if ext:find("/aa#subExtension[id='" .. prof:attr("name") .. "'][type='aa#View']"):is_empty() then lQuery.create("Extension", {id=prof:attr("name"), type="aa#View"}):link("aa#owner", ext) :link("aa#graphDiagram", lQuery("GraphDiagram:has(/graphDiagramType[id='OWL'])")) end end) syncProfile.syncProfile(profileName) end end) styleMechanism.syncExtensionViews() --atjaunot listBox refreshListBox() end function saveProfileSnapshot() local objects_to_export = lQuery("AA#Configuration") local export_spec = { include = { ["AA#Configuration"] = { context = serialize.export_as_table ,profile = serialize.export_as_table ,tagType = serialize.export_as_table } ,["AA#Profile"] = { field = serialize.export_as_table ,view = serialize.export_as_table ,tag = serialize.export_as_table } ,["AA#TagType"] = {} ,["AA#ContextType"] = { fieldInContext = serialize.export_as_table } ,["AA#View"] = { styleSetting = serialize.export_as_table } ,["AA#Field"] = { tag = serialize.export_as_table ,translet = serialize.export_as_table ,selfStyleSetting = serialize.export_as_table ,dependency = serialize.export_as_table ,choiceItem = serialize.export_as_table ,subField = serialize.export_as_table } ,["AA#ChoiceItem"] = { tag = serialize.export_as_table ,styleSetting = serialize.export_as_table ,dependency = serialize.export_as_table } ,["AA#Tag"] = {} ,["AA#Translet"] = {} ,["AA#Dependency"] = {} ,["AA#FieldStyleSetting"] = {} ,["AA#ViewStyleSetting"] = {} }, border = { ["AA#Field"] = { -- fieldType = serialize.make_exporter(function(object) -- return "AA#RowType[typeName=" .. lQuery(object):attr("typeName") .. "]" -- end) } ,["AA#Translet"] = { task = serialize.make_exporter(function(object) return "AA#TransletTask[taskName=" .. lQuery(object):attr("taskName") .. "]" end) } ,["AA#FieldStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } ,["AA#ViewStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } } } local start_folder if tda.isWeb then start_folder = tda.FindPath(tda.GetToolPath() .. "/AllPlugins", "OWLGrEd_UserFields") .. "/snapshot/" MakeDir(tda.FindPath(tda.GetToolPath() .. "/AllPlugins", "OWLGrEd_UserFields") .. "/snapshot") else start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\snapshot\\" MakeDir(tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\snapshot") end local path = start_folder .. "snapshot.txt" serialize.save_to_file(objects_to_export, export_spec, path) end --padara profilu nokluseto prieks skatijumiem function defaultForViews() --izveletais profils local selectedItem = lQuery("D#ListBox[id='ListWithProfiles']/selected") if selectedItem:is_not_empty() then local profileName = selectedItem:attr("value") local viewSize = string.find(profileName, " ") if viewSize~=nil then profileName = string.sub(profileName, 1, viewSize-1) end --nedrikst padarit profilu nokluseto, ja zem ta ir izveidoti lauki if selectedItem:is_not_empty() and lQuery("AA#Profile[name='" .. profileName .. "']/field"):is_empty() then if lQuery("AA#Profile[name='" .. profileName .. "']"):attr("isDefaultForViews")=="true" then lQuery("AA#Profile[name='" .. profileName .. "']"):attr("isDefaultForViews", false) refreshListBox() else if lQuery("AA#Profile[isDefaultForViews='true']"):is_empty() then lQuery("AA#Profile[name='" .. profileName .. "']"):attr("isDefaultForViews", true) refreshListBox() else showNotificationForm() end end --atjaunot listBox --refreshListBox() end end end function showNotificationForm() local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") local close_button = lQuery.create("D#Button", { caption = "No" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noChangeDefaultForViews()") }) local create_button = lQuery.create("D#Button", { caption = "Yes" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.yesChangeDefaultForViews()") }) local form = lQuery.create("D#Form", { id = "changeDefaultForViews" ,caption = "Confirmation" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noChangeDefaultForViews()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption="Do you want to save the profile for auto loading?"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,component = {create_button, close_button}}) } }) dialog_utilities.show_form(form) end function noChangeDefaultForViews() lQuery("D#Event"):delete() utilities.close_form("changeDefaultForViews") end function yesChangeDefaultForViews() local selectedItem = lQuery("D#ListBox[id='ListWithProfiles']/selected") local profileName = selectedItem:attr("value") local viewSize = string.find(profileName, " ") if viewSize~=nil then profileName = string.sub(profileName, 1, viewSize-1) end lQuery("AA#Profile"):attr("isDefaultForViews", false) lQuery("AA#Profile[name='" .. profileName .. "']"):attr("isDefaultForViews", true) noChangeDefaultForViews() refreshListBox() end --atver profila konfiguracijas formu function openProfileProperties() local selectedItem = lQuery("D#ListBox[id='ListWithProfiles']/selected") if selectedItem:is_not_empty() then local profileName = selectedItem:attr("value") local viewSize = string.find(profileName, " ") if viewSize~=nil then profileName = string.sub(profileName, 1, viewSize-1) end if selectedItem:is_not_empty() and lQuery("AA#Profile[name='" .. profileName.. "']"):attr("isDefaultForViews")~="true" then joProfile.Profile(profileName) else pleaseSelectNotDefaultProfile("Please use a profile that is not default for views to enter and manage user field definitions") end else pleseSelectProfile() end end function pleseSelectProfile() local close_button = lQuery.create("D#Button", { caption = "Ok" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") }) local form = lQuery.create("D#Form", { id = "contextTypesMissing" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption = "Please select a profile"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" --,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end --izdzes profilu no projekta function deleteProfile() --atrast profilu local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") if profileName:is_not_empty() then local profileName = profileName:attr("value") local viewSize = string.find(profileName, " ") if viewSize~=nil then profileName = string.sub(profileName, 1, viewSize-1) end local profile = lQuery("AA#Profile[name = '" .. profileName .. "']") --izdzest AA# Dalu lQuery(profile):find("/field"):each(function(obj) deleteField(obj) end) --saglabajam stilus lQuery("GraphDiagram:has(/graphDiagramType[id='OWL'])"):each(function(diagram) utilities.execute_cmd("SaveDgrCmd", {graphDiagram = diagram}) end) --palaist sinhronizaciju syncProfile.syncProfile(profileName) viewMechanism.deleteViewFromProfile(profileName) --izdzest profilu, extension lQuery(profile):delete() lQuery("Extension[id='" .. profileName .. "'][type='aa#Profile']"):delete() --atjaunot listBox refreshListBox() end end --izdzes lietotaja defineto lauku un visu, kas ir saistits ar to (field-dzesamais lauks) function deleteField(field) lQuery(field):find("/tag"):delete() lQuery(field):find("/translet"):delete() lQuery(field):find("/dependency"):delete() lQuery(field):find("/selfStyleSetting"):delete() lQuery(field):find("/choiceItem/tag"):delete() lQuery(field):find("/choiceItem/styleSetting"):delete() lQuery(field):find("/choiceItem"):delete() --lQuery(field):find("/fieldType"):remove_link("field", field) lQuery(field):find("/subField"):each(function(obj) deleteField(obj) end) lQuery(field):delete() end --atver formu jauno profilu veidosanai function newProfile() local close_button = lQuery.create("D#Button", { caption = "Close" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeNewProfileForm()") }) local create_button = lQuery.create("D#Button", { caption = "Create" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.createNewProfile()") }) local form = lQuery.create("D#Form", { id = "newProfile" ,caption = "Create new profile" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeNewProfileForm()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#InputField", { id = "InputFieldForNewProfile" ,text = "" }) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,horizontalAlignment = 1 ,component = {create_button, close_button}}) } }) dialog_utilities.show_form(form) end --izveido jaunu profilu function createNewProfile() local newProfileValue = lQuery("D#InputField[id='InputFieldForNewProfile']"):attr("text") if newProfileValue ~="" then closeNewProfileForm() --izveidojam profilu local profile = lQuery.create("AA#Profile", {name = newProfileValue}):link("configuration", lQuery("AA#Configuration")) local profileExtension = lQuery.create("Extension", {id = newProfileValue, type = "aa#Profile"}):link("aa#owner", lQuery("Extension[id = 'OWL_Fields']")) --izveidojam nokluseto skatijumu -- lQuery.create("AA#View", {name = "Default", isDefault = 1}):link("profile", profile) -- lQuery.create("Extension", {id = "Default", type = "aa#View"}):link("aa#owner", profileExtension) --atverm profila configuracijas formu -- joProfile.Profile(newProfileValue) --atjaunot listBox refreshListBox() end end --atjauno sarakstu ar profiliem function refreshListBox() lQuery("D#ListBox[id='ListWithProfiles']"):delete() lQuery.create("D#ListBox", { id = "ListWithProfiles" ,item = collectProfiles() }):link("container", lQuery("D#VerticalBox[id='VerticalBoxWithListBox']")) lQuery("D#VerticalBox[id='VerticalBoxWithListBox']"):link("command", utilities.enqued_cmd("D#Command", {info = "Refresh"})) end --savac visus profilus no projekta function collectProfiles() local values = lQuery("AA#Profile"):map( function(obj) return {lQuery(obj):attr("name"), lQuery(obj):attr("isDefaultForViews")} end) return lQuery.map(values, function(profile) local profileName = profile[1] if profile[2]=="true" then profileName = profileName .. " (Default for views)" end return lQuery.create("D#Item", { value = profileName }) end) end function anywhere (p) return lpeg.P{ p + 1 * lpeg.V(1) } end --ielade profilu no teksta faila function import() caption = "Select text file" filter = "text file(*.txt)" local start_folder if tda.isWeb then start_folder = tda.FindPath(tda.GetToolPath() .. "/AllPlugins", "OWLGrEd_UserFields") .. "/examples/" else start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\examples\\" end start_file = "" save = false local path = tda.BrowseForFile(caption, filter, start_folder, start_file, save) if path ~= "" then f = assert(io.open(path, "r")) local t = f:read("*all") f:close() local contextTypeTable = {} local Letter = lpeg.R("az") + lpeg.R("AZ") + lpeg.R("09") + lpeg.S("_/:#.<>='(){}?!@$%^&*-+|") local String = lpeg.C(Letter * (Letter) ^ 0) local ct = lpeg.P("AA#ContextType[id=") local compartTypeTable = {} local ctP = (ct * String * "]") ctP = lpeg.P(ctP) ctP = lpeg.Cs((ctP/(function(a) table.insert(compartTypeTable, a) end) + 1)^0) lpeg.match(ctP, t) local l = 0 for i,v in pairs(compartTypeTable) do if lQuery("AA#ContextType[id='" .. v .. "']"):is_empty() then l = 1 end end if l ~= 1 then local profileName local pat = lpeg.P([["AA#Profile", ["properties"] = { ["name"] = "]]) local p = pat * String * '"' p = anywhere (p) profileName = lpeg.match(p, t) or "" if lQuery("Extension[id='" .. profileName .. "'][type='aa#Profile']"):is_empty() then serialize.import_from_file(path) --izveidojam profilu if profileName == "" then lQuery("AA#Profile"):each(function(obj) if lQuery("Extension[id='" .. obj:attr("name") .. "'][type='aa#Profile']"):is_empty() then profileName = obj:attr("name") end end) end local ext = lQuery.create("Extension", {id = profileName, type = "aa#Profile"})--:link("aa#owner", lQuery("Extension[id = 'OWL_Fields']")) lQuery("Extension[id = 'OWL_Fields']"):link("aa#subExtension", ext) --ja ir saite uz AA#RowType, nonemam tas lQuery("AA#Field"):each(function(obj) local fieldType = obj:find("/fieldType") if fieldType:is_not_empty() then obj:attr("fieldType", fieldType:attr("typeName")) fieldType:remove_link("field", obj) end end) --izveidojam profila skatijumus lQuery("AA#Profile[name='" .. profileName .. "']/view"):each(function(obj) lQuery.create("Extension", {id = obj:attr("name"), type = "aa#View"}):link("aa#owner", ext) :link("aa#graphDiagram", lQuery("GraphDiagram:has(/graphDiagramType[id='OWL'])")) end) --saglabajam izmainas lQuery("GraphDiagram:has(/graphDiagramType[id='OWL'])"):each(function(diagram) utilities.execute_cmd("SaveDgrCmd", {graphDiagram = diagram}) end) lQuery("AA#Profile"):remove_link("configuration", lQuery("AA#Profile/configuration")) lQuery("AA#Profile"):link("configuration", lQuery("AA#Configuration")) --sinhronizejam profilu syncProfile.syncProfile(profileName) --sinhronizejam skatijumus styleMechanism.syncExtensionViews() --atjaunot listBox refreshListBox() else -- print("Import was canceled")--!!!!!!!!!!!! -- print("Profile with this name already exists")--!!!!!!!!!! end else contextTypesMissing() -- print("Import was canceled") -- print("Some ContextTypes are missing") -- print("Please create or load corresponding configuration.") end else --print("Import was canceled") end end function pleaseSelectNotDefaultProfile() local close_button = lQuery.create("D#Button", { caption = "Ok" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") }) local form = lQuery.create("D#Form", { id = "contextTypesMissing" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption = "Please use a profile that is not default for views"}) ,lQuery.create("D#Label", {caption = "to enter and manage user field definitions"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" --,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end function contextTypesMissing() local close_button = lQuery.create("D#Button", { caption = "Ok" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") }) local form = lQuery.create("D#Form", { id = "contextTypesMissing" ,caption = "Create new profile" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption = "The profile to be imported requires extend profile configuration"}) ,lQuery.create("D#Label", {caption = "Please import the profiles configuration from"}) ,lQuery.create("D#Label", {caption = "'Advanced..'->'Manage configuration' form"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" --,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end --parada dialoga logu ar jautajumu vai ir jaielade profils automatiski function load() local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") if profileName:is_not_empty() then local close_button = lQuery.create("D#Button", { caption = "No" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noLoadForm()") }) local create_button = lQuery.create("D#Button", { caption = "Yes" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.yesLoadForm(()") }) local form = lQuery.create("D#Form", { id = "loadProfile" ,caption = "Load profile" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noLoadFormClose()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption="Do you want to save the profile for auto loading?"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,component = {create_button, close_button}}) } }) dialog_utilities.show_form(form) end end function noLoadForm() local close_button = lQuery.create("D#Button", { caption = "Close" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.loadProfileNameClose()") }) local create_button = lQuery.create("D#Button", { caption = "Ok" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noLoadFormExport()") }) local form = lQuery.create("D#Form", { id = "exportFileNameForm" ,caption = "Export file name" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.loadProfileNameClose()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption="Enter export file name"}) ,lQuery.create("D#InputField", { id = "exportFileName", text = lQuery("D#ListBox[id='ListWithProfiles']/selected"):attr("value") .. "_" .. os.date("%m_%d_%Y_%H_%M_%S") }) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,component = {create_button, close_button}} ) } }) dialog_utilities.show_form(form) end function loadProfileNameClose() lQuery("D#Event"):delete() utilities.close_form("exportFileNameForm") end function noLoadFormClose() lQuery("D#Event"):delete() utilities.close_form("loadProfile") end function noLoadFormExport() if export() then -- modified by SK lQuery("D#Event"):delete() --utilities.close_form("loadProfile") --print("by SK: deleting form loadProfile") utilities.close_form("loadProfile") -- by SK!!! else --print("by SK: do not deleting the form") end end function yesLoadForm() lQuery("D#Event"):delete() utilities.close_form("loadProfile") local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") if profileName:is_not_empty() then local objects_to_export = lQuery("AA#Profile[name = '" .. profileName:attr("value") .. "']") local export_spec = { include = { ["AA#Profile"] = { field = serialize.export_as_table ,view = serialize.export_as_table ,tag = serialize.export_as_table } ,["AA#View"] = { styleSetting = serialize.export_as_table } ,["AA#Field"] = { tag = serialize.export_as_table ,translet = serialize.export_as_table ,selfStyleSetting = serialize.export_as_table ,dependency = serialize.export_as_table ,choiceItem = serialize.export_as_table ,subField = serialize.export_as_table } ,["AA#ChoiceItem"] = { tag = serialize.export_as_table ,styleSetting = serialize.export_as_table ,dependency = serialize.export_as_table } ,["AA#Tag"] = {} ,["AA#Translet"] = {} ,["AA#Dependency"] = {} ,["AA#FieldStyleSetting"] = {} ,["AA#ViewStyleSetting"] = {} }, border = { ["AA#Field"] = { context = serialize.make_exporter(function(object) return "AA#ContextType[id=" .. lQuery(object):attr("id") .. "]" end) -- ,fieldType = serialize.make_exporter(function(object) -- return "AA#RowType[typeName=" .. lQuery(object):attr("typeName") .. "]" -- end) } ,["AA#Translet"] = { task = serialize.make_exporter(function(object) return "AA#TransletTask[taskName=" .. lQuery(object):attr("taskName") .. "]" end) } ,["AA#FieldStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } ,["AA#ViewStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } } } local start_folder if tda.isWeb then start_folder = tda.FindPath(tda.GetToolPath() .. "/AllPlugins", "OWLGrEd_UserFields") .. "/user/AutoLoad/" else start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\user\\AutoLoad\\" end local path = start_folder .. profileName:attr("value") .. ".txt" serialize.save_to_file(objects_to_export, export_spec, path) end end --saglaba profilu teksta failaa function export() local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") if profileName:is_not_empty() then local objects_to_export = lQuery("AA#Profile[name = '" .. profileName:attr("value") .. "']") local export_spec = { include = { ["AA#Profile"] = { field = serialize.export_as_table ,view = serialize.export_as_table ,tag = serialize.export_as_table } ,["AA#View"] = { styleSetting = serialize.export_as_table } ,["AA#Field"] = { tag = serialize.export_as_table ,translet = serialize.export_as_table ,selfStyleSetting = serialize.export_as_table ,dependency = serialize.export_as_table ,choiceItem = serialize.export_as_table ,subField = serialize.export_as_table } ,["AA#ChoiceItem"] = { tag = serialize.export_as_table ,styleSetting = serialize.export_as_table ,dependency = serialize.export_as_table } ,["AA#Tag"] = {} ,["AA#Translet"] = {} ,["AA#Dependency"] = {} ,["AA#FieldStyleSetting"] = {} ,["AA#ViewStyleSetting"] = { customStyleSetting = serialize.export_as_table } ,["AA#CustomStyleSetting"] = {} }, border = { ["AA#Field"] = { context = serialize.make_exporter(function(object) return "AA#ContextType[id=" .. lQuery(object):attr("id") .. "]" end) -- ,fieldType = serialize.make_exporter(function(object) -- return "AA#RowType[typeName=" .. lQuery(object):attr("typeName") .. "]" -- end) } ,["AA#Translet"] = { task = serialize.make_exporter(function(object) return "AA#TransletTask[taskName=" .. lQuery(object):attr("taskName") .. "]" end) } ,["AA#FieldStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } ,["AA#ViewStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } } } local deteTime = os.date("%m_%d_%Y_%H_%M_%S") local caption = "select folder" if tda.isWeb then start_folder = "" -- relative to the user's home directory (currently, ignored) else start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\user\\" end local folder = tda.BrowseForFolder(caption, start_folder) if folder == nil then -- by SK return false -- do not delete the form end if folder ~= "" then local path if tda.isWeb then path = folder .. "/" .. lQuery("D#InputField[id='exportFileName']"):attr("text") .. ".txt" else path = folder .. "\\" .. lQuery("D#InputField[id='exportFileName']"):attr("text") .. ".txt" end serialize.save_to_file(objects_to_export, export_spec, path) loadProfileNameClose() else --print("Export was canceled") end end return true -- by SK end function closeContextTypesMissing() lQuery("D#Event"):delete() utilities.close_form("contextTypesMissing") end function closeAdvanced() lQuery("D#Event"):delete() utilities.close_form("AdvencedManegement") end function close() lQuery("D#Event"):delete() utilities.close_form("allProfiles") end function closeNewProfileForm() lQuery("D#Event"):delete() utilities.close_form("newProfile") end
local CookieToHeaders = require("kong.plugins.base_plugin"):extend() function CookieToHeaders:new() CookieToHeaders.super.new(self, "cookies-to-headers") end function CookieToHeaders:access(plugin_conf) CookieToHeaders.super.access(self) local cookie = require "resty.cookie" local ck = cookie:new() local cookieValue, err = ck:get(plugin_conf.cookie_name) if not cookieValue then ngx.log(ngx.ERR, err) else if string.lower(plugin_conf.header_name) == "authorization" then ngx.req.set_header("Authorization", "Bearer " .. cookieValue) else ngx.req.set_header(plugin_conf.header_name, cookieValue) end end end CookieToHeaders.PRIORITY = 900 return CookieToHeaders
local rings = require 'lua/rings/rings' local value = require 'lua/rings/value' local sh = require 'lua/sh' local list_disks = sh.command('df | grep ^/dev/sd | sed "s|^.*% ||g" | head -n 5 | tac') local function ring_def(name, disk, idx) return { caption = name, value = value.eval(string.format('fs_used_perc %s', disk)), y = 560, thickness = 7, radius = 65 - idx * 15 } end local function draw(display) local disks = list_disks() local i = 0 for disk in string.gmatch(disks,'[^\r\n]+') do local last = string.gsub(disk, '(.+/)', '') rings.draw(display, ring_def(last, disk, i)) i = i + 1 end end return { draw = draw }
require 'xlua' require 'pl' -- global settings if package.preload.settings then return package.preload.settings end -- default tensor type torch.setdefaulttensortype('torch.FloatTensor') local settings = {} local cmd = torch.CmdLine() cmd:text() cmd:text("waifu2x") cmd:text("Options:") cmd:option("-seed", 11, 'fixed input seed') cmd:option("-data_dir", "./data", 'data directory') cmd:option("-test", "images/miku_small.png", 'test image file') cmd:option("-model_dir", "./models", 'model directory') cmd:option("-method", "scale", '(noise|scale|noise_scale)') cmd:option("-noise_level", 1, '(1|2)') cmd:option("-scale", 2.0, 'scale') cmd:option("-learning_rate", 0.00025, 'learning rate for adam') cmd:option("-random_half", 1, 'enable data augmentation using half resolution image') cmd:option("-crop_size", 128, 'crop size') cmd:option("-batch_size", 2, 'mini batch size') cmd:option("-epoch", 200, 'epoch') cmd:option("-core", 2, 'cpu core') local opt = cmd:parse(arg) for k, v in pairs(opt) do settings[k] = v end if settings.method == "noise" then settings.model_file = string.format("%s/noise%d_model.t7", settings.model_dir, settings.noise_level) elseif settings.method == "scale" then settings.model_file = string.format("%s/scale%.1fx_model.t7", settings.model_dir, settings.scale) elseif settings.method == "noise_scale" then settings.model_file = string.format("%s/noise%d_scale%.1fx_model.t7", settings.model_dir, settings.noise_level, settings.scale) else error("unknown method: " .. settings.method) end if not (settings.scale == math.floor(settings.scale) and settings.scale % 2 == 0) then error("scale must be mod-2") end if settings.random_half == 1 then settings.random_half = true else settings.random_half = false end torch.setnumthreads(settings.core) settings.images = string.format("%s/images.t7", settings.data_dir) settings.image_list = string.format("%s/image_list.txt", settings.data_dir) settings.validation_ratio = 0.1 settings.validation_crops = 40 local srcnn = require './srcnn' if (settings.method == "scale" or settings.method == "noise_scale") and settings.scale == 4 then settings.create_model = srcnn.waifu4x settings.block_offset = 13 else settings.create_model = srcnn.waifu2x settings.block_offset = 7 end return settings
tohex = function (num) if not type(num) == "number" then error("Number expected got "..type(num)) end local out = "" local a = string.format("%X",num) for i=a:len(), 1, -1 do local s = a:sub(i,i) if s == "x" or s == "" then s = "0" end local val = string.format("%c",tonumber("0x0"..s)*2+33) out = val..out end if out:len()%2 == 1 then out = "!"..out end return out end todec = function (str) if not type(str) == "string" then error("String expected got "..type(str)) end local out = "0x" for i=1, str:len() do local a = string.format("%x",(string.byte(str:sub(i,i)) - 33)/2) out = out..a end return tonumber(out,16) end
local awful = require('awful') local filesystem = require('gears.filesystem') local apps = {} apps.default = { terminal = "alacritty", launcher = "rofi -modi drun -show drun", --lock = "xsecurelock", --screenshot = "gnome-screenshot", filebrowser = "thunar", browser = "firefox", editor = "geany" } local run_on_start_up = { "picom $HOME/.config/picom/picom.conf", "nitrogen --restore", --"unclutter", "thunar --daemon", --"blueman-applet", "blueman-tray", "nm-applet", "volumeicon" --"xfce4-power-manager --restart", --"numlockx" } function apps.autostart() for _, app in ipairs(run_on_start_up) do local findme = app local firstspace = app:find(" ") if firstspace then findme = app:sub(0, firstspace - 1) end awful.spawn.with_shell(string.format("pgrep -u $USER -x %s > /dev/null || (%s)", findme, app), false) end end return apps
-- Test suite for snippets.lua local SnippetManager = package_require 'snippets.manager' local Config = package_require 'snippets.config' local Editor = package_require 'snippets.editor' local Parser = package_require 'snippets.parser' -- BUG -- cancel tab activation with selected text -- TODO -- snippets.scivar = "$(FilePath)" local manager = SnippetManager:new() local function print(...) ide:Print(...) end local function test_snippets(editor) manager:load_config { {activation = "tabs", text = "${3:three} ${1:one} ${2:two}" }, {activation = "etabs", text = "${2:one ${1:two} ${3:three}} ${4:four}" }, {activation = "mirrors", text = "${1:one} ${2:two} ${1} ${2}" }, {activation = "rmirrors", text = "${1:one} ${1/one/two/}" }, {activation = "rgroups", text = [[Ordered pair: ${1:(2, 8)} so ${1/(\d), (\d)/x = $1, y = $2/}]]}, {activation = "trans", text = "${1:one} ${1/o(ne)?/O$1/}" }, {activation = "esc1", text = [[\${1:fake one} ${1:real one} {${2:\} two}]]}, {activation = "esc2", text = [[\${1:fake one} ${1:real one} {${2:\} two}${0}]]}, {activation = "eruby", text = "${1:one} ${1/.+/#{$0.capitalize}/}" }, {activation = "cursor", text = "begin${0}end" }, {activation = "dcursor", text = "begin${0: hello}end" }, {activation = "skip", text = "${1:one} ${3:three}" }, {activation = "popup", text = "${0|one,two,three} ${1|hello,world}" }, -- TODO test it {activation = "indent", text = "hello\t\n\tworld" }, } manager:release(editor) local eol = Editor.GetEOL(editor) local indent = Editor.GetIndentString(editor) do -- Tab stops editor:ClearAll() print('testing tab stops') editor:AddText("tabs"); manager:insert(editor) assert( Editor.GetSelText(editor) == "one" ) assert( editor:GetText(editor) == "${3:three} one ${2:two}" .. eol ) editor:ReplaceSelection('foo') manager:next(editor) assert( Editor.GetSelText(editor) == "two" ) assert( editor:GetText(editor) == "${3:three} foo two" .. eol ) manager:prev(editor) assert( Editor.GetSelText(editor) == "one" ) assert( editor:GetText(editor) == "${3:three} one ${2:two}" .. eol ) manager:next(editor) assert( Editor.GetSelText(editor) == "two" ) assert( editor:GetText(editor) == "${3:three} one two" .. eol ) manager:next(editor) assert( Editor.GetSelText(editor) == "three" ) manager:next(editor) assert( editor:GetText() == "three one two" ) print('tab stops passed') end do -- Embedded tab stops editor:ClearAll() print('testing embedded tab stops') editor:AddText('etabs'); manager:insert(editor) assert( Editor.GetSelText(editor) == 'two') manager:next(editor) assert( Editor.GetSelText(editor) == 'one two ${3:three}' ) manager:next(editor) assert(Editor.GetSelText(editor) == 'three') manager:next(editor) manager:next(editor) assert( editor:GetText() == 'one two three four' ) print('embedded tabs passed') end do -- Mirrors editor:ClearAll() print('testing mirrors') editor:AddText('mirrors'); manager:insert(editor) manager:next(editor) assert( editor:GetText() == 'one two one ${2}' .. eol ) manager:prev(editor) assert( editor:GetText() == 'one ${2:two} ${1} ${2}' .. eol ) assert( Editor.GetSelText(editor) == 'one' ) manager:next(editor) assert( editor:GetText() == 'one two one ${2}' .. eol ) editor:DeleteBack(); editor:AddText('three') manager:next(editor) assert( editor:GetText() == 'one three one three' ) print('mirrors passed') end do -- Regex Mirrors editor:ClearAll() print('testing regex mirrors') editor:AddText('rmirrors'); manager:insert(editor) manager:next(editor) assert( editor:GetText() == 'one two' ) editor:ClearAll() editor:AddText('rmirrors'); manager:insert(editor) editor:DeleteBack(); editor:AddText('two') manager:next(editor) assert( editor:GetText() == 'two ' ) print('regex mirrors passed') end do -- Regex Groups editor:ClearAll() print('testing regex groups') editor:AddText('rgroups'); manager:insert(editor) manager:next(editor) assert( editor:GetText() == 'Ordered pair: (2, 8) so x = 2, y = 8' ) editor:ClearAll() editor:AddText('rgroups'); manager:insert(editor) editor:DeleteBack(); editor:AddText('[5, 9]') manager:next(editor) assert( editor:GetText() == 'Ordered pair: [5, 9] so x = 5, y = 9' ) print('regex groups passed') end do -- Transformations editor:ClearAll() print('testing transformations') editor:AddText('trans'); manager:insert(editor) manager:next(editor) assert( editor:GetText() == 'one One' ) editor:ClearAll() editor:AddText('trans'); manager:insert(editor) editor:DeleteBack(); editor:AddText('once') manager:next(editor) assert( editor:GetText() == 'once O' ) print('transformations passed') end if false then -- SciTE variables editor:ClearAll() print('testing scite variables') editor:AddText('scivar'); manager:insert(editor) assert( editor:GetText() == props['FilePath'] ) print('scite variables passed') end do -- Escapes for _, name in ipairs{'esc1', 'esc2'} do editor:ClearAll() print('testing escapes - ' .. name) editor:AddText(name); manager:insert(editor) assert( Editor.GetSelText(editor) == 'real one' ) manager:next(editor) assert( Editor.GetSelText(editor) == '} two' ) manager:next(editor) assert( editor:GetText() == '${1:fake one} real one {} two' ) print('escapes passed' .. name) end end do -- Embeded Ruby editor:ClearAll() print('testing embedded ruby') editor:AddText('eruby'); manager:insert(editor) manager:next(editor) assert( editor:GetText() == 'one One' ) editor:ClearAll() editor:AddText('eruby'); manager:insert(editor) editor:DeleteBack(); editor:AddText('two') manager:next(editor) assert( editor:GetText() == 'two Two' ) print('embedded ruby passed') end do -- Default value for cursor position editor:ClearAll() print('testing cursor position') editor:AddText('cursor'); manager:insert(editor) manager:next(editor) assert( editor:GetText() == 'beginend' ) assert( editor:GetCurrentPos() == 5 ) assert( Editor.GetSelText(editor) == '' ) assert( not manager:has_active_snippet(editor) ) print('cursor position passed') end do -- Default value for cursor position editor:ClearAll() print('testing cursor position with default value') editor:AddText('dcursor'); manager:insert(editor) manager:next(editor) assert( editor:GetText() == 'begin helloend' ) assert( editor:GetCurrentPos() == 11 ) assert( Editor.GetSelText(editor) == ' hello' ) assert( not manager:has_active_snippet(editor) ) print('cursor position with default value passed') end do -- Stops on last missing placeholder editor:ClearAll() print('testing stops on last missing placeholder') editor:AddText('skip'); manager:insert(editor) assert( editor:GetText() == 'one ${3:three}' .. eol ) assert( Editor.GetSelText(editor) == 'one') assert( manager:has_active_snippet(editor) ) manager:next(editor) assert( editor:GetText() == 'one ${3:three}' ) assert( editor:GetCurrentPos() == 14 ) assert( Editor.GetSelText(editor) == '') assert( not manager:has_active_snippet(editor) ) print('stops on last missing placeholder passed') end do -- EOL editor:ClearAll() print('testing remove eol') local s = eol .. 'foo.boo()' .. eol .. 'bbb' editor:AddText('rmirrors' .. s); editor:SetSelection(8,8) manager:insert(editor) assert( editor:GetText() == 'one ${1/one/two/}' .. eol .. s) assert( Editor.GetSelText(editor) == 'one') assert( manager:has_active_snippet(editor) ) manager:next(editor) assert( editor:GetText() == 'one two' .. s) assert( editor:GetCurrentPos() == 7 ) assert( not manager:has_active_snippet(editor) ) end do -- inden editor:ClearAll() print('testing indent') local prefix = '{' .. eol .. indent editor:AddText(prefix .. 'indent'); manager:insert(editor) local text = prefix .. 'hello\t' .. eol .. indent .. indent .. 'world' assert(editor:GetText() == text) print('indent passed') end end local function test_cancel(editor) manager:load_config{ { activation = {'key', 'Ctrl+1'}, text = '<b>$(SelectedText)${1:}</b>' }, { activation = {'tab', '111222'}, text = '<b>$(SelectedText)${1:}</b>' } } manager:release(editor) local eol = Editor.GetEOL(editor) if true then -- ignore unknown shourtcuts print('testing ingnoring unknown shortcuts') editor:ClearAll() editor:AddText("111222333") editor:SetAnchor(3) editor:SetCurrentPos(6) manager:insert(editor, 'Ctrl+I') -- Do not change selection for unknown snippet assert( Editor.GetSelText(editor) == "222" ) assert( editor:GetCurrentPos() == 6 ) editor:SetAnchor(6) editor:SetCurrentPos(3) manager:insert(editor, 'Ctrl+I') -- Do not change selection for unknown snippet assert( Editor.GetSelText(editor) == "222" ) assert( editor:GetCurrentPos() == 3 ) end if true then -- cancel key editor:ClearAll() print('testing cancel snippet with key activation') editor:AddText("111222333") for i = 1, 2 do if i == 1 then editor:SetAnchor(6) editor:SetCurrentPos(3) else editor:SetAnchor(3) editor:SetCurrentPos(6) end manager:insert(editor, 'Ctrl+1') assert( editor:GetText() == '111<b>222</b>' .. eol .. '333' ) assert( editor:GetCurrentPos() == 9 ) assert( Editor.GetSelText(editor) == "" ) editor:AddText('444') assert( editor:GetText() == '111<b>222444</b>' .. eol .. '333' ) manager:cancel(editor) assert( editor:GetText() == '111222333' ) assert( Editor.GetSelText(editor) == "222" ) assert( editor:GetCurrentPos() == 6 ) -- TODO restore correct position end print('testing cancel snippet with key activation passed') end if true then -- ignore unknown shourtcuts print('testing ingnoring unknown tab activators') editor:ClearAll() editor:AddText("111222333") editor:SetAnchor(3) editor:SetCurrentPos(5) manager:insert(editor) assert( Editor.GetSelText(editor) == "22" ) assert( editor:GetCurrentPos() == 5 ) editor:SetAnchor(5) editor:SetCurrentPos(3) manager:insert(editor) assert( Editor.GetSelText(editor) == "22" ) assert( editor:GetCurrentPos() == 3 ) print('test ingnoring unknown tab activators passed') end if true then -- cancel tab editor:ClearAll() print('testing cancel snippet with tab activation (without selection)') editor:AddText("111222333") editor:SetSelection(6, 6); manager:insert(editor) assert( editor:GetText() == '<b></b>' .. eol .. '333' ) assert( editor:GetCurrentPos() == 3 ) assert( Editor.GetSelText(editor) == "" ) editor:AddText('444') manager:cancel(editor) assert( editor:GetText() == '111222333' ) assert( editor:GetCurrentPos() == 6 ) -- TODO restore correct position print('test cancel snippet with tab activation (without selection) passed') end if true then -- TODO FIX not supported correctly cancel for tab activatin with selection editor:ClearAll() editor:AddText("111222333") editor:SetAnchor(3) editor:SetCurrentPos(6) assert( Editor.GetSelText(editor) == "222" ) manager:insert(editor) assert( editor:GetText() == '<b>222</b>' .. eol .. '333' ) assert( editor:GetCurrentPos() == 6 ) assert( Editor.GetSelText(editor) == "" ) editor:AddText('444') manager:cancel(editor) assert( editor:GetText() == '222333' ) -- BUG in assert( editor:GetCurrentPos() == 3 ) print('TODO FIX not supported correctly cancel for tab activatin with selection') end if true then -- TODO FIX not supported correctly cancel for tab activatin with selection editor:ClearAll() editor:AddText("111222333") editor:SetAnchor(9) editor:SetCurrentPos(6) assert( Editor.GetSelText(editor) == "333" ) manager:insert(editor) assert( editor:GetText() == '<b>333</b>' .. eol .. '333') assert( editor:GetCurrentPos() == 6 ) assert( Editor.GetSelText(editor) == "" ) editor:AddText('444') manager:cancel(editor) assert( editor:GetText() == '333333' ) -- BUG assert( editor:GetCurrentPos() == 3 ) print('TODO FIX not supported correctly cancel for tab activatin with selection') end end local function run() local editor = NewFile() test_snippets(editor) test_cancel(editor) ide:GetDocument(editor):SetModified(false) ClosePage() Config.__self_test__() Parser.__self_test__() print('snippet tests passed') end return run
atrributes = { name = "USB 2-Axis 8-Button Gamepad" } controls = { { id = 0, usagePage = 1, usage = 48, name = "X", minimum = 0, maximum = 255, expression = "" }, { id = 1, usagePage = 1, usage = 49, name = "Y", minimum = 0, maximum = 255, expression = "" }, { id = 2, usagePage = 9, usage = 1, name = "Button 1", minimum = 0, maximum = 1, expression = "" }, { id = 3, usagePage = 9, usage = 2, name = "Button 2", minimum = 0, maximum = 1, expression = "" }, { id = 4, usagePage = 9, usage = 3, name = "Button 3", minimum = 0, maximum = 1, expression = "" }, { id = 5, usagePage = 9, usage = 4, name = "Button 4", minimum = 0, maximum = 1, expression = "" }, { id = 6, usagePage = 9, usage = 5, name = "Button 5", minimum = 0, maximum = 1, expression = "" }, { id = 7, usagePage = 9, usage = 6, name = "Button 6", minimum = 0, maximum = 1, expression = "" }, { id = 8, usagePage = 9, usage = 7, name = "Button 7", minimum = 0, maximum = 1, expression = "" }, { id = 9, usagePage = 9, usage = 8, name = "Button 8", minimum = 0, maximum = 1, expression = "" }, }
local Charagen = require("mod.elona.api.Charagen") local Calc = require("mod.elona.api.Calc") local Chara = require("api.Chara") local Item = require("api.Item") local Gui = require("api.Gui") local Rand = require("api.Rand") local Effect = require("mod.elona.api.Effect") local Skill = require("mod.elona_sys.api.Skill") local Input = require("api.Input") local Anim = require("mod.elona_sys.api.Anim") local Action = require("api.Action") local Magic = require("mod.elona_sys.api.Magic") local Enum = require("api.Enum") local I18N = require("api.I18N") local IItemRod = require("mod.elona.api.aspect.IItemRod") local ElonaMagic = {} -- BUG: we have to return false or nil instead of player_turn_query to support -- characters other than the player using items! function ElonaMagic.drink_potion(magic_id, power, item, params) -- TODO: allow multiple magic IDs to be passed at once, or maybe a callback -- function even. local chara = params.chara local triggered_by = params.triggered_by or "potion" local curse_state = params.curse_state or (item and item:calc("curse_state")) or Enum.CurseState.Normal if triggered_by == "potion_thrown" then local throw_power = params.throw_power or 100 power = power * throw_power / 100 curse_state = item:calc("curse_state") elseif triggered_by == "potion" then curse_state = item:calc("curse_state") elseif triggered_by == "potion_spilt" then -- pass end local magic_params = { source = chara, -- TODO target if thrown power = power, item = item, target = params.chara, curse_state = curse_state, triggered_by = triggered_by } local did_something, result = Magic.cast(magic_id, magic_params) if result and item and chara:is_player() and result.obvious then Effect.identify_item(item, Enum.IdentifyState.Name) end return did_something end --- @tparam IItem item --- @tparam table magic --- @tparam table params --- @treturn string function ElonaMagic.read_scroll(item, magic, params) -- >>>>>>>> shade2/proc.hsp:1465 *readScroll .. params = params or {} params.chara = params.chara or nil params.no_consume_item = params.no_consume_item local chara = params.chara or item:get_owning_chara() if chara:has_effect("elona.blindness") then if chara:is_in_fov() then Gui.mes("action.read.cannot_see", chara) end return "turn_end" end if chara:has_effect("elona.dimming") or chara:has_effect("elona.confusion") then if not Rand.one_in(4) then if chara:is_in_fov() then Gui.mes("action.read.scroll.dimmed_or_confused", chara) end return "turn_end" end end if chara:is_in_fov() then Gui.mes("action.read.scroll.execute", chara, item:build_name(1)) end if not params.no_consume then item.amount = item.amount - 1 Skill.gain_skill_exp(chara, "elona.literacy", 25, 2) end local did_something, result for _, pair in ipairs(magic) do local magic_id = pair._id local power = pair.power assert(magic_id and power, ("Missing _id (%s) or power (%s) for magic callback"):format(magic_id, power)) did_something, result = Magic.cast(magic_id, {power=power,item=item,source=chara,target=chara}) end result = result or {} if result.obvious == nil then result.obvious = true end if result and chara:is_player() and result.obvious then Effect.identify_item(item, Enum.IdentifyState.Name) end return "turn_end" -- <<<<<<<< shade2/proc.hsp:1488 return true .. end --- @tparam IItem item --- @tparam magic_id id:elona_sys.magic --- @tparam uint power --- @tparam table params --- @treturn string function ElonaMagic.zap_rod(item, magic_id, power, params) -- >>>>>>>> shade2/proc.hsp:1491 *zapStaff .. params = params or {} -- HACK local skill_data = Magic.skills_for_magic(magic_id)[1] or nil local chara = params.chara or item:get_owning_chara() local aspect = item:get_aspect(IItemRod) if aspect and not aspect:is_charged(item) then Gui.mes("action.zap.execute", item:build_name(1)) Gui.mes("common.nothing_happens") return "turn_end" end local curse_state = item:calc("curse_state") if curse_state == Enum.CurseState.Blessed then curse_state = Enum.CurseState.Normal end local magic_pos if skill_data then local target = chara:get_target() local success success, magic_pos = Magic.get_magic_location(skill_data.target_type, skill_data.range, chara, params.triggered_by or "wand", target, skill_data.ai_check_ranged_if_self, skill_data.on_choose_target) if not success then return "turn_end" end -- <<<<<<<< shade2/proc.hsp:1499 gosub *effect_selectTg .. else -- >>>>>>>> shade2/proc.hsp:1563 if efId>tailSpAct:tc=cc:return true .. magic_pos = { source = chara, target = chara } -- <<<<<<<< shade2/proc.hsp:1563 if efId>tailSpAct:tc=cc:return true .. end -- >>>>>>>> shade2/proc.hsp:1500 if stat=false : efSource=false: return false .. if magic_pos.no_effect then if chara:is_in_fov() then Gui.mes("action.zap.execute", item:build_name(1)) Gui.mes("common.nothing_happens") end if Item.is_alive(item) then item:refresh_cell_on_map() end local sep = item:separate() local sep_aspect = sep:get_aspect(IItemRod) if sep_aspect then sep_aspect:modify_charges(sep, -1) end return "turn_end" end if chara:is_in_fov() then Gui.mes("action.zap.execute", item:build_name(1)) end -- <<<<<<<< shade2/proc.hsp:1507 if sync(cc) : txtActZap : txtMore .. -- >>>>>>>> shade2/proc.hsp:1509 efP = efP*( 100 + sMagicDevice(cc) * 10 + sMAG(cc .. local magic_device = chara:skill_level("elona.magic_device") local stat_magic = chara:skill_level("elona.stat_magic") local stat_perception = chara:skill_level("elona.stat_perception") local adjusted_power = power * (100 + magic_device * 10 + stat_magic / 2 + stat_perception / 2) / 100 local success = chara:emit("elona.calc_wand_success", {magic_id=magic_id,item=item}, false) if success then local range = skill_data and skill_data.range or 0 local magic_params = { power=adjusted_power, item=item, curse_state=curse_state, x = magic_pos.x, y = magic_pos.y, range = range, source = magic_pos.source, target = magic_pos.target } local did_something, result = Magic.cast(magic_id, magic_params) result = result or {} if result.obvious == nil then result.obvious = true end if result and chara:is_player() and result.obvious then Effect.identify_item(item, Enum.IdentifyState.Name) end if chara:is_player() then Skill.gain_skill_exp(chara, "elona.magic_device", 40) end else if chara:is_in_fov() then Gui.mes("action.zap.fail", chara) end end if Item.is_alive(item) then item:refresh_cell_on_map() local sep = item:separate() local sep_aspect = sep:get_aspect(IItemRod) if sep_aspect then sep_aspect:modify_charges(sep, -1) end end return "turn_end" -- <<<<<<<< shade2/proc.hsp:1536 return true .. end function ElonaMagic.check_can_cast_spell(skill_id, caster) local skill_data = data["base.skill"]:ensure(skill_id) if skill_data.on_check_can_cast then if not skill_data.on_check_can_cast(skill_data, caster) then return false end end return true end function ElonaMagic.calc_spellbook_success(chara, difficulty, skill_level) -- >>>>>>>> shade2/calculation.hsp:1079 *calcReadCheck .. if chara:has_effect("elona.blindness") then return false end if chara:has_effect("elona.confusion") or chara:has_effect("elona.dimming") then if not Rand.one_in(4) then return false else return true end end if Rand.rnd(chara:skill_level("elona.literacy") * skill_level * 4 + 250) < Rand.rnd(difficulty + 1) then if Rand.one_in(7) then return false end if skill_level * 10 < difficulty and Rand.rnd(skill_level * 10 + 1) < Rand.rnd(difficulty + 1) then return false end if skill_level * 20 < difficulty and Rand.rnd(skill_level * 20 + 1) < Rand.rnd(difficulty + 1) then return false end if skill_level * 30 < difficulty and Rand.rnd(skill_level * 30 + 1) < Rand.rnd(difficulty + 1) then return false end end -- <<<<<<<< shade2/calculation.hsp:1094 if f=true:return true .. return true end function ElonaMagic.fail_to_read_spellbook(chara, difficulty, skill_level) -- >>>>>>>> shade2/calculation.hsp:1092 if rnd(4)=0{ ... if Rand.one_in(4) then Gui.mes_visible("misc.fail_to_cast.mana_is_absorbed", chara) if chara:is_player() then chara:damage_mp(chara:calc("max_mp")) else chara:damage_mp(chara:calc("max_mp") / 3) end return end if Rand.one_in(4) then if chara:is_in_fov() then if chara:has_effect("elona.confusion") then Gui.mes("misc.fail_to_cast.is_confused_more", chara) else Gui.mes("misc.fail_to_cast.too_difficult") end end chara:apply_effect("elona.confusion", 100) return end if Rand.one_in(4) then Gui.mes_visible("misc.fail_to_cast.creatures_are_summoned", chara) local player = Chara.player() local player_level = player:calc("level") local map = player:current_map() for i = 1, 2 + Rand.rnd(3) do local level = Calc.calc_object_level(player_level * 3 / 2 + 3, map) local quality = Calc.calc_object_quality(Enum.Quality.Normal) local spawned = Charagen.create(player.x, player.y, { level = level, quality = quality }) if spawned and chara:relation_towards(player) <= Enum.Relation.Enemy then spawned:set_relation_towards(player, Enum.Relation.Dislike) end end return end Gui.mes_visible("misc.fail_to_cast.dimension_door_opens", chara) Magic.cast("elona.teleport", { source = chara, target = chara }) return -- <<<<<<<< shade2/calculation.hsp:1114 return false .. end -- Tries to read a spellbook, and on failure causes a negative effect to happen. function ElonaMagic.try_to_read_spellbook(chara, difficulty, skill_level) -- >>>>>>>> shade2/calculation.hsp:1096 if rnd(4)=0{ .. local success = ElonaMagic.calc_spellbook_success(chara, difficulty, skill_level) if success then return true end ElonaMagic.fail_to_read_spellbook(chara, difficulty, skill_level) return false -- <<<<<<<< shade2/calculation.hsp:1118 return false .. end function ElonaMagic.do_cast_spell(skill_id, caster, use_mp) -- >>>>>>>> elona122/shade2/proc.hsp:1282 *cast_proc .. local skill_data = data["base.skill"]:ensure(skill_id) local params = { triggered_by = "spell", curse_state = "normal", power = Skill.calc_spell_power(skill_id, caster), range = skill_data.range } if caster:is_player() then if Skill.calc_spell_mp_cost(skill_id, caster) > caster.mp and config.elona.warn_on_spell_overcast then Gui.mes("action.cast.overcast_warning") if not Input.yes_no() then return false end end end if not ElonaMagic.check_can_cast_spell(skill_id, caster) then return false end local target = caster:get_target() local success, result = Magic.get_magic_location(skill_data.target_type, skill_data.range, caster, params.triggered_by, target, skill_data.ai_check_ranged_if_self, skill_data.on_choose_target) if not success then return false end params = table.merge(params, result) if caster:is_player() or use_mp then if caster:is_player() then local stock = caster:spell_stock(skill_id) stock = math.max(stock - Skill.calc_spell_stock_cost(skill_id, caster), 0) caster:set_spell_stock(skill_id, stock) end local mp_used = Skill.calc_actual_spell_mp_cost(skill_id, caster) caster:damage_mp(mp_used, false, true) if not Chara.is_alive(caster) then return true end end if caster:has_effect("elona.confusion") or caster:has_effect("elona.dimming") then Gui.mes_visible("action.cast.confused", caster.x, caster.y, caster) local read_success = ElonaMagic.try_to_read_spellbook(caster, skill_data.difficulty, caster:skill_level(skill_data._id)) if not read_success then return true end else local cast_style = "ui.cast_style." .. (caster:calc("cast_style") or "default") if caster:is_player() then local skill_name = I18N.localize("base.skill", skill_id, "name") Gui.mes_visible("action.cast.self", caster.x, caster.y, caster, skill_name, cast_style) else Gui.mes_visible("action.cast.other", caster.x, caster.y, caster, cast_style) end end if caster:get_buff("elona.mist_of_silence") ~= nil then Gui.mes_visible("action.cast.silenced", caster) return true end if Rand.rnd(100) >= Skill.calc_spell_success_chance(skill_id, caster) then if caster:is_in_fov() then Gui.mes("action.cast.fail", caster) local cb = Anim.failure_to_cast(caster.x, caster.y) Gui.start_draw_callback(cb) end return true end if params.no_effect then Gui.mes("common.nothing_happens") return true end local enc = caster:find_merged_enchantment("elona.power_magic") if enc then params.power = params.power * (100 + enc.total_power / 10) / 100 end local rapid_magic if caster:calc("can_cast_rapid_magic") and skill_data.is_rapid_magic then rapid_magic = 1 + (Rand.one_in(3) and 1 or 0) + (Rand.one_in(2) and 1 or 0) end if rapid_magic then for i = 1, rapid_magic do Magic.cast(skill_data.effect_id, params) if not Chara.is_alive(params.target) then local target = Action.find_target(caster) if target == nil or caster:relation_towards(target) > Enum.Relation.Enemy then break else params.target = target end end end else Magic.cast(skill_data.effect_id, params) end return true -- <<<<<<<< elona122/shade2/proc.hsp:1350 return true .. end local function gain_spell_and_casting_experience(skill_id, caster) local skill_entry = data["base.skill"]:ensure(skill_id) if caster:is_player() then Skill.gain_skill_exp(caster, skill_id, skill_entry.cost * 4 + 20, 4, 5) end Skill.gain_skill_exp(caster, "elona.casting", skill_entry.cost + 10, 5) end function ElonaMagic.cast_spell(skill_id, caster, use_mp) local success = ElonaMagic.do_cast_spell(skill_id, caster, use_mp) if success then gain_spell_and_casting_experience(skill_id, caster) return true end return false end function ElonaMagic.do_action(skill_id, caster) -- >>>>>>>> shade2/proc.hsp:1539 *action ... -- TODO: action: death word -- local skill_data = data["base.skill"]:ensure(skill_id) local params = { triggered_by = "action", curse_state = "normal", power = Skill.calc_spell_power(skill_id, caster), range = skill_data.range } local target = caster:get_target() local success, result = Magic.get_magic_location(skill_data.target_type, skill_data.range, caster, "action", target, skill_data.ai_check_ranged_if_self, skill_data.on_choose_target) if not success then return false end params = table.merge(params, result) if skill_data.target_type ~= "self_or_nearby" and skill_data.target_type ~= "self" then if caster:has_effect("elona.confusion") or caster:has_effect("elona.blindness") then if Rand.one_in(5) then Gui.mes_visible("misc.shakes_head", caster.x, caster.y, caster) return true end end end if skill_data.type == "action" then local success = Effect.do_stamina_check(caster, skill_data.cost, skill_data.related_skill) if not success then Gui.mes("magic.common.too_exhausted") return true end end params.range = skill_data.range params.power = Skill.calc_spell_power(skill_id, caster) if params.no_effect and not skill_data.ignore_missing_target then Gui.mes("common.nothing_happens") return true end local did_something = Magic.cast(skill_data.effect_id, params) return did_something -- <<<<<<<< shade2/proc.hsp:1557 return true .. end function ElonaMagic.apply_buff(buff_id, params) -- >>>>>>>> shade2/proc.hsp:1664 if buffType(p)=buffBless:animeLoad 11,tc:else:if .. local buff = data["elona_sys.buff"]:ensure(buff_id) local target = params.target local source = params.source if buff.type == "blessing" then local cb = Anim.load("elona.anim_buff", target.x, target.y) Gui.start_draw_callback(cb) elseif buff.type == "hex" then local cb = Anim.heal(target.x, target.y, "base.curse_effect", "base.curse1", -1) Gui.start_draw_callback(cb) end if buff.target_rider then -- TODO riding end assert(buff.params, ("Buff '%s' missing 'params' callback"):format(buff_id)) local power = buff:params(params) params.buff = power local buff_data = Effect.add_buff(target, source, buff_id, power.power, power.duration) if buff_data and buff.on_add then buff.on_add(buff_data, params) end return buff_data -- <<<<<<<< shade2/proc.hsp:1682 goto *effect_end .. end function ElonaMagic.read_spellbook(item, skill_id, params) -- >>>>>>>> shade2/proc.hsp:1168 *readSpellbook .. local chara = params.chara or item:get_owning_chara() if chara:has_effect("elona.blindness") then Gui.mes_visible("action.read.cannot_see", chara) return "turn_end" end local skill_data = data["base.skill"]:ensure(skill_id) local sep = item:separate() assert(Item.is_alive(sep)) chara:set_item_using(sep) local turns = skill_data.difficulty / (2 * chara:skill_level("elona.literacy")) + 1 chara:start_activity("elona.reading_spellbook", { skill_id = skill_id, spellbook = sep }, turns) return "turn_end" -- <<<<<<<< shade2/proc.hsp:1191 } .. end return ElonaMagic
require 'util' local execute = vim.api.nvim_command function setup_markdown() opt('o', 'colorcolumn', '81') opt('o', 'textwidth', 80) execute(':setlocal spell') execute(':hi ColorColumn ctermbg=grey guibg=grey') end function remove_newlines(s) return string.gsub(s, '\n', '') end
-- ----------------------------------------------------------------------------- -- Star Wars: Imperial Assault - Skirmish -- by Ikon -- ----------------------------------------------------------------------------- local UTILS = require("swia-skirmish-tts/modules/common/utils") local Logger = require("swia-skirmish-tts/modules/common/logger") local logger = Logger:create("overlay", "Pink"):setState(false) -- ----------------------------------------------------------------------------- -- XML templating -- ----------------------------------------------------------------------------- local XML_HEADER = [[ <Defaults> <Button onClick="onClick" fontStyle="Bold" textColor="black" color="#00000000" /> </Defaults> ]] local XML_PANEL = [[ <Panel position="0 0 -%d" rotation="%d 270 90" scale="0.2 0.2"> <Panel height="%d" width="%d" position="0 %d 0"> <HorizontalLayout spacing="5">%s</HorizontalLayout> </Panel> </Panel> ]] local XML_BUTTON = [[ <Button id="%s" color="#FFFFFF00" active="true"><Image image="%s" preserveAspect="true"></Image></Button> ]] -- ----------------------------------------------------------------------------- -- Overlay -- ----------------------------------------------------------------------------- local Overlay = {} Overlay.__index = Overlay Overlay.CURRENT_VERSION = "1.0.0" Overlay.FOCUSED = "token_condition_beneficial_focused" Overlay.HIDDEN = "token_condition_beneficial_hidden" Overlay.BLEEDING = "token_condition_harmful_bleeding" Overlay.STUNNED = "token_condition_harmful_stunned" Overlay.WEAKENED = "token_condition_harmful_weakened" Overlay.BLOCK = "token_power_block" Overlay.DAMAGE = "token_power_damage" Overlay.EVADE = "token_power_evade" Overlay.SURGE = "token_power_surge" Overlay.RECON = "token_recon" Overlay.POWER = "token_power" function Overlay:create(json) logger:debug({json}, "Overlay:create") local obj = {} setmetatable(obj, Overlay) obj.symbols = {} if json ~= nil then data = JSON.decode(json) or {} if data.version == Overlay.CURRENT_VERSION then obj.symbols = data.symbols end end return obj end function Overlay:toJson() return JSON.encode({ version = Overlay.CURRENT_VERSION, symbols = self.symbols }) end function Overlay:_allowMultiple(symbol) return string.match(symbol, Overlay.POWER) ~= nil end function Overlay:add(symbol) logger:debug({self, #self.symbols, symbol}, "Overlay:add") if not self:_allowMultiple(symbol) then for _, sym in ipairs(self.symbols) do if symbol == sym then return false end end end table.insert(self.symbols, symbol) logger:debug({self, symbol}, "Overlay:add") return true end function Overlay:remove(symbol) logger:debug({self, symbol}, "Overlay:remove") for i, sym in ipairs(self.symbols) do if symbol == sym then table.remove(self.symbols, i) logger:debug({self, symbol, i}, "Overlay:remove") return true end end return false end function Overlay:size() logger:debug({self}, "Overlay:size") return #self.symbols end function Overlay:_createPanelXML(height, width, rotation) table.sort(self.symbols) logger:debug({self, #self.symbols, height, rotation}, "Overlay:_createPanelXML") local btn_xml1 = "" local btn_xml2 = "" for _, symbol in ipairs(self.symbols) do local button = string.format(XML_BUTTON, symbol, symbol) btn_xml1 = btn_xml1..button btn_xml2 = button..btn_xml2 end local xml = XML_HEADER local size = self:size() xml = xml..string.format(XML_PANEL, height, rotation, width, size*width, height, btn_xml1) rotation = UTILS.round(math.fmod(rotation + 180, 360), 1) xml = xml..string.format(XML_PANEL, height, rotation, width, size*width, height, btn_xml2) return xml end function Overlay:apply(object, height, width) logger:debug({self, object, height}, "Overlay:apply") if object ~= nil then local rotation = UTILS.round(math.fmod(object.getRotation().y + 270, 360), 1) local xml = self:_createPanelXML(height, width, rotation) logger:debug({xml}, "Overlay:apply") object.UI.setXml(xml) end end return Overlay
require "SvgWriter" require "vmath" require "Viewport" require "SubImage" require "GridAxis" require "PixelImage" require "_utils" -- Sizing local imageSize = vmath.vec2(400, 400); local subImages = SubImage.SubImage(1, 1, imageSize.x, imageSize.y, 0, 50); local coordSize = 6; local coordWidth = coordSize * (imageSize.x / imageSize.y); --image local image = PixelImage.PixelImage("NearestSampleDiag.txt") local pixelSize = image:Size(); pixelSize = pixelSize / 2; pixelSize.y = pixelSize.y; local vp = Viewport.Viewport(imageSize, pixelSize, image:Size()) local trans2 = Viewport.Transform2D() vp:SetTransform(trans2); --styles local styleLib = SvgWriter.StyleLibrary(); image:Style(styleLib); styleLib:AddStyle(nil, "grid", SvgWriter.Style():stroke("#888"):stroke_width("1.5px"):fill("none")); styleLib:AddStyle(nil, "sample_box", SvgWriter.Style():stroke("red"):stroke_width("7px"):stroke_opacity(0.7) :stroke_linejoin("round"):fill("none")); styleLib:AddStyle(nil, "sample_pt", SvgWriter.Style():stroke("none"):fill("goldenrod")); --Sample point. local samplePt = vmath.vec2(1.75, 1.75); local pts = { samplePt - vmath.vec2(0.4, 0.4), samplePt + vmath.vec2(0.4, 0.4), } pts = vp:Transform(pts); local pathSampleArea = SvgWriter:Path(); pathSampleArea :M(pts[1]) :L{pts[1].x, pts[2].y} :L(pts[2]) :L{pts[2].x, pts[1].y} :Z() samplePt = vp:Transform(samplePt); local ptRadius = vp:Length(0.05) local writer = SvgWriter.SvgWriter(ConstructSVGName(arg[0]), {subImages:Size().x .."px", subImages:Size().y .. "px"}); writer:StyleLibrary(styleLib); writer:BeginDefinitions(); writer:EndDefinitions(); image:Draw(writer, vmath.vec2(0, 0), subImages:Size(), {"grid"}); writer:Path(pathSampleArea, {"sample_box"}) writer:Circle(samplePt, ptRadius, {"sample_pt"}) writer:Close();
ModelConfig = { } ModelConfig[10001]={id=10001,remark='骷髅模型1',path='modelprefabs/Role_Mimi',ccHeight=2.6,ccRadius=0.3} ModelConfig[10002]={id=10002,remark='骷髅模型2',path='modelprefabs/Player_002',ccHeight=2.6,ccRadius=0.3} ModelConfig[10003]={id=10003,remark='骷髅模型3',path='modelprefabs/Player_001',ccHeight=2.6,ccRadius=0.3} ModelConfig[10004]={id=10004,remark='骷髅模型4',path='modelprefabs/Player_001',ccHeight=2.6,ccRadius=0.3} ModelConfig[10005]={id=10005,remark='骷髅模型5',path='modelprefabs/Player_001',ccHeight=2.6,ccRadius=0.3} ModelConfig[10006]={id=10006,remark='骷髅模型6',path='modelprefabs/Player_001',ccHeight=2.6,ccRadius=0.3} ModelConfig[10007]={id=10007,remark='骷髅模型7',path='modelprefabs/Player_001',ccHeight=2.6,ccRadius=0.3} ModelConfig[10008]={id=10008,remark='骷髅模型8',path='modelprefabs/Player_001',ccHeight=2.6,ccRadius=0.3} ModelConfig[10009]={id=10009,remark='骷髅模型9',path='modelprefabs/Player_001',ccHeight=2.6,ccRadius=0.3} ModelConfig[10010]={id=10010,remark='骷髅模型10',path='modelprefabs/Player_001',ccHeight=2.6,ccRadius=0.3}
return recursivedtrequire("components", "components")
local t = Def.ActorFrame{ LoadActor("mid")..{ InitCommand=cmd(CenterX); }; --[[LoadFont("Common Normal") .. { InitCommand=cmd(CenterX;addx,-100;addy,-10); --Text="asduahshdiaufhaifjaifujiasdjs"; CurrentSongChangedMessageCommand=cmd(playcommand,"Refresh"); RefreshCommand=function(self) local vSong = GAMESTATE:GetCurrentSong(); local vCourse = GAMESTATE:GetCurrentCourse(); local sText = "" if vSong then sText = vSong:GetDisplayFullTitle() .. "\n" .. vSong:GetDisplayArtist() end if vCourse then sText = vSong:GetDisplayFullTitle() .. "\n" .. vSong:GetDisplayArtist() end self:settext( sText ); self:horizalign(left); self:playcommand( "On" ); self:strokecolor(color("#000000")); self:maxwidth(376); end; };]] Def.TextBanner{ InitCommand = function(self) self:Load("TextBannerGameplay") :x(SCREEN_CENTER_X-170):y(-14) if GAMESTATE:IsAnExtraStage() then self:zoomy(-1) end if GAMESTATE:GetCurrentSong() then self:SetFromSong(GAMESTATE:GetCurrentSong()) end end; CurrentSongChangedMessageCommand = function(self) self:SetFromSong(GAMESTATE:GetCurrentSong()) end; }; }; if GAMESTATE:IsPlayerEnabled('PlayerNumber_P1') then --P1 Score Frame t[#t+1]=Def.ActorFrame{ InitCommand=cmd(addy,-14); Def.Quad{ InitCommand=cmd(halign,0;x,SCREEN_LEFT;setsize,388,32;diffuse,color("#666666")); }; Def.Quad{ InitCommand=cmd(halign,0;x,SCREEN_LEFT;setsize,382,28;diffuse,color("0,0,0,1")); }; }; end; if GAMESTATE:IsPlayerEnabled('PlayerNumber_P2') then t[#t+1]=Def.ActorFrame{ InitCommand=cmd(addy,-14); Def.Quad{ InitCommand=cmd(halign,1;x,SCREEN_RIGHT;setsize,388,32;diffuse,color("#666666")); }; Def.Quad{ InitCommand=cmd(halign,1;x,SCREEN_RIGHT;setsize,382,28;diffuse,color("0,0,0,1")); }; }; end; return t;
-- Class "Module" local M = {} function M:new (mass) local t = {} t.mass = mass self.__index = self setmetatable(t, self) return t end function M:getfuelrequired () return math.floor(self.mass / 3) - 2 end -- Humble unit testing if not pcall(debug.getlocal, 4, 1) then local testset = { { mass = 12, fuel = 2 }, { mass = 14, fuel = 2 }, { mass = 1969, fuel = 654 }, { mass = 100756, fuel = 33583 } } for _, test in pairs(testset) do local fuel = M:new(test.mass):getfuelrequired() assert(fuel == test.fuel, string.format("Fuel required %d does not match expected value %d", fuel, test.fuel)) end end return M
local utils = require "utils" local function find_corrupted(str) local stack = {} for i = 1, #str do local char = str:sub(i, i) if char == "(" or char == "[" or char == "{" or char == "<" then table.insert(stack, char) elseif char == ")" and stack[#stack] ~= "(" then return 3 elseif char == "]" and stack[#stack] ~= "[" then return 57 elseif char == "}" and stack[#stack] ~= "{" then return 1197 elseif char == ">" and stack[#stack] ~= "<" then return 25137 else table.remove(stack) end end return 0 end local function solve_part_1(lines) local score = 0 for _, line in ipairs(lines) do score = score + find_corrupted(line) end return score end local function discard_corrupted(lines) local filtered = {} for _, line in ipairs(lines) do if find_corrupted(line) == 0 then table.insert(filtered, line) end end return filtered end local function discard_pairs(line) local stack = {} for i = 1, #line do local char = line:sub(i, i) if char == "(" or char == "[" or char == "{" or char == "<" then table.insert(stack, char) else table.remove(stack) end end return stack end local function score_completion(line) local score = 0 for i = #line, 1, -1 do local char = line[i] if char == "(" then score = score * 5 + 1 elseif char == "[" then score = score * 5 + 2 elseif char == "{" then score = score * 5 + 3 elseif char == "<" then score = score * 5 + 4 else error("Invalid open character") end end return score end local function solve_part_2(lines) local incomplete = discard_corrupted(lines) local scores = {} for _, line in ipairs(incomplete) do local opening = discard_pairs(line) table.insert(scores, score_completion(opening)) end table.sort(scores) return scores[math.ceil(#scores / 2)] end local input_lines = utils.read_file_lines("day_10.txt") print("Part 1: " .. solve_part_1(input_lines)) print("Part 2: " .. solve_part_2(input_lines))
function ShadeColor(c) local rgb = { ParseColor(c) } -- SKIN:Bang('!Log', table.concat(rgb, ','), 'Debug') local hsv = { tonumber(getHue(rgb) * 6), tonumber(getSat(rgb)), tonumber(getVal(rgb)) } if (hsv[3] < 0.45 and percent < 0.55) or percent > 0.5 then hsv[3] = hsv[3] + percent else hsv[3] = hsv[3] - percent end return HSVtoRGB(hsv) end--apply shaded function InvertColor(c) local rgb = { ParseColor(c) } -- SKIN:Bang('!Log', table.concat(rgb, ','), 'Debug') local hsv = { tonumber(getHue(rgb) * 6), tonumber(getSat(rgb)), tonumber(getVal(rgb)) } if hsv[3] > 0.25 and hsv[3] < 0.75 then if hsv[3] > 0.5 then hsv[3] = hsv[3] + (0.5-hsv[3]) - 0.25 else hsv[3] = hsv[3] + (0.5-hsv[3]) + 0.25 end else hsv[3] = math.abs(hsv[3]-1) end return HSVtoRGB(hsv) end function ParseColor(c) --parse color segments from string 'c' then return table of 3 numbers (base 10) -- SKIN:Bang('!Log', c, 'Debug') local rgb = {} if string.find(c, ',') == nil then --assumes a 6 digit hex code rgb[1] = tonumber(string.sub(c, 1, 2), 16) rgb[2] = tonumber(string.sub(c, 3, 4), 16) rgb[3] = tonumber(string.sub(c, 5, 6), 16) else --find comma & extract substring local comma = string.find(c, ",") rgb[1] = tonumber(string.sub(c, 1, (comma-1)), 10) --find 2nd comma & extract substring comma = string.find(c, ",", comma) rgb[2] = tonumber(string.sub(c, comma+1, string.find(c, ",", comma+1)-1), 10) --extract substring from last comma to string.len(c) comma = string.find(c, ",", comma+1) rgb[3] = tonumber(string.sub(c, comma+1, -1), 10) end--end make table of {red, green, blue} return rgb[1], rgb[2], rgb[3] end--end parse color function getHue(rgb) local hue -- SKIN:Bang('!Log', table.concat(rgb, ','), 'Debug') if (2*rgb[1]-rgb[2]-rgb[3]) == 0 then hue = 0 else hue = math.atan2((math.sqrt(3)*(rgb[2]-rgb[3])), (2*rgb[1]-rgb[2]-rgb[3])) end if hue < 0.0 then hue = hue + 6 end return hue / 6 end function getSat(rgb) local Min = math.min(tonumber(rgb[1]), tonumber(rgb[2]), tonumber(rgb[3])) / 255 local Max = math.max(tonumber(rgb[1]), tonumber(rgb[2]), tonumber(rgb[3])) / 255 --chroma = max - min unles max == 0 if Max == 0 then return 0 else return (Max - Min) / Max end end function getVal(rgb) local Max = math.max(tonumber(rgb[1]), tonumber(rgb[2]), tonumber(rgb[3])) / 255 return Max end function HSVtoRGB(hsv) local chroma = hsv[3] * hsv[2] local mid = chroma * (1 - math.abs(hsv[1] % 2 - 1)) local Match = hsv[3] - chroma --[[for Debug SKIN:Bang('!Log', "h = " .. hsv[1], 'Debug') SKIN:Bang('!Log', "Chroma = " .. chroma, 'Debug') SKIN:Bang('!Log', "mid = " .. mid, 'Debug') SKIN:Bang('!Log', "match = " .. Match, 'Debug') ]]-- local newRGB = {} if 0 <= hsv[1] and hsv[1] < 1 then newRGB[1] = math.floor((255 * (chroma + Match)) + 0.5) newRGB[2] = math.floor((255 * (mid + Match)) + 0.5) newRGB[3] = math.floor((255 * (0 + Match)) + 0.5) elseif 1 <= hsv[1] and hsv[1] < 2 then newRGB[1] = math.floor((255 * (mid + Match)) + 0.5) newRGB[2] = math.floor((255 * (chroma + Match)) + 0.5) newRGB[3] = math.floor((255 * (0 + Match)) + 0.5) elseif 2 <= hsv[1] and hsv[1] < 3 then newRGB[1] = math.floor((255 * (0 + Match)) + 0.5) newRGB[2] = math.floor((255 * (chroma + Match)) + 0.5) newRGB[3] = math.floor((255 * (mid + Match)) + 0.5) elseif 3 <= hsv[1] and hsv[1] < 4 then newRGB[1] = math.floor((255 * (0 + Match)) + 0.5) newRGB[2] = math.floor((255 * (mid + Match)) + 0.5) newRGB[3] = math.floor((255 * (chroma + Match)) + 0.5) elseif 4 <= hsv[1] and hsv[1] < 5 then newRGB[1] = math.floor((255 * (mid + Match)) + 0.5) newRGB[2] = math.floor((255 * (0 + Match)) + 0.5) newRGB[3] = math.floor((255 * (chroma + Match)) + 0.5) elseif 5 <= hsv[1] and hsv[1] <= 6 then newRGB[1] = math.floor((255 * (chroma + Match)) + 0.5) newRGB[2] = math.floor((255 * (0 + Match)) + 0.5) newRGB[3] = math.floor((255 * (mid + Match)) + 0.5) end--set newRGB table return table.concat(newRGB, ',') end function convertAlpha(d) --can be used to compensate the alpha value of a color if said color is changed from dec -> hex SKIN:Bang('!SetVariable', 'ConvertedAlpha', string.format("%02x", d) ) end function Initialize() alpha = tonumber(SKIN:GetVariable('ClockAlpha')) percent = tonumber(SELF:GetOption('Percent')) end -- make sure any hex color code is saved as rgb color code function forceRGB(c) local rgb = { ParseColor(c) } return table.concat(rgb, ',') end function Update() local color1 = tostring(SELF:GetOption('Color1')) local color2 = tostring(SELF:GetOption('Color2')) local seconds = tostring(SKIN:GetVariable('SecondsColor')) local minutes = tostring(SKIN:GetVariable('MinutesColor')) local hours = tostring(SKIN:GetVariable('HoursColor')) local bgColor = tostring(SKIN:GetVariable('BGColor')) if color1 ~= "nil" then SKIN:Bang('!SetVariable', 'Color1Shadow', ShadeColor(color1)) end if color2 ~= "nil" then SKIN:Bang('!SetVariable', 'Color2Shadow', ShadeColor(color2)) end if seconds ~= "nil" then SKIN:Bang('!SetVariable', 'SecondsColorShadow', ShadeColor(seconds)) end if minutes ~= "nil" then SKIN:Bang('!SetVariable', 'MinutesColorShadow', ShadeColor(minutes)) end if hours ~= "nil" then SKIN:Bang('!SetVariable', 'HoursColorShadow', ShadeColor(hours)) end if bgColor ~= "nil" then SKIN:Bang('!SetVariable', 'ClockColor', InvertColor(bgColor)) end return forceRGB(bgColor) end
AddCSLuaFile( "shared.lua" ); AddCSLuaFile( "cl_init.lua" ); include( "shared.lua" ); function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS; end
-- config (client) local cacheMessages = { -- Crate Event "Found a drop, sent it to your GPS. Others will be looking for it, too.", "Got a hit on a drop, it's on your GPS. Better find it before someone else.", "Drop Located. Sent coords to your GPS. First come first serve, get going.", "Got another hit on a drop, better get moving. You're not alone.", "Another drop coming your way, better get on it." } function RandomCacheMessage() return cacheMessages[math.random(#cacheMessages)] end -- Draws text on screen as positional function DrawText3D(x, y, z, text) SetDrawOrigin(x, y, z, 0); BeginTextCommandDisplayText("STRING") SetTextScale(0.3, 0.3) SetTextFont(0) SetTextProportional(1) SetTextColour(80, 255, 80, 140) SetTextDropshadow(0, 0, 0, 0, 140) SetTextEdge(2, 0, 0, 0, 150) SetTextDropShadow() SetTextOutline() SetTextCentre(1) AddTextComponentString(text) DrawText(0.0, 0.0) ClearDrawOrigin() end
CLinear = torch.class('CLinear') function CLinear:__init(nInputs) self.nInputs = nInputs self.teTheta = torch.zeros(1, nInputs + 1) self.teGradTheta = torch.zeros(self.teTheta:size()) end function CLinear:predict(teInput) local teV1 = torch.Tensor(teInput:size(1), 1):fill(self.teTheta[1][1]) -- bias local teV2 = self.teTheta:narrow(2, 2, self.teTheta:size(2)-1):t() local teOutput = torch.addmm(teV1, teInput, teV2) return teOutput end function CLinear:train(teInput, teTarget) local teA = torch.cat(torch.ones(teInput:size(1), 1), teInput) local teB = teTarget local teX = torch.gels(teB, teA) self.teTheta:copy(teX) end function CLinear:getGradInput(teInput, teGradOutput) local teV2 = self.teTheta:narrow(2, 2, self.teTheta:size(2)-1) return torch.mm(teGradOutput, teV2) end function CLinear:getParamPointer() return self.teTheta end function CLinear:getGradParamPointer() return self.teGradTheta end function CLinear:accGradParameters(teInput, teGradOutput, scale) local teGrad = self.teGradTheta:narrow(2, 2, self.teGradTheta:size(2)-1) teGrad:addmm(scale, teGradOutput:t(), teInput) self.teGradTheta[1][1] = self.teGradTheta[1][1] + torch.sum(teGradOutput)*scale end
local class = require('middleclass') local NodeList = require('lash.core.NodeList') --[[ The default class for managing a NodeList. This class creates the NodeList and adds and removes nodes to/from the list as the entities and the components in the engine change. It uses the basic entity matching pattern of an entity system - entities are added to the list if they contain components matching all the public properties of the node class. ]] local ComponentMatchingFamily = class('ComponentMatchingFamily') --[[ The constructor. Creates a ComponentMatchingFamily to provide a NodeList for the given node class. @param nodespec (node table) The type of node to create and manage a NodeList for. @param engine (Engine) The engine that this family is managing teh NodeList for. ]] function ComponentMatchingFamily:initialize(nodespec, engine) self.nodespec = nodespec self.engine = engine self.nodes = NodeList() self.components = {} for k,v in pairs(nodespec) do self.components[v] = k end end --[[ ComponentMatchingFamily.nodes The nodelist managed by this family. This is a reference that remains valid always since it is retained and reused by Systems that use the list. i.e. we never recreate the list, we always modify it in place. ]] -- If the entity is not in this family's NodeList, tests the components of the entity to see -- if it should be in this NodeList and adds it if so. local function addIfMatch(self, entity) if self.nodes:has(entity) then return end for componentClass, _ in pairs(self.components) do if not entity:has(componentClass) then return end end local node = {} node.entity = entity for componentClass, field in pairs(self.components) do node[field] = entity:get(componentClass) end self.nodes:_add(node) end -- Removes the entity if it is in this family's NodeList. local function removeIfMatch(self, entity) local node = self.nodes:get(entity) if node then self.nodes:_remove(node) end end --[[ Called by the engine when an entity has been added to it. We check if the entity should be in this family's NodeList and add it if appropriate. ]] function ComponentMatchingFamily:newEntity(entity) addIfMatch(self, entity) end --[[ Called by the engine when a component has been added to an entity. We check if the entity is not in this family's NodeList and should be, and add it if appropriate. ]] function ComponentMatchingFamily:componentAddedToEntity(entity, componentClass) if self.components[componentClass] then addIfMatch(self, entity) end end --[[ Called by the engine when a component has been removed from an entity. We check if the removed component is required by this family's NodeList and if so, we check if the entity is in this this NodeList and remove it if so. ]] function ComponentMatchingFamily:componentRemovedFromEntity(entity, componentClass) if self.components[componentClass] then removeIfMatch(self, entity) end end --[[ Called by the engine when an entity has been rmoved from it. We check if the entity is in this family's NodeList and remove it if so. ]] function ComponentMatchingFamily:removeEntity(entity) removeIfMatch(self, entity) end --[[ Removes all nodes from the NodeList. ]] function ComponentMatchingFamily:cleanUp() self.nodes:_removeAll() end return ComponentMatchingFamily
--- The current list of jobs in the system. local jobList = { "builder", "crafter", "fisherman", "gatherer", "miner", "woodcutter", } --- Jobs jobs = {} --- Add a player to a job. function jobs:add(uuid, job, lvl) -- Make sure the player will not go -- over the max job limit in settings. if self:count(uuid) < settings.maxJobs then self[job][uuid] = lvl or 0 -- Default to zero. else return false end return true end --- Get the numbers of jobs a player has. function jobs:count(uuid) local c = 0 for i = 1, #jobList do if self[jobList[i]][uuid] then c = c + 1 end end return c end --- Dispatch a job. function jobs:dispatch(uuid, job, btype) if self:has(uuid, job) then return values:coin(job, btype) end return nil end --- Remove player from job. function jobs:drop(uuid, job) -- Set to nil and get cleaned up in -- garbage collection. self[job][uuid] = nil return true end --- Does the player have the job. function jobs:has(uuid, job) -- The same as == nil return self[job] and self[job][uuid] end --- Return a list of jobs for player id. function jobs:list(uuid, job) local s = {} for i = 1, #jobList do if self[jobList[i]][uuid] then table.insert(s, jobList[i]) end end return table.concat(s, ", ") end --- Get the player level for a job. function jobs:level(uuid, job) return self[job][uuid] end --- Level up a player in a job. function jobs:lvlPlayer(uuid, job) -- Get current job level. local lvl = self:level(uuid, job) -- Add a level. lvl = lvl + 1 -- Update the player's level. self[job][uuid] = lvl -- Return level. return lvl end --- Load the ini file into memory. function jobs:load() local file = cIniFile() -- Try to read settings.ini file. if file:ReadFile(f:path() .. 'jobs.ini') then -- Loop over job keys. for k = 0, (file:GetNumKeys() - 1) do -- Get the name of the job key. local job = file:GetKeyName(k) self[job] = {} -- Loop over the players and -- load their job levels into memory. for v = 0, (file:GetNumValues(k) - 1) do -- Get the uuid of the player. local uuid = file:GetValueName(k, v) -- Add to in-memory table. self[job][uuid] = file:GetValueI(k, v) end end return true end return false end --- Save player jobs to the ini file. function jobs:save() local file = cIniFile() for i = 1, #jobList do local job = jobList[i] local k = file:AddKeyName(job) for uuid, lvl in pairs(jobs[job]) do file:SetValueI(job, uuid, lvl, true) end end if file:WriteFile(f:path() .. 'jobs.ini') then f:log("jobs.ini file saved.") else f:log("unable to save jobs.ini file.") end end return jobs
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by shuieryin. --- DateTime: 12/01/2018 9:14 PM --- function polyFeatures(X, p) --POLYFEATURES Maps X (1D vector) into the p-th power -- [X_poly] = POLYFEATURES(X, p) takes a data matrix X (size m x 1) and -- maps each example into its polynomial features where -- X_poly(i, :) = [X(i) X(i).^2 X(i).^3 ... X(i).^p]; -- You need to return the following variables correctly. local X_poly = torch.zeros(X:numel(), p) -- ====================== YOUR CODE HERE ====================== -- Instructions: Given a vector X, return a matrix X_poly where the p-th -- column of X contains the values of X to the p-th power. -- ========================================================================= return X_poly end
AddCSLuaFile( "cl_init.lua" ) -- Make sure clientside AddCSLuaFile( "shared.lua" ) -- and shared scripts are sent. include('shared.lua')