repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
ILOVEPIE/Cxbx-Reloaded
src/CxbxDebugger/Form1.cs
39647
// Written by x1nixmzeng for the Cxbx-Reloaded project // using System; using System.Windows.Forms; using System.Threading; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using cs_x86; namespace CxbxDebugger { public partial class Form1 : Form { Thread DebuggerWorkerThread; Debugger DebuggerInst; string[] CachedArgs; string CachedTitle = ""; bool SuspendedOnBp = false; DebuggerFormEvents DebugEvents; List<DebuggerThread> DebugThreads = new List<DebuggerThread>(); List<DebuggerModule> DebugModules = new List<DebuggerModule>(); DebuggerProcess MainProcess = null; FileWatchManager fileWatchMan; DebugOutputManager debugStrMan; PatchManager patchMan; List<DebuggerMessages.FileOpened> FileHandles = new List<DebuggerMessages.FileOpened>(); public Form1() { InitializeComponent(); // TODO: Cleanup arg handling string[] args = Environment.GetCommandLineArgs(); // Arguments are expected before the Form is created if (args.Length < 2) { throw new Exception("Incorrect usage"); } var items = new List<string>(args.Length - 1); for (int i = 1; i < args.Length; ++i) { items.Add(args[i]); } CachedArgs = items.ToArray(); DebugEvents = new DebuggerFormEvents(this); SetDebugProcessActive(false); txDisassembly.InlineLinkClicked += OnDisassemblyNavigation; foreach (string FileEventEnum in Enum.GetNames(typeof(FileEventType))) { cbAction.Items.Add(FileEventEnum); } cbAction.SelectedIndex = 0; foreach (string VariableEnum in Enum.GetNames(typeof(PatchType))) { cbDataFormat.Items.Add(VariableEnum); } cbDataFormat.SelectedIndex = 0; InvokePatchTypeChange(); fileWatchMan = new FileWatchManager(clbBreakpoints); debugStrMan = new DebugOutputManager(lbDebug); patchMan = new PatchManager(); } private void OnDisassemblyNavigation(object sender, InlineLinkClickedEventArgs e) { // TODO: Switch to memory region Console.WriteLine("Attempting to view memory at " + e.Link); ShowDisassemblyAt(e.Link); } private void StartDebugging() { bool Create = false; if (DebuggerWorkerThread == null) { // First launch Create = true; } else if (DebuggerWorkerThread.ThreadState == ThreadState.Stopped) { // Further launches Create = true; } if (Create) { // Create debugger instance DebuggerInst = new Debugger(CachedArgs); DebuggerInst.RegisterEventInterfaces(DebugEvents); DebuggerInst.RegisterEventInterfaces(patchMan); // Setup new debugger thread DebuggerWorkerThread = new Thread(x => { if (DebuggerInst.Launch()) { DebuggerInst.RunThreaded(); } }); DebuggerWorkerThread.Name = "CxbxDebugger"; DebuggerWorkerThread.Start(); } } private void PopulateThreadList(ToolStripComboBox cbItems, DebuggerThread FocusThread) { cbItems.Items.Clear(); uint AutoThreadId = DebugThreads[0].OwningProcess.MainThread.ThreadID; if (FocusThread != null) AutoThreadId = FocusThread.ThreadID; int AutoIndex = 0; foreach (DebuggerThread Thread in DebugThreads) { bool IsMainThread = (Thread.Handle == Thread.OwningProcess.MainThread.Handle); bool IsFocusThread = (FocusThread != null) && (Thread.Handle == FocusThread.Handle); string PrefixStr = ""; // Threads with focus are marked differently if (IsFocusThread) PrefixStr = "* "; // Main threads always override any existing prefix if (IsMainThread) PrefixStr = "> "; string DisplayStr = string.Format("{0}[{1}] ", PrefixStr, (uint)Thread.Handle); // Resolve thread name if (IsMainThread) { DisplayStr += "Main Thread"; } else if (Thread.DebugName != null) { DisplayStr += Thread.DebugName; } else { string fn = Path.GetFileName(Thread.OwningProcess.Path); DisplayStr += string.Format("{0}!{1:X8}", fn, (uint)Thread.StartAddress); } // Check if the thread is already suspended if (Thread.WasSuspended) { DisplayStr += " (suspended)"; } if (AutoThreadId == Thread.ThreadID) { AutoIndex = cbItems.Items.Count; } cbItems.Items.Add(DisplayStr); } // Auto-select this thread cbItems.SelectedIndex = AutoIndex; } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (DebuggerWorkerThread != null) { if (DebuggerWorkerThread.ThreadState == ThreadState.Running) { DebuggerWorkerThread.Abort(); } } if (DebuggerInst != null) { DebuggerInst.Dispose(); } } private void OutputString(string Message) { debugStrMan.AddLine(Message); } private void DebugLog(string Message) { string MessageStamped = string.Format("[{0}] {1}", DateTime.Now.ToLongTimeString(), Message); if (InvokeRequired) { // Ensure we Add items on the right thread Invoke(new MethodInvoker(delegate () { lbConsole.Items.Insert(0, MessageStamped); })); } else { lbConsole.Items.Insert(0, MessageStamped); } } private void DebugFileEvent(FileEvents Event) { Invoke(new MethodInvoker(delegate () { lvFileDetails.BeginUpdate(); { var lvi = lvFileDetails.Items.Insert(0, Event.Type.ToString()); lvi.SubItems.Add(Event.Name); switch (Event.Type) { case FileEventType.Read: case FileEventType.Write: string text = string.Format("{0} bytes", Event.Length.ToString()); if (Event.Offset != uint.MaxValue) { text += string.Format(" from offset {0}", Event.Offset); } lvi.SubItems.Add(text); break; case FileEventType.FailedOpen: lvi.SubItems.Add("Failed to open file"); break; } } lvFileDetails.EndUpdate(); switch (Event.Type) { case FileEventType.Opened: case FileEventType.Closed: case FileEventType.FailedOpen: { lbOpenedFiles.BeginUpdate(); lbOpenedFiles.Items.Clear(); foreach (DebuggerMessages.FileOpened FOpen in FileHandles) { lbOpenedFiles.Items.Add(FOpen.FileName); } lbOpenedFiles.EndUpdate(); } break; } })); // TODO: Move to breakpoint manager if (fileWatchMan.Match(Event)) { if (DebuggerInst != null) { Invoke(new MethodInvoker(delegate () { Suspend("file open"); })); } } } private void DebugTitle(string Title) { Invoke(new MethodInvoker(delegate () { CachedTitle = Title; Text = string.Format("{0} - Cxbx-Reloaded Debugger", CachedTitle); // This is done too late - modules are already loaded //LoadCheatTable(string.Format("{0}.ct", CachedTitle)); })); } private bool DebugAsk(string Message) { return MessageBox.Show(Message, "Cxbx Debugger", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; } private void DebugBreakpoint(DebuggerModule Module, uint Address) { Invoke(new MethodInvoker(delegate () { SuspendedOnBp = true; bool auto_resume = true; if (cbBreakpointAll.Checked == false) { // Ignore all submodule breakpoints // (effectively triggers from Cxbx.exe and default.xbe) if (cbBreakpointCxbx.Checked) { auto_resume = (!Module.Core); } } if (auto_resume) { Resume(); } else { string module_name = Path.GetFileName(Module.Path); Suspend(string.Format("Breakpoint hit in {0} at 0x{1:x}", module_name, Address)); // Forces a refresh at the breakpoint address (not the callstack trace) DumpDisassembly(Address); } })); } private void SetDebugProcessActive(bool Active) { if (InvokeRequired) { Invoke(new MethodInvoker(delegate () { // Disable when active btnStart.Enabled = !Active; // Enable when active btnSuspend.Enabled = Active; btnResume.Enabled = Active; lblStatus.Text = (Active ? "Running" : "Inactive"); })); } else { // Disable when active btnStart.Enabled = !Active; // Enable when active btnSuspend.Enabled = Active; btnResume.Enabled = Active; lblStatus.Text = (Active ? "Running" : "Inactive"); } } private void btnClearLog_Click(object sender, EventArgs e) { lbConsole.Items.Clear(); } class DebuggerFormEvents : IDebuggerGeneralEvents, IDebuggerProcessEvents, IDebuggerModuleEvents, IDebuggerThreadEvents, IDebuggerOutputEvents, IDebuggerExceptionEvents, IDebuggerFileEvents { Form1 frm; public DebuggerFormEvents(Form1 main) { frm = main; } public void OnProcessCreate(DebuggerProcess Process) { frm.DebugModules.Add(Process); frm.MainProcess = Process; } public void OnProcessExit(DebuggerProcess Process, uint ExitCode) { int remainingThreads = Process.Threads.Count; frm.DebugLog(string.Format("Process exited {0} ({1})", Process.ProcessID, NtStatus.PrettyPrint(ExitCode))); frm.DebugLog(string.Format("{0} child thread(s) remain open", remainingThreads)); frm.DebugModules.Clear(); // Ask to close if the process was forced to exit if (ExitCode == 1) { if (frm.DebugAsk("The debugger was detached from the host\n\nDo you want to close the debugger?")) { frm.Close(); } } } public void OnDebugStart() { frm.SetDebugProcessActive(true); frm.DebugLog("Started debugging session"); } public void OnDebugEnd() { frm.SetDebugProcessActive(false); frm.DebugLog("Ended debugging session"); } public void OnDebugTitleLoaded(string Title) { frm.DebugLog(string.Format("Loaded title \"{0}\"", Title)); frm.DebugTitle(Title); } public void OnThreadCreate(DebuggerThread Thread) { frm.DebugLog(string.Format("Thread created {0}", Thread.ThreadID)); frm.DebugThreads.Add(Thread); } public void OnThreadExit(DebuggerThread Thread, uint ExitCode) { frm.DebugLog(string.Format("Thread exited {0} ({1})", Thread.ThreadID, NtStatus.PrettyPrint(ExitCode))); frm.DebugThreads.Remove(Thread); } public void OnThreadNamed(DebuggerThread Thread) { frm.DebugLog(string.Format("Thread {0} named {1}", Thread.ThreadID, Thread.DebugName)); } public void OnModuleLoaded(DebuggerModule Module) { frm.DebugLog(string.Format("Loaded module \"{0}\"", Module.Path)); frm.DebugModules.Add(Module); } public void OnModuleUnloaded(DebuggerModule Module) { frm.DebugLog(string.Format("Unloaded module \"{0}\"", Module.Path)); frm.DebugModules.Remove(Module); } public void OnDebugOutput(string Message) { frm.OutputString(Message); } public bool OnAccessViolation(DebuggerThread Thread, uint Code, uint Address) { string ProcessName = "??"; var Module = frm.DebuggerInst.ResolveModule(Address); if (Module != null) { ProcessName = Path.GetFileName(Module.Path); } // TODO Include GetLastError string string ExceptionMessage = string.Format("Access violation thrown at 0x{0:X8} ({1})", Address, ProcessName); ExceptionMessage += string.Format("\n\nException code {0:X8}", Code); frm.DebugLog(ExceptionMessage); // Already suspended at this point, so we can rebuild the callstack list frm.PopulateThreadList(frm.cbThreads, Thread); ExceptionMessage += "\n\nAttempt to ignore this and risk crashing the app?"; return frm.DebugAsk(ExceptionMessage); } public void OnBreakpoint(DebuggerThread Thread, uint Address, uint Code, bool FirstChance) { frm.DebugLog(string.Format("Breakpoint hit at 0x{0:X8} with code {1:X8}", Address, Code)); var Module = frm.DebuggerInst.ResolveModule(Address); if (Module != null) { frm.DebugBreakpoint(Module, Address); } } public void OnFileOpened(DebuggerMessages.FileOpened Info) { if (Info.Succeeded) { frm.FileHandles.Add(Info); frm.DebugLog(string.Format("Opened file: \"{0}\"", Info.FileName)); frm.DebugFileEvent(FileEvents.Opened(Info.FileName)); } else { frm.DebugLog(string.Format("Opened file FAILED: \"{0}\"", Info.FileName)); frm.DebugFileEvent(FileEvents.OpenedFailed(Info.FileName)); } } public void OnFileRead(DebuggerMessages.FileRead Info) { var Found = frm.FileHandles.Find(FileInfo => FileInfo.Handle == Info.Handle); if (Found != null) { frm.DebugLog(string.Format("Reading {0} byte(s) from: {1}", Info.Length, Found.FileName)); frm.DebugFileEvent(FileEvents.Read(Found.FileName, Info.Length, Info.Offset)); } } public void OnFileWrite(DebuggerMessages.FileWrite Info) { var Found = frm.FileHandles.Find(FileInfo => FileInfo.Handle == Info.Handle); if (Found != null) { frm.DebugLog(string.Format("Writing {0} byte(s) to: {1}", Info.Length, Found.FileName)); frm.DebugFileEvent(FileEvents.Write(Found.FileName, Info.Length, Info.Offset)); } } public void OnFileClosed(DebuggerMessages.FileClosed Info) { var Found = frm.FileHandles.Find(FileInfo => FileInfo.Handle == Info.Handle); if (Found != null) { frm.FileHandles.Remove(Found); frm.DebugFileEvent(FileEvents.Closed(Found.FileName)); frm.DebugLog(string.Format("Closed file: \"{0}\"", Found.FileName)); } } } private void toolStripButton1_Click(object sender, EventArgs e) { StartDebugging(); } private void Suspend(string Reason) { if (DebuggerInst != null) { if (!SuspendedOnBp) { DebuggerInst.Break(); } // Update thread context cache DebuggerInst.Trace(); NativeWrappers.FlashWindowTray(Handle); PopulateThreadList(cbThreads, null); } lblStatus.Text = string.Format("Suspended ({0})", Reason); cbThreads.Enabled = true; cbFrames.Enabled = true; } private void Resume() { if (DebuggerInst != null) { if (SuspendedOnBp) { DebuggerInst.BreakpointContinue(); SuspendedOnBp = false; } else { DebuggerInst.Resume(); } } lblStatus.Text = "Running"; cbThreads.Enabled = false; cbFrames.Enabled = false; } private void toolStripButton2_Click(object sender, EventArgs e) { Suspend("manually triggered"); } private void toolStripButton3_Click(object sender, EventArgs e) { Resume(); } struct CallstackInfo { public uint InstructionPointer; public uint ModuleBase; public CallstackInfo(uint IP, uint Base) { InstructionPointer = IP; ModuleBase = Base; } }; List<CallstackInfo> CallstackDump = new List<CallstackInfo>(); static private bool ReadAddress(ComboBox Source, ref uint Out) { string SelString = Source.Text; if (Common.ReadHex(SelString, ref Out)) { // Only add new addresses if (Source.SelectedIndex == -1) { Source.Items.Insert(0, SelString); } return true; } return false; } private byte[] ReadMemory() { uint addr = 0; if (!Common.ReadHex(txAddress.Text, ref addr)) { return null; } int size = 0; Common.ReadNumeric(txSize.Text, ref size); if (size < 0) size = 256; // Pick any thread to find the owner process return DebugThreads[0].OwningProcess.ReadMemoryBlock(new IntPtr(addr), (uint)size); } private void button1_Click(object sender, EventArgs e) { if (DebuggerInst == null) return; byte[] data = ReadMemory(); if (data == null) return; string hexData = ""; int i = 0; while (i < data.Length) { hexData += string.Format("{0:X2} ", data[i]); ++i; if (i > 0 && (i % 16) == 0) hexData += "\r\n"; } txMemoryDump.Text = hexData; } public delegate void DisResultOther(string Part); public delegate void DisResultAddress(uint Address); public static void ExtractSymbols(string Text, DisResultOther ProcessOtherData, DisResultAddress ProcessAddrData, DisResultAddress ProcessIndirectAddr) { // This regex will match addresses in the format "0x123" // TODO: Fix ajoined addresses ie "0x1230x123" - treated as 0x1230 MatchCollection Matches = Regex.Matches(Text, "(-?0x[a-f0-9]+)", RegexOptions.IgnoreCase); int LastIndex = 0; for (int i = 0; i < Matches.Count; ++i) { if (Matches[i].Index > LastIndex) { var Last = Text.Substring(LastIndex, Matches[i].Index - LastIndex); ProcessOtherData(Last); } string MatchStr = Matches[i].ToString(); if (MatchStr.StartsWith("-")) { uint Address = Convert.ToUInt32(MatchStr.Substring(1), 16); Address = ~Address; ProcessAddrData(Address); } else { uint Address = Convert.ToUInt32(MatchStr, 16); ProcessAddrData(Address); } LastIndex = Matches[i].Index + Matches[i].Length; } if (LastIndex < Text.Length) { ProcessOtherData(Text.Substring(LastIndex)); } } class SymbolInfoHelper { uint EP = 0; string Name = ""; public SymbolInfoHelper(Debugger dbgr, uint Address) { var Module = dbgr.ResolveModule(Address); if (Module != null) { EP = (uint)Module.ImageBase; Name = Path.GetFileName(Module.Path); } } public void GenerateLink(RicherTextBox tb, uint Address) { if (EP != 0) { string LinkName = string.Format("{0} +{1:x}", Name, Address - EP); string Link = string.Format("0x{0:x8}", Address); tb.InsertLink(LinkName, Link); } else { tb.Add(string.Format("0x{0:X8}", Address)); } } } private void DumpDisassembly(uint DisAddress) { // No threads if (DebugThreads.Count == 0) return; // Read preceeding bytes for more context // TODO: This MUST align with a previous instruction or our disassembler will fail uint OffsetAddr = DisAddress; // -16 byte[] data = DebugThreads[0].OwningProcess.ReadMemoryBlock(new IntPtr(OffsetAddr), 64); // Dump requested after crashing - and read memory handles this silently if (data == null) return; txDisassembly.BeginUpdate(); txDisassembly.Clear(); // TODO: Needs refactoring var ModuleInfo = new SymbolInfoHelper(DebuggerInst, OffsetAddr); // TODO: "call dword ptr [0x00XXXXXX]" instructions should be resolved using (Capstone cs = Capstone.CreateEngine()) { cs.DisassembleIt(data, OffsetAddr, delegate (CapstoneInstruction Instruction) { string Cursor = (Instruction.Address == DisAddress) ? "> " : " "; txDisassembly.Add(Cursor); ModuleInfo.GenerateLink(txDisassembly, (uint)Instruction.Address); txDisassembly.Add(" "); ExtractSymbols ( Instruction.Disassembly, // Regular instruction text delegate (string RegData) { txDisassembly.Add(RegData); }, // Raw address delegate (uint address) { var Info = new SymbolInfoHelper(DebuggerInst, address); Info.GenerateLink(txDisassembly, address); }, // Indirect address delegate (uint address) { // stub }); txDisassembly.AddLine(""); }); } txDisassembly.EndUpdate(); txDisassembly.Select(0, 0); } private void cbFrames_SelectedIndexChanged(object sender, EventArgs e) { if (cbFrames.SelectedIndex != -1) { CallstackInfo info = CallstackDump[cbFrames.SelectedIndex]; if (info.InstructionPointer == 0) return; DumpDisassembly(info.InstructionPointer); } } private void btnDumpMemory_Click(object sender, EventArgs e) { if (DebuggerInst == null) return; if (diagSaveMemory.ShowDialog() == DialogResult.OK) { byte[] data = ReadMemory(); if (data == null) return; var Strm = File.OpenWrite(diagSaveMemory.FileNames[0]); Strm.Write(data, 0, data.Length); Strm.Close(); MessageBox.Show("Memory dumped!"); } } private void DumpCallstack(bool ShowExternal = true) { int Index = cbThreads.SelectedIndex; if (Index == -1) return; CallstackDump.Clear(); cbFrames.Items.Clear(); int OtherModuleCount = 0; var Callstack = DebugThreads[Index].CallstackCache; foreach (DebuggerStackFrame StackFrame in Callstack.StackFrames) { string ModuleName = "??"; uint ModuleBase = 0; var Module = DebuggerInst.ResolveModule((uint)StackFrame.PC); if (Module != null) { if (!ShowExternal) { if (!Module.Core) { OtherModuleCount++; continue; } } ModuleName = Path.GetFileName(Module.Path); ModuleBase = (uint)Module.ImageBase; } else { if (!ShowExternal) { OtherModuleCount++; } continue; } if (!ShowExternal) { if (OtherModuleCount > 0) { CallstackDump.Add(new CallstackInfo()); cbFrames.Items.Add("[External Code]"); OtherModuleCount = 0; } } uint ModuleOffset = (uint)StackFrame.PC - ModuleBase; string FrameString = string.Format("{0} +{1:X8} ({2:X8})", ModuleName, ModuleOffset, (uint)StackFrame.PC); // To program counter CallstackDump.Add(new CallstackInfo((uint)StackFrame.PC, ModuleBase)); cbFrames.Items.Add(FrameString); } if (!ShowExternal) { if (OtherModuleCount > 0) { CallstackDump.Add(new CallstackInfo()); cbFrames.Items.Add("[External Code]"); OtherModuleCount = 0; } } if (cbFrames.Items.Count > 0) { // Auto-select the first item to dump cbFrames.SelectedIndex = 0; } } private void cbThreads_SelectedIndexChanged(object sender, EventArgs e) { DumpCallstack(); } private void ShowMemoryAt(string Address) { // Switch to memory page and set address string tabContainer.SelectedTab = tabMemory; txAddress.Text = string.Format("0x{0}", Address); } private void ShowDisassemblyAt(string Address) { tabContainer.SelectedTab = tabDisassembly; uint addr = 0; if (Common.ReadHex(Address, ref addr)) { // Insert disassembly history // TODO: Keep symbol name cbDisAddr.Items.Insert(0, Address); cbDisAddr.Text = Address; DumpDisassembly(addr); } } private void button1_Click_2(object sender, EventArgs e) { FileEventType Event = (FileEventType)cbAction.SelectedIndex; fileWatchMan.Add(Event, tbFilter.Text); } private void clbBreakpoints_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { if (clbBreakpoints.SelectedIndex != -1) { fileWatchMan.Delete(clbBreakpoints.SelectedIndex); } } } private void clbBreakpoints_ItemCheck(object sender, ItemCheckEventArgs e) { fileWatchMan.SetEnabled(e.Index, e.NewValue == CheckState.Checked); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.F5) { StartDebugging(); return true; } return false; } private void HandleDisasmGo() { uint addr = 0; if (ReadAddress(cbDisAddr, ref addr)) { DumpDisassembly(addr); } } private void HandleDisasmGo(int Offset) { int TargetIndex = cbDisAddr.SelectedIndex + Offset; if (TargetIndex < 0) return; if (TargetIndex < cbDisAddr.Items.Count) { cbDisAddr.SelectedIndex = TargetIndex; HandleDisasmGo(); } } private void button2_Click(object sender, EventArgs e) { HandleDisasmGo(); } private void comboBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { HandleDisasmGo(); } } private void button3_Click(object sender, EventArgs e) { HandleDisasmGo(1); } private void button4_Click(object sender, EventArgs e) { HandleDisasmGo(-1); } private void cbDisAddr_SelectedIndexChanged(object sender, EventArgs e) { HandleDisasmGo(); } private void RefreshPatches() { lvCEMemory.BeginUpdate(); lvCEMemory.Items.Clear(); foreach (Patch DataPatch in patchMan.Data) { var li = lvCEMemory.Items.Add(string.Format("{0} 0x{1:x}", DataPatch.Module, DataPatch.Offset)); li.SubItems.Add(DataPatch.Name); li.SubItems.Add(string.Format("{0} byte(s)", DataPatch.Patched.Length)); if (MainProcess != null) { li.SubItems.Add(patchMan.Read(MainProcess, DataPatch)); } else { li.SubItems.Add("??"); } } lvCEMemory.EndUpdate(); lvCEAssembly.BeginUpdate(); lvCEAssembly.Items.Clear(); foreach (Patch patch in patchMan.Assembly) { var li = lvCEAssembly.Items.Add(string.Format("{0} 0x{1:x}", patch.Module, patch.Offset)); li.SubItems.Add(patch.Name); li.SubItems.Add(PrettyPrint(patch.Original)); li.SubItems.Add(PrettyPrint(patch.Patched)); } lvCEAssembly.EndUpdate(); } static private byte[] Fill(int Count, byte Val) { List<byte> ByteList = new List<byte>(Count); for (int i = 0; i < Count; ++i) ByteList.Add(Val); return ByteList.ToArray(); } static private byte[] Nops(int Count) { return Fill(Count, 0x90); } static private string PrettyPrint(byte[] Bytes) { if (Bytes == null) return "??"; string Str = ""; int Max = Math.Min(5, Bytes.Length); for (int i = 0; i < Max; ++i) { Str += string.Format("{0:X2} ", Bytes[i]); } return Str; } private void LoadCheatTable(string filename) { string path = Directory.GetCurrentDirectory(); if (File.Exists(filename)) { DebugLog(string.Format("Attempting to load \"{0}\"", filename)); CheatEngine.CheatTable ct_data = CheatEngine.CheatTableReader.FromFile(filename); if (ct_data != null) { foreach (CheatEngine.CheatEntry Entry in ct_data.CheatEntries) { uint addr = 0; if (Common.ReadHex(Entry.Address, ref addr)) { Patch DataPatch = new Patch(); DataPatch.DisplayAs = PatchType.Array; DataPatch.Name = Entry.Description; DataPatch.Module = ""; DataPatch.Offset = addr; DataPatch.Original = null; DataPatch.Patched = Nops(CheatEngine.Helpers.VariableSize(Entry.VariableType)); patchMan.Data.Add(DataPatch); } } foreach (CheatEngine.CodeEntry Entry in ct_data.CodeEntires) { Patch DataPatch = new Patch(); DataPatch.DisplayAs = PatchType.Array; DataPatch.Name = Entry.Description; DataPatch.Module = Entry.ModuleName; DataPatch.Offset = Entry.ModuleNameOffset; DataPatch.Original = Entry.Actual; DataPatch.Patched = Nops(Entry.Actual.Length); patchMan.Assembly.Add(DataPatch); } DebugLog(string.Format("Loaded {0} auto-assembler entries", ct_data.CodeEntires.Count)); DebugLog(string.Format("Loaded {0} cheat entries", ct_data.CheatEntries.Count)); RefreshPatches(); } } } private void button5_Click(object sender, EventArgs e) { PatchType PatchType = (PatchType)cbDataFormat.SelectedIndex; int PatchSize = PatchManager.PatchTypeLength(PatchType); if (PatchSize == 0) { if (!Common.ReadNumeric(textBox2.Text, ref PatchSize)) return; if (PatchSize < 0) return; } uint addr = 0; if (Common.ReadHex(txAddress.Text, ref addr)) { Patch DataPatch = new Patch(); DataPatch.DisplayAs = PatchType; DataPatch.Name = string.Format("Patched {0}", PatchType); DataPatch.Module = ""; DataPatch.Offset = addr; // TODO: Read original memory at this location DataPatch.Original = Nops(PatchSize); DataPatch.Patched = Nops(PatchSize); patchMan.Data.Add(DataPatch); RefreshPatches(); } } private void button6_Click(object sender, EventArgs e) { uint addr = 0; if (ReadAddress(cbDisAddr, ref addr)) { txAddress.Text = cbDisAddr.Text; tabContainer.SelectedTab = tabMemory; } } private void button2_Click_2(object sender, EventArgs e) { if (diagBrowseCT.ShowDialog() == DialogResult.OK) { string filename = diagBrowseCT.FileNames[0]; LoadCheatTable(filename); } } private void button1_Click_1(object sender, EventArgs e) { RefreshPatches(); } private void InvokePatchTypeChange() { PatchType Type = (PatchType)cbDataFormat.SelectedIndex; textBox2.Text = PatchManager.PatchTypeLength(Type).ToString(); textBox2.Enabled = (Type == PatchType.Array); } private void cbDataFormat_SelectionChangeCommitted(object sender, EventArgs e) { InvokePatchTypeChange(); } private void button3_Click_1(object sender, EventArgs e) { if (lvCEMemory.SelectedIndices.Count != 1) return; string Value = txNewValue.Text; if (Value.Length != 0) { Patch DataPatch = patchMan.Data[lvCEMemory.SelectedIndices[0]]; if (patchMan.Write(MainProcess, DataPatch, Value)) { RefreshPatches(); } } } } }
gpl-2.0
hatharry/Emby
MediaBrowser.Controller/LiveTv/ILiveTvRecording.cs
1267
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Library; using MediaBrowser.Model.LiveTv; using System; using System.Threading; using System.Threading.Tasks; namespace MediaBrowser.Controller.LiveTv { public interface ILiveTvRecording : IHasImages, IHasMediaSources, IHasUserData, IHasStartDate, IHasProgramAttributes { string ServiceName { get; set; } string ExternalId { get; set; } string ChannelId { get; } string MediaType { get; } string Container { get; } long? RunTimeTicks { get; set; } string GetClientTypeName(); bool IsParentalAllowed(User user); Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken); PlayAccess GetPlayAccess(User user); bool CanDelete(); bool CanDelete(User user); string SeriesTimerId { get; set; } string TimerId { get; set; } RecordingStatus Status { get; set; } DateTime? EndDate { get; set; } DateTime DateLastSaved { get; set; } DateTime DateCreated { get; set; } DateTime DateModified { get; set; } } }
gpl-2.0
dkjha52/testlinkdev
lib/functions/tlAttachment.class.php
9647
<?php /** * TestLink Open Source Project - http://testlink.sourceforge.net/ * This script is distributed under the GNU General Public License 2 or later. * * @package TestLink * @author Francisco Mancardi * @copyright 2007-2009, TestLink community * @version CVS: $Id: tlAttachment.class.php,v 1.2 2009/12/28 08:53:37 franciscom Exp $ * @link http://www.teamst.org/index.php * */ /** parenthal class */ require_once( 'object.class.php' ); /** * An attachment helper class used to manage the storage of the attachment's meta information * Attachments contents are handled by the repository * @package TestLink */ class tlAttachment extends tlDBObject { /** * @var integer error code for invalid title length */ const E_TITLELENGTH = -1; /** * @var int $fkid the foreign key id (attachments.fk_id) */ protected $fkID; /** * @var string $fktableName the tablename to which the $id refers to (attachments.fk_table) */ protected $fkTableName; /** * @var string the filename the attachment is stored to */ protected $fName; /** * @var string the title used for the attachment */ protected $title; /** * @var string $fType the mime-type of the file */ protected $fType; /** * @var int $fSize the filesize (uncompressed) */ protected $fSize; /** * @var string $destFPath the path to file within the repository */ protected $destFPath; /** * @var string $fContents the contents of the file */ protected $fContents; /** * * @var int the compression type used for the attachment * @see TL_REPOSITORY_COMPRESSIONTYPE_NONE * @see TL_REPOSITORY_COMPRESSIONTYPE_GZIP * */ protected $compressionType; /** * @var string a description for the attachment */ protected $description; /** * @var timestamp the timestampe when the attachment was added */ protected $dateAdded; /** * @var string the path to the repository */ protected $repositoryPath; /** * @var unknown_type */ protected $attachmentCfg; /* Cleanup function to set the object to an initial state * @param $options options to control the initialization */ protected function _clean($options = self::TLOBJ_O_SEARCH_BY_ID) { $this->fkID = NULL; $this->fkTableName = NULL; $this->fName = NULL; $this->title = NULL; $this->fType = NULL; $this->fSize = NULL; $this->destFPath = NULL; $this->fContents = NULL; $this->description = NULL; $this->dateAdded = NULL; if (!($options & self::TLOBJ_O_SEARCH_BY_ID)) { $this->dbID = null; } } /** * Class constructor * * @param $dbID integer the database identifier of the attachment */ function __construct($dbID = null) { parent::__construct(); $this->compressionType = tlAttachmentRepository::getCompression(); $this->repositoryPath = tlAttachmentRepository::getPathToRepository(); $this->attachmentCfg = config_get('attachments'); $this->_clean(); $this->dbID = $dbID; } /* * Class destructor, cleans the object */ function __destruct() { parent::__destruct(); $this->_clean(); } /* * */ function setID($id) { $this->dbID = $id; } /* * Initializes the attachment object * * @param object $db [ref] the db-object * @param int $fkid the foreign key id (attachments.fk_id) * @param string $fktableName the tablename to which the $id refers to (attachments.fk_table) * @param string $fName the filename * @param string $destFPath the file path * @param string $fContents the contents of the file * @param string $fType the mime-type of the file * @param int $fSize the filesize (uncompressed) * @param string $title the title used for the attachment * * @return integer returns tl::OK */ public function create($fkid,$fkTableName,$fName,$destFPath,$fContents,$fType,$fSize,$title) { $this->_clean(); $title = trim($title); $config = $this->attachmentCfg; if($title == "") { switch($config->action_on_save_empty_title) { case 'use_filename': $title = $fName; break; default: break; } } if(!$config->allow_empty_title && $title == "") { return self::E_TITLELENGTH; } $this->fkID = $fkid; $this->fkTableName = trim($fkTableName); $this->fType = trim($fType); $this->fSize = $fSize; $this->fName = $fName; $this->destFPath = trim($destFPath); $this->fContents = $fContents; //for FS-repository, the path to the repository itself is cut off, so the path is // relative to the repository itself $this->destFPath = str_replace($this->repositoryPath.DIRECTORY_SEPARATOR,"",$destFPath); $this->title = trim($title); return tl::OK; } /* Read the attachment information from the database, for filesystem repository this doesn't read * the contents of the attachments * * @param $db [ref] the database connection * @param $options integer null or TLOBJ_O_SEARCH_BY_ID * * @return integer returns tl::OK on success, tl::ERROR else */ public function readFromDB(&$db,$options = self::TLOBJ_O_SEARCH_BY_ID) { $this->_clean($options); $query = "SELECT id,title,description,file_name,file_type,file_size,date_added,". "compression_type,file_path,fk_id,fk_table FROM {$this->tables['attachments']} "; $clauses = null; if ($options & self::TLOBJ_O_SEARCH_BY_ID) $clauses[] = "id = {$this->dbID}"; if ($clauses) $query .= " WHERE " . implode(" AND ",$clauses); $info = $db->fetchFirstRow($query); if ($info) { $this->fkID = $info['fk_id']; $this->fkTableName = $info['fk_table']; $this->fName = $info['file_name']; $this->destFPath = $info['file_path']; $this->fType = $info['file_type']; $this->fSize = $info['file_size']; $this->dbID = $info['id']; $this->description = $info['description']; $this->dateAdded = $info['date_added']; $this->title = $info['title']; $this->compressionType = $info['compression_type']; } return $info ? tl::OK : tl::ERROR; } /** * Returns the attachment meta information in a legacy way * * @return array array with the attachment information */ public function getInfo() { return array("id" => $this->dbID,"title" => $this->title, "description" => $this->description, "file_name" => $this->fName, "file_type" => $this->fType, "file_size" => $this->fSize, "date_added" => $this->dateAdded, "compression_type" => $this->compressionType, "file_path" => $this->destFPath, "fk_id" => $this->fkID,"fk_table" => $this->fkTableName, ); } /* * Writes the attachment into the database, for database repositories also the contents * of the attachments are written * * @return integer returns tl::OK on success, tl::ERROR else */ public function writeToDB(&$db) { $tableName = $db->prepare_string($this->fkTableName); $fName = $db->prepare_string($this->fName); $title = $db->prepare_string($this->title); $fType = $db->prepare_string($this->fType); $destFPath = is_null($this->destFPath) ? 'NULL' : "'".$db->prepare_string($this->destFPath)."'"; // for FS-repository the contents are null $fContents = is_null($this->fContents) ? 'NULL' : "'".$db->prepare_string($this->fContents)."'"; $query = "INSERT INTO {$this->tables['attachments']} (fk_id,fk_table,file_name,file_path,file_size,file_type, date_added,content,compression_type,title) VALUES ({$this->fkID},'{$tableName}','{$fName}',{$destFPath},{$this->fSize},'{$this->fType}'," . $db->db_now() . ",$fContents,{$this->compressionType},'{$title}')"; $result = $db->exec_query($query); if ($result) { $this->dbID = $db->insert_id(); } return $result ? tl::OK : tl::ERROR; } /* * Deletes an attachment from the db, for databse repositories also the contents are deleted * * @return integer return tl::OK on success, tl::ERROR else */ public function deleteFromDB(&$db) { $query = "DELETE FROM {$this->tables['attachments']} WHERE id = {$this->dbID}"; $result = $db->exec_query($query); return $result ? tl::OK : tl::ERROR; } /** * Creates an attachment by a given database identifier * * @param $db [ref] the database connection * @param $id the database identifier of the attachment * @param $detailLevel the detailLevel * @return tlAttachment the created attachment or null on failure */ static public function getByID(&$db,$id,$detailLevel = self::TLOBJ_O_GET_DETAIL_FULL) { return tlDBObject::createObjectFromDB($db,$id,__CLASS__,tlAttachment::TLOBJ_O_SEARCH_BY_ID,$detailLevel); } /** * Creates some attachments by given database identifiers * * @param $db [ref] the database connection * @param $id the database identifier of the attachment * @param $detailLevel the detailLevel * @return array returns an array of tlAttachment (the created attachments) or null on failure */ static public function getByIDs(&$db,$ids,$detailLevel = self::TLOBJ_O_GET_DETAIL_FULL) { return self::handleNotImplementedMethod(__FUNCTION__); } /** * Currently not implemented * * @param $db [ref] the database connection * @param $whereClause string and addtional where clause * @param $column string the name of column which holds the id * @param $orderBy string an additional ORDER BY clause * @param $detailLevel the detailLevel * @return unknown_type */ static public function getAll(&$db,$whereClause = null,$column = null,$orderBy = null,$detailLevel = self::TLOBJ_O_GET_DETAIL_FULL) { return self::handleNotImplementedMethod(__FUNCTION__); } }; ?>
gpl-2.0
dalinhuang/cameras
vincent_zc_install/includes/templates/template_default/templates/system_setup_default.php
4212
<?php /** * @package Installer * @access private * @copyright Copyright 2003-2007 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: system_setup_default.php 7180 2007-10-05 12:24:30Z drbyte $ */ if ($zc_install->error) include(DIR_WS_INSTALL_TEMPLATE . 'templates/display_errors.php'); ?> <form method="post" action="index.php?main_page=system_setup<?php echo zcInstallAddSID(); ?>"> <fieldset> <legend><?php echo SERVER_SETTINGS; ?></legend> <div class="section"> <input type="text" id="physical_path" name="physical_path" tabindex="1" value="<?php echo PHYSICAL_PATH_VALUE; ?>" size="50" /> <label for="physical_path"><?php echo PHYSICAL_PATH; ?></label> <p><?php echo PHYSICAL_PATH_INSTRUCTION . '<a href="javascript:popupWindow(\'popup_help_screen.php?error_code=4\')"> ' . TEXT_HELP_LINK . '</a>'; ?></p> </div> <div class="section"> <input type="text" id="virtual_http_path" name="virtual_http_path" tabindex="2" value="<?php echo VIRTUAL_HTTP_PATH_VALUE; ?>" size="50" /> <label for="virtual_http_path"><?php echo VIRTUAL_HTTP_PATH; ?></label> <p><?php echo VIRTUAL_HTTP_PATH_INSTRUCTION . '<a href="javascript:popupWindow(\'popup_help_screen.php?error_code=5\')"> ' . TEXT_HELP_LINK . '</a>'; ?></p> </div> </fieldset> <fieldset> <legend><?php echo SSL_OPTIONS; ?></legend> <p><?php echo TEXT_SSL_INTRO; ?></p> <div class="section"> <input type="text" id="virtual_https_server" name="virtual_https_server" tabindex="3" value="<?php echo VIRTUAL_HTTPS_SERVER_VALUE; ?>" size="50" /> <label for="virtual_https_server"><?php echo VIRTUAL_HTTPS_SERVER; ?></label> <p><?php echo VIRTUAL_HTTPS_SERVER_INSTRUCTION . '<a href="javascript:popupWindow(\'popup_help_screen.php?error_code=6\')"> ' . TEXT_HELP_LINK . '</a>'; ?></p> </div> <div class="section"> <input type="text" id="virtual_https_path" name="virtual_https_path" tabindex="4" value="<?php echo VIRTUAL_HTTPS_PATH_VALUE; ?>" size="50" /> <label for="virtual_https_path"><?php echo VIRTUAL_HTTPS_PATH; ?></label> <p><?php echo VIRTUAL_HTTPS_PATH_INSTRUCTION . '<a href="javascript:popupWindow(\'popup_help_screen.php?error_code=7\')"> ' . TEXT_HELP_LINK . '</a>'; ?></p> </div> <p class="attention"><?php echo TEXT_SSL_WARNING; ?></p> <div class="section"> <div class="input"> <input type="radio" name="enable_ssl" id="enable_ssl_yes" tabindex="6" value="true" <?php echo ENABLE_SSL_TRUE; ?>/> <label for="enable_ssl_yes"><?php echo YES; ?></label> <input type="radio" name="enable_ssl" id="enable_ssl_no" tabindex="7" value="false" <?php echo ENABLE_SSL_FALSE; ?>/> <label for="enable_ssl_no"><?php echo NO; ?></label> </div> <span class="label"><?php echo ENABLE_SSL; ?></span> <p><?php echo ENABLE_SSL_INSTRUCTION . '<a href="javascript:popupWindow(\'popup_help_screen.php?error_code=8\')"> ' . TEXT_HELP_LINK . '</a>'; ?></p> </div> <div class="section"> <div class="input"> <input type="radio" name="enable_ssl_admin" id="enable_ssl_admin_yes" tabindex="8" value="true" <?php echo ENABLE_SSL_TRUE; ?>/> <label for="enable_ssl_admin_yes"><?php echo YES; ?></label> <input type="radio" name="enable_ssl_admin" id="enable_ssl_admin_no" tabindex="9" value="false" <?php echo ENABLE_SSL_FALSE; ?>/> <label for="enable_ssl_admin_no"><?php echo NO; ?></label> </div> <span class="label"><?php echo ENABLE_SSL_ADMIN; ?></span> <p><?php echo ENABLE_SSL_ADMIN_INSTRUCTION . '<a href="javascript:popupWindow(\'popup_help_screen.php?error_code=8\')"> ' . TEXT_HELP_LINK . '</a>'; ?></p> </div> </fieldset> <input type="submit" name="submit" class="button" tabindex="10" value="<?php echo SAVE_SYSTEM_SETTINGS; ?>" /> <input type="submit" name="rediscover" class="button" tabindex="11" value="<?php echo REDISCOVER; ?>" /> <?php echo $zc_install->getConfigKeysAsPost(); ?> </form>
gpl-2.0
Masterjun3/dolphin
Source/Core/DolphinQt2/Config/PropertiesDialog.cpp
1390
// Copyright 2016 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include <QDialogButtonBox> #include <QTabWidget> #include <QVBoxLayout> #include "DolphinQt2/Config/FilesystemWidget.h" #include "DolphinQt2/Config/GeckoCodeWidget.h" #include "DolphinQt2/Config/InfoWidget.h" #include "DolphinQt2/Config/PropertiesDialog.h" PropertiesDialog::PropertiesDialog(QWidget* parent, const GameFile& game) : QDialog(parent) { setWindowTitle( QStringLiteral("%1: %2 - %3").arg(game.GetFileName(), game.GetGameID(), game.GetLongName())); QVBoxLayout* layout = new QVBoxLayout(); QTabWidget* tab_widget = new QTabWidget(this); InfoWidget* info = new InfoWidget(game); GeckoCodeWidget* gecko = new GeckoCodeWidget(game); connect(gecko, &GeckoCodeWidget::OpenGeneralSettings, this, &PropertiesDialog::OpenGeneralSettings); tab_widget->addTab(info, tr("Info")); tab_widget->addTab(gecko, tr("Gecko Codes")); if (DiscIO::IsDisc(game.GetPlatformID())) { FilesystemWidget* filesystem = new FilesystemWidget(game); tab_widget->addTab(filesystem, tr("Filesystem")); } layout->addWidget(tab_widget); QDialogButtonBox* ok_box = new QDialogButtonBox(QDialogButtonBox::Ok); connect(ok_box, &QDialogButtonBox::accepted, this, &PropertiesDialog::accept); layout->addWidget(ok_box); setLayout(layout); }
gpl-2.0
levski87/midwoodcandle
wp-content/themes/flatsome/woocommerce/content-single-product-lightbox.php
2963
<?php global $post, $product, $woocommerce; $attachment_ids = $product->get_gallery_attachment_ids(); // run quick view hooks do_action('wc_quick_view_before_single_product'); ?> <div class="row collapse"> <div class="large-7 columns"> <div class="product-image images"> <div class="iosSlider product-gallery-slider" style="height:<?php $height = get_option('shop_single_image_size'); echo ($height['height']-60).'px!important'; ?>"> <div class="slider" > <?php if ( has_post_thumbnail() ) : ?> <?php //Get the Thumbnail URL $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), false, '' ); ?> <div class="slide" > <span itemprop="image"><?php echo get_the_post_thumbnail( $post->ID, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ) ) ?></span> </div> <?php endif; ?> <?php if ( $attachment_ids ) { $loop = 0; $columns = apply_filters( 'woocommerce_product_thumbnails_columns', 3 ); foreach ( $attachment_ids as $attachment_id ) { $classes = array( 'zoom' ); if ( $loop == 0 || $loop % $columns == 0 ) $classes[] = 'first'; if ( ( $loop + 1 ) % $columns == 0 ) $classes[] = 'last'; $image_link = wp_get_attachment_url( $attachment_id ); if ( ! $image_link ) continue; $image = wp_get_attachment_image( $attachment_id, apply_filters( 'single_product_small_thumbnail_size', 'shop_thumbnail' ) ); $image_class = esc_attr( implode( ' ', $classes ) ); $image_title = esc_attr( get_the_title( $attachment_id ) ); printf( '<div class="slide"><span>%s</span></div>', wp_get_attachment_image( $attachment_id, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ) ), wp_get_attachment_url( $attachment_id ) ); $loop++; } } ?> </div> <div class="sliderControlls dark"> <div class="sliderNav small hide-for-small"> <a href="javascript:void(0)" class="nextSlide prev_product_slider"><span class="icon-angle-left"></span></a> <a href="javascript:void(0)" class="prevSlide next_product_slider"><span class="icon-angle-right"></span></a> </div> </div><!-- .sliderControlls --> </div><!-- .slider --> </div><!-- .product-image --> </div><!-- large-6 --> <div class="large-5 columns"> <div class="product-lightbox-inner product-info"> <h1 itemprop="name" class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> <div class="tx-div small"></div> <?php do_action( 'woocommerce_single_product_lightbox_summary' ); ?> </div> </div>
gpl-2.0
RJRetro/mame
src/mame/drivers/tispellb.cpp
16116
// license:BSD-3-Clause // copyright-holders:hap, Sean Riddle /*************************************************************************** ** subclass of hh_tms1k_state (includes/hh_tms1k.h, drivers/hh_tms1k.cpp) ** Texas Instruments Spelling B hardware The Spelling B was introduced together with the Speak & Spell. It is a handheld educational toy with booklet. Two revisions of the hardware exist. (* indicates not dumped) 1st revision: Spelling B (US), 1978 - TMS0270 MCU TMC0272 (die label 0272A T0270B) - TMS1980 MCU TMC1984 (die label 1980A 84A) - 8-digit cyan VFD display (seen with and without apostrophe) Spelling ABC (UK), 1979: exact same hardware as US version 2nd revision: Spelling B (US), 1979 - TMS0270 MCU TMC0274 - TMC0355 4KB VSM ROM CD2602 - 8-digit cyan VFD display - 1-bit sound (indicated by a music note symbol on the top-right of the casing) - note: much rarer than the 1978 version, not much luck finding one on eBay Spelling ABC (UK), 1979: exact same hardware as US version Spelling ABC (Germany), 1979: different VSM - TMC0355 4KB VSM ROM CD2607* Mr. Challenger (US), 1979 - TMS0270 MCU TMC0273 - TMC0355 4KB VSM ROM CD2601 - 8-digit cyan VFD display - 1-bit sound Letterlogic (UK), 1980: exact same hardware as US Mr. Challenger Letterlogic (France), 1980: different VSM - TMC0355 4KB VSM ROM CD2603* Letterlogic (Germany), 1980: different VSM - TMC0355 4KB VSM ROM CD2604* ---------------------------------------------------------------------------- TODO: - spellb fetches wrong word sometimes (on lv1 SPOON and ANT) - roms were doublechecked ***************************************************************************/ #include "includes/hh_tms1k.h" #include "machine/tms6100.h" // internal artwork #include "spellb.lh" class tispellb_state : public hh_tms1k_state { public: tispellb_state(const machine_config &mconfig, device_type type, const char *tag) : hh_tms1k_state(mconfig, type, tag), m_subcpu(*this, "subcpu"), m_tms6100(*this, "tms6100") { } // devices optional_device<cpu_device> m_subcpu; optional_device<tms6100_device> m_tms6100; UINT8 m_rev1_ctl; UINT16 m_sub_o; UINT16 m_sub_r; virtual DECLARE_INPUT_CHANGED_MEMBER(power_button) override; void power_off(); void prepare_display(); bool vfd_filament_on() { return m_display_decay[15][16] != 0; } DECLARE_READ8_MEMBER(main_read_k); DECLARE_WRITE16_MEMBER(main_write_o); DECLARE_WRITE16_MEMBER(main_write_r); DECLARE_READ8_MEMBER(rev1_ctl_r); DECLARE_WRITE8_MEMBER(rev1_ctl_w); DECLARE_READ8_MEMBER(sub_read_k); DECLARE_WRITE16_MEMBER(sub_write_o); DECLARE_WRITE16_MEMBER(sub_write_r); DECLARE_WRITE16_MEMBER(rev2_write_o); DECLARE_WRITE16_MEMBER(rev2_write_r); protected: virtual void machine_start() override; }; void tispellb_state::machine_start() { hh_tms1k_state::machine_start(); // zerofill m_rev1_ctl = 0; m_sub_o = 0; m_sub_r = 0; // register for savestates save_item(NAME(m_rev1_ctl)); save_item(NAME(m_sub_o)); save_item(NAME(m_sub_r)); } /*************************************************************************** I/O ***************************************************************************/ // common void tispellb_state::power_off() { m_maincpu->set_input_line(INPUT_LINE_RESET, ASSERT_LINE); if (m_subcpu) m_subcpu->set_input_line(INPUT_LINE_RESET, ASSERT_LINE); m_power_on = false; } void tispellb_state::prepare_display() { // almost same as snspell UINT16 gridmask = vfd_filament_on() ? 0xffff : 0x8000; set_display_segmask(0xff, 0x3fff); display_matrix(16+1, 16, m_plate | 1<<16, m_grid & gridmask); } WRITE16_MEMBER(tispellb_state::main_write_o) { // reorder opla to led14seg, plus DP as d14 and AP as d15, same as snspell m_plate = BITSWAP16(data,12,15,10,7,8,9,11,6,13,3,14,0,1,2,4,5); prepare_display(); } WRITE16_MEMBER(tispellb_state::main_write_r) { // R13: power-off request, on falling edge if (~data & m_r & 0x2000) power_off(); // R0-R6: input mux // R0-R7: select digit // R15: filament on m_r = data; m_inp_mux = data & 0x7f; m_grid = data & 0x80ff; prepare_display(); } READ8_MEMBER(tispellb_state::main_read_k) { // K: multiplexed inputs (note: the Vss row is always on) return m_inp_matrix[7]->read() | read_inputs(7); } // 1st revision mcu/mcu comms WRITE8_MEMBER(tispellb_state::rev1_ctl_w) { // main CTL write data m_rev1_ctl = data & 0xf; } READ8_MEMBER(tispellb_state::sub_read_k) { // sub K8421 <- main CTL3210 return m_rev1_ctl; } WRITE16_MEMBER(tispellb_state::sub_write_o) { // sub O write data m_sub_o = data; } READ8_MEMBER(tispellb_state::rev1_ctl_r) { // main CTL3210 <- sub O6043 return BITSWAP8(m_sub_o,7,5,2,1,6,0,4,3) & 0xf; } WRITE16_MEMBER(tispellb_state::sub_write_r) { // sub R: unused? m_sub_r = data; } // 2nd revision specifics WRITE16_MEMBER(tispellb_state::rev2_write_o) { // SEG DP: speaker out m_speaker->level_w(data >> 15 & 1); // SEG DP and SEG AP are not connected to VFD, rest is same as rev1 main_write_o(space, offset, data & 0x6fff); } WRITE16_MEMBER(tispellb_state::rev2_write_r) { // R12: TMC0355 CS // R4: TMC0355 M1 // R6: TMC0355 M0 m_tms6100->cs_w(data >> 12 & 1); m_tms6100->m1_w(data >> 4 & 1); m_tms6100->m0_w(data >> 6 & 1); m_tms6100->clk_w(1); m_tms6100->clk_w(0); // rest is same as rev1 main_write_r(space, offset, data); } /*************************************************************************** Inputs ***************************************************************************/ INPUT_CHANGED_MEMBER(tispellb_state::power_button) { int on = (int)(FPTR)param; if (on && !m_power_on) { m_power_on = true; m_maincpu->set_input_line(INPUT_LINE_RESET, CLEAR_LINE); if (m_subcpu) m_subcpu->set_input_line(INPUT_LINE_RESET, CLEAR_LINE); } else if (!on && m_power_on) power_off(); } static INPUT_PORTS_START( spellb ) PORT_START("IN.0") // R0 PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B') PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C') PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A') PORT_START("IN.1") // R1 PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_G) PORT_CHAR('G') PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_H) PORT_CHAR('H') PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_I) PORT_CHAR('I') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_J) PORT_CHAR('J') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F') PORT_START("IN.2") // R2 PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_L) PORT_CHAR('L') PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_M) PORT_CHAR('M') PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_N) PORT_CHAR('N') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_O) PORT_CHAR('O') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_K) PORT_CHAR('K') PORT_START("IN.3") // R3 PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q') PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_R) PORT_CHAR('R') PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_S) PORT_CHAR('S') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_T) PORT_CHAR('T') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_P) PORT_CHAR('P') PORT_START("IN.4") // R4 PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_V) PORT_CHAR('V') PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_W) PORT_CHAR('W') PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_X) PORT_CHAR('X') PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y') PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_U) PORT_CHAR('U') PORT_START("IN.5") // R5 PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_EQUALS) PORT_NAME("Memory") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_MINUS) PORT_NAME("Clue") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_DEL) PORT_CODE(KEYCODE_BACKSPACE) PORT_NAME("Erase") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_ENTER) PORT_NAME("Enter") PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z') PORT_START("IN.6") // R6 PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CODE(KEYCODE_HOME) PORT_NAME("Go") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_PGDN) PORT_NAME("Off") // -> auto_power_off PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_SLASH) PORT_NAME("Level") PORT_START("IN.7") // Vss! PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_NAME("Missing Letter") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_NAME("Mystery Word") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_NAME("Scramble") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_PGUP) PORT_NAME("Spelling B/On") PORT_CHANGED_MEMBER(DEVICE_SELF, tispellb_state, power_button, (void *)true) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_NAME("Starts With") INPUT_PORTS_END static INPUT_PORTS_START( mrchalgr ) PORT_INCLUDE( spellb ) // same key layout as spellb PORT_MODIFY("IN.5") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_EQUALS) PORT_NAME("2nd Player") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_ENTER) PORT_NAME("Score") PORT_MODIFY("IN.7") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_NAME("Crazy Letters") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_NAME("Letter Guesser") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_NAME("Word Challenge") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_PGUP) PORT_NAME("Mystery Word/On") PORT_CHANGED_MEMBER(DEVICE_SELF, tispellb_state, power_button, (void *)true) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_NAME("Replay") INPUT_PORTS_END /*************************************************************************** Machine Config ***************************************************************************/ static MACHINE_CONFIG_START( rev1, tispellb_state ) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", TMS0270, 350000) // approximation MCFG_TMS1XXX_READ_K_CB(READ8(tispellb_state, main_read_k)) MCFG_TMS1XXX_WRITE_O_CB(WRITE16(tispellb_state, main_write_o)) MCFG_TMS1XXX_WRITE_R_CB(WRITE16(tispellb_state, main_write_r)) MCFG_TMS0270_READ_CTL_CB(READ8(tispellb_state, rev1_ctl_r)) MCFG_TMS0270_WRITE_CTL_CB(WRITE8(tispellb_state, rev1_ctl_w)) MCFG_CPU_ADD("subcpu", TMS1980, 350000) // approximation MCFG_TMS1XXX_READ_K_CB(READ8(tispellb_state, sub_read_k)) MCFG_TMS1XXX_WRITE_O_CB(WRITE16(tispellb_state, sub_write_o)) MCFG_TMS1XXX_WRITE_R_CB(WRITE16(tispellb_state, sub_write_r)) MCFG_QUANTUM_PERFECT_CPU("maincpu") MCFG_TIMER_DRIVER_ADD_PERIODIC("display_decay", hh_tms1k_state, display_decay_tick, attotime::from_msec(1)) MCFG_DEFAULT_LAYOUT(layout_spellb) /* no sound! */ MACHINE_CONFIG_END static MACHINE_CONFIG_START( rev2, tispellb_state ) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", TMS0270, 350000) // approximation MCFG_TMS1XXX_READ_K_CB(READ8(tispellb_state, main_read_k)) MCFG_TMS1XXX_WRITE_O_CB(WRITE16(tispellb_state, rev2_write_o)) MCFG_TMS1XXX_WRITE_R_CB(WRITE16(tispellb_state, rev2_write_r)) MCFG_TMS0270_READ_CTL_CB(DEVREAD8("tms6100", tms6100_device, data_r)) MCFG_TMS0270_WRITE_CTL_CB(DEVWRITE8("tms6100", tms6100_device, add_w)) MCFG_DEVICE_ADD("tms6100", TMS6100, 350000) MCFG_TMS6100_4BIT_MODE() MCFG_TIMER_DRIVER_ADD_PERIODIC("display_decay", hh_tms1k_state, display_decay_tick, attotime::from_msec(1)) MCFG_DEFAULT_LAYOUT(layout_spellb) /* sound hardware */ MCFG_SPEAKER_STANDARD_MONO("mono") MCFG_SOUND_ADD("speaker", SPEAKER_SOUND, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25) MACHINE_CONFIG_END /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( spellb ) ROM_REGION( 0x1000, "maincpu", 0 ) ROM_LOAD( "tmc0272nl", 0x0000, 0x1000, CRC(f90318ff) SHA1(7cff03fafbc66b0e07b3c70a513fbb0b11eef4ea) ) ROM_REGION( 1246, "maincpu:ipla", 0 ) ROM_LOAD( "tms0980_common1_instr.pla", 0, 1246, CRC(42db9a38) SHA1(2d127d98028ec8ec6ea10c179c25e447b14ba4d0) ) ROM_REGION( 2127, "maincpu:mpla", 0 ) ROM_LOAD( "tms0270_common2_micro.pla", 0, 2127, CRC(86737ac1) SHA1(4aa0444f3ddf88738ea74aec404c684bf54eddba) ) ROM_REGION( 1246, "maincpu:opla", 0 ) ROM_LOAD( "tms0270_spellb_output.pla", 0, 1246, CRC(3e021cbd) SHA1(c9bdfe10601b8a5a70442fe4805e4bfed8bbed35) ) ROM_REGION( 0x1000, "subcpu", 0 ) ROM_LOAD( "tmc1984nl", 0x0000, 0x1000, CRC(78c9c83a) SHA1(6307fe2a0228fd1b8d308fcaae1b8e856d40fe57) ) ROM_REGION( 1246, "subcpu:ipla", 0 ) ROM_LOAD( "tms0980_common1_instr.pla", 0, 1246, CRC(42db9a38) SHA1(2d127d98028ec8ec6ea10c179c25e447b14ba4d0) ) ROM_REGION( 2127, "subcpu:mpla", 0 ) ROM_LOAD( "tms0270_common2_micro.pla", 0, 2127, CRC(86737ac1) SHA1(4aa0444f3ddf88738ea74aec404c684bf54eddba) ) ROM_REGION( 525, "subcpu:opla", 0 ) ROM_LOAD( "tms1980_spellb_output.pla", 0, 525, CRC(1e26a719) SHA1(eb031aa216fe865bc9e40b070ca5de2b1509f13b) ) ROM_END ROM_START( spellb79 ) ROM_REGION( 0x1000, "maincpu", 0 ) ROM_LOAD( "tmc0274n2l", 0x0000, 0x1000, CRC(98e3bd32) SHA1(e79b59ac29b0183bf1ee8d84b2944450c5e5d8fb) ) ROM_REGION( 1246, "maincpu:ipla", 0 ) ROM_LOAD( "tms0980_common1_instr.pla", 0, 1246, CRC(42db9a38) SHA1(2d127d98028ec8ec6ea10c179c25e447b14ba4d0) ) ROM_REGION( 2127, "maincpu:mpla", 0 ) ROM_LOAD( "tms0270_common2_micro.pla", 0, 2127, CRC(86737ac1) SHA1(4aa0444f3ddf88738ea74aec404c684bf54eddba) ) ROM_REGION( 1246, "maincpu:opla", 0 ) ROM_LOAD( "tms0270_spellb79_output.pla", 0, 1246, CRC(b95e35e6) SHA1(430917486856c9e6c28af10ff3758242048096c4) ) ROM_REGION( 0x1000, "tms6100", 0 ) ROM_LOAD( "cd2602.vsm", 0x0000, 0x1000, CRC(dd1fff8c) SHA1(f1760b29aa50fc96a1538db814cc73289654ac25) ) ROM_END ROM_START( mrchalgr ) ROM_REGION( 0x1000, "maincpu", 0 ) ROM_LOAD( "tmc0273nll", 0x0000, 0x1000, CRC(ef6d23bd) SHA1(194e3b022c299e99a731bbcfba5bf8a3a9f0d07e) ) // matches patent US4421487 ROM_REGION( 1246, "maincpu:ipla", 0 ) ROM_LOAD( "tms0980_common1_instr.pla", 0, 1246, CRC(42db9a38) SHA1(2d127d98028ec8ec6ea10c179c25e447b14ba4d0) ) ROM_REGION( 2127, "maincpu:mpla", 0 ) ROM_LOAD( "tms0270_common2_micro.pla", 0, 2127, CRC(86737ac1) SHA1(4aa0444f3ddf88738ea74aec404c684bf54eddba) ) ROM_REGION( 1246, "maincpu:opla", 0 ) ROM_LOAD( "tms0270_mrchalgr_output.pla", 0, 1246, CRC(4785289c) SHA1(60567af0ea120872a4ccf3128e1365fe84722aa8) ) ROM_REGION( 0x1000, "tms6100", 0 ) ROM_LOAD( "cd2601.vsm", 0x0000, 0x1000, CRC(a9fbe7e9) SHA1(9d480cb30313b8cbce2d048140c1e5e6c5b92452) ) ROM_END /* YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY, FULLNAME, FLAGS */ COMP( 1978, spellb, 0, 0, rev1, spellb, driver_device, 0, "Texas Instruments", "Spelling B (1978 version)", MACHINE_SUPPORTS_SAVE | MACHINE_NO_SOUND_HW ) COMP( 1979, spellb79, spellb, 0, rev2, spellb, driver_device, 0, "Texas Instruments", "Spelling B (1979 version)", MACHINE_SUPPORTS_SAVE ) COMP( 1979, mrchalgr, 0, 0, rev2, mrchalgr, driver_device, 0, "Texas Instruments", "Mr. Challenger", MACHINE_SUPPORTS_SAVE )
gpl-2.0
xmbcrios/xmbcrios.repository
plugin.video.pulsar/navigation.py
154
import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'resources', 'site-packages')) from pulsar import navigation navigation.run()
gpl-2.0
vufind-org/vufind
module/VuFind/src/VuFind/Recommend/SummonResultsDeferred.php
3056
<?php /** * SummonResultsDeferred Recommendations Module * * PHP version 7 * * Copyright (C) Villanova University 2010. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package Recommendations * @author Lutz Biedinger <lutz.biedinger@gmail.com> * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development:plugins:recommendation_modules Wiki */ namespace VuFind\Recommend; /** * SummonResultsDeferred Recommendations Module * * This class sets up an AJAX call to trigger a call to the SummonResults * module. * * @category VuFind * @package Recommendations * @author Lutz Biedinger <lutz.biedigner@gmail.com> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development:plugins:recommendation_modules Wiki */ class SummonResultsDeferred extends AbstractSummonRecommendDeferred { /** * Label for current search type * * @var string */ protected $typeLabel = ''; /** * Constructor */ public function __construct() { $this->module = 'SummonResults'; $this->paramCount = 2; } /** * Called before the Search Results object performs its main search * (specifically, in response to \VuFind\Search\SearchRunner::EVENT_CONFIGURED). * This method is responsible for setting search parameters needed by the * recommendation module and for reading any existing search parameters that may * be needed. * * @param \VuFind\Search\Base\Params $params Search parameter object * @param \Laminas\Stdlib\Parameters $request Parameter object representing user * request. * * @return void */ public function init($params, $request) { parent::init($params, $request); // Collect the label for the current search type: if (is_object($params)) { $this->typeLabel = $params->getOptions()->getLabelForBasicHandler( $params->getSearchHandler() ); } } /** * Get the URL parameters needed to make the AJAX recommendation request. * * @return string */ public function getUrlParams() { return parent::getUrlParams() . '&typeLabel=' . urlencode($this->typeLabel); } }
gpl-2.0
nekrozar/ygopro-scripts
c91862578.lua
483
--激昂のムカムカ function c91862578.initial_effect(c) --atkup local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetRange(LOCATION_MZONE) e1:SetValue(c91862578.val) c:RegisterEffect(e1) --defup local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENSE) c:RegisterEffect(e2) end function c91862578.val(e,c) return Duel.GetFieldGroupCount(c:GetControler(),LOCATION_HAND,0)*400 end
gpl-2.0
YPaquis/RHumeurs.net
wp-content/plugins/contact-form-7/includes/shortcodes.php
4588
<?php class WPCF7_ShortcodeManager { var $shortcode_tags = array(); // Taggs scanned at the last time of do_shortcode() var $scanned_tags = null; // Executing shortcodes (true) or just scanning (false) var $exec = true; function add_shortcode( $tag, $func, $has_name = false ) { if ( is_callable( $func ) ) $this->shortcode_tags[$tag] = array( 'function' => $func, 'has_name' => (boolean) $has_name ); } function remove_shortcode( $tag ) { unset( $this->shortcode_tags[$tag] ); } function normalize_shortcode( $content ) { if ( empty( $this->shortcode_tags ) || ! is_array( $this->shortcode_tags ) ) return $content; $pattern = $this->get_shortcode_regex(); return preg_replace_callback( '/' . $pattern . '/s', array( &$this, 'normalize_space_cb' ), $content ); } function normalize_space_cb( $m ) { // allow [[foo]] syntax for escaping a tag if ( $m[1] == '[' && $m[6] == ']' ) return $m[0]; return preg_replace( '/\s+/', ' ', $m[0] ); } function do_shortcode( $content, $exec = true ) { $this->exec = (bool) $exec; $this->scanned_tags = array(); if ( empty( $this->shortcode_tags ) || ! is_array( $this->shortcode_tags ) ) return $content; $pattern = $this->get_shortcode_regex(); return preg_replace_callback( '/' . $pattern . '/s', array( &$this, 'do_shortcode_tag' ), $content ); } function scan_shortcode( $content ) { $this->do_shortcode( $content, false ); return $this->scanned_tags; } function get_shortcode_regex() { $tagnames = array_keys( $this->shortcode_tags ); $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) ); return '(\[?)\[(' . $tagregexp . ')(?:\s(.*?))?(?:\s(\/))?\](?:(.+?)\[\/\2\])?(\]?)'; } function do_shortcode_tag( $m ) { // allow [[foo]] syntax for escaping a tag if ( $m[1] == '[' && $m[6] == ']' ) { return substr( $m[0], 1, -1 ); } $tag = $m[2]; $attr = $this->shortcode_parse_atts( $m[3] ); $scanned_tag = array(); $scanned_tag['type'] = $tag; if ( is_array( $attr ) ) { if ( is_array( $attr['options'] ) ) { if ( $this->shortcode_tags[$tag]['has_name'] && ! empty( $attr['options'] ) ) { $scanned_tag['name'] = array_shift( $attr['options'] ); if ( ! wpcf7_is_name( $scanned_tag['name'] ) ) return $m[0]; // Invalid name is used. Ignore this tag. } $scanned_tag['options'] = (array) $attr['options']; } $scanned_tag['raw_values'] = (array) $attr['values']; if ( WPCF7_USE_PIPE ) { $pipes = new WPCF7_Pipes( $scanned_tag['raw_values'] ); $scanned_tag['values'] = $pipes->collect_befores(); $scanned_tag['pipes'] = $pipes; } else { $scanned_tag['values'] = $scanned_tag['raw_values']; } $scanned_tag['labels'] = $scanned_tag['values']; } else { $scanned_tag['attr'] = $attr; } $content = trim( $m[5] ); $content = preg_replace( "/<br\s*\/?>$/m", '', $content ); $scanned_tag['content'] = $content; $scanned_tag = apply_filters( 'wpcf7_form_tag', $scanned_tag, $this->exec ); $this->scanned_tags[] = $scanned_tag; if ( $this->exec ) { $func = $this->shortcode_tags[$tag]['function']; return $m[1] . call_user_func( $func, $scanned_tag ) . $m[6]; } else { return $m[0]; } } function shortcode_parse_atts( $text ) { $atts = array( 'options' => array(), 'values' => array() ); $text = preg_replace( "/[\x{00a0}\x{200b}]+/u", " ", $text ); $text = stripcslashes( trim( $text ) ); $pattern = '%^([-+*=0-9a-zA-Z:.!?#$&@_/|\%\s]*?)((?:\s*"[^"]*"|\s*\'[^\']*\')*)$%'; if ( preg_match( $pattern, $text, $match ) ) { if ( ! empty( $match[1] ) ) { $atts['options'] = preg_split( '/[\s]+/', trim( $match[1] ) ); } if ( ! empty( $match[2] ) ) { preg_match_all( '/"[^"]*"|\'[^\']*\'/', $match[2], $matched_values ); $atts['values'] = wpcf7_strip_quote_deep( $matched_values[0] ); } } else { $atts = $text; } return $atts; } } $wpcf7_shortcode_manager = new WPCF7_ShortcodeManager(); function wpcf7_add_shortcode( $tag, $func, $has_name = false ) { global $wpcf7_shortcode_manager; return $wpcf7_shortcode_manager->add_shortcode( $tag, $func, $has_name ); } function wpcf7_remove_shortcode( $tag ) { global $wpcf7_shortcode_manager; return $wpcf7_shortcode_manager->remove_shortcode( $tag ); } function wpcf7_do_shortcode( $content ) { global $wpcf7_shortcode_manager; return $wpcf7_shortcode_manager->do_shortcode( $content ); } function wpcf7_get_shortcode_regex() { global $wpcf7_shortcode_manager; return $wpcf7_shortcode_manager->get_shortcode_regex(); } ?>
gpl-2.0
jluissandovalm/lammps_smd
src/verlet.cpp
10274
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "string.h" #include "verlet.h" #include "neighbor.h" #include "domain.h" #include "comm.h" #include "atom.h" #include "atom_vec.h" #include "force.h" #include "pair.h" #include "bond.h" #include "angle.h" #include "dihedral.h" #include "improper.h" #include "kspace.h" #include "output.h" #include "update.h" #include "modify.h" #include "compute.h" #include "fix.h" #include "timer.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ Verlet::Verlet(LAMMPS *lmp, int narg, char **arg) : Integrate(lmp, narg, arg) {} /* ---------------------------------------------------------------------- initialization before run ------------------------------------------------------------------------- */ void Verlet::init() { Integrate::init(); // warn if no fixes if (modify->nfix == 0 && comm->me == 0) error->warning(FLERR,"No fixes defined, atoms won't move"); // virial_style: // 1 if computed explicitly by pair->compute via sum over pair interactions // 2 if computed implicitly by pair->virial_fdotr_compute via sum over ghosts if (force->newton_pair) virial_style = 2; else virial_style = 1; // setup lists of computes for global and per-atom PE and pressure ev_setup(); // detect if fix omp is present for clearing force arrays int ifix = modify->find_fix("package_omp"); if (ifix >= 0) external_force_clear = 1; // set flags for arrays to clear in force_clear() torqueflag = extraflag = 0; if (atom->torque_flag) torqueflag = 1; if (atom->avec->forceclearflag) extraflag = 1; // orthogonal vs triclinic simulation box triclinic = domain->triclinic; } /* ---------------------------------------------------------------------- setup before run ------------------------------------------------------------------------- */ void Verlet::setup() { if (comm->me == 0 && screen) fprintf(screen,"Setting up run ...\n"); update->setupflag = 1; // setup domain, communication and neighboring // acquire ghosts // build neighbor lists atom->setup(); modify->setup_pre_exchange(); if (triclinic) domain->x2lamda(atom->nlocal); domain->pbc(); domain->reset_box(); comm->setup(); if (neighbor->style) neighbor->setup_bins(); comm->exchange(); if (atom->sortfreq > 0) atom->sort(); comm->borders(); if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost); domain->image_check(); domain->box_too_small_check(); modify->setup_pre_neighbor(); neighbor->build(); neighbor->ncalls = 0; // compute all forces ev_set(update->ntimestep); force_clear(); modify->setup_pre_force(vflag); if (pair_compute_flag) force->pair->compute(eflag,vflag); else if (force->pair) force->pair->compute_dummy(eflag,vflag); if (atom->molecular) { if (force->bond) force->bond->compute(eflag,vflag); if (force->angle) force->angle->compute(eflag,vflag); if (force->dihedral) force->dihedral->compute(eflag,vflag); if (force->improper) force->improper->compute(eflag,vflag); } if (force->kspace) { force->kspace->setup(); if (kspace_compute_flag) force->kspace->compute(eflag,vflag); else force->kspace->compute_dummy(eflag,vflag); } if (force->newton) comm->reverse_comm(); modify->setup(vflag); output->setup(); update->setupflag = 0; } /* ---------------------------------------------------------------------- setup without output flag = 0 = just force calculation flag = 1 = reneighbor and force calculation ------------------------------------------------------------------------- */ void Verlet::setup_minimal(int flag) { update->setupflag = 1; // setup domain, communication and neighboring // acquire ghosts // build neighbor lists if (flag) { modify->setup_pre_exchange(); if (triclinic) domain->x2lamda(atom->nlocal); domain->pbc(); domain->reset_box(); comm->setup(); if (neighbor->style) neighbor->setup_bins(); comm->exchange(); comm->borders(); if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost); domain->image_check(); domain->box_too_small_check(); modify->setup_pre_neighbor(); neighbor->build(); neighbor->ncalls = 0; } // compute all forces ev_set(update->ntimestep); force_clear(); modify->setup_pre_force(vflag); if (pair_compute_flag) force->pair->compute(eflag,vflag); else if (force->pair) force->pair->compute_dummy(eflag,vflag); if (atom->molecular) { if (force->bond) force->bond->compute(eflag,vflag); if (force->angle) force->angle->compute(eflag,vflag); if (force->dihedral) force->dihedral->compute(eflag,vflag); if (force->improper) force->improper->compute(eflag,vflag); } if (force->kspace) { force->kspace->setup(); if (kspace_compute_flag) force->kspace->compute(eflag,vflag); else force->kspace->compute_dummy(eflag,vflag); } if (force->newton) comm->reverse_comm(); modify->setup(vflag); update->setupflag = 0; } /* ---------------------------------------------------------------------- run for N steps ------------------------------------------------------------------------- */ void Verlet::run(int n) { bigint ntimestep; int nflag,sortflag; int n_post_integrate = modify->n_post_integrate; int n_pre_exchange = modify->n_pre_exchange; int n_pre_neighbor = modify->n_pre_neighbor; int n_pre_force = modify->n_pre_force; int n_post_force = modify->n_post_force; int n_end_of_step = modify->n_end_of_step; if (atom->sortfreq > 0) sortflag = 1; else sortflag = 0; for (int i = 0; i < n; i++) { ntimestep = ++update->ntimestep; ev_set(ntimestep); // initial time integration modify->initial_integrate(vflag); if (n_post_integrate) modify->post_integrate(); // regular communication vs neighbor list rebuild nflag = neighbor->decide(); if (nflag == 0) { timer->stamp(); comm->forward_comm(); timer->stamp(TIME_COMM); } else { if (n_pre_exchange) modify->pre_exchange(); if (triclinic) domain->x2lamda(atom->nlocal); domain->pbc(); if (domain->box_change) { domain->reset_box(); comm->setup(); if (neighbor->style) neighbor->setup_bins(); } timer->stamp(); comm->exchange(); if (sortflag && ntimestep >= atom->nextsort) atom->sort(); comm->borders(); if (triclinic) domain->lamda2x(atom->nlocal+atom->nghost); timer->stamp(TIME_COMM); if (n_pre_neighbor) modify->pre_neighbor(); neighbor->build(); timer->stamp(TIME_NEIGHBOR); } // force computations // important for pair to come before bonded contributions // since some bonded potentials tally pairwise energy/virial // and Pair:ev_tally() needs to be called before any tallying force_clear(); if (n_pre_force) modify->pre_force(vflag); timer->stamp(); if (pair_compute_flag) { force->pair->compute(eflag,vflag); timer->stamp(TIME_PAIR); } if (atom->molecular) { if (force->bond) force->bond->compute(eflag,vflag); if (force->angle) force->angle->compute(eflag,vflag); if (force->dihedral) force->dihedral->compute(eflag,vflag); if (force->improper) force->improper->compute(eflag,vflag); timer->stamp(TIME_BOND); } if (kspace_compute_flag) { force->kspace->compute(eflag,vflag); timer->stamp(TIME_KSPACE); } // reverse communication of forces if (force->newton) { comm->reverse_comm(); timer->stamp(TIME_COMM); } // force modifications, final time integration, diagnostics if (n_post_force) modify->post_force(vflag); modify->final_integrate(); if (n_end_of_step) modify->end_of_step(); // all output if (ntimestep == output->next) { timer->stamp(); output->write(ntimestep); timer->stamp(TIME_OUTPUT); } } } /* ---------------------------------------------------------------------- */ void Verlet::cleanup() { modify->post_run(); domain->box_too_small_check(); update->update_time(); } /* ---------------------------------------------------------------------- clear force on own & ghost atoms clear other arrays as needed ------------------------------------------------------------------------- */ void Verlet::force_clear() { int i; size_t nbytes; if (external_force_clear) return; // clear force on all particles // if either newton flag is set, also include ghosts // when using threads always clear all forces. int nlocal = atom->nlocal; if (neighbor->includegroup == 0) { nbytes = sizeof(double) * nlocal; if (force->newton) nbytes += sizeof(double) * atom->nghost; if (nbytes) { memset(&atom->f[0][0],0,3*nbytes); if (torqueflag) memset(&atom->torque[0][0],0,3*nbytes); if (extraflag) atom->avec->force_clear(0,nbytes); } // neighbor includegroup flag is set // clear force only on initial nfirst particles // if either newton flag is set, also include ghosts } else { nbytes = sizeof(double) * atom->nfirst; if (nbytes) { memset(&atom->f[0][0],0,3*nbytes); if (torqueflag) memset(&atom->torque[0][0],0,3*nbytes); if (extraflag) atom->avec->force_clear(0,nbytes); } if (force->newton) { nbytes = sizeof(double) * atom->nghost; if (nbytes) { memset(&atom->f[nlocal][0],0,3*nbytes); if (torqueflag) memset(&atom->torque[nlocal][0],0,3*nbytes); if (extraflag) atom->avec->force_clear(nlocal,nbytes); } } } }
gpl-2.0
bogzybodo/FrozenCore-3.3.5
src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp
6126
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Magisters_Terrace SD%Complete: 100 SDComment: Quest support: 11490(post-event) SDCategory: Magisters Terrace EndScriptData */ /* ContentData npc_kalecgos EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" /*###### ## npc_kalecgos ######*/ enum eEnums { SPELL_TRANSFORM_TO_KAEL = 44670, SPELL_ORB_KILL_CREDIT = 46307, NPC_KAEL = 24848, //human form entry POINT_ID_LAND = 1 }; const float afKaelLandPoint[] = {225.045f, -276.236f, -5.434f}; #define GOSSIP_ITEM_KAEL_1 "Who are you?" #define GOSSIP_ITEM_KAEL_2 "What can we do to assist you?" #define GOSSIP_ITEM_KAEL_3 "What brings you to the Sunwell?" #define GOSSIP_ITEM_KAEL_4 "You're not alone here?" #define GOSSIP_ITEM_KAEL_5 "What would Kil'jaeden want with a mortal woman?" // This is friendly keal that appear after used Orb. // If we assume DB handle summon, summon appear somewhere outside the platform where Orb is class npc_kalecgos : public CreatureScript { public: npc_kalecgos() : CreatureScript("npc_kalecgos") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); switch (action) { case GOSSIP_ACTION_INFO_DEF: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAEL_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); player->SEND_GOSSIP_MENU(12500, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+1: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAEL_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); player->SEND_GOSSIP_MENU(12502, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+2: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAEL_4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); player->SEND_GOSSIP_MENU(12606, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+3: player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAEL_5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); player->SEND_GOSSIP_MENU(12607, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+4: player->SEND_GOSSIP_MENU(12608, creature->GetGUID()); break; } return true; } bool OnGossipHello(Player* player, Creature* creature) { if (creature->isQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAEL_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); player->SEND_GOSSIP_MENU(12498, creature->GetGUID()); return true; } CreatureAI* GetAI(Creature* creature) const { return new npc_kalecgosAI(creature); } struct npc_kalecgosAI : public ScriptedAI { npc_kalecgosAI(Creature* creature) : ScriptedAI(creature) {} uint32 m_uiTransformTimer; void Reset() { m_uiTransformTimer = 0; // we must assume he appear as dragon somewhere outside the platform of orb, and then move directly to here if (me->GetEntry() != NPC_KAEL) me->GetMotionMaster()->MovePoint(POINT_ID_LAND, afKaelLandPoint[0], afKaelLandPoint[1], afKaelLandPoint[2]); } void MovementInform(uint32 uiType, uint32 uiPointId) { if (uiType != POINT_MOTION_TYPE) return; if (uiPointId == POINT_ID_LAND) m_uiTransformTimer = MINUTE*IN_MILLISECONDS; } // some targeting issues with the spell, so use this workaround as temporary solution void DoWorkaroundForQuestCredit() { Map* map = me->GetMap(); if (!map || map->IsHeroic()) return; Map::PlayerList const &lList = map->GetPlayers(); if (lList.isEmpty()) return; SpellInfo const* spell = sSpellMgr->GetSpellInfo(SPELL_ORB_KILL_CREDIT); for (Map::PlayerList::const_iterator i = lList.begin(); i != lList.end(); ++i) { if (Player* player = i->getSource()) { if (spell && spell->Effects[0].MiscValue) player->KilledMonsterCredit(spell->Effects[0].MiscValue, 0); } } } void UpdateAI(const uint32 uiDiff) { if (m_uiTransformTimer) { if (m_uiTransformTimer <= uiDiff) { DoCast(me, SPELL_ORB_KILL_CREDIT, false); DoWorkaroundForQuestCredit(); // Transform and update entry, now ready for quest/read gossip DoCast(me, SPELL_TRANSFORM_TO_KAEL, false); me->UpdateEntry(NPC_KAEL); m_uiTransformTimer = 0; } else m_uiTransformTimer -= uiDiff; } } }; }; void AddSC_magisters_terrace() { new npc_kalecgos(); }
gpl-2.0
xstory61/server
scripts/reactor/9102005.js
1123
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @author BubblesDev * @purpose Drops Brown Primrose Seeds (4001098) * @map Primrose Hill */ function act() { rm.dropItems(); }
gpl-2.0
ChuguluGames/mediawiki
includes/Block.php
25265
<?php /** * @file * Blocks and bans object */ /** * The block class * All the functions in this class assume the object is either explicitly * loaded or filled. It is not load-on-demand. There are no accessors. * * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags * * @todo This could be used everywhere, but it isn't. */ class Block { /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry, $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName, $mBlockEmail, $mByName, $mAngryAutoblock, $mAllowUsertalk; /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster; const EB_KEEP_EXPIRED = 1; const EB_FOR_UPDATE = 2; const EB_RANGE_ONLY = 4; function __construct( $address = '', $user = 0, $by = 0, $reason = '', $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0, $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byName = false ) { $this->mId = 0; # Expand valid IPv6 addresses $address = IP::sanitizeIP( $address ); $this->mAddress = $address; $this->mUser = $user; $this->mBy = $by; $this->mReason = $reason; $this->mTimestamp = wfTimestamp( TS_MW, $timestamp ); $this->mAuto = $auto; $this->mAnonOnly = $anonOnly; $this->mCreateAccount = $createAccount; $this->mExpiry = self::decodeExpiry( $expiry ); $this->mEnableAutoblock = $enableAutoblock; $this->mHideName = $hideName; $this->mBlockEmail = $blockEmail; $this->mAllowUsertalk = $allowUsertalk; $this->mForUpdate = false; $this->mFromMaster = false; $this->mByName = $byName; $this->mAngryAutoblock = false; $this->initialiseRange(); } /** * Load a block from the database, using either the IP address or * user ID. Tries the user ID first, and if that doesn't work, tries * the address. * * @param $address String: IP address of user/anon * @param $user Integer: user id of user * @param $killExpired Boolean: delete expired blocks on load * @return Block Object */ public static function newFromDB( $address, $user = 0, $killExpired = true ) { $block = new Block; $block->load( $address, $user, $killExpired ); if ( $block->isValid() ) { return $block; } else { return null; } } /** * Load a blocked user from their block id. * * @param $id Integer: Block id to search for * @return Block object */ public static function newFromID( $id ) { $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*', array( 'ipb_id' => $id ), __METHOD__ ) ); $block = new Block; if ( $block->loadFromResult( $res ) ) { return $block; } else { return null; } } /** * Check if two blocks are effectively equal * * @return Boolean */ public function equals( Block $block ) { return ( $this->mAddress == $block->mAddress && $this->mUser == $block->mUser && $this->mAuto == $block->mAuto && $this->mAnonOnly == $block->mAnonOnly && $this->mCreateAccount == $block->mCreateAccount && $this->mExpiry == $block->mExpiry && $this->mEnableAutoblock == $block->mEnableAutoblock && $this->mHideName == $block->mHideName && $this->mBlockEmail == $block->mBlockEmail && $this->mAllowUsertalk == $block->mAllowUsertalk && $this->mReason == $block->mReason ); } /** * Clear all member variables in the current object. Does not clear * the block from the DB. */ public function clear() { $this->mAddress = $this->mReason = $this->mTimestamp = ''; $this->mId = $this->mAnonOnly = $this->mCreateAccount = $this->mEnableAutoblock = $this->mAuto = $this->mUser = $this->mBy = $this->mHideName = $this->mBlockEmail = $this->mAllowUsertalk = 0; $this->mByName = false; } /** * Get the DB object and set the reference parameter to the select options. * The options array will contain FOR UPDATE if appropriate. * * @param $options Array * @return Database */ protected function &getDBOptions( &$options ) { global $wgAntiLockFlags; if ( $this->mForUpdate || $this->mFromMaster ) { $db = wfGetDB( DB_MASTER ); if ( !$this->mForUpdate || ( $wgAntiLockFlags & ALF_NO_BLOCK_LOCK ) ) { $options = array(); } else { $options = array( 'FOR UPDATE' ); } } else { $db = wfGetDB( DB_SLAVE ); $options = array(); } return $db; } /** * Get a block from the DB, with either the given address or the given username * * @param $address string The IP address of the user, or blank to skip IP blocks * @param $user int The user ID, or zero for anonymous users * @param $killExpired bool Whether to delete expired rows while loading * @return Boolean: the user is blocked from editing * */ public function load( $address = '', $user = 0, $killExpired = true ) { wfDebug( "Block::load: '$address', '$user', $killExpired\n" ); $options = array(); $db = $this->getDBOptions( $options ); if ( 0 == $user && $address === '' ) { # Invalid user specification, not blocked $this->clear(); return false; } # Try user block if ( $user ) { $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ), __METHOD__, $options ) ); if ( $this->loadFromResult( $res, $killExpired ) ) { return true; } } # Try IP block # TODO: improve performance by merging this query with the autoblock one # Slightly tricky while handling killExpired as well if ( $address !== '' ) { $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 ); $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) ); if ( $this->loadFromResult( $res, $killExpired ) ) { if ( $user && $this->mAnonOnly ) { # Block is marked anon-only # Whitelist this IP address against autoblocks and range blocks # (but not account creation blocks -- bug 13611) if ( !$this->mCreateAccount ) { $this->clear(); } return false; } else { return true; } } } # Try range block if ( $this->loadRange( $address, $killExpired, $user ) ) { if ( $user && $this->mAnonOnly ) { # Respect account creation blocks on logged-in users -- bug 13611 if ( !$this->mCreateAccount ) { $this->clear(); } return false; } else { return true; } } # Try autoblock if ( $address ) { $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 ); if ( $user ) { $conds['ipb_anon_only'] = 0; } $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) ); if ( $this->loadFromResult( $res, $killExpired ) ) { return true; } } # Give up $this->clear(); return false; } /** * Fill in member variables from a result wrapper * * @param $res ResultWrapper: row from the ipblocks table * @param $killExpired Boolean: whether to delete expired rows while loading * @return Boolean */ protected function loadFromResult( ResultWrapper $res, $killExpired = true ) { $ret = false; if ( 0 != $res->numRows() ) { # Get first block $row = $res->fetchObject(); $this->initFromRow( $row ); if ( $killExpired ) { # If requested, delete expired rows do { $killed = $this->deleteIfExpired(); if ( $killed ) { $row = $res->fetchObject(); if ( $row ) { $this->initFromRow( $row ); } } } while ( $killed && $row ); # If there were any left after the killing finished, return true if ( $row ) { $ret = true; } } else { $ret = true; } } $res->free(); return $ret; } /** * Search the database for any range blocks matching the given address, and * load the row if one is found. * * @param $address String: IP address range * @param $killExpired Boolean: whether to delete expired rows while loading * @param $user Integer: if not 0, then sets ipb_anon_only * @return Boolean */ public function loadRange( $address, $killExpired = true, $user = 0 ) { $iaddr = IP::toHex( $address ); if ( $iaddr === false ) { # Invalid address return false; } # Only scan ranges which start in this /16, this improves search speed # Blocks should not cross a /16 boundary. $range = substr( $iaddr, 0, 4 ); $options = array(); $db = $this->getDBOptions( $options ); $conds = array( 'ipb_range_start' . $db->buildLike( $range, $db->anyString() ), "ipb_range_start <= '$iaddr'", "ipb_range_end >= '$iaddr'" ); if ( $user ) { $conds['ipb_anon_only'] = 0; } $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) ); $success = $this->loadFromResult( $res, $killExpired ); return $success; } /** * Given a database row from the ipblocks table, initialize * member variables * * @param $row ResultWrapper: a row from the ipblocks table */ public function initFromRow( $row ) { $this->mAddress = $row->ipb_address; $this->mReason = $row->ipb_reason; $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp ); $this->mUser = $row->ipb_user; $this->mBy = $row->ipb_by; $this->mAuto = $row->ipb_auto; $this->mAnonOnly = $row->ipb_anon_only; $this->mCreateAccount = $row->ipb_create_account; $this->mEnableAutoblock = $row->ipb_enable_autoblock; $this->mBlockEmail = $row->ipb_block_email; $this->mAllowUsertalk = $row->ipb_allow_usertalk; $this->mHideName = $row->ipb_deleted; $this->mId = $row->ipb_id; $this->mExpiry = self::decodeExpiry( $row->ipb_expiry ); if ( isset( $row->user_name ) ) { $this->mByName = $row->user_name; } else { $this->mByName = $row->ipb_by_text; } $this->mRangeStart = $row->ipb_range_start; $this->mRangeEnd = $row->ipb_range_end; } /** * Once $mAddress has been set, get the range they came from. * Wrapper for IP::parseRange */ protected function initialiseRange() { $this->mRangeStart = ''; $this->mRangeEnd = ''; if ( $this->mUser == 0 ) { list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress ); } } /** * Delete the row from the IP blocks table. * * @return Boolean */ public function delete() { if ( wfReadOnly() ) { return false; } if ( !$this->mId ) { throw new MWException( "Block::delete() now requires that the mId member be filled\n" ); } $dbw = wfGetDB( DB_MASTER ); $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ ); return $dbw->affectedRows() > 0; } /** * Insert a block into the block table. Will fail if there is a conflicting * block (same name and options) already in the database. * * @return Boolean: whether or not the insertion was successful. */ public function insert( $dbw = null ) { wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" ); if ( $dbw === null ) $dbw = wfGetDB( DB_MASTER ); $this->validateBlockParams(); $this->initialiseRange(); # Don't collide with expired blocks Block::purgeExpired(); $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' ); $dbw->insert( 'ipblocks', array( 'ipb_id' => $ipb_id, 'ipb_address' => $this->mAddress, 'ipb_user' => $this->mUser, 'ipb_by' => $this->mBy, 'ipb_by_text' => $this->mByName, 'ipb_reason' => $this->mReason, 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ), 'ipb_auto' => $this->mAuto, 'ipb_anon_only' => $this->mAnonOnly, 'ipb_create_account' => $this->mCreateAccount, 'ipb_enable_autoblock' => $this->mEnableAutoblock, 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ), 'ipb_range_start' => $this->mRangeStart, 'ipb_range_end' => $this->mRangeEnd, 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite 'ipb_block_email' => $this->mBlockEmail, 'ipb_allow_usertalk' => $this->mAllowUsertalk ), 'Block::insert', array( 'IGNORE' ) ); $affected = $dbw->affectedRows(); if ( $affected ) $this->doRetroactiveAutoblock(); return (bool)$affected; } /** * Update a block in the DB with new parameters. * The ID field needs to be loaded first. */ public function update() { wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" ); $dbw = wfGetDB( DB_MASTER ); $this->validateBlockParams(); $dbw->update( 'ipblocks', array( 'ipb_user' => $this->mUser, 'ipb_by' => $this->mBy, 'ipb_by_text' => $this->mByName, 'ipb_reason' => $this->mReason, 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ), 'ipb_auto' => $this->mAuto, 'ipb_anon_only' => $this->mAnonOnly, 'ipb_create_account' => $this->mCreateAccount, 'ipb_enable_autoblock' => $this->mEnableAutoblock, 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ), 'ipb_range_start' => $this->mRangeStart, 'ipb_range_end' => $this->mRangeEnd, 'ipb_deleted' => $this->mHideName, 'ipb_block_email' => $this->mBlockEmail, 'ipb_allow_usertalk' => $this->mAllowUsertalk ), array( 'ipb_id' => $this->mId ), 'Block::update' ); return $dbw->affectedRows(); } /** * Make sure all the proper members are set to sane values * before adding/updating a block */ protected function validateBlockParams() { # Unset ipb_anon_only for user blocks, makes no sense if ( $this->mUser ) { $this->mAnonOnly = 0; } # Unset ipb_enable_autoblock for IP blocks, makes no sense if ( !$this->mUser ) { $this->mEnableAutoblock = 0; } # bug 18860: non-anon-only IP blocks should be allowed to block email if ( !$this->mUser && $this->mAnonOnly ) { $this->mBlockEmail = 0; } if ( !$this->mByName ) { if ( $this->mBy ) { $this->mByName = User::whoIs( $this->mBy ); } else { global $wgUser; $this->mByName = $wgUser->getName(); } } } /** * Retroactively autoblocks the last IP used by the user (if it is a user) * blocked by this Block. * * @return Boolean: whether or not a retroactive autoblock was made. */ public function doRetroactiveAutoblock() { $dbr = wfGetDB( DB_SLAVE ); # If autoblock is enabled, autoblock the LAST IP used # - stolen shamelessly from CheckUser_body.php if ( $this->mEnableAutoblock && $this->mUser ) { wfDebug( "Doing retroactive autoblocks for " . $this->mAddress . "\n" ); $options = array( 'ORDER BY' => 'rc_timestamp DESC' ); $conds = array( 'rc_user_text' => $this->mAddress ); if ( $this->mAngryAutoblock ) { // Block any IP used in the last 7 days. Up to five IPs. $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) ); $options['LIMIT'] = 5; } else { // Just the last IP used. $options['LIMIT'] = 1; } $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds, __METHOD__ , $options ); if ( !$dbr->numRows( $res ) ) { # No results, don't autoblock anything wfDebug( "No IP found to retroactively autoblock\n" ); } else { foreach ( $res as $row ) { if ( $row->rc_ip ) { $this->doAutoblock( $row->rc_ip ); } } } } } /** * Checks whether a given IP is on the autoblock whitelist. * * @param $ip String: The IP to check * @return Boolean */ public static function isWhitelistedFromAutoblocks( $ip ) { global $wgMemc; // Try to get the autoblock_whitelist from the cache, as it's faster // than getting the msg raw and explode()'ing it. $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' ); $lines = $wgMemc->get( $key ); if ( !$lines ) { $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) ); $wgMemc->set( $key, $lines, 3600 * 24 ); } wfDebug( "Checking the autoblock whitelist..\n" ); foreach ( $lines as $line ) { # List items only if ( substr( $line, 0, 1 ) !== '*' ) { continue; } $wlEntry = substr( $line, 1 ); $wlEntry = trim( $wlEntry ); wfDebug( "Checking $ip against $wlEntry..." ); # Is the IP in this range? if ( IP::isInRange( $ip, $wlEntry ) ) { wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" ); return true; } else { wfDebug( " No match\n" ); } } return false; } /** * Autoblocks the given IP, referring to this Block. * * @param $autoblockIP String: the IP to autoblock. * @param $justInserted Boolean: the main block was just inserted * @return Boolean: whether or not an autoblock was inserted. */ public function doAutoblock( $autoblockIP, $justInserted = false ) { # If autoblocks are disabled, go away. if ( !$this->mEnableAutoblock ) { return; } # Check for presence on the autoblock whitelist if ( Block::isWhitelistedFromAutoblocks( $autoblockIP ) ) { return; } # # Allow hooks to cancel the autoblock. if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) { wfDebug( "Autoblock aborted by hook.\n" ); return false; } # It's okay to autoblock. Go ahead and create/insert the block. $ipblock = Block::newFromDB( $autoblockIP ); if ( $ipblock ) { # If the user is already blocked. Then check if the autoblock would # exceed the user block. If it would exceed, then do nothing, else # prolong block time if ( $this->mExpiry && ( $this->mExpiry < Block::getAutoblockExpiry( $ipblock->mTimestamp ) ) ) { return; } # Just update the timestamp if ( !$justInserted ) { $ipblock->updateTimestamp(); } return; } else { $ipblock = new Block; } # Make a new block object with the desired properties wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" ); $ipblock->mAddress = $autoblockIP; $ipblock->mUser = 0; $ipblock->mBy = $this->mBy; $ipblock->mByName = $this->mByName; $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason ); $ipblock->mTimestamp = wfTimestampNow(); $ipblock->mAuto = 1; $ipblock->mCreateAccount = $this->mCreateAccount; # Continue suppressing the name if needed $ipblock->mHideName = $this->mHideName; $ipblock->mAllowUsertalk = $this->mAllowUsertalk; # If the user is already blocked with an expiry date, we don't # want to pile on top of that! if ( $this->mExpiry ) { $ipblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ) ); } else { $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp ); } # Insert it return $ipblock->insert(); } /** * Check if a block has expired. Delete it if it is. * @return Boolean */ public function deleteIfExpired() { wfProfileIn( __METHOD__ ); if ( $this->isExpired() ) { wfDebug( "Block::deleteIfExpired() -- deleting\n" ); $this->delete(); $retVal = true; } else { wfDebug( "Block::deleteIfExpired() -- not expired\n" ); $retVal = false; } wfProfileOut( __METHOD__ ); return $retVal; } /** * Has the block expired? * @return Boolean */ public function isExpired() { wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" ); if ( !$this->mExpiry ) { return false; } else { return wfTimestampNow() > $this->mExpiry; } } /** * Is the block address valid (i.e. not a null string?) * @return Boolean */ public function isValid() { return $this->mAddress != ''; } /** * Update the timestamp on autoblocks. */ public function updateTimestamp() { if ( $this->mAuto ) { $this->mTimestamp = wfTimestamp(); $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp ); $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'ipblocks', array( /* SET */ 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ), 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ), ), array( /* WHERE */ 'ipb_address' => $this->mAddress ), 'Block::updateTimestamp' ); } } /** * Get the user id of the blocking sysop * * @return Integer */ public function getBy() { return $this->mBy; } /** * Get the username of the blocking sysop * * @return String */ public function getByName() { return $this->mByName; } /** * Get/set the SELECT ... FOR UPDATE flag */ public function forUpdate( $x = null ) { return wfSetVar( $this->mForUpdate, $x ); } /** * Get/set a flag determining whether the master is used for reads */ public function fromMaster( $x = null ) { return wfSetVar( $this->mFromMaster, $x ); } /** * Get the block name, but with autoblocked IPs hidden as per standard privacy policy * @return String */ public function getRedactedName() { if ( $this->mAuto ) { return '#' . $this->mId; } else { return $this->mAddress; } } /** * Encode expiry for DB * * @param $expiry String: timestamp for expiry, or * @param $db Database object * @return String */ public static function encodeExpiry( $expiry, $db ) { if ( $expiry == '' || $expiry == Block::infinity() ) { return Block::infinity(); } else { return $db->timestamp( $expiry ); } } /** * Decode expiry which has come from the DB * * @param $expiry String: Database expiry format * @param $timestampType Requested timestamp format * @return String */ public static function decodeExpiry( $expiry, $timestampType = TS_MW ) { if ( $expiry == '' || $expiry == Block::infinity() ) { return Block::infinity(); } else { return wfTimestamp( $timestampType, $expiry ); } } /** * Get a timestamp of the expiry for autoblocks * * @return String */ public static function getAutoblockExpiry( $timestamp ) { global $wgAutoblockExpiry; return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry ); } /** * Gets rid of uneeded numbers in quad-dotted/octet IP strings * For example, 127.111.113.151/24 -> 127.111.113.0/24 * @param $range String: IP address to normalize * @return string */ public static function normaliseRange( $range ) { $parts = explode( '/', $range ); if ( count( $parts ) == 2 ) { // IPv6 if ( IP::isIPv6( $range ) && $parts[1] >= 64 && $parts[1] <= 128 ) { $bits = $parts[1]; $ipint = IP::toUnsigned( $parts[0] ); # Native 32 bit functions WON'T work here!!! # Convert to a padded binary number $network = wfBaseConvert( $ipint, 10, 2, 128 ); # Truncate the last (128-$bits) bits and replace them with zeros $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT ); # Convert back to an integer $network = wfBaseConvert( $network, 2, 10 ); # Reform octet address $newip = IP::toOctet( $network ); $range = "$newip/{$parts[1]}"; } // IPv4 elseif ( IP::isIPv4( $range ) && $parts[1] >= 16 && $parts[1] <= 32 ) { $shift = 32 - $parts[1]; $ipint = IP::toUnsigned( $parts[0] ); $ipint = $ipint >> $shift << $shift; $newip = long2ip( $ipint ); $range = "$newip/{$parts[1]}"; } } return $range; } /** * Purge expired blocks from the ipblocks table */ public static function purgeExpired() { $dbw = wfGetDB( DB_MASTER ); $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ ); } /** * Get a value to insert into expiry field of the database when infinite expiry * is desired. In principle this could be DBMS-dependant, but currently all * supported DBMS's support the string "infinity", so we just use that. * * @return String */ public static function infinity() { # This is a special keyword for timestamps in PostgreSQL, and # works with CHAR(14) as well because "i" sorts after all numbers. # BEGIN DatabaseMssql hack # Since MSSQL doesn't recognize the infinity keyword, set date manually. # TO-DO: Refactor for better DB portability and remove magic date $dbr = wfGetDB( DB_SLAVE ); if ( $dbr->getType() == 'mssql' ) { return '3000-01-31 00:00:00.000'; } # End DatabaseMssql hack return 'infinity'; } /** * Convert a DB-encoded expiry into a real string that humans can read. * * @param $encoded_expiry String: Database encoded expiry time * @return Html-escaped String */ public static function formatExpiry( $encoded_expiry ) { static $msg = null; if ( is_null( $msg ) ) { $msg = array(); $keys = array( 'infiniteblock', 'expiringblock' ); foreach ( $keys as $key ) { $msg[$key] = wfMsgHtml( $key ); } } $expiry = Block::decodeExpiry( $encoded_expiry ); if ( $expiry == 'infinity' ) { $expirystr = $msg['infiniteblock']; } else { global $wgLang; $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) ); $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) ); $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) ); } return $expirystr; } /** * Convert a typed-in expiry time into something we can put into the database. * @param $expiry_input String: whatever was typed into the form * @return String: more database friendly */ public static function parseExpiryInput( $expiry_input ) { if ( $expiry_input == 'infinite' || $expiry_input == 'indefinite' ) { $expiry = 'infinity'; } else { $expiry = strtotime( $expiry_input ); if ( $expiry < 0 || $expiry === false ) { return false; } } return $expiry; } }
gpl-2.0
csaldana/Proyecto-final
ZombieSystem1.2.0/Proyecto V 1.1.1/Zombie System V1.2/Proyecto/Cliente.Designer.cs
15151
/* * Created by SharpDevelop. * User: jonathan * Date: 05/12/2013 * Time: 11:53 p. m. * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ namespace Proyecto { partial class Cliente { /// <summary> /// Designer variable used to keep track of non-visual components. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Disposes resources used by the form. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } /// <summary> /// This method is required for Windows Forms designer support. /// Do not change the method contents inside the source code editor. The Forms designer might /// not be able to load this method if it was changed manually. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Cliente)); this.label1 = new System.Windows.Forms.Label(); this.textNombre = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.textApellp = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textapellm = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.textFechaN = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.textTelefono = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.textCorreo = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.textCalle = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.textNumInt = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.textNumExt = new System.Windows.Forms.TextBox(); this.label11 = new System.Windows.Forms.Label(); this.textCP = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.textcolonia = new System.Windows.Forms.TextBox(); this.textMunicipio = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.textEstado = new System.Windows.Forms.TextBox(); this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker(); this.ButGuardar = new System.Windows.Forms.Button(); this.textid = new System.Windows.Forms.TextBox(); this.label15 = new System.Windows.Forms.Label(); this.butSalir = new System.Windows.Forms.Button(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.buActualizar = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(37, 43); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 23); this.label1.TabIndex = 0; this.label1.Text = "Nombre"; // // textNombre // this.textNombre.Location = new System.Drawing.Point(37, 69); this.textNombre.Name = "textNombre"; this.textNombre.Size = new System.Drawing.Size(151, 20); this.textNombre.TabIndex = 1; // // label2 // this.label2.Location = new System.Drawing.Point(220, 43); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(100, 23); this.label2.TabIndex = 2; this.label2.Text = "Apellido paterno"; // // textApellp // this.textApellp.Location = new System.Drawing.Point(220, 69); this.textApellp.Name = "textApellp"; this.textApellp.Size = new System.Drawing.Size(100, 20); this.textApellp.TabIndex = 3; // // label3 // this.label3.Location = new System.Drawing.Point(354, 43); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(100, 23); this.label3.TabIndex = 4; this.label3.Text = "Apellido materno"; // // textapellm // this.textapellm.Location = new System.Drawing.Point(354, 69); this.textapellm.Name = "textapellm"; this.textapellm.Size = new System.Drawing.Size(100, 20); this.textapellm.TabIndex = 5; // // label4 // this.label4.Location = new System.Drawing.Point(501, 43); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(125, 23); this.label4.TabIndex = 6; this.label4.Text = "Fecha de nacimiento"; // // textFechaN // this.textFechaN.Location = new System.Drawing.Point(501, 69); this.textFechaN.Name = "textFechaN"; this.textFechaN.Size = new System.Drawing.Size(100, 20); this.textFechaN.TabIndex = 7; // // label5 // this.label5.Location = new System.Drawing.Point(632, 43); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(100, 23); this.label5.TabIndex = 8; this.label5.Text = "Teléfono"; // // textTelefono // this.textTelefono.Location = new System.Drawing.Point(632, 69); this.textTelefono.Name = "textTelefono"; this.textTelefono.Size = new System.Drawing.Size(136, 20); this.textTelefono.TabIndex = 9; // // label6 // this.label6.Location = new System.Drawing.Point(37, 105); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(100, 23); this.label6.TabIndex = 11; this.label6.Text = "Correo Electrónico"; // // textCorreo // this.textCorreo.Location = new System.Drawing.Point(37, 131); this.textCorreo.Name = "textCorreo"; this.textCorreo.Size = new System.Drawing.Size(138, 20); this.textCorreo.TabIndex = 12; // // label8 // this.label8.Location = new System.Drawing.Point(202, 105); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(100, 23); this.label8.TabIndex = 14; this.label8.Text = "Calle"; // // textCalle // this.textCalle.Location = new System.Drawing.Point(202, 131); this.textCalle.Name = "textCalle"; this.textCalle.Size = new System.Drawing.Size(136, 20); this.textCalle.TabIndex = 15; // // label9 // this.label9.Location = new System.Drawing.Point(474, 105); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(100, 23); this.label9.TabIndex = 16; this.label9.Text = "Número Interior"; // // textNumInt // this.textNumInt.Location = new System.Drawing.Point(354, 131); this.textNumInt.Name = "textNumInt"; this.textNumInt.Size = new System.Drawing.Size(100, 20); this.textNumInt.TabIndex = 17; this.textNumInt.TextChanged += new System.EventHandler(this.TextNumIntTextChanged); // // label10 // this.label10.Location = new System.Drawing.Point(354, 105); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(100, 23); this.label10.TabIndex = 18; this.label10.Text = "Número Exterior"; // // textNumExt // this.textNumExt.Location = new System.Drawing.Point(474, 131); this.textNumExt.Name = "textNumExt"; this.textNumExt.Size = new System.Drawing.Size(100, 20); this.textNumExt.TabIndex = 19; // // label11 // this.label11.Location = new System.Drawing.Point(288, 171); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(100, 23); this.label11.TabIndex = 20; this.label11.Text = "Código postal"; // // textCP // this.textCP.Location = new System.Drawing.Point(288, 197); this.textCP.Name = "textCP"; this.textCP.Size = new System.Drawing.Size(100, 20); this.textCP.TabIndex = 21; // // label12 // this.label12.Location = new System.Drawing.Point(591, 105); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(100, 23); this.label12.TabIndex = 22; this.label12.Text = "Colonia"; // // textcolonia // this.textcolonia.Location = new System.Drawing.Point(591, 131); this.textcolonia.Name = "textcolonia"; this.textcolonia.Size = new System.Drawing.Size(177, 20); this.textcolonia.TabIndex = 23; // // textMunicipio // this.textMunicipio.Location = new System.Drawing.Point(37, 197); this.textMunicipio.Name = "textMunicipio"; this.textMunicipio.Size = new System.Drawing.Size(100, 20); this.textMunicipio.TabIndex = 24; // // label13 // this.label13.Location = new System.Drawing.Point(37, 171); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(100, 23); this.label13.TabIndex = 25; this.label13.Text = "Municipio"; // // label14 // this.label14.Location = new System.Drawing.Point(157, 171); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(100, 23); this.label14.TabIndex = 26; this.label14.Text = "Estado"; // // textEstado // this.textEstado.Location = new System.Drawing.Point(157, 197); this.textEstado.Name = "textEstado"; this.textEstado.Size = new System.Drawing.Size(100, 20); this.textEstado.TabIndex = 27; // // dateTimePicker1 // this.dateTimePicker1.Location = new System.Drawing.Point(628, 12); this.dateTimePicker1.Name = "dateTimePicker1"; this.dateTimePicker1.Size = new System.Drawing.Size(200, 20); this.dateTimePicker1.TabIndex = 28; // // ButGuardar // this.ButGuardar.Location = new System.Drawing.Point(672, 540); this.ButGuardar.Name = "ButGuardar"; this.ButGuardar.Size = new System.Drawing.Size(75, 24); this.ButGuardar.TabIndex = 29; this.ButGuardar.Text = "Guardar"; this.ButGuardar.UseVisualStyleBackColor = true; this.ButGuardar.Click += new System.EventHandler(this.Botguardar); // // textid // this.textid.Location = new System.Drawing.Point(105, 7); this.textid.Name = "textid"; this.textid.Size = new System.Drawing.Size(68, 20); this.textid.TabIndex = 30; // // label15 // this.label15.Location = new System.Drawing.Point(1, 7); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(100, 23); this.label15.TabIndex = 31; this.label15.Text = "Número de Cliente"; this.label15.Click += new System.EventHandler(this.Label15Click); // // butSalir // this.butSalir.Location = new System.Drawing.Point(753, 540); this.butSalir.Name = "butSalir"; this.butSalir.Size = new System.Drawing.Size(75, 24); this.butSalir.TabIndex = 32; this.butSalir.Text = "Salir"; this.butSalir.UseVisualStyleBackColor = true; this.butSalir.Click += new System.EventHandler(this.ButSalirClick); // // dataGridView1 // this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(22, 235); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(781, 299); this.dataGridView1.TabIndex = 33; // // buActualizar // this.buActualizar.Location = new System.Drawing.Point(591, 540); this.buActualizar.Name = "buActualizar"; this.buActualizar.Size = new System.Drawing.Size(75, 24); this.buActualizar.TabIndex = 34; this.buActualizar.Text = "Actualizar"; this.buActualizar.UseVisualStyleBackColor = true; this.buActualizar.Click += new System.EventHandler(this.BuActualizarClick); // // Cliente // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(840, 576); this.Controls.Add(this.buActualizar); this.Controls.Add(this.dataGridView1); this.Controls.Add(this.butSalir); this.Controls.Add(this.label15); this.Controls.Add(this.textid); this.Controls.Add(this.ButGuardar); this.Controls.Add(this.dateTimePicker1); this.Controls.Add(this.textEstado); this.Controls.Add(this.label14); this.Controls.Add(this.label13); this.Controls.Add(this.textMunicipio); this.Controls.Add(this.textcolonia); this.Controls.Add(this.label12); this.Controls.Add(this.textCP); this.Controls.Add(this.label11); this.Controls.Add(this.textNumExt); this.Controls.Add(this.label10); this.Controls.Add(this.textNumInt); this.Controls.Add(this.label9); this.Controls.Add(this.textCalle); this.Controls.Add(this.label8); this.Controls.Add(this.textCorreo); this.Controls.Add(this.label6); this.Controls.Add(this.textTelefono); this.Controls.Add(this.label5); this.Controls.Add(this.textFechaN); this.Controls.Add(this.label4); this.Controls.Add(this.textapellm); this.Controls.Add(this.label3); this.Controls.Add(this.textApellp); this.Controls.Add(this.label2); this.Controls.Add(this.textNombre); this.Controls.Add(this.label1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Cliente"; this.Text = "Alta de Clientes"; this.Load += new System.EventHandler(this.ClienteLoad); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } private System.Windows.Forms.Button buActualizar; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.Button butSalir; private System.Windows.Forms.Label label15; private System.Windows.Forms.TextBox textid; private System.Windows.Forms.Button ButGuardar; private System.Windows.Forms.DateTimePicker dateTimePicker1; private System.Windows.Forms.TextBox textEstado; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox textMunicipio; private System.Windows.Forms.TextBox textcolonia; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox textCP; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox textNumExt; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox textNumInt; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox textCalle; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox textCorreo; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox textTelefono; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox textFechaN; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textapellm; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textApellp; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textNombre; private System.Windows.Forms.Label label1; } }
gpl-2.0
thomasmckay/katello
app/lib/actions/pulp/repository/remove_docker_image.rb
232
module Actions module Pulp module Repository class RemoveDockerImage < Pulp::Repository::AbstractRemoveContent def content_extension pulp_extensions.docker_image end end end end end
gpl-2.0
Jun-Yuan/percona-server
storage/rocksdb/rdb_sst_info.cc
12234
/* Copyright (c) 2016, Facebook, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* This C++ file's header file */ #include "./rdb_sst_info.h" /* C++ standard header files */ #include <cstdio> #include <string> #include <vector> /* MySQL header files */ #include "../sql/log.h" #include "./my_dir.h" /* RocksDB header files */ #include "rocksdb/db.h" #include "rocksdb/options.h" /* MyRocks header files */ #include "./ha_rocksdb.h" #include "./ha_rocksdb_proto.h" #include "./rdb_cf_options.h" namespace myrocks { Rdb_sst_file::Rdb_sst_file(rocksdb::DB *const db, rocksdb::ColumnFamilyHandle *const cf, const rocksdb::DBOptions &db_options, const std::string &name, const bool tracing) : m_db(db), m_cf(cf), m_db_options(db_options), m_sst_file_writer(nullptr), m_name(name), m_tracing(tracing) { DBUG_ASSERT(db != nullptr); DBUG_ASSERT(cf != nullptr); } Rdb_sst_file::~Rdb_sst_file() { // Make sure we clean up delete m_sst_file_writer; m_sst_file_writer = nullptr; // In case something went wrong attempt to delete the temporary file. // If everything went fine that file will have been renamed and this // function call will fail. std::remove(m_name.c_str()); } rocksdb::Status Rdb_sst_file::open() { DBUG_ASSERT(m_sst_file_writer == nullptr); rocksdb::ColumnFamilyDescriptor cf_descr; rocksdb::Status s = m_cf->GetDescriptor(&cf_descr); if (!s.ok()) { return s; } // Create an sst file writer with the current options and comparator const rocksdb::Comparator *comparator = m_cf->GetComparator(); const rocksdb::EnvOptions env_options(m_db_options); const rocksdb::Options options(m_db_options, cf_descr.options); m_sst_file_writer = new rocksdb::SstFileWriter(env_options, options, comparator, m_cf); s = m_sst_file_writer->Open(m_name); if (m_tracing) { // NO_LINT_DEBUG sql_print_information("SST Tracing: Open(%s) returned %s", m_name.c_str(), s.ok() ? "ok" : "not ok"); } if (!s.ok()) { delete m_sst_file_writer; m_sst_file_writer = nullptr; } return s; } rocksdb::Status Rdb_sst_file::put(const rocksdb::Slice &key, const rocksdb::Slice &value) { DBUG_ASSERT(m_sst_file_writer != nullptr); // Add the specified key/value to the sst file writer return m_sst_file_writer->Add(key, value); } std::string Rdb_sst_file::generateKey(const std::string &key) { static char const hexdigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; std::string res; res.reserve(key.size() * 2); for (auto ch : key) { res += hexdigit[((uint8_t)ch) >> 4]; res += hexdigit[((uint8_t)ch) & 0x0F]; } return res; } // This function is run by the background thread rocksdb::Status Rdb_sst_file::commit() { DBUG_ASSERT(m_sst_file_writer != nullptr); rocksdb::Status s; rocksdb::ExternalSstFileInfo fileinfo; /// Finish may should be modified // Close out the sst file s = m_sst_file_writer->Finish(&fileinfo); if (m_tracing) { // NO_LINT_DEBUG sql_print_information("SST Tracing: Finish returned %s", s.ok() ? "ok" : "not ok"); } if (s.ok()) { if (m_tracing) { // NO_LINT_DEBUG sql_print_information("SST Tracing: Adding file %s, smallest key: %s, " "largest key: %s, file size: %lu, " "num_entries: %lu", fileinfo.file_path.c_str(), generateKey(fileinfo.smallest_key).c_str(), generateKey(fileinfo.largest_key).c_str(), fileinfo.file_size, fileinfo.num_entries); } // Add the file to the database // Set the snapshot_consistency parameter to false since no one // should be accessing the table we are bulk loading rocksdb::IngestExternalFileOptions opts; opts.move_files = true; opts.snapshot_consistency = false; opts.allow_global_seqno = false; opts.allow_blocking_flush = false; s = m_db->IngestExternalFile(m_cf, {m_name}, opts); if (m_tracing) { // NO_LINT_DEBUG sql_print_information("SST Tracing: AddFile(%s) returned %s", fileinfo.file_path.c_str(), s.ok() ? "ok" : "not ok"); } } delete m_sst_file_writer; m_sst_file_writer = nullptr; return s; } Rdb_sst_info::Rdb_sst_info(rocksdb::DB *const db, const std::string &tablename, const std::string &indexname, rocksdb::ColumnFamilyHandle *const cf, const rocksdb::DBOptions &db_options, const bool &tracing) : m_db(db), m_cf(cf), m_db_options(db_options), m_curr_size(0), m_sst_count(0), m_error_msg(""), #if defined(RDB_SST_INFO_USE_THREAD) m_queue(), m_mutex(), m_cond(), m_thread(nullptr), m_finished(false), #endif m_sst_file(nullptr), m_tracing(tracing) { m_prefix = db->GetName() + "/"; std::string normalized_table; if (rdb_normalize_tablename(tablename.c_str(), &normalized_table)) { // We failed to get a normalized table name. This should never happen, // but handle it anyway. m_prefix += "fallback_" + std::to_string(reinterpret_cast<intptr_t>( reinterpret_cast<void *>(this))) + "_" + indexname + "_"; } else { m_prefix += normalized_table + "_" + indexname + "_"; } rocksdb::ColumnFamilyDescriptor cf_descr; const rocksdb::Status s = m_cf->GetDescriptor(&cf_descr); if (!s.ok()) { // Default size if we can't get the cf's target size m_max_size = 64 * 1024 * 1024; } else { // Set the maximum size to 3 times the cf's target size m_max_size = cf_descr.options.target_file_size_base * 3; } } Rdb_sst_info::~Rdb_sst_info() { DBUG_ASSERT(m_sst_file == nullptr); #if defined(RDB_SST_INFO_USE_THREAD) DBUG_ASSERT(m_thread == nullptr); #endif } int Rdb_sst_info::open_new_sst_file() { DBUG_ASSERT(m_sst_file == nullptr); // Create the new sst file's name const std::string name = m_prefix + std::to_string(m_sst_count++) + m_suffix; // Create the new sst file object m_sst_file = new Rdb_sst_file(m_db, m_cf, m_db_options, name, m_tracing); // Open the sst file const rocksdb::Status s = m_sst_file->open(); if (!s.ok()) { set_error_msg(s.ToString()); delete m_sst_file; m_sst_file = nullptr; return HA_EXIT_FAILURE; } m_curr_size = 0; return HA_EXIT_SUCCESS; } void Rdb_sst_info::close_curr_sst_file() { DBUG_ASSERT(m_sst_file != nullptr); DBUG_ASSERT(m_curr_size > 0); #if defined(RDB_SST_INFO_USE_THREAD) if (m_thread == nullptr) { // We haven't already started a background thread, so start one m_thread = new std::thread(thread_fcn, this); } DBUG_ASSERT(m_thread != nullptr); { // Add this finished sst file to the queue (while holding mutex) const std::lock_guard<std::mutex> guard(m_mutex); m_queue.push(m_sst_file); } // Notify the background thread that there is a new entry in the queue m_cond.notify_one(); #else const rocksdb::Status s = m_sst_file->commit(); if (!s.ok()) { set_error_msg(s.ToString()); } delete m_sst_file; #endif // Reset for next sst file m_sst_file = nullptr; m_curr_size = 0; } int Rdb_sst_info::put(const rocksdb::Slice &key, const rocksdb::Slice &value) { int rc; if (m_curr_size >= m_max_size) { // The current sst file has reached its maximum, close it out close_curr_sst_file(); // While we are here, check to see if we have had any errors from the // background thread - we don't want to wait for the end to report them if (!m_error_msg.empty()) { return HA_EXIT_FAILURE; } } if (m_curr_size == 0) { // We don't have an sst file open - open one rc = open_new_sst_file(); if (rc != 0) { return rc; } } DBUG_ASSERT(m_sst_file != nullptr); // Add the key/value to the current sst file const rocksdb::Status s = m_sst_file->put(key, value); if (!s.ok()) { set_error_msg(s.ToString()); return HA_EXIT_FAILURE; } m_curr_size += key.size() + value.size(); return HA_EXIT_SUCCESS; } int Rdb_sst_info::commit() { if (m_curr_size > 0) { // Close out any existing files close_curr_sst_file(); } #if defined(RDB_SST_INFO_USE_THREAD) if (m_thread != nullptr) { // Tell the background thread we are done m_finished = true; m_cond.notify_one(); // Wait for the background thread to finish m_thread->join(); delete m_thread; m_thread = nullptr; } #endif // Did we get any errors? if (!m_error_msg.empty()) { return HA_EXIT_FAILURE; } return HA_EXIT_SUCCESS; } void Rdb_sst_info::set_error_msg(const std::string &msg) { #if defined(RDB_SST_INFO_USE_THREAD) // Both the foreground and background threads can set the error message // so lock the mutex to protect it. We only want the first error that // we encounter. const std::lock_guard<std::mutex> guard(m_mutex); #endif my_printf_error(ER_UNKNOWN_ERROR, "bulk load error: %s", MYF(0), msg.c_str()); if (m_error_msg.empty()) { m_error_msg = msg; } } #if defined(RDB_SST_INFO_USE_THREAD) // Static thread function - the Rdb_sst_info object is in 'object' void Rdb_sst_info::thread_fcn(void *object) { reinterpret_cast<Rdb_sst_info *>(object)->run_thread(); } void Rdb_sst_info::run_thread() { const std::unique_lock<std::mutex> lk(m_mutex); do { // Wait for notification or 1 second to pass m_cond.wait_for(lk, std::chrono::seconds(1)); // Inner loop pulls off all Rdb_sst_file entries and processes them while (!m_queue.empty()) { const Rdb_sst_file *const sst_file = m_queue.front(); m_queue.pop(); // Release the lock - we don't want to hold it while committing the file lk.unlock(); // Close out the sst file and add it to the database const rocksdb::Status s = sst_file->commit(); if (!s.ok()) { set_error_msg(s.ToString()); } delete sst_file; // Reacquire the lock for the next inner loop iteration lk.lock(); } // If the queue is empty and the main thread has indicated we should exit // break out of the loop. } while (!m_finished); DBUG_ASSERT(m_queue.empty()); } #endif void Rdb_sst_info::init(const rocksdb::DB *const db) { const std::string path = db->GetName() + FN_DIRSEP; struct st_my_dir *const dir_info = my_dir(path.c_str(), MYF(MY_DONT_SORT)); // Access the directory if (dir_info == nullptr) { // NO_LINT_DEBUG sql_print_warning("RocksDB: Could not access database directory: %s", path.c_str()); return; } // Scan through the files in the directory const struct fileinfo *file_info = dir_info->dir_entry; for (uint ii = 0; ii < dir_info->number_off_files; ii++, file_info++) { // find any files ending with m_suffix ... const std::string name = file_info->name; const size_t pos = name.find(m_suffix); if (pos != std::string::npos && name.size() - pos == m_suffix.size()) { // ... and remove them const std::string fullname = path + name; my_delete(fullname.c_str(), MYF(0)); } } // Release the directory entry my_dirend(dir_info); } std::string Rdb_sst_info::m_suffix = ".bulk_load.tmp"; } // namespace myrocks
gpl-2.0
cjw-network/cjwpublish1411
vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/Persistence/Elasticsearch/Content/Search/Location/CriterionVisitor/Location/PriorityIn.php
2053
<?php /** * File containing the range PriorityIn Priority criterion visitor class * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.11.1 */ namespace eZ\Publish\Core\Persistence\Elasticsearch\Content\Search\Location\CriterionVisitor\Location; use eZ\Publish\Core\Persistence\Elasticsearch\Content\Search\CriterionVisitorDispatcher as Dispatcher; use eZ\Publish\Core\Persistence\Elasticsearch\Content\Search\CriterionVisitor; use eZ\Publish\API\Repository\Values\Content\Query\Criterion; use eZ\Publish\API\Repository\Values\Content\Query\Criterion\Operator; /** * Visits the Priority criterion with IN or EQ operator. */ class PriorityIn extends CriterionVisitor { /** * Check if visitor is applicable to current criterion * * @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion * * @return boolean */ public function canVisit( Criterion $criterion ) { return $criterion instanceof Criterion\Location\Priority && ( ( $criterion->operator ?: Operator::IN ) === Operator::IN || $criterion->operator === Operator::EQ ); } /** * Map field value to a proper Elasticsearch filter representation * * @throws \eZ\Publish\Core\Base\Exceptions\InvalidArgumentException If no searchable fields are found for the given criterion target. * * @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion * @param \eZ\Publish\Core\Persistence\Elasticsearch\Content\Search\CriterionVisitorDispatcher $dispatcher * @param array $fieldFilters * * @return mixed */ public function visitFilter( Criterion $criterion, Dispatcher $dispatcher, array $fieldFilters ) { return array( "terms" => array( "priority_i" => $criterion->value ) ); } }
gpl-2.0
leybal/HomeWork5
wp-content/plugins/cp-multi-view-calendar/DC_MultiViewCal/language/multiview_lang_ru_RU.js
9603
var i18n = jQuery.extend({}, i18n || {}, { dcmvcal: { dateformat: { "fulldaykey": "MMddyyyy", "fulldayshow": "d L yyyy", "fulldayvalue": "d/M/yyyy", "Md": "W d/M", "nDaysView": "d/M", "listViewDate": "d L yyyy", "Md3": "d L", "separator": "/", "year_index": 2, "month_index": 0, "day_index": 1, "day": "d", "sun2": "Вс", "mon2": "Пн", "tue2": "Вт", "wed2": "Ср", "thu2": "Чт", "fri2": "Пн", "sat2": "Сб", "sun": "Вск", "mon": "Пнд", "tue": "Втр", "wed": "Срд", "thu": "Чтв", "fri": "Птн", "sat": "Сбт", "sunday": "Воскресенье", "monday": "Понедельник", "tuesday": "Вторник", "wednesday": "Среда", "thursday": "Четверг", "friday": "Пятница", "saturday": "Суббота", "jan": "Янв", "feb": "Фев", "mar": "Мрт", "apr": "Апр", "may": "Май", "jun": "Июн", "jul": "Июл", "aug": "Авг", "sep": "Сен", "oct": "Окт", "nov": "Нбр", "dec": "Дек", "l_jan": "Январь", "l_feb": "Февраль", "l_mar": "Март", "l_apr": "Апрель", "l_may": "Май", "l_jun": "Июнь", "l_jul": "Июль", "l_aug": "Август", "l_sep": "Сентябрь", "l_oct": "Октябрь", "l_nov": "Ноябрь", "l_dec": "Декабрь" }, "no_implemented": "Не реализовано", "to_date_view": "Нажмите, чтобы увидеть дату", "i_undefined": "Не определено", "allday_event": "Целый день", "repeat_event": "Повторить событие", "time": "Время", "event": "Событие", "location": "Местонахождение", "participant": "Участник", "get_data_exception": "Исключение при получении данных", "new_event": "Новое событие", "confirm_delete_event": "Удалить событие ?", "confrim_delete_event_or_all": "Do you want to delete all repeat events or only this event? \r\nClick [OK] to delete only this event, click [Cancel] delete all events", "data_format_error": "Неверный формат даты", "invalid_title": "Укажите название события ($<>)", "view_no_ready": "View is not ready", "example": "например: встреча в кафе в 18:00", "content": "Тема", "create_event": "Создать событие", "update_detail": "Редактировать", "click_to_detail": "Подробнее", "i_delete": "Удалить", "i_save": "Сохранить", "i_close": "Закрыть", "day_plural": "дни", "others": "Другие", "item": "", "loading_data":"Загрузка данных...", "request_processed":"Запрос обрабатывается...", "success":"Выполнено", "are_you_sure_delete":"Удалить это событие ?", "ok":"Ok", "cancel":"Отмена", "manage_the_calendar":"Управление календарём", "error_occurs":"Произошла ошибка", "color":"Цвет", "invalid_date_format":"Неверный формат даты", "invalid_time_format":"Неверный формат времени", "_simbol_not_allowed":"$<> не допускаются", "subject":"Объект", "time":"Дата", "to":"Для", "all_day_event":"Целый день", "location":"Местонахождение", "remark":"Описание", "click_to_create_new_event":"Нажмите, чтобы создать событие", "new_event":"Новое событие", "click_to_back_to_today":"Нажмите, чтобы вернуться назад", "today":"Сегодня", "sday":"День", "week":"Неделя", "month":"Месяц", "ndays":"Дней", "list":"List", "nmonth":"Год", "refresh_view":"Обновить", "refresh":"Обновить", "prev":"Пред", "next":"След", "loading":"Загрузка", "error_overlapping":"Это событие накладывается на другое", "sorry_could_not_load_your_data":"К сожалению, не удалось загрузить ваши данные, повторите попытку позже", "first":"Первый", "second":"Второй", "third":"Третий", "fourth":"Четвёртый", "last":"последний", "repeat":"Повтор: ", "edit":"Редактировать", "edit_recurring_event":"Редактировать повтор события", "would_you_like_to_change_only_this_event_all_events_in_the_series_or_this_and_all_following_events_in_the_series":"Хотели бы Вы изменить только это событие, все события в серии, или это и все последующие события в серии?", "only_this_event":"Только это событие", "all_other_events_in_the_series_will_remain_the_same":"Все остальные события в серии останутся прежними.", "following_events":"Следующие события", "this_and_all_the_following_events_will_be_changed":"Это и все последующие события будут изменены.", "any_changes_to_future_events_will_be_lost":"Все изменения в наступающих событиях будут потеряны.", "all_events":"Все события", "all_events_in_the_series_will_be_changed":"Все события в этой серии будут изменены.", "any_changes_made_to_other_events_will_be_kept":"Все изменения в других событиях, будут сохранены.", "cancel_this_change":"Отменить это изменение", "delete_recurring_event":"Удалить повторяющееся событие", "would_you_like_to_delete_only_this_event_all_events_in_the_series_or_this_and_all_future_events_in_the_series":"Хотели бы Вы, чтобы удалить только это событие, все события в серии, или это и все последующие события в серии?", "only_this_instance":"Только в этом случае", "all_other_events_in_the_series_will_remain":"Все остальные события в серии останутся", "all_following":"Все последующие", "this_and_all_the_following_events_will_be_deleted":"Это и все последующие события будут удалены.", "all_events_in_the_series":"Все события в серии", "all_events_in_the_series_will_be_deleted":"Все события в серии будут удалены.", "repeats":"Повторы", "daily":"Ежедневно", "every_weekday_monday_to_friday":"Каждый будний день (с понедельника по пятницу)", "every_monday_wednesday_and_friday":"Каждый понедельник, среду и пятницу", "every_tuesday_and_thursday":"Каждый вторник и четверг", "weekly":"Еженедельно", "monthly":"Ежемесячно", "yearly":"Ежегодно", "repeat_every":"Повтор каждый:", "weeks":"недели", "repeat_on":"Повторить с:", "repeat_by":"Повторить по:", "day_of_the_month":"день месяца", "day_of_the_week":"день недели", "starts_on":"Начинать с:", "ends":"Заканчивать:", "never":" Никогда", "after":"После", "occurrences":"входы", "summary":"Резюме:", "every":"Каждый", "weekly_on_weekdays":"Еженедельно по будням", "weekly_on_monday_wednesday_friday":"Еженедельно по понедельникам, средам, пятница", "weekly_on_tuesday_thursday":"Еженедельно по вторникам, четвергам", "on":"в", "on_day":"в день", "on_the":"на", "months":"месяцев", "annually":"ежегодно", "years":"лет", "once":"один раз", "times":"раз", "readmore":"read more", "readmore_less":"less", "until":"до" } });
gpl-2.0
vanfanel/scummvm
engines/myst3/detection.cpp
10095
/* ResidualVM - A 3D game interpreter * * ResidualVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the AUTHORS * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "common/translation.h" #include "engines/advancedDetector.h" #include "engines/myst3/detection.h" #include "engines/myst3/myst3.h" namespace Myst3 { static const PlainGameDescriptor myst3Games[] = { { "myst3", "Myst III Exile" }, { 0, 0 } }; static const DebugChannelDef debugFlagList[] = { {Myst3::kDebugVariable, "Variable", "Track Variable Accesses"}, {Myst3::kDebugSaveLoad, "SaveLoad", "Track Save/Load Function"}, {Myst3::kDebugScript, "Script", "Track Script Execution"}, {Myst3::kDebugNode, "Node", "Track Node Changes"}, DEBUG_CHANNEL_END }; static const char *directoryGlobs[] = { "bin", "M3Data", "MYST3BIN", "TEXT", 0 }; #define MYST3ENTRY(lang, langFile, md5lang, extra, flags) \ { \ { \ "myst3", \ extra, \ { \ { "RSRC.m3r", 0, "a2c8ed69800f60bf5667e5c76a88e481", 1223862 }, \ { langFile, 0, md5lang, -1 }, \ }, \ lang, \ Common::kPlatformWindows, \ ADGF_NO_FLAGS, \ GUIO_NONE \ }, \ flags \ }, #define MYST3ENTRY_DVD(lang, langFile, md5lang, extra, flags) \ { \ { \ "myst3", \ extra, \ { \ { "RSRC.m3r", 0, "a2c8ed69800f60bf5667e5c76a88e481", 1223862 }, \ { "ENGLISH.m3t", 0, "74726de866c0594d3f2a05ff754c973d", 3407120 }, \ { langFile, 0, md5lang, -1 }, \ }, \ lang, \ Common::kPlatformWindows, \ ADGF_NO_FLAGS, \ GUIO_NONE \ }, \ flags \ }, #define MYST3ENTRY_XBOX(lang, langFile, md5lang) \ { \ { \ "myst3", \ 0, \ { \ { "RSRC.m3r", 0, "3de23eb5a036a62819186105478f9dde", 1226192 }, \ { langFile, 0, md5lang, -1 }, \ }, \ lang, \ Common::kPlatformXbox, \ ADGF_UNSTABLE, \ GUIO_NONE \ }, \ kLocMulti6 \ }, static const Myst3GameDescription gameDescriptions[] = { // Initial US release (English only) MYST3ENTRY(Common::EN_ANY, "ENGLISH.m3t", "3ca92b097c4319a2ace7fd6e911d6b0f", 0, kLocMonolingual) // European releases (Country language + English) (1.2) MYST3ENTRY(Common::NL_NLD, "DUTCH.m3u", "0e8019cfaeb58c2de00ac114cf122220", 0, kLocMulti2) MYST3ENTRY(Common::FR_FRA, "FRENCH.m3u", "3a7e270c686806dfc31c2091e09c03ec", 0, kLocMulti2) MYST3ENTRY(Common::DE_DEU, "GERMAN.m3u", "1b2fa162a951fa4ed65617dd3f0c8a53", 0, kLocMulti2) // #1323, andrews05 MYST3ENTRY(Common::IT_ITA, "ITALIAN.m3u", "906645a87ac1cbbd2b88c277c2b4fda2", 0, kLocMulti2) // #1323, andrews05 MYST3ENTRY(Common::ES_ESP, "SPANISH.m3u", "28003569d9536cbdf6020aee8e9bcd15", 0, kLocMulti2) // #1323, goodoldgeorge MYST3ENTRY(Common::PL_POL, "POLISH.m3u", "8075e4e822e100ec79a5842a530dbe24", 0, kLocMulti2) // Russian release (Russian only) (1.2) MYST3ENTRY(Common::RU_RUS, "ENGLISH.m3t", "57d36d8610043fda554a0708d71d2681", 0, kLocMonolingual) // Hebrew release (Hebrew only) (1.2 - Patched using the patch CD) MYST3ENTRY(Common::HE_ISR, "HEBREW.m3u", "16fbbe420fed366249a8d44a759f966c", 0, kLocMonolingual) // #1348, BLooperZ // Japanese release (1.2) MYST3ENTRY(Common::JA_JPN, "JAPANESE.m3u", "21bbd040bcfadd13b9dc84360c3de01d", 0, kLocMulti2) MYST3ENTRY(Common::JA_JPN, "JAPANESE.m3u", "1e7c3156417978a1187fa6bc0e2cfafc", "Subtitles only", kLocMulti2) // Multilingual CD release (1.21) MYST3ENTRY(Common::EN_ANY, "ENGLISH.m3u", "b62ca55aa17724cddbbcc78cba988337", 0, kLocMulti6) MYST3ENTRY(Common::FR_FRA, "FRENCH.m3u", "73519070cba1c7bea599adbddeae304f", 0, kLocMulti6) MYST3ENTRY(Common::NL_NLD, "DUTCH.m3u", "c4a8d8fb0eb3fecb9c435a8517bc1f9a", 0, kLocMulti6) MYST3ENTRY(Common::DE_DEU, "GERMAN.m3u", "5b3be343dd20f03ebdf16381b873f035", 0, kLocMulti6) MYST3ENTRY(Common::IT_ITA, "ITALIAN.m3u", "73db43aac3fe8671e2c4e227977fbb61", 0, kLocMulti6) MYST3ENTRY(Common::ES_ESP, "SPANISH.m3u", "55ceb165dad02211ef2d25946c3aac8e", 0, kLocMulti6) // DVD releases (1.27) MYST3ENTRY_DVD(Common::EN_ANY, "ENGLISH.m3u", "e200b416f43e70fee76148a80d195d5c", "DVD", kLocMulti6) MYST3ENTRY_DVD(Common::FR_FRA, "FRENCH.m3u", "5679ce65c5e9af8899835ef9af398f1a", "DVD", kLocMulti6) MYST3ENTRY_DVD(Common::NL_NLD, "DUTCH.m3u", "2997afdb4306c573153fdbb391ed2fff", "DVD", kLocMulti6) MYST3ENTRY_DVD(Common::DE_DEU, "GERMAN.m3u", "09f32e6ceb414463e8fc22ca1a9564d3", "DVD", kLocMulti6) MYST3ENTRY_DVD(Common::IT_ITA, "ITALIAN.m3u", "51fb02f6bf37dde811d7cde648365260", "DVD", kLocMulti6) MYST3ENTRY_DVD(Common::ES_ESP, "SPANISH.m3u", "e27e610fe8ce35223a3239ff170a85ec", "DVD", kLocMulti6) // Myst 3 Xbox (PAL) MYST3ENTRY_XBOX(Common::EN_ANY, "ENGLISHX.m3t", "c4d012ab02b8ca7d0c7e79f4dbd4e676") MYST3ENTRY_XBOX(Common::FR_FRA, "FRENCHX.m3t", "94c9dcdec8794751e4d773776552751a") MYST3ENTRY_XBOX(Common::DE_DEU, "GERMANX.m3t", "b9b66fcd5d4fbb95ac2d7157577991a5") MYST3ENTRY_XBOX(Common::IT_ITA, "ITALIANX.m3t", "3ca266019eba68123f6b7cae57cfc200") MYST3ENTRY_XBOX(Common::ES_ESP, "SPANISHX.m3t", "a9aca36ccf6709164249f3fb6b1ef148") // Myst 3 Xbox (RUS) MYST3ENTRY_XBOX(Common::RU_RUS, "ENGLISHX.m3t", "18cb50f5c5317586a128ca9eb3e03279") { // Myst 3 PS2 (NTSC-U/C) { "myst3", _s("PS2 version is not yet supported"), AD_ENTRY1s("RSRC.m3r", "c60d37bfd3bb8b0bee143018447bb460", 346618151), Common::UNK_LANG, Common::kPlatformPS2, ADGF_UNSUPPORTED, GUIO_NONE }, 0 }, { // Myst 3 PS2 (PAL) { "myst3", _s("PS2 version is not yet supported"), AD_ENTRY1s("RSRC.m3r", "f0e0c502f77157e6b5272686c661ea75", 91371793), Common::UNK_LANG, Common::kPlatformPS2, ADGF_UNSUPPORTED, GUIO_NONE }, 0 }, { AD_TABLE_END_MARKER, 0 } }; #define GAMEOPTION_WIDESCREEN_MOD GUIO_GAMEOPTIONS1 static const ADExtraGuiOptionsMap optionsList[] = { { GAMEOPTION_WIDESCREEN_MOD, { _s("Widescreen mod"), _s("Enable widescreen rendering in fullscreen mode."), "widescreen_mod", false } }, AD_EXTRA_GUI_OPTIONS_TERMINATOR }; class Myst3MetaEngineDetection : public AdvancedMetaEngineDetection { public: Myst3MetaEngineDetection() : AdvancedMetaEngineDetection(gameDescriptions, sizeof(Myst3GameDescription), myst3Games, optionsList) { _guiOptions = GUIO5(GUIO_NOMIDI, GUIO_NOSFX, GUIO_NOSPEECH, GUIO_NOSUBTITLES, GAMEOPTION_WIDESCREEN_MOD); _maxScanDepth = 3; _directoryGlobs = directoryGlobs; } const char *getName() const override { return "Myst III"; } const char *getEngineId() const override { return "myst3"; } const char *getOriginalCopyright() const override { return "Myst III Exile (C) Presto Studios"; } const DebugChannelDef *getDebugChannels() const override { return debugFlagList; } }; } // End of namespace Myst3 REGISTER_PLUGIN_STATIC(MYST3_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, Myst3::Myst3MetaEngineDetection);
gpl-2.0
JanetteA/dsmsales
sites/all/libraries/modernizr/feature-detects/websockets.js
789
/*! { "name": "WebSockets Support", "property": "websockets", "authors": ["Phread [fearphage]", "Mike Sherov [mikesherov]", "Burak Yigit Kaya [BYK]"], "caniuse": "websockets", "tags": ["html5"], "warnings": [ "This test will reject any old version of WebSockets even if it is not prefixed such as in Safari 5.1" ], "notes": [{ "name": "CLOSING State and Spec", "href": "http://www.w3.org/TR/websockets/#the-websocket-interface" }], "polyfills": [ "sockjs", "socketio", "kaazing-websocket-gateway", "websocketjs", "atmosphere", "graceful-websocket", "portal", "datachannel" ] } !*/ define(['Modernizr'], function( Modernizr ) { Modernizr.addTest('websockets', 'WebSocket' in window && window.WebSocket.CLOSING === 2); });
gpl-2.0
Pengostores/magento1_training
app/code/core/Mage/Paygate/sql/paygate_setup/install-1.6.0.0.php
1036
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Paygate * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** @var $installer Mage_Core_Model_Resource_Setup */ $installer = $this;
gpl-3.0
mm3/shattered-pixel-dungeon
src/com/shatteredpixel/shatteredpixeldungeon/windows/WndClass.java
6032
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.windows; import com.watabou.noosa.BitmapText; import com.watabou.noosa.BitmapTextMultiline; import com.watabou.noosa.Group; import com.shatteredpixel.shatteredpixeldungeon.Badges; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.HeroClass; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.HeroSubClass; import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene; import com.shatteredpixel.shatteredpixeldungeon.utils.Utils; public class WndClass extends WndTabbed { private static final String TXT_MASTERY = "Mastery"; private static final int WIDTH = 110; private static final int TAB_WIDTH = 50; private HeroClass cl; private PerksTab tabPerks; private MasteryTab tabMastery; public WndClass( HeroClass cl ) { super(); this.cl = cl; tabPerks = new PerksTab(); add( tabPerks ); Tab tab = new RankingTab( Utils.capitalize( cl.title() ), tabPerks ); tab.setSize( TAB_WIDTH, tabHeight() ); add( tab ); if (Badges.isUnlocked( cl.masteryBadge() )) { tabMastery = new MasteryTab(); add( tabMastery ); tab = new RankingTab( TXT_MASTERY, tabMastery ); tab.setSize( TAB_WIDTH, tabHeight() ); add( tab ); resize( (int)Math.max( tabPerks.width, tabMastery.width ), (int)Math.max( tabPerks.height, tabMastery.height ) ); } else { resize( (int)tabPerks.width, (int)tabPerks.height ); } select( 0 ); } private class RankingTab extends LabeledTab { private Group page; public RankingTab( String label, Group page ) { super( label ); this.page = page; } @Override protected void select( boolean value ) { super.select( value ); if (page != null) { page.visible = page.active = selected; } } } private class PerksTab extends Group { private static final int MARGIN = 4; private static final int GAP = 4; private static final String DOT = "\u007F"; public float height; public float width; public PerksTab() { super(); float dotWidth = 0; String[] items = cl.perks(); float pos = MARGIN; for (int i=0; i < items.length; i++) { if (i > 0) { pos += GAP; } BitmapText dot = PixelScene.createText( DOT, 6 ); dot.x = MARGIN; dot.y = pos; if (dotWidth == 0) { dot.measure(); dotWidth = dot.width(); } add( dot ); BitmapTextMultiline item = PixelScene.createMultiline( items[i], 6 ); item.x = dot.x + dotWidth; item.y = pos; item.maxWidth = (int)(WIDTH - MARGIN * 2 - dotWidth); item.measure(); add( item ); pos += item.height(); float w = item.width(); if (w > width) { width = w; } } width += MARGIN + dotWidth; height = pos + MARGIN; } } private class MasteryTab extends Group { private static final int MARGIN = 4; private BitmapTextMultiline normal; private BitmapTextMultiline highlighted; public float height; public float width; public MasteryTab() { super(); String text = null; switch (cl) { case WARRIOR: text = HeroSubClass.GLADIATOR.desc() + "\n\n" + HeroSubClass.BERSERKER.desc(); break; case MAGE: text = HeroSubClass.BATTLEMAGE.desc() + "\n\n" + HeroSubClass.WARLOCK.desc(); break; case ROGUE: text = HeroSubClass.FREERUNNER.desc() + "\n\n" + HeroSubClass.ASSASSIN.desc(); break; case HUNTRESS: text = HeroSubClass.SNIPER.desc() + "\n\n" + HeroSubClass.WARDEN.desc(); break; } Highlighter hl = new Highlighter( text ); normal = PixelScene.createMultiline( hl.text, 6 ); normal.maxWidth = WIDTH - MARGIN * 2; normal.measure(); normal.x = MARGIN; normal.y = MARGIN; add( normal ); if (hl.isHighlighted()) { normal.mask = hl.inverted(); highlighted = PixelScene.createMultiline( hl.text, 6 ); highlighted.maxWidth = normal.maxWidth; highlighted.measure(); highlighted.x = normal.x; highlighted.y = normal.y; add( highlighted ); highlighted.mask = hl.mask; highlighted.hardlight( TITLE_COLOR ); } height = normal.y + normal.height() + MARGIN; width = normal.x + normal.width() + MARGIN; } } }
gpl-3.0
job/librenms
includes/discovery/processors/junos.inc.php
2575
<?php // JUNOS Processors if ($device['os'] == "junos") { echo("JUNOS : "); $processors_array = snmpwalk_cache_multi_oid($device, "jnxOperatingCPU", $processors_array, "JUNIPER-MIB" , '+'.$config['install_dir']."/mibs/junos"); $processors_array = snmpwalk_cache_multi_oid($device, "jnxOperatingDRAMSize", $processors_array, "JUNIPER-MIB" , '+'.$config['install_dir']."/mibs/junos"); $processors_array = snmpwalk_cache_multi_oid($device, "jnxOperatingMemory", $processors_array, "JUNIPER-MIB" , '+'.$config['install_dir']."/mibs/junos"); $processors_array = snmpwalk_cache_multi_oid($device, "jnxOperatingDescr", $processors_array, "JUNIPER-MIB" , '+'.$config['install_dir']."/mibs/junos"); if ($debug) { print_r($processors_array); } if (is_array($processors_array)) { foreach ($processors_array as $index => $entry) { if (strlen(strstr($entry['jnxOperatingDescr'], "Routing Engine")) || $entry['jnxOperatingDRAMSize'] && !strpos($entry['jnxOperatingDescr'], "sensor") && !strstr($entry['jnxOperatingDescr'], "fan")) { if (stripos($entry['jnxOperatingDescr'], "sensor") || stripos($entry['jnxOperatingDescr'], "fan")) continue; if ($debug) { echo($index . " " . $entry['jnxOperatingDescr'] . " -> " . $entry['jnxOperatingCPU'] . " -> " . $entry['jnxOperatingDRAMSize'] . "\n"); } $usage_oid = ".1.3.6.1.4.1.2636.3.1.13.1.8." . $index; $descr = $entry['jnxOperatingDescr']; $usage = $entry['jnxOperatingCPU']; if (!strstr($descr, "No") && !strstr($usage, "No") && $descr != "") { discover_processor($valid['processor'], $device, $usage_oid, $index, "junos", $descr, "1", $usage, NULL, NULL); } } // End if checks } // End Foreach } // End if array $srx_processors_array = snmpwalk_cache_multi_oid($device, "jnxJsSPUMonitoringCPUUsage", $srx_processors_array, "JUNIPER-SRX5000-SPU-MONITORING-MIB" , '+'.$config['install_dir']."/mibs/junos"); if ($debug) { print_r($processors_array); } if (is_array($srx_processors_array)) { foreach ($srx_processors_array as $index => $entry) { if (isset($index) && $index >= 0) { $usage_oid = ".1.3.6.1.4.1.2636.3.39.1.12.1.1.1.4." . $index; $descr = "CPU"; # No description in the table? $usage = $entry['jnxJsSPUMonitoringCPUUsage']; discover_processor($valid['processor'], $device, $usage_oid, $index, "junos", $descr, "1", $usage, NULL, NULL); } } } } // End JUNOS Processors unset ($processors_array); unset ($srx_processors_array); ?>
gpl-3.0
qPCR4vir/orange
source/include/common.cpp
766
#ifdef _MSC_VER #include <limits> using namespace std; #ifdef _STLP_LIMITS #define _STLP_FLOAT_INF_REP { 0, 0x7f80 } #define _STLP_FLOAT_QNAN_REP { 0, 0xffc0 } #define _STLP_FLOAT_SNAN_REP { 0x5555, 0x7f85 } #define _STLP_DOUBLE_INF_REP { 0, 0, 0, 0x7ff0 } #define _STLP_DOUBLE_QNAN_REP { 0, 0, 0, 0xfff8 } #define _STLP_DOUBLE_SNAN_REP { 0x5555, 0x5555, 0x5555, 0x7ff5 } const _F_rep _LimG<bool>::_F_inf = _STLP_FLOAT_INF_REP; const _F_rep _LimG<bool>::_F_qNaN = _STLP_FLOAT_QNAN_REP; const _F_rep _LimG<bool>::_F_sNaN = _STLP_FLOAT_SNAN_REP; //const _D_rep _LimG<bool>::_D_inf = _STLP_DOUBLE_INF_REP; const _D_rep _LimG<bool>::_D_qNaN = _STLP_DOUBLE_QNAN_REP; const _D_rep _LimG<bool>::_D_sNaN = _STLP_DOUBLE_SNAN_REP; #endif #endif
gpl-3.0
fabada/pootle
pootle/apps/pootle_app/management/commands/list_languages.py
1705
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from optparse import make_option from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--project', action='append', dest='projects', help='Limit to PROJECTS'), make_option("--modified-since", action="store", dest="modified_since", type=int, help="Only process translations newer than specified " "revision"), ) help = "List language codes." def handle_noargs(self, **options): self.list_languages(**options) def list_languages(self, **options): """List all languages on the server or the given projects.""" projects = options.get('projects', []) from pootle_translationproject.models import TranslationProject tps = TranslationProject.objects.distinct() tps = tps.exclude(language__code='templates').order_by('language__code') revision = options.get("modified_since", 0) if revision: tps = tps.filter(submission__unit__revision__gt=revision) if projects: tps = tps.filter(project__code__in=projects) for lang in tps.values_list('language__code', flat=True): self.stdout.write(lang)
gpl-3.0
ChMat/CoreBundle
Form/AdminAnalyticsTopType.php
2981
<?php /* * This file is part of the Claroline Connect package. * * (c) Claroline Consortium <consortium@claroline.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Claroline\CoreBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class AdminAnalyticsTopType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add( 'top_type', 'choice', array( 'label' => 'show', 'attr' => array( 'class' => 'input-sm' ), 'choices' => array( 'top_extension' => 'top_extension', 'top_workspaces_resources' => 'top_workspaces_resources', 'top_workspaces_connections' => 'top_workspaces_connections', 'top_resources_views' => 'top_resources_views', 'top_resources_downloads' => 'top_resources_downloads', 'top_users_workspaces_owners' => 'top_users_workspaces_owners', 'top_users_workspaces_enrolled' => 'top_users_workspaces_enrolled', 'top_users_connections' => 'top_users_connections', 'top_media_views' => 'top_media_views' ), 'theme_options' => array('label_width' => 'col-md-2', 'control_width' => 'col-md-4') ) ) ->add( 'range', 'daterange', array( 'label' => 'for_period', 'required' => false, 'attr' => array('class' => 'input-sm'), 'theme_options' => array('label_width' => 'col-md-2', 'control_width' => 'col-md-4') ) ) ->add( 'top_number', 'buttongroupselect', array( 'label' => 'top', 'attr' => array('class' => 'input-sm'), 'choices' => array( '20' => '20', '30' => '30', '50' => '50', '100' => '100' ), 'theme_options' => array('label_width' => 'col-md-2', 'control_width' => 'col-md-3') ) ); } public function getName() { return 'admin_analytics_top_form'; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver ->setDefaults( array( 'translation_domain' => 'platform', 'csrf_protection' => false ) ); } }
gpl-3.0
will4wachter/Project1
scripts/globals/abilities/invincible.lua
440
----------------------------------- -- Ability: Invincible ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- OnUseAbility ----------------------------------- function OnAbilityCheck(player,target,ability) return 0,0; end; function OnUseAbility(player, target, ability) player:addStatusEffect(EFFECT_INVINCIBLE,1,0,30); end;
gpl-3.0
revi/mh-puppet
modules/stdlib/lib/puppet/parser/functions/member.rb
2095
# TODO(Krzysztof Wilczynski): We need to add support for regular expression ... # TODO(Krzysztof Wilczynski): Support for strings and hashes too ... # # member.rb # module Puppet::Parser::Functions newfunction(:member, :type => :rvalue, :doc => <<-DOC This function determines if a variable is a member of an array. The variable can be a string, fixnum, or array. *Examples:* member(['a','b'], 'b') Would return: true member(['a', 'b', 'c'], ['a', 'b']) would return: true member(['a','b'], 'c') Would return: false member(['a', 'b', 'c'], ['d', 'b']) would return: false Note: Since Puppet 4.0.0 the same can be performed in the Puppet language. For single values the operator `in` can be used: 'a' in ['a', 'b'] # true And for arrays by using operator `-` to compute a diff: ['d', 'b'] - ['a', 'b', 'c'] == [] # false because 'd' is not subtracted ['a', 'b'] - ['a', 'b', 'c'] == [] # true because both 'a' and 'b' are subtracted Also note that since Puppet 5.2.0 the general form of testing content of an array or hash is to use the built-in `any` and `all` functions. DOC ) do |arguments| raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'member(): Requires array to work with') end unless arguments[1].is_a?(String) || arguments[1].is_a?(Integer) || arguments[1].is_a?(Array) raise(Puppet::ParseError, 'member(): Item to search for must be a string, fixnum, or array') end item = if arguments[1].is_a?(String) || arguments[1].is_a?(Integer) [arguments[1]] else arguments[1] end raise(Puppet::ParseError, 'member(): You must provide item to search for within array given') if item.respond_to?('empty?') && item.empty? result = (item - array).empty? return result end end # vim: set ts=2 sw=2 et :
gpl-3.0
abioyeayo/proj-ardu-pilot
ardupilot/libraries/AP_HAL_VRBRAIN/Storage.cpp
8741
#include <AP_HAL/AP_HAL.h> #if CONFIG_HAL_BOARD == HAL_BOARD_VRBRAIN #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <ctype.h> #include "Storage.h" using namespace VRBRAIN; /* This stores eeprom data in the VRBRAIN MTD interface with a 4k size, and a in-memory buffer. This keeps the latency and devices IOs down. */ // name the storage file after the sketch so you can use the same sd // card for ArduCopter and ArduPlane #define STORAGE_DIR "/fs/microsd/APM" #define OLD_STORAGE_FILE STORAGE_DIR "/" SKETCHNAME ".stg" #define OLD_STORAGE_FILE_BAK STORAGE_DIR "/" SKETCHNAME ".bak" //#define SAVE_STORAGE_FILE STORAGE_DIR "/" SKETCHNAME ".sav" #define MTD_PARAMS_FILE "/fs/mtd" #define MTD_SIGNATURE 0x14012014 #define MTD_SIGNATURE_OFFSET (8192-4) #define STORAGE_RENAME_OLD_FILE 0 extern const AP_HAL::HAL& hal; VRBRAINStorage::VRBRAINStorage(void) : _fd(-1), _dirty_mask(0), _perf_storage(perf_alloc(PC_ELAPSED, "APM_storage")), _perf_errors(perf_alloc(PC_COUNT, "APM_storage_errors")) { } /* get signature from bytes at offset MTD_SIGNATURE_OFFSET */ uint32_t VRBRAINStorage::_mtd_signature(void) { int mtd_fd = open(MTD_PARAMS_FILE, O_RDONLY); if (mtd_fd == -1) { AP_HAL::panic("Failed to open " MTD_PARAMS_FILE); } uint32_t v; if (lseek(mtd_fd, MTD_SIGNATURE_OFFSET, SEEK_SET) != MTD_SIGNATURE_OFFSET) { AP_HAL::panic("Failed to seek in " MTD_PARAMS_FILE); } bus_lock(true); if (read(mtd_fd, &v, sizeof(v)) != sizeof(v)) { AP_HAL::panic("Failed to read signature from " MTD_PARAMS_FILE); } bus_lock(false); close(mtd_fd); return v; } /* put signature bytes at offset MTD_SIGNATURE_OFFSET */ void VRBRAINStorage::_mtd_write_signature(void) { int mtd_fd = open(MTD_PARAMS_FILE, O_WRONLY); if (mtd_fd == -1) { AP_HAL::panic("Failed to open " MTD_PARAMS_FILE); } uint32_t v = MTD_SIGNATURE; if (lseek(mtd_fd, MTD_SIGNATURE_OFFSET, SEEK_SET) != MTD_SIGNATURE_OFFSET) { AP_HAL::panic("Failed to seek in " MTD_PARAMS_FILE); } bus_lock(true); if (write(mtd_fd, &v, sizeof(v)) != sizeof(v)) { AP_HAL::panic("Failed to write signature in " MTD_PARAMS_FILE); } bus_lock(false); close(mtd_fd); } /* upgrade from microSD to MTD (FRAM) */ void VRBRAINStorage::_upgrade_to_mtd(void) { // the MTD is completely uninitialised - try to get a // copy from OLD_STORAGE_FILE int old_fd = open(OLD_STORAGE_FILE, O_RDONLY); if (old_fd == -1) { ::printf("Failed to open %s\n", OLD_STORAGE_FILE); return; } int mtd_fd = open(MTD_PARAMS_FILE, O_WRONLY); if (mtd_fd == -1) { AP_HAL::panic("Unable to open MTD for upgrade"); } if (::read(old_fd, _buffer, sizeof(_buffer)) != sizeof(_buffer)) { close(old_fd); close(mtd_fd); ::printf("Failed to read %s\n", OLD_STORAGE_FILE); return; } close(old_fd); ssize_t ret; bus_lock(true); if ((ret=::write(mtd_fd, _buffer, sizeof(_buffer))) != sizeof(_buffer)) { ::printf("mtd write of %u bytes returned %d errno=%d\n", sizeof(_buffer), ret, errno); AP_HAL::panic("Unable to write MTD for upgrade"); } bus_lock(false); close(mtd_fd); #if STORAGE_RENAME_OLD_FILE rename(OLD_STORAGE_FILE, OLD_STORAGE_FILE_BAK); #endif ::printf("Upgraded MTD from %s\n", OLD_STORAGE_FILE); } void VRBRAINStorage::_storage_open(void) { if (_initialised) { return; } struct stat st; _have_mtd = (stat(MTD_PARAMS_FILE, &st) == 0); // VRBRAIN should always have /fs/mtd_params if (!_have_mtd) { AP_HAL::panic("Failed to find " MTD_PARAMS_FILE); } /* cope with upgrading from OLD_STORAGE_FILE to MTD */ bool good_signature = (_mtd_signature() == MTD_SIGNATURE); if (stat(OLD_STORAGE_FILE, &st) == 0) { if (good_signature) { #if STORAGE_RENAME_OLD_FILE rename(OLD_STORAGE_FILE, OLD_STORAGE_FILE_BAK); #endif } else { _upgrade_to_mtd(); } } // we write the signature every time, even if it already is // good, as this gives us a way to detect if the MTD device is // functional. It is better to panic now than to fail to save // parameters in flight _mtd_write_signature(); _dirty_mask = 0; int fd = open(MTD_PARAMS_FILE, O_RDONLY); if (fd == -1) { AP_HAL::panic("Failed to open " MTD_PARAMS_FILE); } const uint16_t chunk_size = 128; for (uint16_t ofs=0; ofs<sizeof(_buffer); ofs += chunk_size) { bus_lock(true); ssize_t ret = read(fd, &_buffer[ofs], chunk_size); bus_lock(false); if (ret != chunk_size) { ::printf("storage read of %u bytes at %u to %p failed - got %d errno=%d\n", (unsigned)sizeof(_buffer), (unsigned)ofs, &_buffer[ofs], (int)ret, (int)errno); AP_HAL::panic("Failed to read " MTD_PARAMS_FILE); } } close(fd); #ifdef SAVE_STORAGE_FILE fd = open(SAVE_STORAGE_FILE, O_WRONLY|O_CREAT|O_TRUNC, 0644); if (fd != -1) { write(fd, _buffer, sizeof(_buffer)); close(fd); ::printf("Saved storage file %s\n", SAVE_STORAGE_FILE); } #endif _initialised = true; } /* mark some lines as dirty. Note that there is no attempt to avoid the race condition between this code and the _timer_tick() code below, which both update _dirty_mask. If we lose the race then the result is that a line is written more than once, but it won't result in a line not being written. */ void VRBRAINStorage::_mark_dirty(uint16_t loc, uint16_t length) { uint16_t end = loc + length; for (uint8_t line=loc>>VRBRAIN_STORAGE_LINE_SHIFT; line <= end>>VRBRAIN_STORAGE_LINE_SHIFT; line++) { _dirty_mask |= 1U << line; } } void VRBRAINStorage::read_block(void *dst, uint16_t loc, size_t n) { if (loc >= sizeof(_buffer)-(n-1)) { return; } _storage_open(); memcpy(dst, &_buffer[loc], n); } void VRBRAINStorage::write_block(uint16_t loc, const void *src, size_t n) { if (loc >= sizeof(_buffer)-(n-1)) { return; } if (memcmp(src, &_buffer[loc], n) != 0) { _storage_open(); memcpy(&_buffer[loc], src, n); _mark_dirty(loc, n); } } void VRBRAINStorage::bus_lock(bool lock) { } void VRBRAINStorage::_timer_tick(void) { if (!_initialised || _dirty_mask == 0) { return; } perf_begin(_perf_storage); if (_fd == -1) { _fd = open(MTD_PARAMS_FILE, O_WRONLY); if (_fd == -1) { perf_end(_perf_storage); perf_count(_perf_errors); return; } } // write out the first dirty set of lines. We don't write more // than one to keep the latency of this call to a minimum uint8_t i, n; for (i=0; i<VRBRAIN_STORAGE_NUM_LINES; i++) { if (_dirty_mask & (1<<i)) { break; } } if (i == VRBRAIN_STORAGE_NUM_LINES) { // this shouldn't be possible perf_end(_perf_storage); perf_count(_perf_errors); return; } uint32_t write_mask = (1U<<i); // see how many lines to write for (n=1; (i+n) < VRBRAIN_STORAGE_NUM_LINES && n < (VRBRAIN_STORAGE_MAX_WRITE>>VRBRAIN_STORAGE_LINE_SHIFT); n++) { if (!(_dirty_mask & (1<<(n+i)))) { break; } // mark that line clean write_mask |= (1<<(n+i)); } /* write the lines. This also updates _dirty_mask. Note that because this is a SCHED_FIFO thread it will not be preempted by the main task except during blocking calls. This means we don't need a semaphore around the _dirty_mask updates. */ if (lseek(_fd, i<<VRBRAIN_STORAGE_LINE_SHIFT, SEEK_SET) == (i<<VRBRAIN_STORAGE_LINE_SHIFT)) { _dirty_mask &= ~write_mask; bus_lock(true); ssize_t ret = write(_fd, &_buffer[i<<VRBRAIN_STORAGE_LINE_SHIFT], n<<VRBRAIN_STORAGE_LINE_SHIFT); bus_lock(false); if (ret != n<<VRBRAIN_STORAGE_LINE_SHIFT) { // write error - likely EINTR _dirty_mask |= write_mask; close(_fd); _fd = -1; perf_count(_perf_errors); } } perf_end(_perf_storage); } #endif // CONFIG_HAL_BOARD
gpl-3.0
thica/ORCA-Remote
custombuildscripts/debian/patch_kivy.1.11/pyinstaller_hooks/pyi_rth_kivy.py
634
import os import sys root = os.path.join(sys._MEIPASS, 'kivy_install') os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data') os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules') os.environ['GST_PLUGIN_PATH'] = '{}{}{}'.format( sys._MEIPASS, os.pathsep, os.path.join(sys._MEIPASS, 'gst-plugins')) os.environ['GST_REGISTRY'] = os.path.join(sys._MEIPASS, 'registry.bin') sys.path += [os.path.join(root, '_libs')] if sys.platform == 'darwin': sitepackages = os.path.join(sys._MEIPASS, 'sitepackages') sys.path += [sitepackages, os.path.join(sitepackages, 'gst-0.10')] os.putenv('GST_REGISTRY_FORK', 'no')
gpl-3.0
163gal/Time-Line
libs64/wxPython/lib/popupctl.py
446
## This file imports items from the wx package into the wxPython package for ## backwards compatibility. Some names will also have a 'wx' added on if ## that is how they used to be named in the old wxPython package. import wx.lib.popupctl __doc__ = wx.lib.popupctl.__doc__ PopButton = wx.lib.popupctl.PopButton wxPopupDialog = wx.lib.popupctl.PopupDialog wxPopupControl = wx.lib.popupctl.PopupControl wxPopupCtrl = wx.lib.popupctl.PopupCtrl
gpl-3.0
ustegrew/ustegrew.github.io
courses/it001/lib/dojo/gridx/modules/NestedSort.js
7480
define([ "dojo/_base/declare", "dojo/_base/array", "dojo/_base/lang", "dojo/_base/event", "dojo/query", "dojo/string", "dojo/dom-class", "dojo/dom-construct", "dojo/keys", "../core/_Module", "../core/model/extensions/Sort", "./HeaderRegions" ], function(declare, array, lang, event, query, string, domClass, domConstruct, keys, _Module, Sort){ /*===== return declare(_Module, { // summary: // module name: sort. // Sort multiple columns in a nested way. getSortData: function(){ // summary: // TODOC }, sort: function(sortData){ // summary: // TODOC }, isSorted: function(colId){ // summary: // TODOC }, clear: function(){ // summary: // Clear the sorting state }, isSortable: function(colId){ // summary: // TODOC } }); =====*/ var filter = array.filter, indexOf = array.indexOf, removeClass = domClass.remove, addClass = domClass.add, a11yText = { 'dojoxGridDescending': '<span class="gridxNestedSortBtnText">&#9662;</span>', 'dojoxGridAscending': '<span class="gridxNestedSortBtnText">&#9652;</span>', 'dojoxGridAscendingTip': '<span class="gridxNestedSortBtnText">&#1784;</span>', 'dojoxGridDescendingTip': '<span class="gridxNestedSortBtnText">&#1783;</span>', 'dojoxGridUnsortedTip': '<span class="gridxNestedSortBtnText">x</span>' //'&#10006;' }; return declare(_Module, { name: 'sort', required: ['headerRegions'], modelExtensions: [Sort], preload: function(args){ var t = this, g = t.grid; t._sortData = t.arg('initialOrder', []); if(g.persist){ var d = g.persist.registerAndLoad('sort', function(){ return t._sortData; }); if(d){ t._sortData = d; } } t._sortData = filter(t._sortData, function(d){ return t.isSortable(d.colId); }); if(t._sortData.length){ g.model.sort(t._sortData); } t.connect(g.headerRegions, 'refresh', t._updateUI); g.headerRegions.add(lang.hitch(t, t._createBtn, 1), 10, 1); g.headerRegions.add(lang.hitch(t, t._createBtn, 0), 11, 1); }, columnMixin: { isSorted: function(){ return this.grid.sort.isSorted(this.id); }, isSortable: function(){ return this.grid.sort.isSortable(this.id); } }, getSortData: function(){ return this._sortData; }, sort: function(sortData){ var t = this; t._sortData = filter(sortData, function(d){ return t.isSortable(d.colId); }); t._doSort(); }, isSorted: function(colId){ var ret = 0; array.some(this._sortData, function(d){ if(d.colId == colId){ ret = d.descending ? -1 : 1; return 1; } }); return ret; }, isSortable: function(colId){ var col = this.grid._columnsById[colId]; return col && (col.sortable || col.sortable === undefined); }, clear: function(){ this._sortData.length = 0; this._doSort(); }, //Private--------------------------------------------------------------------------- _createBtn: function(isSingle, col){ var t = this, nls = t.grid.nls; if(t.isSortable(col.id)){ var btn = domConstruct.create('div', { 'class': 'gridxSortBtn gridxSortBtn' + (isSingle ? 'Single' : 'Nested'), tabIndex: -1, title: isSingle ? nls.singleSort + ' - ' + nls.ascending : nls.nestedSort + ' - ' + nls.ascending, innerHTML: isSingle ? a11yText.dojoxGridAscendingTip + '&nbsp;' : t._sortData.length + 1 + a11yText.dojoxGridAscendingTip }); t.connect(btn, 'onmousedown', function(){ t._sort(col, btn, isSingle); }); t.connect(btn, 'onkeydown', function(e){ if(e.keyCode == keys.ENTER){ event.stop(e); t._sort(col, btn, isSingle); } }); return btn; } }, _sort: function(col, btn, isSingle){ var t = this, d, sortData = t._sortData; if(isSingle){ if(sortData.length > 1){ sortData.length = 0; } d = filter(sortData, function(data){ return data.colId === col.id; })[0]; sortData.length = 0; if(d){ sortData.push(d); } }else{ d = filter(sortData, function(d){ return d.colId === col.id; })[0]; } if(d){ if(d.descending){ sortData.splice(indexOf(sortData, d), 1); } d.descending = !d.descending; }else{ d = { colId: col.id, descending: false }; sortData.push(d); } t._doSort(); }, _doSort: function(){ var g = this.grid, d = this._sortData; this._updateUI(); g.model.sort(d.length ? d : null); g.body.refresh(); }, _updateUI: function(){ var t = this, g = t.grid, nls = g.nls, dn = g.domNode, sortData = array.filter(t._sortData, function(s){ return g._columnsById[s.colId]; }); removeClass(dn, 'gridxSingleSorted'); removeClass(dn, 'gridxNestedSorted'); if(sortData.length == 1){ addClass(dn, 'gridxSingleSorted'); }else if(sortData.length > 1){ addClass(dn, 'gridxNestedSorted'); } query('.gridxCell', g.header.domNode).forEach(function(cell){ var colid = cell.getAttribute('colid'); if(t.isSortable(colid)){ array.forEach(['', 'Desc', 'Asc', 'Main'], function(s){ removeClass(cell, 'gridxCellSorted' + s); }); var singleBtn = query('.gridxSortBtnSingle', cell)[0], nestedBtn = query('.gridxSortBtnNested', cell)[0]; singleBtn.title = nls.singleSort + ' - ' + nls.ascending; nestedBtn.title = nls.nestedSort + ' - ' + nls.ascending; singleBtn.innerHTML = a11yText.dojoxGridAscendingTip + '&nbsp;'; nestedBtn.innerHTML = sortData.length + 1 + a11yText.dojoxGridAscendingTip; var d = filter(sortData, function(data){ return data.colId === colid; })[0]; t._setWaiState(cell, colid, d); if(d){ nestedBtn.innerHTML = indexOf(sortData, d) + 1; addClass(cell, 'gridxCellSorted'); if(d == sortData[0]){ addClass(cell, 'gridxCellSortedMain'); } var len = sortData.length; if(d.descending){ addClass(cell, 'gridxCellSortedDesc'); if(len == 1){ singleBtn.title = nls.singleSort + ' - ' + nls.unsorted; singleBtn.innerHTML = a11yText.dojoxGridDescending + '&nbsp;'; }else{ nestedBtn.title = nls.nestedSort + ' - ' + nls.unsorted; nestedBtn.innerHTML += a11yText.dojoxGridDescending; } }else{ addClass(cell, 'gridxCellSortedAsc'); if(len == 1){ singleBtn.title = nls.singleSort + ': ' + nls.descending; singleBtn.innerHTML = a11yText.dojoxGridAscending + '&nbsp;'; }else{ nestedBtn.title = nls.nestedSort + ' - ' + nls.descending; nestedBtn.innerHTML += a11yText.dojoxGridAscending; } } } } }); }, _setWaiState: function(cell, colid, data){ var col = this.grid.column(colid), columnInfo = 'Column ' + col.name(), orderState = 'none', orderAction = 'ascending'; if(data){ orderState = data.descending ? 'descending' : 'ascending'; orderAction = data.descending ? 'none' : 'descending'; } var a11ySingleLabel = string.substitute(this.grid.nls.waiSingleSortLabel, [columnInfo, orderState, orderAction]), a11yNestedLabel = string.substitute(this.grid.nls.waiNestedSortLabel, [columnInfo, orderState, orderAction]); query('.gridxSortBtnSingle', cell)[0].setAttribute("aria-label", a11ySingleLabel); query('.gridxSortBtnNested', cell)[0].setAttribute("aria-label", a11yNestedLabel); } }); });
gpl-3.0
zhuango/Cpp
cppPrimerPlus6/plus_code/Chapter 18/lambda0.cpp
2076
// lambda0.cpp -- using lambda expressions #include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <ctime> const long Size1 = 39L; const long Size2 = 100*Size1; const long Size3 = 100*Size2; bool f3(int x) {return x % 3 == 0;} bool f13(int x) {return x % 13 == 0;} int main() { using std::cout; std::vector<int> numbers(Size1); std::srand(std::time(0)); std::generate(numbers.begin(), numbers.end(), std::rand); // using function pointers cout << "Sample size = " << Size1 << '\n'; int count3 = std::count_if(numbers.begin(), numbers.end(), f3); cout << "Count of numbers divisible by 3: " << count3 << '\n'; int count13 = std::count_if(numbers.begin(), numbers.end(), f13); cout << "Count of numbers divisible by 13: " << count13 << "\n\n"; // increase number of numbers numbers.resize(Size2); std::generate(numbers.begin(), numbers.end(), std::rand); cout << "Sample size = " << Size2 << '\n'; // using a functor class f_mod { private: int dv; public: f_mod(int d = 1) : dv(d) {} bool operator()(int x) {return x % dv == 0;} }; count3 = std::count_if(numbers.begin(), numbers.end(), f_mod(3)); cout << "Count of numbers divisible by 3: " << count3 << '\n'; count13 = std::count_if(numbers.begin(), numbers.end(), f_mod(13)); cout << "Count of numbers divisible by 13: " << count13 << "\n\n"; // increase number of numbers again numbers.resize(Size3); std::generate(numbers.begin(), numbers.end(), std::rand); cout << "Sample size = " << Size3 << '\n'; // using lambdas count3 = std::count_if(numbers.begin(), numbers.end(), [](int x){return x % 3 == 0;}); cout << "Count of numbers divisible by 3: " << count3 << '\n'; count13 = std::count_if(numbers.begin(), numbers.end(), [](int x){return x % 13 == 0;}); cout << "Count of numbers divisible by 13: " << count13 << '\n'; // std::cin.get(); return 0; }
gpl-3.0
phip1611/hueman
parts/single-heading.php
117
<h1 class="post-title entry-title"><?php the_title(); ?></h1> <?php get_template_part('parts/single-author-date'); ?>
gpl-3.0
wiki2014/Learning-Summary
alps/cts/tools/vm-tests-tf/src/dot/junit/opcodes/not_long/d/T_not_long_1.java
751
/* * Copyright (C) 2008 The Android Open Source Project * * 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. */ package dot.junit.opcodes.not_long.d; public class T_not_long_1 { public long run(long d) { return ~d; } }
gpl-3.0
phiratio/Pluralsight-materials
Paths/HTML5/09.HTML5-Advanced-Topics/materials/04. Web workers/OfflineDemo/debug-manifest.aspx.cs
87
 namespace OfflineDemo { public partial class debug_manifest : NoCachePage { } }
gpl-3.0
nicolas17/boinc
lib/md5_file.cpp
3807
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. #if defined(_WIN32) && !defined(__STDWX_H__) #include "boinc_win.h" #elif defined(_WIN32) && defined(__STDWX_H__) #include "stdwx.h" #else #include "config.h" #ifdef _USING_FCGI_ #include "boinc_fcgi.h" #else #include <cstdio> #endif #endif #ifdef _WIN32 #include <wincrypt.h> #endif #ifdef ANDROID #include <stdlib.h> #endif #include "error_numbers.h" #include "md5.h" #include "md5_file.h" int md5_file(const char* path, char* output, double& nbytes, bool is_gzip) { unsigned char buf[4096]; unsigned char binout[16]; md5_state_t state; int i, n; nbytes = 0; #ifndef _USING_FCGI_ FILE *f = fopen(path, "rb"); #else FILE *f = FCGI::fopen(path, "rb"); #endif if (!f) { fprintf(stderr, "md5_file: can't open %s\n", path); #ifndef _USING_FCGI_ std::perror("md5_file"); #else FCGI::perror("md5_file"); #endif return ERR_FOPEN; } md5_init(&state); // check and skip gzip header if needed // if (is_gzip) { n = (int)fread(buf, 1, 10, f); if (n != 10) { fclose(f); return ERR_BAD_FORMAT; } if (buf[0] != 0x1f || buf[1] != 0x8b || buf[2] != 0x08) { fclose(f); return ERR_BAD_FORMAT; } nbytes = 10; } while (1) { n = (int)fread(buf, 1, 4096, f); if (n<=0) break; nbytes += n; md5_append(&state, buf, n); } md5_finish(&state, binout); for (i=0; i<16; i++) { sprintf(output+2*i, "%02x", binout[i]); } output[32] = 0; fclose(f); return 0; } int md5_block(const unsigned char* data, int nbytes, char* output) { unsigned char binout[16]; int i; md5_state_t state; md5_init(&state); md5_append(&state, data, nbytes); md5_finish(&state, binout); for (i=0; i<16; i++) { sprintf(output+2*i, "%02x", binout[i]); } output[32] = 0; return 0; } std::string md5_string(const unsigned char* data, int nbytes) { char output[MD5_LEN]; md5_block(data, nbytes, output); return std::string(output); } // make a random 32-char string // (the MD5 of some quasi-random bits) // int make_random_string(char* out) { char buf[256]; #ifdef _WIN32 HCRYPTPROV hCryptProv; if(! CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0)) { return -1; } if(! CryptGenRandom(hCryptProv, (DWORD) 32, (BYTE *) buf)) { CryptReleaseContext(hCryptProv, 0); return -1; } CryptReleaseContext(hCryptProv, 0); #elif defined ANDROID // /dev/random not available on Android, using stdlib function instead int i = rand(); snprintf(buf, sizeof(buf), "%d", i); #else #ifndef _USING_FCGI_ FILE* f = fopen("/dev/random", "r"); #else FILE* f = FCGI::fopen("/dev/random", "r"); #endif if (!f) { return -1; } size_t n = fread(buf, 32, 1, f); fclose(f); if (n != 1) return -1; #endif md5_block((const unsigned char*)buf, 32, out); return 0; }
gpl-3.0
EliasFarhan/gsn
gsn-tiny/src/tinygsn/model/wrappers/utils/MICSensor.java
11824
/** * Global Sensor Networks (GSN) Source Code * Copyright (c) 2006-2014, Ecole Polytechnique Federale de Lausanne (EPFL) * * This file is part of GSN. * * GSN is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GSN is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GSN. If not, see <http://www.gnu.org/licenses/>. * * File: gsn-tiny/src/tinygsn/model/wrappers/utils/MICSensor.java * * @author Do Ngoc Hoan */ package tinygsn.model.wrappers.utils; import java.io.Serializable; import java.util.Arrays; import tinygsn.beans.DataField; import tinygsn.beans.StreamElement; import android.app.Activity; import android.os.Handler; import android.widget.Toast; import ch.serverbox.android.ftdiusb.FTDI_USB_Handler; /* This class draws the measurement screen. * All the communication with the sensor happens here. */ public class MICSensor extends FTDI_USB_Handler { public interface ReadyListener { public void onReady(); } public interface VirtualSensorDataListener { public void consume(StreamElement se); } private VirtualSensorDataListener listener = null; private ReadyListener initListener = null; private DataField[] df; // Calibration values private double k = 0.025; private double a0 = 0.7; private double a1 = 0.02; private double b0 = 0.7; private double b1 = 0.02; private int interval = 30; // Create an handler for drawing toast messages from other threads etc. private Handler handler; // Boolean flags to check for sensor answers etc private boolean waitForDiagnostic; // private boolean waitForAuto; private boolean waitForStop; // private boolean waitForTimer; private boolean measurementReceived; private boolean sensorInitialized; protected boolean saveToFile; private boolean autoMeasurementThreadFlag; private boolean initThreadFlag; private boolean stopThreadFlag; private char[] receiveBuffer; // A buffer to store the received bytes private int bufferIndex; // The buffer index for the receive buffer public MICSensor(Activity a) { super(a); try { df = new DataField[6]; df[0] = new DataField("resistanceO", "int"); df[1] = new DataField("resistanceV", "int"); df[2] = new DataField("humidity", "double"); df[3] = new DataField("temperature", "double"); df[4] = new DataField("ozoneCalibrated", "double"); df[5] = new DataField("vocCalibrated", "double"); } catch (Exception e) { } handler = new Handler(); // Initialize the receive buffer bufferIndex = 0; receiveBuffer = new char[32]; // 32 is the largest string size for the // sensor. waitForDiagnostic = false; measurementReceived = false; sensorInitialized = false; autoMeasurementThreadFlag = false; initThreadFlag = false; stopThreadFlag = false; } public void setListener(VirtualSensorDataListener listener) { this.listener = listener; } public void setInitListener(ReadyListener initListener) { this.initListener = initListener; } public DataField[] getDataField() { return df; } /* * Toggle automatic measurements. The measurements are polled in the interval * specified in the preferences. Handled in its own thread so it is * non-blocking. */ public boolean toggleAutoMeasurements(boolean isChecked) { Thread thread = new Thread() { public void run() { while (autoMeasurementThreadFlag) { getMeasurement(); try { // Sleep for interval seconds. sleep(interval * 1000); } catch (InterruptedException e) { e.printStackTrace(); } // If no answer was received, wait a bit longer. // If we try to get a reading when the sensor is updating itself, it // doesn't respond. if (measurementReceived == false) { try { sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; // Start the auto update thread when the button is on. if (isChecked) { // If the sensor couldn't initialize, we don't start the thread. /* * if(sensorInitialized==false) { Toast.makeText(activity, * "Sensor not initialized", Toast.LENGTH_SHORT).show(); // Return false * to indicate that the button has to be turned off again. * * return false; } else { */ autoMeasurementThreadFlag = true; thread.start(); // } } else { autoMeasurementThreadFlag = false; } return true; } /* * Send a {M} to get a measurement from the sensor. The received data is * handled in the onDataReceived routine. */ public void getMeasurement() { if (sensorInitialized == false) { // Toast // .makeText(activity, "Sensor not yet initialized", Toast.LENGTH_SHORT) // .show(); initSensor(); return; } measurementReceived = false; write("{M}\n".getBytes()); } /* * Process a read input string. */ private void processInput(String receivedString, int length) { // Valid strings start with { and end with }. Anything else is discarded. if (receivedString.charAt(0) != '{' || receivedString.charAt(length - 1) != '}') { return; } // A diagnostic message is received. // {A00}->OK if (receivedString.charAt(1) == 'A' && receivedString.charAt(2) == '0' && receivedString.charAt(3) == '0') { waitForDiagnostic = false; } else if (receivedString.charAt(1) == 'Q') { waitForStop = false; } // If it is a measurement, extract the values. // A correct measurement always has length 18. else if (receivedString.charAt(1) == 'M') { measurementReceived = true; // Convert the received string to hex values. String[] values = receivedString.split("[,|}|{M]"); // split string: // pos 1: temp // pos 2: humidity // pos 3: resistance VOC // pos 4: resistance O3 int resistanceV = Integer.parseInt(values[4]); int resistanceO = Integer.parseInt(values[5]); // double resistanceV = Double.parseDouble(values[4]); // double resistanceO = Double.parseDouble(values[5]); double temperature = Double.parseDouble(values[2]); double humidity = Double.parseDouble(values[3]); double resistanceCompensatedO = resistanceO * Math.exp(k * ((temperature - 25))); double resistanceCompensatedV = resistanceV * Math.exp(k * ((temperature - 25))); double ozoneCalculated = a0 + a1 * resistanceCompensatedO; double vocCalculated = b0 + b1 * resistanceCompensatedV; StreamElement se = new StreamElement(df, new Serializable[] { resistanceO, resistanceV, humidity, temperature, ozoneCalculated, vocCalculated }); if (listener != null) { listener.consume(se); } } } /* * Initialize the sensor. Do it in its own thread, to avoid blocking. {A}, * {S}, {W...} is sent sequentially. After every step we wait for the correct * answer. If no answer is received for 1 second, the init thread is aborted. */ public void initSensor() { // The thread which sends the commands and waits for the answers from the // sensor. Runnable runnable = new Runnable() { public void run() { if (initThreadFlag) return; int counter = 0; // Set the thread flag. initThreadFlag = true; // Wait for a diagnostics message. waitForDiagnostic = true; // Send a {A} to get a diagnostics answer from the sensor. // The sensor should send a {A00} back. write("{A}\n".getBytes()); handler.post(new Runnable() { public void run() { Toast.makeText(activity.getApplicationContext(), "Initialization started", Toast.LENGTH_SHORT).show(); } }); l("diagnostic sent"); while (waitForDiagnostic == true) { try { Thread.sleep(100); } catch (InterruptedException e) { } counter++; if (counter > 600) { initThreadFlag = false; initToast(false); return; } } // Successfully initialized. sensorInitialized = true; // Clear the thread flag. initThreadFlag = false; initToast(true); // showLog("Successfully initialized."); } private void initToast(boolean success) { if (success) { handler.post(new Runnable() { public void run() { if (initListener != null) initListener.onReady(); Toast.makeText(activity.getApplicationContext(), "Initialization succeded", Toast.LENGTH_SHORT).show(); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(activity.getApplicationContext(), "Initialization failed", Toast.LENGTH_SHORT).show(); } }); } } }; // Start the sensor init thread. if (initThreadFlag == false) { new Thread(runnable).start(); } else { // Toast.makeText(activity, "Already initializing", Toast.LENGTH_SHORT) // .show(); } } /* * Pause the sensor. The sensor has to be reinitialized after that */ public void Pause() { // The thread which sends the commands and waits for the answers from the // sensor. Runnable runnable = new Runnable() { public void run() { int counter = 0; // Set the thread flag. stopThreadFlag = true; // Wait for a diagnostics message. waitForStop = true; // Send a {A} to get a diagnostics answer from the sensor. // The sensor should send a {A00} back. write("{Q}\n".getBytes()); handler.post(new Runnable() { public void run() { Toast.makeText(activity.getApplicationContext(), "Sensor stopped", Toast.LENGTH_SHORT).show(); } }); l("stop sent"); while (waitForStop == true) { try { Thread.sleep(100); } catch (InterruptedException e) { } counter++; if (counter > 50) { stopThreadFlag = false; return; } } // Successfully uninitialized. sensorInitialized = false; // Clear the thread flag. stopThreadFlag = false; } }; // Start the sensor init thread. if (stopThreadFlag == false) { new Thread(runnable).start(); } else { Toast.makeText(activity, "Already uninitializing", Toast.LENGTH_SHORT) .show(); } } /* * Process any data that's coming from the usb port. */ @Override protected void onDataReceived(final byte[] buffer, final int size) { new Thread(new Runnable() { public void run() { l("receive:" + new String(buffer, 0, size)); // showLog("onDataReceived " + "receive:" + new String(buffer, 0, // size)); if (receiveBuffer != null) { for (int i = 0; i < size; i++) { if ((char) buffer[i] == '{') { bufferIndex = 0; Arrays.fill(receiveBuffer, (char) 0); } // Write the read byte into the receive buffer. receiveBuffer[bufferIndex] = (char) buffer[i]; // If a } is received, process the read data. if (receiveBuffer[bufferIndex] == '}') { processInput(new String(receiveBuffer), bufferIndex + 1); // Clear the buffer. bufferIndex = 0; Arrays.fill(receiveBuffer, (char) 0); } else { // Update the buffer index. Don't let it overflow. bufferIndex = bufferIndex >= receiveBuffer.length - 1 ? receiveBuffer.length - 1 : bufferIndex + 1; } } } } }).start(); } // void showLog(final String text) { // activity.runOnUiThread(new Runnable() { // public void run() { // Toast.makeText(activity, text, Toast.LENGTH_SHORT).show(); // } // }); // } }
gpl-3.0
crosslink/huai
components/com_kunena/lib/kunena.file.class.1.6.php
4109
<?php /** * @version $Id$ * Kunena Component * @package Kunena * @Copyright (C) 2011 Kunena All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org **/ defined( '_JEXEC' ) or die(); jimport('joomla.filesystem.path'); jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.file'); class CKunenaPath extends JPath { function tmpdir() { static $tmpdir=false; if ($tmpdir) return realpath($tmpdir); jimport('joomla.filesystem.file'); jimport('joomla.user.helper'); $tmp = md5(JUserHelper::genRandomPassword(16)); $ssp = ini_get('session.save_path'); $jtp = JPATH_SITE.'/tmp'; // Try to find a writable directory $tmpdir = @is_writable('/tmp') ? '/tmp' : false; // $tmpdir = (!$tmpdir && is_writable($ssp)) ? $ssp : false; $tmpdir = (!$tmpdir && is_writable($jtp)) ? $jtp : false; if (!$tmpdir) { $temp=tempnam(JPATH_ROOT . '/tmp',''); if (file_exists($temp)) { unlink($temp); $tmpdir = dirname($temp); } } return realpath($tmpdir); } function isWritable($path) { if (is_writable($path) || self::isOwner($path)) return true; return false; } } class CKunenaFolder extends JFolder { static function createIndex($folder) { // Make sure we have an index.html file in the current folder if (!CKunenaFile::exists($folder.'/index.html')) { CKunenaFile::write($folder.'/index.html','<html><body></body></html>'); } } } class CKunenaFile extends JFile { static function copy($src, $dest, $path = null) { // Initialize variables jimport('joomla.client.helper'); $FTPOptions = JClientHelper::getCredentials('ftp'); if ($path) { $src = CKunenaPath::clean($path.'/'.$src); $dest = CKunenaPath::clean($path.'/'.$dest); } if ($FTPOptions['enabled'] == 1) { // Make sure that we can copy file in FTP mode if (self::exists($dest) && !CKunenaPath::isOwner($dest)) @chmod($dest, 0777); } $ret = parent::copy($src, $dest); if ($ret === false && $FTPOptions['enabled'] == 1) @chmod($dest, 0644); return $ret; } static function move($src, $dest, $path = null) { // Initialize variables jimport('joomla.client.helper'); $FTPOptions = JClientHelper::getCredentials('ftp'); if ($path) { $src = CKunenaPath::clean($path.'/'.$src); $dest = CKunenaPath::clean($path.'/'.$dest); } if ($FTPOptions['enabled'] == 1) { // Make sure that we can move file in FTP mode if (self::exists($dest) && !CKunenaPath::isOwner($dest)) @chmod($dest, 0777); // If owner is not right, copy the file if (self::exists($src) && !CKunenaPath::isOwner($src)) { if (($ret = self::copy($src, $dest)) === true) { self::delete($src); } } else { $ret = parent::move($src, $dest); } } else { $ret = parent::move($src, $dest); } if ($ret === false && $FTPOptions['enabled'] == 1) @chmod($dest, 0644); return $ret; } static function write($file, $buffer) { // Initialize variables jimport('joomla.client.helper'); $FTPOptions = JClientHelper::getCredentials('ftp'); if ($FTPOptions['enabled'] == 1) { // Make sure that we can copy file in FTP mode if (self::exists($file) && !CKunenaPath::isOwner($file)) @chmod($file, 0777); } $ret = parent::write($file, $buffer); if ($ret === false && $FTPOptions['enabled'] == 1) @chmod($file, 0644); return $ret; } static function upload($src, $dest) { // Initialize variables jimport('joomla.client.helper'); $FTPOptions = JClientHelper::getCredentials('ftp'); $ret = false; if (is_uploaded_file($src)) { if ($FTPOptions['enabled'] == 1 && self::exists($dest) && !CKunenaPath::isOwner($dest)) @chmod($dest, 0777); $ret = parent::upload($src, $dest); if ($FTPOptions['enabled'] == 1) { if ($ret === true) { jimport('joomla.client.ftp'); $ftp = & JFTP::getInstance($FTPOptions['host'], $FTPOptions['port'], null, $FTPOptions['user'], $FTPOptions['pass']); @unlink($src); $ret = true; } else { @chmod($src, 0644); } } } else { JError::raiseWarning(21, JText::_('WARNFS_ERR02')); } } } ?>
gpl-3.0
huncrys/mtasa-blue
Server/mods/deathmatch/logic/lua/CLuaModule.cpp
12401
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: mods/deathmatch/logic/lua/CLuaModule.cpp * PURPOSE: Lua module extension class * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #include "StdInc.h" extern CGame* g_pGame; CLuaModule::CLuaModule(CLuaModuleManager* pLuaModuleManager, CScriptDebugging* pScriptDebugging, const char* szFileName, const char* szShortFileName) { // Set module manager m_pLuaModuleManager = pLuaModuleManager; // Set script debugging m_pScriptDebugging = pScriptDebugging; // set module path m_szFileName = SString("%s", szFileName); m_szShortFileName = SString("%s", szShortFileName); // set as uninitialised m_bInitialised = false; } CLuaModule::~CLuaModule() { if (m_hModule) { if (m_bInitialised) { // Shutdown module m_FunctionInfo.ShutdownModule(); // Unregister Functions _UnregisterFunctions(); CLogger::LogPrintf("MODULE: Unloaded \"%s\" (%.2f) by \"%s\"\n", m_FunctionInfo.szModuleName, m_FunctionInfo.fVersion, m_FunctionInfo.szAuthor); } // Unload Module _UnloadModule(); } } #ifdef WIN32 bool IsModule32Bit(const SString& strExpectedPathFilename) { FILE* fh = File::Fopen(strExpectedPathFilename, "rb"); fseek(fh, 60, SEEK_SET); int offset = 0; fread(&offset, sizeof(offset), 1, fh); fseek(fh, offset + 24, SEEK_SET); ushort type = 0; fread(&type, sizeof(type), 1, fh); fclose(fh); return type == 0x010b; } #endif int CLuaModule::_LoadModule() { InitModuleFunc pfnInitFunc; // Load Module SString strError; #ifdef WIN32 // Search the mod path for dependencies SString strSavedCurrentDirectory = GetSystemCurrentDirectory(); SetCurrentDirectory(PathJoin(g_pServerInterface->GetModManager()->GetServerPath(), SERVER_BIN_PATH_MOD)); m_hModule = LoadLibrary(m_szFileName); if (m_hModule == NULL) strError = SString("%d", GetLastError()); SetCurrentDirectory(strSavedCurrentDirectory); #else m_hModule = dlopen(m_szFileName, RTLD_NOW); if (m_hModule == NULL) strError = dlerror(); #endif if (m_hModule == NULL) { // Module failed to load SString strExpectedPathFilename = PathJoin(SERVER_BIN_PATH_MOD, "modules", m_szShortFileName); if (!FileExists(strExpectedPathFilename)) { CLogger::LogPrintf("MODULE: File not found - %s\n", *strExpectedPathFilename); } else #ifdef WIN_x64 if (IsModule32Bit(strExpectedPathFilename)) { CLogger::LogPrintf("MODULE: File not 64 bit - %s\n", *strExpectedPathFilename); } else #endif #ifdef WIN_x86 if (!IsModule32Bit(strExpectedPathFilename)) { CLogger::LogPrintf("MODULE: File not 32 bit - %s\n", *strExpectedPathFilename); } else #endif { CLogger::LogPrintf("MODULE: Unable to load %s (%s)\n", *strExpectedPathFilename, *strError); } return 1; } // Find the initialisation function #ifdef WIN32 pfnInitFunc = (InitModuleFunc)(GetProcAddress(m_hModule, "InitModule")); if (pfnInitFunc == NULL) { CLogger::LogPrintf("MODULE: Unable to initialize %s!\n", *PathJoin(SERVER_BIN_PATH_MOD, "modules", m_szShortFileName)); return 2; } #else pfnInitFunc = (InitModuleFunc)(dlsym(m_hModule, "InitModule")); if (dlerror() != NULL) { CLogger::LogPrintf("MODULE: Unable to initialize %s (%s)!\n", *PathJoin(SERVER_BIN_PATH_MOD, "modules", m_szShortFileName), dlerror()); return 2; } #endif // Initialise m_FunctionInfo.szFileName = m_szShortFileName; #ifdef WIN32 m_FunctionInfo.DoPulse = (DefaultModuleFunc)(GetProcAddress(m_hModule, "DoPulse")); if (m_FunctionInfo.DoPulse == NULL) return 3; m_FunctionInfo.ShutdownModule = (DefaultModuleFunc)(GetProcAddress(m_hModule, "ShutdownModule")); if (m_FunctionInfo.ShutdownModule == NULL) return 4; m_FunctionInfo.RegisterFunctions = (RegisterModuleFunc)(GetProcAddress(m_hModule, "RegisterFunctions")); if (m_FunctionInfo.RegisterFunctions == NULL) return 5; m_FunctionInfo.ResourceStopping = (RegisterModuleFunc)(GetProcAddress(m_hModule, "ResourceStopping")); // No error for backward compatibility // if ( m_FunctionInfo.ResourceStopping == NULL ) return 6; m_FunctionInfo.ResourceStopped = (RegisterModuleFunc)(GetProcAddress(m_hModule, "ResourceStopped")); // if ( m_FunctionInfo.ResourceStopped == NULL ) return 7; #else m_FunctionInfo.DoPulse = (DefaultModuleFunc)(dlsym(m_hModule, "DoPulse")); if (m_FunctionInfo.DoPulse == NULL) return 3; m_FunctionInfo.ShutdownModule = (DefaultModuleFunc)(dlsym(m_hModule, "ShutdownModule")); if (m_FunctionInfo.ShutdownModule == NULL) return 4; m_FunctionInfo.RegisterFunctions = (RegisterModuleFunc)(dlsym(m_hModule, "RegisterFunctions")); if (m_FunctionInfo.RegisterFunctions == NULL) return 5; m_FunctionInfo.ResourceStopping = (RegisterModuleFunc)(dlsym(m_hModule, "ResourceStopping")); // if ( m_FunctionInfo.ResourceStopping == NULL ) return 6; m_FunctionInfo.ResourceStopped = (RegisterModuleFunc)(dlsym(m_hModule, "ResourceStopped")); // if ( m_FunctionInfo.ResourceStopped == NULL ) return 7; #endif // Run initialisation function if (!pfnInitFunc(this, &m_FunctionInfo.szModuleName[0], &m_FunctionInfo.szAuthor[0], &m_FunctionInfo.fVersion)) { CLogger::LogPrintf("MODULE: Unable to initialize %s!\n", *PathJoin(SERVER_BIN_PATH_MOD, "modules", m_szShortFileName)); return 2; } m_bInitialised = true; CLogger::LogPrintf("MODULE: Loaded \"%s\" (%.2f) by \"%s\"\n", m_FunctionInfo.szModuleName, m_FunctionInfo.fVersion, m_FunctionInfo.szAuthor); return 0; } void CLuaModule::_UnloadModule() { // Unload from memory #ifdef WIN32 FreeLibrary(m_hModule); #else dlclose(m_hModule); #endif } void CLuaModule::_RegisterFunctions(lua_State* luaVM) { m_FunctionInfo.RegisterFunctions(luaVM); } void CLuaModule::_UnregisterFunctions() { list<CLuaMain*>::const_iterator liter = m_pLuaModuleManager->GetLuaManager()->IterBegin(); for (; liter != m_pLuaModuleManager->GetLuaManager()->IterEnd(); ++liter) { lua_State* luaVM = (*liter)->GetVM(); vector<SString>::iterator iter = m_Functions.begin(); for (; iter != m_Functions.end(); ++iter) { // points function to nill lua_pushnil(luaVM); lua_setglobal(luaVM, iter->c_str()); // Remove func from CLuaCFunctions CLuaCFunctions::RemoveFunction(*iter); } } } void CLuaModule::_DoPulse() { m_FunctionInfo.DoPulse(); } void CLuaModule::_ResourceStopping(lua_State* luaVM) { if (m_FunctionInfo.ResourceStopping) m_FunctionInfo.ResourceStopping(luaVM); } void CLuaModule::_ResourceStopped(lua_State* luaVM) { if (m_FunctionInfo.ResourceStopped) m_FunctionInfo.ResourceStopped(luaVM); vector<SString>::iterator iter = m_Functions.begin(); for (; iter != m_Functions.end(); ++iter) { // points function to nil lua_pushnil(luaVM); lua_setglobal(luaVM, (iter)->c_str()); } } bool CLuaModule::_DoesFunctionExist(const char* szFunctionName) { vector<SString>::iterator iter = m_Functions.begin(); for (; iter != m_Functions.end(); ++iter) { if (strcmp((iter)->c_str(), szFunctionName) == 0) { return true; } } return false; } // Module Functions void CLuaModule::ErrorPrintf(const char* szFormat, ...) { va_list args; va_start(args, szFormat); CLogger::ErrorPrintf(szFormat, va_pass(args)); va_end(args); } void CLuaModule::DebugPrintf(lua_State* luaVM, const char* szFormat, ...) { va_list args; va_start(args, szFormat); m_pScriptDebugging->LogInformation(luaVM, szFormat, va_pass(args)); va_end(args); } void CLuaModule::Printf(const char* szFormat, ...) { va_list args; va_start(args, szFormat); CLogger::LogPrintf(szFormat, va_pass(args)); va_end(args); } bool CLuaModule::RegisterFunction(lua_State* luaVM, const char* szFunctionName, lua_CFunction Func) { if (luaVM) { if (szFunctionName) { CLuaCFunctions::AddFunction(szFunctionName, Func); lua_register(luaVM, szFunctionName, Func); if (!_DoesFunctionExist(szFunctionName)) { // Check or it adds for each resource m_Functions.push_back(szFunctionName); } } } else { CLogger::LogPrintf("MODULE: Lua is not initialised.\n"); } return true; } bool CLuaModule::GetResourceName(lua_State* luaVM, std::string& strName) { if (luaVM) { CLuaMain* pLuaMain = m_pLuaModuleManager->GetLuaManager()->GetVirtualMachine(luaVM); if (pLuaMain) { CResource* pResource = pLuaMain->GetResource(); if (pResource) { strName = pResource->GetName(); return true; } } } return false; } CChecksum CLuaModule::GetResourceMetaChecksum(lua_State* luaVM) { if (luaVM) { CLuaMain* pLuaMain = m_pLuaModuleManager->GetLuaManager()->GetVirtualMachine(luaVM); if (pLuaMain) { CResource* pResource = pLuaMain->GetResource(); if (pResource) { return pResource->GetLastMetaChecksum(); } } } return CChecksum(); } CChecksum CLuaModule::GetResourceFileChecksum(lua_State* luaVM, const char* szFile) { if (luaVM) { CLuaMain* pLuaMain = m_pLuaModuleManager->GetLuaManager()->GetVirtualMachine(luaVM); if (pLuaMain) { CResource* pResource = pLuaMain->GetResource(); if (pResource) { list<CResourceFile*>::iterator iter = pResource->IterBegin(); for (; iter != pResource->IterEnd(); ++iter) { if (strcmp((*iter)->GetName(), szFile) == 0) return (*iter)->GetLastChecksum(); } } } } return CChecksum(); } unsigned long CLuaModule::GetVersion() { return CStaticFunctionDefinitions::GetVersion(); } const char* CLuaModule::GetVersionString() { return CStaticFunctionDefinitions::GetVersionString(); } const char* CLuaModule::GetVersionName() { return CStaticFunctionDefinitions::GetVersionName(); } unsigned long CLuaModule::GetNetcodeVersion() { return CStaticFunctionDefinitions::GetNetcodeVersion(); } const char* CLuaModule::GetOperatingSystemName() { return CStaticFunctionDefinitions::GetOperatingSystemName(); } lua_State* CLuaModule::GetResourceFromName(const char* szResourceName) { CResource* pResource = g_pGame->GetResourceManager()->GetResource(szResourceName); if (pResource) { CLuaMain* pLuaMain = pResource->GetVirtualMachine(); if (pLuaMain) { return pLuaMain->GetVM(); } } return NULL; } bool CLuaModule::GetResourceName(lua_State* luaVM, char* szName, size_t length) { std::string resourceName; if (GetResourceName(luaVM, resourceName)) { std::strncpy(szName, resourceName.c_str(), length); return true; } return false; } bool CLuaModule::GetResourceFilePath(lua_State* luaVM, const char* fileName, char* path, size_t length) { if (!luaVM) return false; CLuaMain* pLuaMain = m_pLuaModuleManager->GetLuaManager()->GetVirtualMachine(luaVM); if (!pLuaMain) return false; CResource* pResource = pLuaMain->GetResource(); if (!pResource) return false; std::string p; if (!pResource->GetFilePath(fileName, p)) return false; std::strncpy(path, p.c_str(), length); return true; }
gpl-3.0
marcusmueller/gnuradio
gr-digital/python/digital/qa_crc32.py
1711
#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import cmath from gnuradio import gr, gr_unittest, digital class test_crc32(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test01(self): data = 100*"0" expected_result = 2943744955 result = digital.crc32(data) #print hex(result) self.assertEqual(expected_result, result) def test02(self): data = 100*"1" expected_result = 2326594156 result = digital.crc32(data) #print hex(result) self.assertEqual(expected_result, result) def test03(self): data = 10*"0123456789" expected_result = 3774345973 result = digital.crc32(data) #print hex(result) self.assertEqual(expected_result, result) if __name__ == '__main__': gr_unittest.run(test_crc32, "test_crc32.xml")
gpl-3.0
mcomella/FirefoxAccounts-android
thirdparty/src/main/java/ch/boye/httpclientandroidlib/impl/pool/BasicConnFactory.java
6759
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package ch.boye.httpclientandroidlib.impl.pool; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; import ch.boye.httpclientandroidlib.HttpClientConnection; import ch.boye.httpclientandroidlib.HttpConnectionFactory; import ch.boye.httpclientandroidlib.HttpHost; import ch.boye.httpclientandroidlib.annotation.Immutable; import ch.boye.httpclientandroidlib.config.ConnectionConfig; import ch.boye.httpclientandroidlib.config.SocketConfig; import ch.boye.httpclientandroidlib.impl.DefaultBHttpClientConnection; import ch.boye.httpclientandroidlib.impl.DefaultBHttpClientConnectionFactory; import ch.boye.httpclientandroidlib.params.CoreConnectionPNames; import ch.boye.httpclientandroidlib.params.HttpParamConfig; import ch.boye.httpclientandroidlib.params.HttpParams; import ch.boye.httpclientandroidlib.pool.ConnFactory; import ch.boye.httpclientandroidlib.util.Args; /** * A very basic {@link ConnFactory} implementation that creates * {@link HttpClientConnection} instances given a {@link HttpHost} instance. * * @see HttpHost * @since 4.2 */ @SuppressWarnings("deprecation") @Immutable public class BasicConnFactory implements ConnFactory<HttpHost, HttpClientConnection> { private final SocketFactory plainfactory; private final SSLSocketFactory sslfactory; private final int connectTimeout; private final SocketConfig sconfig; private final HttpConnectionFactory<? extends HttpClientConnection> connFactory; /** * @deprecated (4.3) use * {@link BasicConnFactory#BasicConnFactory(SocketFactory, SSLSocketFactory, int, * SocketConfig, ConnectionConfig)}. */ @Deprecated public BasicConnFactory(final SSLSocketFactory sslfactory, final HttpParams params) { super(); Args.notNull(params, "HTTP params"); this.plainfactory = null; this.sslfactory = sslfactory; this.connectTimeout = params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0); this.sconfig = HttpParamConfig.getSocketConfig(params); this.connFactory = new DefaultBHttpClientConnectionFactory( HttpParamConfig.getConnectionConfig(params)); } /** * @deprecated (4.3) use * {@link BasicConnFactory#BasicConnFactory(int, SocketConfig, ConnectionConfig)}. */ @Deprecated public BasicConnFactory(final HttpParams params) { this(null, params); } /** * @since 4.3 */ public BasicConnFactory( final SocketFactory plainfactory, final SSLSocketFactory sslfactory, final int connectTimeout, final SocketConfig sconfig, final ConnectionConfig cconfig) { super(); this.plainfactory = plainfactory; this.sslfactory = sslfactory; this.connectTimeout = connectTimeout; this.sconfig = sconfig != null ? sconfig : SocketConfig.DEFAULT; this.connFactory = new DefaultBHttpClientConnectionFactory( cconfig != null ? cconfig : ConnectionConfig.DEFAULT); } /** * @since 4.3 */ public BasicConnFactory( final int connectTimeout, final SocketConfig sconfig, final ConnectionConfig cconfig) { this(null, null, connectTimeout, sconfig, cconfig); } /** * @since 4.3 */ public BasicConnFactory(final SocketConfig sconfig, final ConnectionConfig cconfig) { this(null, null, 0, sconfig, cconfig); } /** * @since 4.3 */ public BasicConnFactory() { this(null, null, 0, SocketConfig.DEFAULT, ConnectionConfig.DEFAULT); } /** * @deprecated (4.3) no longer used. */ @Deprecated protected HttpClientConnection create(final Socket socket, final HttpParams params) throws IOException { final int bufsize = params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024); final DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(bufsize); conn.bind(socket); return conn; } public HttpClientConnection create(final HttpHost host) throws IOException { final String scheme = host.getSchemeName(); Socket socket = null; if ("http".equalsIgnoreCase(scheme)) { socket = this.plainfactory != null ? this.plainfactory.createSocket() : new Socket(); } if ("https".equalsIgnoreCase(scheme)) { socket = (this.sslfactory != null ? this.sslfactory : SSLSocketFactory.getDefault()).createSocket(); } if (socket == null) { throw new IOException(scheme + " scheme is not supported"); } final String hostname = host.getHostName(); int port = host.getPort(); if (port == -1) { if (host.getSchemeName().equalsIgnoreCase("http")) { port = 80; } else if (host.getSchemeName().equalsIgnoreCase("https")) { port = 443; } } socket.setSoTimeout(this.sconfig.getSoTimeout()); socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout); socket.setTcpNoDelay(this.sconfig.isTcpNoDelay()); final int linger = this.sconfig.getSoLinger(); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } socket.setKeepAlive(this.sconfig.isSoKeepAlive()); return this.connFactory.createConnection(socket); } }
mpl-2.0
rven/odoo
addons/web/static/src/js/fields/special_fields.js
9393
odoo.define('web.special_fields', function (require) { "use strict"; var core = require('web.core'); var field_utils = require('web.field_utils'); var relational_fields = require('web.relational_fields'); var AbstractField = require('web.AbstractField'); var FieldSelection = relational_fields.FieldSelection; var _t = core._t; var _lt = core._lt; /** * This widget is intended to display a warning near a label of a 'timezone' field * indicating if the browser timezone is identical (or not) to the selected timezone. * This widget depends on a field given with the param 'tz_offset_field', which contains * the time difference between UTC time and local time, in minutes. */ var FieldTimezoneMismatch = FieldSelection.extend({ /** * @override */ start: function () { var interval = navigator.platform.toUpperCase().indexOf('MAC') >= 0 ? 60000 : 1000; this._datetime = setInterval(this._renderDateTimeTimezone.bind(this), interval); return this._super.apply(this, arguments); }, /** * @override */ destroy: function () { clearInterval(this._datetime); return this._super(); }, //-------------------------------------------------------------------------- // Private //-------------------------------------------------------------------------- /** * @override * @private */ _render: function () { this._super.apply(this, arguments); this._renderTimezoneMismatch(); }, /** * Display the time in the user timezone (reload each second) * * @private */ _renderDateTimeTimezone: function () { if (!this.mismatch || !this.$option.html()) { return; } var offset = this.recordData.tz_offset.match(/([+-])([0-9]{2})([0-9]{2})/); offset = (offset[1] === '-' ? -1 : 1) * (parseInt(offset[2])*60 + parseInt(offset[3])); var datetime = field_utils.format.datetime(moment.utc().add(offset, 'minutes'), this.field, {timezone: false}); var content = this.$option.html().split(' ')[0]; content += ' ('+ datetime + ')'; this.$option.html(content); }, /** * Display the timezone alert * * Note: timezone alert is a span that is added after $el, and $el is now a * set of two elements * * @private */ _renderTimezoneMismatch: function () { // we need to clean the warning to have maximum one alert this.$el.last().filter('.o_tz_warning').remove(); this.$el = this.$el.first(); var value = this.$el.val(); var $span = $('<span class="fa fa-exclamation-triangle o_tz_warning"/>'); if (this.$option && this.$option.html()) { this.$option.html(this.$option.html().split(' ')[0]); } var userOffset = this.recordData.tz_offset; this.mismatch = false; if (userOffset && value !== "" && value !== "false") { var offset = -(new Date().getTimezoneOffset()); var browserOffset = (offset < 0) ? "-" : "+"; browserOffset += _.str.sprintf("%02d", Math.abs(offset / 60)); browserOffset += _.str.sprintf("%02d", Math.abs(offset % 60)); this.mismatch = (browserOffset !== userOffset); } if (this.mismatch){ $span.insertAfter(this.$el); $span.attr('title', _t("Timezone Mismatch : This timezone is different from that of your browser.\nPlease, set the same timezone as your browser's to avoid time discrepancies in your system.")); this.$el = this.$el.add($span); this.$option = this.$('option').filter(function () { return $(this).attr('value') === value; }); this._renderDateTimeTimezone(); } else if (value == "false") { $span.insertAfter(this.$el); $span.attr('title', _t("Set a timezone on your user")); this.$el = this.$el.add($span); } }, /** * @override * @private * this.$el can have other elements than select * that should not be touched */ _renderEdit: function () { // FIXME: hack to handle multiple root elements // in this.$el , which is a bad idea // In master we should make this.$el a wrapper // around multiple subelements var $otherEl = this.$el.not('select'); this.$el = this.$el.first(); this._super.apply(this, arguments); $otherEl.insertAfter(this.$el); this.$el = this.$el.add($otherEl); }, }); var FieldReportLayout = relational_fields.FieldMany2One.extend({ // this widget is not generic, so we disable its studio use // supportedFieldTypes: ['many2one', 'selection'], events: _.extend({}, relational_fields.FieldMany2One.prototype.events, { 'click img': '_onImgClicked', }), willStart: function () { var self = this; this.previews = {}; return this._super() .then(function () { return self._rpc({ model: 'report.layout', method: "search_read" }).then(function (values) { self.previews = values; }); }); }, //-------------------------------------------------------------------------- // Private //-------------------------------------------------------------------------- /** * @override * @private */ _render: function () { var self = this; this.$el.empty(); var value = _.isObject(this.value) ? this.value.data.id : this.value; _.each(this.previews, function (val) { var $container = $('<div>').addClass('col-3 text-center'); var $img = $('<img>') .addClass('img img-fluid img-thumbnail ml16') .toggleClass('btn-info', val.view_id[0] === value) .attr('src', val.image) .data('key', val.view_id[0]); $container.append($img); if (val.pdf) { var $previewLink = $('<a>') .text('Example') .attr('href', val.pdf) .attr('target', '_blank'); $container.append($previewLink); } self.$el.append($container); }); }, //-------------------------------------------------------------------------- // Handlers //-------------------------------------------------------------------------- /** * @override * @private * @param {MouseEvent} event */ _onImgClicked: function (event) { this._setValue($(event.currentTarget).data('key')); }, }); const IframeWrapper = AbstractField.extend({ description: _lt("Wrap raw html within an iframe"), // If HTML, don't forget to adjust the sanitize options to avoid stripping most of the metadata supportedFieldTypes: ['text', 'html'], template: "web.IframeWrapper", _render() { const spinner = this.el.querySelector('.o_iframe_wrapper_spinner'); const iframe = this.el.querySelector('.o_preview_iframe'); iframe.style.display = 'none'; spinner.style.display = 'block'; // Promise for tests let resolver; $(iframe).data('ready', new Promise((resolve) => { resolver = resolve; })); /** * Certain browser don't trigger onload events of iframe for particular cases. * In our case, chrome and safari could be problematic depending on version and environment. * This rather unorthodox solution replace the onload event handler. (jquery on('load') doesn't fix it) */ const onloadReplacement = setInterval(() => { const iframeDoc = iframe.contentDocument; if (iframeDoc && (iframeDoc.readyState === 'complete' || iframeDoc.readyState === 'interactive')) { /** * The document.write is not recommended. It is better to manipulate the DOM through $.appendChild and * others. In our case though, we deal with an iframe without src attribute and with metadata to put in * head tag. If we use the usual dom methods, the iframe is automatically created with its document * component containing html > head & body. Therefore, if we want to make it work that way, we would * need to receive each piece at a time to append it to this document (with this.record.data and extra * model fields or with an rpc). It also cause other difficulties getting attribute on the most parent * nodes, parsing to HTML complex elements, etc. * Therefore, document.write makes it much more trivial in our situation. */ iframeDoc.open(); iframeDoc.write(this.value); iframeDoc.close(); iframe.style.display = 'block'; spinner.style.display = 'none'; resolver(); clearInterval(onloadReplacement); } }, 100); } }); return { FieldTimezoneMismatch: FieldTimezoneMismatch, FieldReportLayout: FieldReportLayout, IframeWrapper, }; });
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace-archive/ValueObjects/src/ims/RefMan/vo/onExaminationVo.java
8283
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo; /** * Linked to RefMan.OnExamination business object (ID: 1096100003). */ public class onExaminationVo extends ims.RefMan.vo.OnExaminationRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public onExaminationVo() { } public onExaminationVo(Integer id, int version) { super(id, version); } public onExaminationVo(ims.RefMan.vo.beans.onExaminationVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.catsreferral = bean.getCatsReferral() == null ? null : new ims.RefMan.vo.CatsReferralRefVo(new Integer(bean.getCatsReferral().getId()), bean.getCatsReferral().getVersion()); this.authoringinformation = bean.getAuthoringInformation() == null ? null : bean.getAuthoringInformation().buildVo(); this.relevantpmh = bean.getRelevantPMH(); this.clinicalnote = bean.getClinicalNote() == null ? null : bean.getClinicalNote().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.beans.onExaminationVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.catsreferral = bean.getCatsReferral() == null ? null : new ims.RefMan.vo.CatsReferralRefVo(new Integer(bean.getCatsReferral().getId()), bean.getCatsReferral().getVersion()); this.authoringinformation = bean.getAuthoringInformation() == null ? null : bean.getAuthoringInformation().buildVo(map); this.relevantpmh = bean.getRelevantPMH(); this.clinicalnote = bean.getClinicalNote() == null ? null : bean.getClinicalNote().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.RefMan.vo.beans.onExaminationVoBean bean = null; if(map != null) bean = (ims.RefMan.vo.beans.onExaminationVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.RefMan.vo.beans.onExaminationVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("CATSREFERRAL")) return getCatsReferral(); if(fieldName.equals("AUTHORINGINFORMATION")) return getAuthoringInformation(); if(fieldName.equals("RELEVANTPMH")) return getRelevantPMH(); if(fieldName.equals("CLINICALNOTE")) return getClinicalNote(); return super.getFieldValueByFieldName(fieldName); } public boolean getCatsReferralIsNotNull() { return this.catsreferral != null; } public ims.RefMan.vo.CatsReferralRefVo getCatsReferral() { return this.catsreferral; } public void setCatsReferral(ims.RefMan.vo.CatsReferralRefVo value) { this.isValidated = false; this.catsreferral = value; } public boolean getAuthoringInformationIsNotNull() { return this.authoringinformation != null; } public ims.core.vo.AuthoringInformationVo getAuthoringInformation() { return this.authoringinformation; } public void setAuthoringInformation(ims.core.vo.AuthoringInformationVo value) { this.isValidated = false; this.authoringinformation = value; } public boolean getRelevantPMHIsNotNull() { return this.relevantpmh != null; } public String getRelevantPMH() { return this.relevantpmh; } public static int getRelevantPMHMaxLength() { return 2500; } public void setRelevantPMH(String value) { this.isValidated = false; this.relevantpmh = value; } public boolean getClinicalNoteIsNotNull() { return this.clinicalnote != null; } public ims.core.vo.ReferralNoteVo getClinicalNote() { return this.clinicalnote; } public void setClinicalNote(ims.core.vo.ReferralNoteVo value) { this.isValidated = false; this.clinicalnote = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } if(this.authoringinformation != null) { if(!this.authoringinformation.isValidated()) { this.isBusy = false; return false; } } if(this.clinicalnote != null) { if(!this.clinicalnote.isValidated()) { this.isBusy = false; return false; } } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.catsreferral == null) listOfErrors.add("CatsReferral is mandatory"); if(this.authoringinformation == null) listOfErrors.add("AuthoringInformation is mandatory"); if(this.authoringinformation != null) { String[] listOfOtherErrors = this.authoringinformation.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } if(this.relevantpmh != null) if(this.relevantpmh.length() > 2500) listOfErrors.add("The length of the field [relevantpmh] in the value object [ims.RefMan.vo.onExaminationVo] is too big. It should be less or equal to 2500"); if(this.clinicalnote != null) { String[] listOfOtherErrors = this.clinicalnote.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; onExaminationVo clone = new onExaminationVo(this.id, this.version); clone.catsreferral = this.catsreferral; if(this.authoringinformation == null) clone.authoringinformation = null; else clone.authoringinformation = (ims.core.vo.AuthoringInformationVo)this.authoringinformation.clone(); clone.relevantpmh = this.relevantpmh; if(this.clinicalnote == null) clone.clinicalnote = null; else clone.clinicalnote = (ims.core.vo.ReferralNoteVo)this.clinicalnote.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(onExaminationVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A onExaminationVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((onExaminationVo)obj).getBoId() == null) return -1; return this.id.compareTo(((onExaminationVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.authoringinformation != null) count++; if(this.relevantpmh != null) count++; if(this.clinicalnote != null) count++; return count; } public int countValueObjectFields() { return 3; } protected ims.RefMan.vo.CatsReferralRefVo catsreferral; protected ims.core.vo.AuthoringInformationVo authoringinformation; protected String relevantpmh; protected ims.core.vo.ReferralNoteVo clinicalnote; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
oopcell/openApotti
Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/forms/onexaminationpreview/AccessLogic.java
650
// This code was generated by Catalin Tomozei using IMS Development Environment (version 1.71 build 3607.26880) // Copyright (C) 1995-2009 IMS MAXIMS. All rights reserved. package ims.RefMan.forms.onexaminationpreview; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; // TODO: Add your conditions here. return true; } public boolean isReadOnly() { if(super.isReadOnly()) return true; // TODO: Add your conditions here. return false; } }
agpl-3.0
wfxiang08/sql-layer-1
fdb-sql-layer-core/src/main/java/com/foundationdb/qp/operator/LeafCursor.java
2456
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.qp.operator; /** * LeafCursor handles the cursor processing for the Leaf operators. * Unlike the ChainedCursor or DualChainedCursors, the LeafCursor * isn't reading data from another operator cursor, but is reading it * from an underlying Row source. Usually this is a adapter row, or * row collection. * * @see ChainedCursor * @see MultiChainedCursor * * Used By * @see AncestorLookup_Nested$Execution (non-lookahead) * @see BranchLookup_Nested$Execution * @see Count_TableStatus$Execution * @see GroupScan_Default$Execution * @see HashTableLookup_Default$Execution * @see HKeyRow_Default$Execution * @see IndexScan_Default$Execution * @see ValuesScan_Default$Execution * * @see com.foundationdb.server.service.text.IndexScan_FullText$Execution * @see com.foundationdb.server.test.it.qp.QueryTimeoutIT$DoNothingForever$Execution */ public class LeafCursor extends OperatorCursor { protected final QueryBindingsCursor bindingsCursor; protected QueryBindings bindings; protected LeafCursor(QueryContext context, QueryBindingsCursor bindingsCursor) { super(context); this.bindingsCursor = bindingsCursor; } @Override public void openBindings() { bindingsCursor.openBindings(); } @Override public QueryBindings nextBindings() { CursorLifecycle.checkClosed(this); bindings = bindingsCursor.nextBindings(); return bindings; } @Override public void closeBindings() { bindingsCursor.closeBindings(); } @Override public void cancelBindings(QueryBindings bindings) { CursorLifecycle.checkClosed(this); bindingsCursor.cancelBindings(bindings); } }
agpl-3.0
Carrotlord/Mint-Programming-Language
MintLangSaffronStable [Oldest]/builtin/file/CanReadAndWrite.java
510
package builtin.file; import builtin.BuiltinSub; import mint.FileIO; import mint.Heap; import mint.MintException; import mint.Pointer; import mint.PointerTools; import mint.SmartList; /** * * @author Oliver Chu */ public class CanReadAndWrite extends BuiltinSub { @Override public Pointer apply(SmartList<Pointer> args) throws MintException { String fileName = PointerTools.dereferenceString(args.get(0)); return Heap.allocateTruth(FileIO.canReadAndWrite(fileName)); } }
agpl-3.0
maryamn/gnusocial-clone
plugins/EmailReminder/EmailReminderPlugin.php
6205
<?php /** * StatusNet - the distributed open-source microblogging tool * Copyright (C) 2011, StatusNet, Inc. * * Plugin for sending email reminders about various things * * PHP version 5 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @category OnDemand * @package StatusNet * @author Zach Copley <zach@status.net> * @copyright 2011 StatusNet, Inc. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 * @link http://status.net/ */ if (!defined('STATUSNET')) { // This check helps protect against security problems; // your code file can't be executed directly from the web. exit(1); } /** * Email reminder plugin * * @category Plugin * @package StatusNet * @author Zach Copley <zach@status.net> * @copyright 2011 StatusNet, Inc. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 * @link http://status.net/ */ class EmailReminderPlugin extends Plugin { /** * Set up email_reminder table * * @see Schema * @see ColumnDef * * @return boolean hook value; true means continue processing, false means stop. */ function onCheckSchema() { $schema = Schema::get(); $schema->ensureTable('email_reminder', Email_reminder::schemaDef()); return true; } /** * Register our queue handlers * * @param QueueManager $qm Current queue manager * * @return boolean hook value */ function onEndInitializeQueueManager($qm) { $qm->connect('siterem', 'SiteConfirmReminderHandler'); $qm->connect('uregrem', 'UserConfirmRegReminderHandler'); $qm->connect('uinvrem', 'UserInviteReminderHandler'); return true; } function onEndDocFileForTitle($title, $paths, &$filename) { if (empty($filename)) { $filename = dirname(__FILE__) . '/mail-src/' . $title; return false; } return true; } /** * Send a reminder and record doing so * * @param string $type type of reminder * @param mixed $object Confirm_address or Invitation object * @param string $subject subjct of the email reminder * @param int $day number of days */ static function sendReminder($type, $object, $subject, $day) { // XXX: -1 is a for the special one-time reminder (maybe 30) would be // better? Like >= 30 days? if ($day == -1) { $title = "{$type}-onetime"; } else { $title = "{$type}-{$day}"; } // Record the fact that we sent a reminder if (self::sendReminderEmail($type, $object, $subject, $title)) { try { Email_reminder::recordReminder($type, $object, $day); common_log( LOG_INFO, "Sent {$type} reminder to {$object->address}.", __FILE__ ); } catch (Exception $e) { // oh noez common_log(LOG_ERR, $e->getMessage(), __FILE__); } } return true; } /** * Send a real live email reminder * * @todo This would probably be better as two or more sep functions * * @param string $type type of reminder * @param mixed $object Confirm_address or Invitation object * @param string $subject subjct of the email reminder * @param string $title title of the email reminder * @return boolean true if the email subsystem doesn't explode */ static function sendReminderEmail($type, $object, $subject, $title = null) { $sitename = common_config('site', 'name'); $recipients = array($object->address); $inviter = null; $inviterurl = null; if ($type == UserInviteReminderHandler::INVITE_REMINDER) { $user = User::getKV($object->user_id); if (!empty($user)) { $profile = $user->getProfile(); $inviter = $profile->getBestName(); $inviterUrl = $profile->profileurl; } } $headers['From'] = mail_notify_from(); $headers['To'] = trim($object->address); // TRANS: Subject for confirmation e-mail. // TRANS: %s is the StatusNet sitename. $headers['Subject'] = $subject; $headers['Content-Type'] = 'text/html; charset=UTF-8'; $confirmUrl = common_local_url('register', array('code' => $object->code)); $template = DocFile::forTitle($title, DocFile::mailPaths()); $blankfillers = array('confirmurl' => $confirmUrl); if ($type == UserInviteReminderHandler::INVITE_REMINDER) { $blankfillers['inviter'] = $inviter; $blankfillers['inviterurl'] = $inviterUrl; // @todo private invitation message? } $body = $template->toHTML($blankfillers); return mail_send($recipients, $headers, $body); } /** * * @param type $versions * @return type */ function onPluginVersion(&$versions) { $versions[] = array( 'name' => 'EmailReminder', 'version' => GNUSOCIAL_VERSION, 'author' => 'Zach Copley', 'homepage' => 'http://status.net/wiki/Plugin:EmailReminder', // TRANS: Plugin description. 'rawdescription' => _m('Send email reminders for various things.') ); return true; } }
agpl-3.0
oopcell/openApotti
Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/lookups/NormalcyStatus.java
8572
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocrr.vo.lookups; import ims.framework.cn.data.TreeNode; import java.util.ArrayList; import ims.framework.utils.Image; import ims.framework.utils.Color; public class NormalcyStatus extends ims.vo.LookupInstVo implements TreeNode { private static final long serialVersionUID = 1L; public NormalcyStatus() { super(); } public NormalcyStatus(int id) { super(id, "", true); } public NormalcyStatus(int id, String text, boolean active) { super(id, text, active, null, null, null); } public NormalcyStatus(int id, String text, boolean active, NormalcyStatus parent, Image image) { super(id, text, active, parent, image); } public NormalcyStatus(int id, String text, boolean active, NormalcyStatus parent, Image image, Color color) { super(id, text, active, parent, image, color); } public NormalcyStatus(int id, String text, boolean active, NormalcyStatus parent, Image image, Color color, int order) { super(id, text, active, parent, image, color, order); } public static NormalcyStatus buildLookup(ims.vo.LookupInstanceBean bean) { return new NormalcyStatus(bean.getId(), bean.getText(), bean.isActive()); } public String toString() { if(getText() != null) return getText(); return ""; } public TreeNode getParentNode() { return (NormalcyStatus)super.getParentInstance(); } public NormalcyStatus getParent() { return (NormalcyStatus)super.getParentInstance(); } public void setParent(NormalcyStatus parent) { super.setParentInstance(parent); } public TreeNode[] getChildren() { ArrayList children = super.getChildInstances(); NormalcyStatus[] typedChildren = new NormalcyStatus[children.size()]; for (int i = 0; i < children.size(); i++) { typedChildren[i] = (NormalcyStatus)children.get(i); } return typedChildren; } public int addChild(TreeNode child) { if (child instanceof NormalcyStatus) { super.addChild((NormalcyStatus)child); } return super.getChildInstances().size(); } public int removeChild(TreeNode child) { if (child instanceof NormalcyStatus) { super.removeChild((NormalcyStatus)child); } return super.getChildInstances().size(); } public Image getExpandedImage() { return super.getImage(); } public Image getCollapsedImage() { return super.getImage(); } public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection() { NormalcyStatusCollection result = new NormalcyStatusCollection(); result.add(N); result.add(L); result.add(H); result.add(LL); result.add(HH); result.add(A); result.add(AA); result.add(U); result.add(D); result.add(B); result.add(W); result.add(S); result.add(R); result.add(I); result.add(MS); result.add(VS); result.add(LT); result.add(GT); return result; } public static NormalcyStatus[] getNegativeInstances() { NormalcyStatus[] instances = new NormalcyStatus[18]; instances[0] = N; instances[1] = L; instances[2] = H; instances[3] = LL; instances[4] = HH; instances[5] = A; instances[6] = AA; instances[7] = U; instances[8] = D; instances[9] = B; instances[10] = W; instances[11] = S; instances[12] = R; instances[13] = I; instances[14] = MS; instances[15] = VS; instances[16] = LT; instances[17] = GT; return instances; } public static String[] getNegativeInstanceNames() { String[] negativeInstances = new String[18]; negativeInstances[0] = "N"; negativeInstances[1] = "L"; negativeInstances[2] = "H"; negativeInstances[3] = "LL"; negativeInstances[4] = "HH"; negativeInstances[5] = "A"; negativeInstances[6] = "AA"; negativeInstances[7] = "U"; negativeInstances[8] = "D"; negativeInstances[9] = "B"; negativeInstances[10] = "W"; negativeInstances[11] = "S"; negativeInstances[12] = "R"; negativeInstances[13] = "I"; negativeInstances[14] = "MS"; negativeInstances[15] = "VS"; negativeInstances[16] = "LT"; negativeInstances[17] = "GT"; return negativeInstances; } public static NormalcyStatus getNegativeInstance(String name) { if(name == null) return null; String[] negativeInstances = getNegativeInstanceNames(); for (int i = 0; i < negativeInstances.length; i++) { if(negativeInstances[i].equals(name)) return getNegativeInstances()[i]; } return null; } public static NormalcyStatus getNegativeInstance(Integer id) { if(id == null) return null; NormalcyStatus[] negativeInstances = getNegativeInstances(); for (int i = 0; i < negativeInstances.length; i++) { if(negativeInstances[i].getID() == id) return negativeInstances[i]; } return null; } public int getTypeId() { return TYPE_ID; } public static final int TYPE_ID = 1161037; public static final NormalcyStatus N = new NormalcyStatus(-900, "Normal", true, null, null, Color.Default); public static final NormalcyStatus L = new NormalcyStatus(-1062, "Below low normal", true, null, null, Color.Default); public static final NormalcyStatus H = new NormalcyStatus(-1063, "Above high normal", true, null, null, Color.Default); public static final NormalcyStatus LL = new NormalcyStatus(-1064, "Below lower panic limits", true, null, null, Color.Default); public static final NormalcyStatus HH = new NormalcyStatus(-1065, "Above upper panic limits", true, null, null, Color.Default); public static final NormalcyStatus A = new NormalcyStatus(-1066, "Abnormal", true, null, null, Color.Default); public static final NormalcyStatus AA = new NormalcyStatus(-1067, "Very abnormal", true, null, null, Color.Default); public static final NormalcyStatus U = new NormalcyStatus(-1068, "Significant change up", true, null, null, Color.Default); public static final NormalcyStatus D = new NormalcyStatus(-1069, "Significant change down", true, null, null, Color.Default); public static final NormalcyStatus B = new NormalcyStatus(-1070, "Better", true, null, null, Color.Default); public static final NormalcyStatus W = new NormalcyStatus(-1071, "Worse", true, null, null, Color.Default); public static final NormalcyStatus S = new NormalcyStatus(-1072, "Susceptible", true, null, null, Color.Default); public static final NormalcyStatus R = new NormalcyStatus(-1073, "Resistant", true, null, null, Color.Default); public static final NormalcyStatus I = new NormalcyStatus(-1074, "Intermediate", true, null, null, Color.Default); public static final NormalcyStatus MS = new NormalcyStatus(-1075, "Moderately susceptible", true, null, null, Color.Default); public static final NormalcyStatus VS = new NormalcyStatus(-1076, "Very susceptible", true, null, null, Color.Default); public static final NormalcyStatus LT = new NormalcyStatus(-1077, "Below absolute low-off instrument scale", true, null, null, Color.Default); public static final NormalcyStatus GT = new NormalcyStatus(-1078, "Above absolute high-off instrument scale", true, null, null, Color.Default); }
agpl-3.0
PeaceWorksTechnologySolutions/atom
apps/qubit/modules/physicalobject/actions/browseAction.class.php
2216
<?php /* * This file is part of the Access to Memory (AtoM) software. * * Access to Memory (AtoM) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Access to Memory (AtoM) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Access to Memory (AtoM). If not, see <http://www.gnu.org/licenses/>. */ class PhysicalObjectBrowseAction extends sfAction { public function execute($request) { if (!$this->getUser()->isAuthenticated()) { QubitAcl::forwardUnauthorized(); } if (!isset($request->limit)) { $request->limit = sfConfig::get('app_hits_per_page'); } $criteria = new Criteria; // Do source culture fallback $criteria = QubitCultureFallback::addFallbackCriteria($criteria, 'QubitPhysicalObject'); if (isset($request->subquery)) { $criteria->addJoin(QubitPhysicalObject::ID, QubitPhysicalObjectI18n::ID); $criteria->add(QubitPhysicalObjectI18n::CULTURE, $this->context->user->getCulture()); $criteria->add(QubitPhysicalObjectI18n::NAME, "$request->subquery%", Criteria::LIKE); } switch ($request->sort) { case 'nameDown': $criteria->addDescendingOrderByColumn('name'); break; case 'locationDown': $criteria->addDescendingOrderByColumn('location'); break; case 'locationUp': $criteria->addAscendingOrderByColumn('location'); break; case 'nameUp': default: $request->sort = 'nameUp'; $criteria->addAscendingOrderByColumn('name'); } // Page results $this->pager = new QubitPager('QubitPhysicalObject'); $this->pager->setCriteria($criteria); $this->pager->setMaxPerPage($request->limit); $this->pager->setPage($request->page); } }
agpl-3.0
artsmorgan/crmtecnosagot
app/protected/core/data/DemoDataHelper.php
4646
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2015 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2015. All rights reserved". ********************************************************************************/ /** * Demo Data Helper Class */ class DemoDataHelper { protected $demoData = array(); /** * Get id range for model * @param string $modelName * @return array */ public function getRangeByModelName($modelName) { assert('array_key_exists($modelName, $this->demoData)'); return array('startId' => $this->demoData[$modelName]['startId'], 'endId' => $this->demoData[$modelName]['endId']); } /** * Set id range for model * @param string $modelName * @param int $startId * @param int $endId */ public function setRangeByModelName($modelName, $startId, $endId) { assert('is_string($modelName)'); assert('is_int($startId)'); assert('is_int($endId)'); assert('!array_key_exists($modelName, $this->demoData)'); assert('$endId > $startId'); if (!array_key_exists($modelName, $this->demoData)) { $this->demoData[$modelName]['startId'] = $startId; $this->demoData[$modelName]['endId'] = $endId; } } /** * Get random model (from list of model available ids) * @param string $modelName * @return object $model */ public function getRandomByModelName($modelName) { assert('is_string($modelName)'); assert('is_int($this->demoData[$modelName]["startId"])'); assert('is_int($this->demoData[$modelName]["endId"])'); assert('$this->demoData[$modelName]["endId"] > $this->demoData[$modelName]["startId"]'); $randomId = mt_rand($this->demoData[$modelName]["startId"], $this->demoData[$modelName]["endId"]); $model = $modelName::getById($randomId); assert('$model instanceof $modelName'); return $model; } /** * Check if range is setup for module * @param string $modelName * @return boolean $isSet */ public function isSetRange($modelName) { $isSet = isset($this->demoData[$modelName]['startId']) && isset($this->demoData[$modelName]['endId']) && $this->demoData[$modelName]['startId'] > 0 && $this->demoData[$modelName]['endId'] > 0; return $isSet; } } ?>
agpl-3.0
liuqr/edx-xiaodun
common/lib/xmodule/xmodule/tests/test_video.py
24020
# -*- coding: utf-8 -*- #pylint: disable=W0212 """Test for Video Xmodule functional logic. These test data read from xml, not from mongo. We have a ModuleStoreTestCase class defined in common/lib/xmodule/xmodule/modulestore/tests/django_utils.py. You can search for usages of this in the cms and lms tests for examples. You use this so that it will do things like point the modulestore setting to mongo, flush the contentstore before and after, load the templates, etc. You can then use the CourseFactory and XModuleItemFactory as defined in common/lib/xmodule/xmodule/modulestore/tests/factories.py to create the course, section, subsection, unit, etc. """ import unittest import datetime from mock import Mock from . import LogicTest from lxml import etree from xmodule.modulestore import Location from xmodule.video_module import VideoDescriptor, create_youtube_string from .test_import import DummySystem from xblock.field_data import DictFieldData from xblock.fields import ScopeIds from xmodule.tests import get_test_descriptor_system class VideoModuleTest(LogicTest): """Logic tests for Video Xmodule.""" descriptor_class = VideoDescriptor raw_field_data = { 'data': '<video />' } def test_parse_youtube(self): """Test parsing old-style Youtube ID strings into a dict.""" youtube_str = '0.75:jNCf2gIqpeE,1.00:ZwkTiUPN0mg,1.25:rsq9auxASqI,1.50:kMyNdzVHHgg' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': 'jNCf2gIqpeE', '1.00': 'ZwkTiUPN0mg', '1.25': 'rsq9auxASqI', '1.50': 'kMyNdzVHHgg'}) def test_parse_youtube_one_video(self): """ Ensure that all keys are present and missing speeds map to the empty string. """ youtube_str = '0.75:jNCf2gIqpeE' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': 'jNCf2gIqpeE', '1.00': '', '1.25': '', '1.50': ''}) def test_parse_youtube_invalid(self): """Ensure that ids that are invalid return an empty dict""" # invalid id youtube_str = 'thisisaninvalidid' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': '', '1.00': '', '1.25': '', '1.50': ''}) # another invalid id youtube_str = ',::,:,,' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': '', '1.00': '', '1.25': '', '1.50': ''}) # and another one, partially invalid youtube_str = '0.75_BAD!!!,1.0:AXdE34_U,1.25:KLHF9K_Y,1.5:VO3SxfeD,' output = VideoDescriptor._parse_youtube(youtube_str) self.assertEqual(output, {'0.75': '', '1.00': 'AXdE34_U', '1.25': 'KLHF9K_Y', '1.50': 'VO3SxfeD'}) def test_parse_youtube_key_format(self): """ Make sure that inconsistent speed keys are parsed correctly. """ youtube_str = '1.00:p2Q6BrNhdh8' youtube_str_hack = '1.0:p2Q6BrNhdh8' self.assertEqual( VideoDescriptor._parse_youtube(youtube_str), VideoDescriptor._parse_youtube(youtube_str_hack) ) def test_parse_youtube_empty(self): """ Some courses have empty youtube attributes, so we should handle that well. """ self.assertEqual( VideoDescriptor._parse_youtube(''), {'0.75': '', '1.00': '', '1.25': '', '1.50': ''} ) class VideoDescriptorTest(unittest.TestCase): """Test for VideoDescriptor""" def setUp(self): system = get_test_descriptor_system() location = Location('i4x://org/course/video/name') self.descriptor = system.construct_xblock_from_class( VideoDescriptor, scope_ids=ScopeIds(None, None, location, location), field_data=DictFieldData({}), ) def test_get_context(self): """"test get_context""" correct_tabs = [ { 'name': "Basic", 'template': "video/transcripts.html", 'current': True }, { 'name': 'Advanced', 'template': 'tabs/metadata-edit-tab.html' } ] rendered_context = self.descriptor.get_context() self.assertListEqual(rendered_context['tabs'], correct_tabs) def test_create_youtube_string(self): """ Test that Youtube ID strings are correctly created when writing back out to XML. """ system = DummySystem(load_error_modules=True) location = Location(["i4x", "edX", "video", "default", "SampleProblem1"]) field_data = DictFieldData({'location': location}) descriptor = VideoDescriptor(system, field_data, Mock()) descriptor.youtube_id_0_75 = 'izygArpw-Qo' descriptor.youtube_id_1_0 = 'p2Q6BrNhdh8' descriptor.youtube_id_1_25 = '1EeWXzPdhSA' descriptor.youtube_id_1_5 = 'rABDYkeK0x8' expected = "0.75:izygArpw-Qo,1.00:p2Q6BrNhdh8,1.25:1EeWXzPdhSA,1.50:rABDYkeK0x8" self.assertEqual(create_youtube_string(descriptor), expected) def test_create_youtube_string_missing(self): """ Test that Youtube IDs which aren't explicitly set aren't included in the output string. """ system = DummySystem(load_error_modules=True) location = Location(["i4x", "edX", "video", "default", "SampleProblem1"]) field_data = DictFieldData({'location': location}) descriptor = VideoDescriptor(system, field_data, Mock()) descriptor.youtube_id_0_75 = 'izygArpw-Qo' descriptor.youtube_id_1_0 = 'p2Q6BrNhdh8' descriptor.youtube_id_1_25 = '1EeWXzPdhSA' expected = "0.75:izygArpw-Qo,1.00:p2Q6BrNhdh8,1.25:1EeWXzPdhSA" self.assertEqual(create_youtube_string(descriptor), expected) class VideoDescriptorImportTestCase(unittest.TestCase): """ Make sure that VideoDescriptor can import an old XML-based video correctly. """ def assert_attributes_equal(self, video, attrs): """ Assert that `video` has the correct attributes. `attrs` is a map of {metadata_field: value}. """ for key, value in attrs.items(): self.assertEquals(getattr(video, key), value) def test_constructor(self): sample_xml = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" download_track="true" download_video="true" start_time="00:00:01" end_time="00:01:00"> <source src="http://www.example.com/source.mp4"/> <source src="http://www.example.com/source.ogg"/> <track src="http://www.example.com/track"/> <transcript language="ua" src="ukrainian_translation.srt" /> <transcript language="ge" src="german_translation.srt" /> </video> ''' location = Location(["i4x", "edX", "video", "default", "SampleProblem1"]) field_data = DictFieldData({ 'data': sample_xml, 'location': location }) system = DummySystem(load_error_modules=True) descriptor = VideoDescriptor(system, field_data, Mock()) self.assert_attributes_equal(descriptor, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'download_video': True, 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', 'download_track': True, 'html5_sources': ['http://www.example.com/source.mp4', 'http://www.example.com/source.ogg'], 'data': '', 'transcripts': {'ua': 'ukrainian_translation.srt', 'ge': 'german_translation.srt'} }) def test_from_xml(self): module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" download_track="false" start_time="00:00:01" download_video="false" end_time="00:01:00"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> <transcript language="ua" src="ukrainian_translation.srt" /> <transcript language="ge" src="german_translation.srt" /> </video> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', 'download_track': False, 'download_video': False, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '', 'transcripts': {'ua': 'ukrainian_translation.srt', 'ge': 'german_translation.srt'}, }) def test_from_xml_missing_attributes(self): """ Ensure that attributes have the right values if they aren't explicitly set in XML. """ module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,1.25:1EeWXzPdhSA" show_captions="true"> <source src="http://www.example.com/source.mp4"/> </video> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': '', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': '', 'show_captions': True, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': '', 'download_track': False, 'download_video': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '' }) def test_from_xml_missing_download_track(self): """ Ensure that attributes have the right values if they aren't explicitly set in XML. """ module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,1.25:1EeWXzPdhSA" show_captions="true"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> </video> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': '', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': '', 'show_captions': True, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': 'http://www.example.com/track', 'download_track': True, 'download_video': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '', 'transcripts': {}, }) def test_from_xml_no_attributes(self): """ Make sure settings are correct if none are explicitly set in XML. """ module_system = DummySystem(load_error_modules=True) xml_data = '<video></video>' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': '', 'youtube_id_1_0': 'OEoXaMPEzfM', 'youtube_id_1_25': '', 'youtube_id_1_5': '', 'show_captions': True, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': '', 'download_track': False, 'download_video': False, 'html5_sources': [], 'data': '', 'transcripts': {}, }) def test_from_xml_double_quotes(self): """ Make sure we can handle the double-quoted string format (which was used for exporting for a few weeks). """ module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="&quot;display_name&quot;" html5_sources="[&quot;source_1&quot;, &quot;source_2&quot;]" show_captions="false" download_video="true" sub="&quot;html5_subtitles&quot;" track="&quot;http://download_track&quot;" download_track="true" youtube_id_0_75="&quot;OEoXaMPEzf65&quot;" youtube_id_1_25="&quot;OEoXaMPEzf125&quot;" youtube_id_1_5="&quot;OEoXaMPEzf15&quot;" youtube_id_1_0="&quot;OEoXaMPEzf10&quot;" /> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': 'OEoXaMPEzf65', 'youtube_id_1_0': 'OEoXaMPEzf10', 'youtube_id_1_25': 'OEoXaMPEzf125', 'youtube_id_1_5': 'OEoXaMPEzf15', 'show_captions': False, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': 'http://download_track', 'download_track': True, 'download_video': True, 'html5_sources': ["source_1", "source_2"], 'data': '' }) def test_from_xml_double_quote_concatenated_youtube(self): module_system = DummySystem(load_error_modules=True) xml_data = ''' <video display_name="Test Video" youtube="1.0:&quot;p2Q6BrNhdh8&quot;,1.25:&quot;1EeWXzPdhSA&quot;"> </video> ''' output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': '', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': '', 'show_captions': True, 'start_time': datetime.timedelta(seconds=0.0), 'end_time': datetime.timedelta(seconds=0.0), 'track': '', 'download_track': False, 'download_video': False, 'html5_sources': [], 'data': '' }) def test_old_video_format(self): """ Test backwards compatibility with VideoModule's XML format. """ module_system = DummySystem(load_error_modules=True) xml_data = """ <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" source="http://www.example.com/source.mp4" from="00:00:01" to="00:01:00"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> </video> """ output = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(output, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', # 'download_track': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '', }) def test_old_video_data(self): """ Ensure that Video is able to read VideoModule's model data. """ module_system = DummySystem(load_error_modules=True) xml_data = """ <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" from="00:00:01" to="00:01:00"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> </video> """ video = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(video, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', # 'download_track': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '' }) def test_import_with_float_times(self): """ Ensure that Video is able to read VideoModule's model data. """ module_system = DummySystem(load_error_modules=True) xml_data = """ <video display_name="Test Video" youtube="1.0:p2Q6BrNhdh8,0.75:izygArpw-Qo,1.25:1EeWXzPdhSA,1.5:rABDYkeK0x8" show_captions="false" from="1.0" to="60.0"> <source src="http://www.example.com/source.mp4"/> <track src="http://www.example.com/track"/> </video> """ video = VideoDescriptor.from_xml(xml_data, module_system, Mock()) self.assert_attributes_equal(video, { 'youtube_id_0_75': 'izygArpw-Qo', 'youtube_id_1_0': 'p2Q6BrNhdh8', 'youtube_id_1_25': '1EeWXzPdhSA', 'youtube_id_1_5': 'rABDYkeK0x8', 'show_captions': False, 'start_time': datetime.timedelta(seconds=1), 'end_time': datetime.timedelta(seconds=60), 'track': 'http://www.example.com/track', # 'download_track': True, 'html5_sources': ['http://www.example.com/source.mp4'], 'data': '' }) class VideoExportTestCase(unittest.TestCase): """ Make sure that VideoDescriptor can export itself to XML correctly. """ def assertXmlEqual(self, expected, xml): for attr in ['tag', 'attrib', 'text', 'tail']: self.assertEqual(getattr(expected, attr), getattr(xml, attr)) for left, right in zip(expected, xml): self.assertXmlEqual(left, right) def test_export_to_xml(self): """Test that we write the correct XML on export.""" module_system = DummySystem(load_error_modules=True) location = Location(["i4x", "edX", "video", "default", "SampleProblem1"]) desc = VideoDescriptor(module_system, DictFieldData({}), ScopeIds(None, None, location, location)) desc.youtube_id_0_75 = 'izygArpw-Qo' desc.youtube_id_1_0 = 'p2Q6BrNhdh8' desc.youtube_id_1_25 = '1EeWXzPdhSA' desc.youtube_id_1_5 = 'rABDYkeK0x8' desc.show_captions = False desc.start_time = datetime.timedelta(seconds=1.0) desc.end_time = datetime.timedelta(seconds=60) desc.track = 'http://www.example.com/track' desc.download_track = True desc.html5_sources = ['http://www.example.com/source.mp4', 'http://www.example.com/source.ogg'] desc.download_video = True desc.transcripts = {'ua': 'ukrainian_translation.srt', 'ge': 'german_translation.srt'} xml = desc.definition_to_xml(None) # We don't use the `resource_fs` parameter expected = etree.fromstring('''\ <video url_name="SampleProblem1" start_time="0:00:01" youtube="0.75:izygArpw-Qo,1.00:p2Q6BrNhdh8,1.25:1EeWXzPdhSA,1.50:rABDYkeK0x8" show_captions="false" end_time="0:01:00" download_video="true" download_track="true"> <source src="http://www.example.com/source.mp4"/> <source src="http://www.example.com/source.ogg"/> <track src="http://www.example.com/track"/> <transcript language="ge" src="german_translation.srt" /> <transcript language="ua" src="ukrainian_translation.srt" /> </video> ''') self.assertXmlEqual(expected, xml) def test_export_to_xml_empty_end_time(self): """Test that we write the correct XML on export.""" module_system = DummySystem(load_error_modules=True) location = Location(["i4x", "edX", "video", "default", "SampleProblem1"]) desc = VideoDescriptor(module_system, DictFieldData({}), ScopeIds(None, None, location, location)) desc.youtube_id_0_75 = 'izygArpw-Qo' desc.youtube_id_1_0 = 'p2Q6BrNhdh8' desc.youtube_id_1_25 = '1EeWXzPdhSA' desc.youtube_id_1_5 = 'rABDYkeK0x8' desc.show_captions = False desc.start_time = datetime.timedelta(seconds=5.0) desc.end_time = datetime.timedelta(seconds=0.0) desc.track = 'http://www.example.com/track' desc.download_track = True desc.html5_sources = ['http://www.example.com/source.mp4', 'http://www.example.com/source.ogg'] desc.download_video = True xml = desc.definition_to_xml(None) # We don't use the `resource_fs` parameter expected = etree.fromstring('''\ <video url_name="SampleProblem1" start_time="0:00:05" youtube="0.75:izygArpw-Qo,1.00:p2Q6BrNhdh8,1.25:1EeWXzPdhSA,1.50:rABDYkeK0x8" show_captions="false" download_video="true" download_track="true"> <source src="http://www.example.com/source.mp4"/> <source src="http://www.example.com/source.ogg"/> <track src="http://www.example.com/track"/> </video> ''') self.assertXmlEqual(expected, xml) def test_export_to_xml_empty_parameters(self): """Test XML export with defaults.""" module_system = DummySystem(load_error_modules=True) location = Location(["i4x", "edX", "video", "default", "SampleProblem1"]) desc = VideoDescriptor(module_system, DictFieldData({}), ScopeIds(None, None, location, location)) xml = desc.definition_to_xml(None) expected = '<video url_name="SampleProblem1"/>\n' self.assertEquals(expected, etree.tostring(xml, pretty_print=True))
agpl-3.0
chbfiv/fabric-engine-old
Web/ThirdParty/jQuery/ui/minified/jquery.effects.core.min.js
10578
/* * jQuery UI Effects 1.8.4 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/ */ jQuery.effects||function(f,j){function l(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return[parseInt(a[1], 16),parseInt(a[2],16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return m.transparent;return m[f.trim(c).toLowerCase()]}function r(c,a){var b;do{b=f.curCSS(c,a);if(b!=""&&b!="transparent"||f.nodeName(c,"body"))break;a="backgroundColor"}while(c=c.parentNode);return l(b)}function n(){var c=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle, a={},b,d;if(c&&c.length&&c[0]&&c[c[0]])for(var e=c.length;e--;){b=c[e];if(typeof c[b]=="string"){d=b.replace(/\-(\w)/g,function(g,h){return h.toUpperCase()});a[d]=c[b]}}else for(b in c)if(typeof c[b]==="string")a[b]=c[b];return a}function o(c){var a,b;for(a in c){b=c[a];if(b==null||f.isFunction(b)||a in s||/scrollbar/.test(a)||!/color/i.test(a)&&isNaN(parseFloat(b)))delete c[a]}return c}function t(c,a){var b={_:0},d;for(d in a)if(c[d]!=a[d])b[d]=a[d];return b}function k(c,a,b,d){if(typeof c=="object"){d= a;b=null;a=c;c=a.effect}if(f.isFunction(a)){d=a;b=null;a={}}if(typeof a=="number"||f.fx.speeds[a]){d=b;b=a;a={}}if(f.isFunction(b)){d=b;b=null}a=a||{};b=b||a.duration;b=f.fx.off?0:typeof b=="number"?b:f.fx.speeds[b]||f.fx.speeds._default;d=d||a.complete;return[c,a,b,d]}f.effects={};f.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(c,a){f.fx.step[a]=function(b){if(!b.colorInit){b.start=r(b.elem,a);b.end=l(b.end);b.colorInit= true}b.elem.style[a]="rgb("+Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2],10),255),0)+")"}});var m={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189, 183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255, 165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},p=["add","remove","toggle"],s={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};f.effects.animateClass=function(c,a,b,d){if(f.isFunction(b)){d=b;b=null}return this.each(function(){var e=f(this),g=e.attr("style")||" ",h=o(n.call(this)),q,u=e.attr("className");f.each(p,function(v, i){c[i]&&e[i+"Class"](c[i])});q=o(n.call(this));e.attr("className",u);e.animate(t(h,q),a,b,function(){f.each(p,function(v,i){c[i]&&e[i+"Class"](c[i])});if(typeof e.attr("style")=="object"){e.attr("style").cssText="";e.attr("style").cssText=g}else e.attr("style",g);d&&d.apply(this,arguments)})})};f.fn.extend({_addClass:f.fn.addClass,addClass:function(c,a,b,d){return a?f.effects.animateClass.apply(this,[{add:c},a,b,d]):this._addClass(c)},_removeClass:f.fn.removeClass,removeClass:function(c,a,b,d){return a? f.effects.animateClass.apply(this,[{remove:c},a,b,d]):this._removeClass(c)},_toggleClass:f.fn.toggleClass,toggleClass:function(c,a,b,d,e){return typeof a=="boolean"||a===j?b?f.effects.animateClass.apply(this,[a?{add:c}:{remove:c},b,d,e]):this._toggleClass(c,a):f.effects.animateClass.apply(this,[{toggle:c},a,b,d])},switchClass:function(c,a,b,d,e){return f.effects.animateClass.apply(this,[{add:a,remove:c},b,d,e])}});f.extend(f.effects,{version:"1.8.4",save:function(c,a){for(var b=0;b<a.length;b++)a[b]!== null&&c.data("ec.storage."+a[b],c[0].style[a[b]])},restore:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.css(a[b],c.data("ec.storage."+a[b]))},setMode:function(c,a){if(a=="toggle")a=c.is(":hidden")?"show":"hide";return a},getBaseline:function(c,a){var b;switch(c[0]){case "top":b=0;break;case "middle":b=0.5;break;case "bottom":b=1;break;default:b=c[0]/a.height}switch(c[1]){case "left":c=0;break;case "center":c=0.5;break;case "right":c=1;break;default:c=c[1]/a.width}return{x:c,y:b}},createWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent(); var a={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},b=f("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0});c.wrap(b);b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"})}else{f.extend(a,{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(d,e){a[e]=c.css(e);if(isNaN(parseInt(a[e],10)))a[e]="auto"}); c.css({position:"relative",top:0,left:0})}return b.css(a).show()},removeWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent().replaceWith(c);return c},setTransition:function(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1]});return d}});f.fn.extend({effect:function(c){var a=k.apply(this,arguments);a={options:a[1],duration:a[2],callback:a[3]};var b=f.effects[c];return b&&!f.fx.off?b.call(this,a):this},_show:f.fn.show,show:function(c){if(!c|| typeof c=="number"||f.fx.speeds[c])return this._show.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a)}},_hide:f.fn.hide,hide:function(c){if(!c||typeof c=="number"||f.fx.speeds[c])return this._hide.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a)}},__toggle:f.fn.toggle,toggle:function(c){if(!c||typeof c=="number"||f.fx.speeds[c]||typeof c=="boolean"||f.isFunction(c))return this.__toggle.apply(this, arguments);else{var a=k.apply(this,arguments);a[1].mode="toggle";return this.effect.apply(this,a)}},cssUnit:function(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e]});return b}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function(c,a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e)},easeInQuad:function(c,a,b,d,e){return d*(a/=e)*a+b},easeOutQuad:function(c,a,b,d,e){return-d*(a/=e)*(a-2)+b},easeInOutQuad:function(c, a,b,d,e){if((a/=e/2)<1)return d/2*a*a+b;return-d/2*(--a*(a-2)-1)+b},easeInCubic:function(c,a,b,d,e){return d*(a/=e)*a*a+b},easeOutCubic:function(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b},easeInOutCubic:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b},easeInQuart:function(c,a,b,d,e){return d*(a/=e)*a*a*a+b},easeOutQuart:function(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b},easeInOutQuart:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2)*a*a*a-2)+ b},easeInQuint:function(c,a,b,d,e){return d*(a/=e)*a*a*a*a+b},easeOutQuint:function(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b},easeInOutQuint:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b},easeInSine:function(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b},easeOutSine:function(c,a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b},easeInOutSine:function(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+b},easeInExpo:function(c,a,b,d,e){return a==0?b:d*Math.pow(2, 10*(a/e-1))+b},easeOutExpo:function(c,a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b},easeInOutExpo:function(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b},easeInCirc:function(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b},easeOutCirc:function(c,a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b},easeInOutCirc:function(c,a,b,d,e){if((a/=e/2)<1)return-d/2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt(1-(a-=2)* a)+1)+b},easeInElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g))+b},easeOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*a)*Math.sin((a*e-c)*2*Math.PI/g)+d+b},easeInOutElastic:function(c, a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e/2)==2)return b+d;g||(g=e*0.3*1.5);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);if(a<1)return-0.5*h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)+b;return h*Math.pow(2,-10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)*0.5+d+b},easeInBack:function(c,a,b,d,e,g){if(g==j)g=1.70158;return d*(a/=e)*a*((g+1)*a-g)+b},easeOutBack:function(c,a,b,d,e,g){if(g==j)g=1.70158;return d*((a=a/e-1)*a*((g+1)*a+g)+1)+b},easeInOutBack:function(c, a,b,d,e,g){if(g==j)g=1.70158;if((a/=e/2)<1)return d/2*a*a*(((g*=1.525)+1)*a-g)+b;return d/2*((a-=2)*a*(((g*=1.525)+1)*a+g)+2)+b},easeInBounce:function(c,a,b,d,e){return d-f.easing.easeOutBounce(c,e-a,0,d,e)+b},easeOutBounce:function(c,a,b,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+b:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+b:a<2.5/2.75?d*(7.5625*(a-=2.25/2.75)*a+0.9375)+b:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+b},easeInOutBounce:function(c,a,b,d,e){if(a<e/2)return f.easing.easeInBounce(c,a*2,0,d,e)*0.5+ b;return f.easing.easeOutBounce(c,a*2-e,0,d,e)*0.5+d*0.5+b}})}(jQuery);
agpl-3.0
oopcell/openApotti
Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/EmergencyAttendanceInvestigationCodingVoAssembler.java
19790
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:32 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Rory Fitzpatrick */ public class EmergencyAttendanceInvestigationCodingVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo copy(ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo valueObjectDest, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_EmergencyAttendanceInvestigationCoding(valueObjectSrc.getID_EmergencyAttendanceInvestigationCoding()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // CareContext valueObjectDest.setCareContext(valueObjectSrc.getCareContext()); // InvestigationSequenceCodingItems valueObjectDest.setInvestigationSequenceCodingItems(valueObjectSrc.getInvestigationSequenceCodingItems()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createEmergencyAttendanceInvestigationCodingVoCollectionFromEmergencyAttendanceInvestigationCoding(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding objects. */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection createEmergencyAttendanceInvestigationCodingVoCollectionFromEmergencyAttendanceInvestigationCoding(java.util.Set domainObjectSet) { return createEmergencyAttendanceInvestigationCodingVoCollectionFromEmergencyAttendanceInvestigationCoding(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding objects. */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection createEmergencyAttendanceInvestigationCodingVoCollectionFromEmergencyAttendanceInvestigationCoding(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection voList = new ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject = (ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding) iterator.next(); ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding objects. */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection createEmergencyAttendanceInvestigationCodingVoCollectionFromEmergencyAttendanceInvestigationCoding(java.util.List domainObjectList) { return createEmergencyAttendanceInvestigationCodingVoCollectionFromEmergencyAttendanceInvestigationCoding(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding objects. */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection createEmergencyAttendanceInvestigationCodingVoCollectionFromEmergencyAttendanceInvestigationCoding(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection voList = new ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject = (ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding) domainObjectList.get(i); ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractEmergencyAttendanceInvestigationCodingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection voCollection) { return extractEmergencyAttendanceInvestigationCodingSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractEmergencyAttendanceInvestigationCodingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo vo = voCollection.get(i); ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject = EmergencyAttendanceInvestigationCodingVoAssembler.extractEmergencyAttendanceInvestigationCoding(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractEmergencyAttendanceInvestigationCodingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection voCollection) { return extractEmergencyAttendanceInvestigationCodingList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractEmergencyAttendanceInvestigationCodingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo vo = voCollection.get(i); ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject = EmergencyAttendanceInvestigationCodingVoAssembler.extractEmergencyAttendanceInvestigationCoding(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding object. * @param domainObject ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo create(ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo create(DomainObjectMap map, ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo valueObject = (ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo) map.getValueObject(domainObject, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo insert(ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo valueObject, ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding */ public static ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo insert(DomainObjectMap map, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo valueObject, ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_EmergencyAttendanceInvestigationCoding(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // CareContext if (domainObject.getCareContext() != null) { if(domainObject.getCareContext() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getCareContext(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setCareContext(new ims.core.admin.vo.CareContextRefVo(id, -1)); } else { valueObject.setCareContext(new ims.core.admin.vo.CareContextRefVo(domainObject.getCareContext().getId(), domainObject.getCareContext().getVersion())); } } // InvestigationSequenceCodingItems valueObject.setInvestigationSequenceCodingItems(ims.emergency.vo.domain.EmergencyAttendanceInvestigationCodingSequenceItemVoAssembler.createEmergencyAttendanceInvestigationCodingSequenceItemVoCollectionFromEmergencyAttendanceInvestigationCodingSequenceItem(map, domainObject.getInvestigationSequenceCodingItems()) ); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding extractEmergencyAttendanceInvestigationCoding(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo valueObject) { return extractEmergencyAttendanceInvestigationCoding(domainFactory, valueObject, new HashMap()); } public static ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding extractEmergencyAttendanceInvestigationCoding(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_EmergencyAttendanceInvestigationCoding(); ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding)domMap.get(valueObject); } // ims.emergency.vo.EmergencyAttendanceInvestigationCodingVo ID_EmergencyAttendanceInvestigationCoding field is unknown domainObject = new ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_EmergencyAttendanceInvestigationCoding()); if (domMap.get(key) != null) { return (ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding)domMap.get(key); } domainObject = (ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding) domainFactory.getDomainObject(ims.emergency.domain.objects.EmergencyAttendanceInvestigationCoding.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_EmergencyAttendanceInvestigationCoding()); ims.core.admin.domain.objects.CareContext value1 = null; if ( null != valueObject.getCareContext() ) { if (valueObject.getCareContext().getBoId() == null) { if (domMap.get(valueObject.getCareContext()) != null) { value1 = (ims.core.admin.domain.objects.CareContext)domMap.get(valueObject.getCareContext()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value1 = domainObject.getCareContext(); } else { value1 = (ims.core.admin.domain.objects.CareContext)domainFactory.getDomainObject(ims.core.admin.domain.objects.CareContext.class, valueObject.getCareContext().getBoId()); } } domainObject.setCareContext(value1); domainObject.setInvestigationSequenceCodingItems(ims.emergency.vo.domain.EmergencyAttendanceInvestigationCodingSequenceItemVoAssembler.extractEmergencyAttendanceInvestigationCodingSequenceItemSet(domainFactory, valueObject.getInvestigationSequenceCodingItems(), domainObject.getInvestigationSequenceCodingItems(), domMap)); return domainObject; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace-archive/DomainObjects/src/ims/core/clinical/domain/objects/MedicationRoute.java
12335
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated: 16/04/2014, 12:34 * */ package ims.core.clinical.domain.objects; /** * * @author Neil McAnaspie * Generated. */ public class MedicationRoute extends ims.domain.DomainObject implements java.io.Serializable { public static final int CLASSID = 1003100113; private static final long serialVersionUID = 1003100113L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } /** Route */ private ims.domain.lookups.LookupInstance route; /** RouteUnits * Collection of ims.core.clinical.domain.objects.MedicationUnit. */ private java.util.List routeUnits; public MedicationRoute (Integer id, int ver) { super(id, ver); } public MedicationRoute () { super(); } public MedicationRoute (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); } public Class getRealDomainClass() { return ims.core.clinical.domain.objects.MedicationRoute.class; } public ims.domain.lookups.LookupInstance getRoute() { return route; } public void setRoute(ims.domain.lookups.LookupInstance route) { this.route = route; } public java.util.List getRouteUnits() { if ( null == routeUnits ) { routeUnits = new java.util.ArrayList(); } return routeUnits; } public void setRouteUnits(java.util.List paramValue) { this.routeUnits = paramValue; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Configuration".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*route* :"); if (route != null) auditStr.append(route.getText()); auditStr.append("; "); auditStr.append("\r\n*routeUnits* :"); if (routeUnits != null) { int i2=0; for (i2=0; i2<routeUnits.size(); i2++) { if (i2 > 0) auditStr.append(","); ims.core.clinical.domain.objects.MedicationUnit obj = (ims.core.clinical.domain.objects.MedicationUnit)routeUnits.get(i2); if (obj != null) { if (i2 == 0) { auditStr.append(toShortClassName(obj)); auditStr.append("["); } auditStr.append(obj.toString()); } } if (i2 > 0) auditStr.append("] " + i2); } auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" id=\"" + this.getId() + "\""); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); String keyClassName = "MedicationRoute"; String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName(); ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId()); if (impObj == null) { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(this.getId()); impObj.setExternalSource(externalSource); impObj.setDomainObject(this); impObj.setLocalId(this.getId()); impObj.setClassName(keyClassName); domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj); } return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getRoute() != null) { sb.append("<route>"); sb.append(this.getRoute().toXMLString()); sb.append("</route>"); } if (this.getRouteUnits() != null) { if (this.getRouteUnits().size() > 0 ) { sb.append("<routeUnits>"); sb.append(ims.domain.DomainObject.toXMLString(this.getRouteUnits(), domMap)); sb.append("</routeUnits>"); } } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); MedicationRoute domainObject = getMedicationRoutefromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); MedicationRoute domainObject = getMedicationRoutefromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static MedicationRoute getMedicationRoutefromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getMedicationRoutefromXML(doc.getRootElement(), factory, domMap); } public static MedicationRoute getMedicationRoutefromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!MedicationRoute.class.getName().equals(className)) { Class clz = Class.forName(className); if (!MedicationRoute.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the MedicationRoute class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (MedicationRoute)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(MedicationRoute.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } MedicationRoute ret = null; int extId = Integer.parseInt(el.attributeValue("id")); String externalSource = el.attributeValue("source"); ret = (MedicationRoute)factory.getImportedDomainObject(MedicationRoute.class, externalSource, extId); if (ret == null) { ret = new MedicationRoute(); } String keyClassName = "MedicationRoute"; ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId); if (impObj != null) { return (MedicationRoute)impObj.getDomainObject(); } else { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(extId); impObj.setExternalSource(externalSource); impObj.setDomainObject(ret); domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, MedicationRoute obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("route"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setRoute(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("routeUnits"); if(fldEl != null) { fldEl = fldEl.element("list"); obj.setRouteUnits(ims.core.clinical.domain.objects.MedicationUnit.fromListXMLString(fldEl, factory, obj.getRouteUnits(), domMap)); } } public static String[] getCollectionFields() { return new String[]{ "routeUnits" }; } public static class FieldNames { public static final String ID = "id"; public static final String Route = "route"; public static final String RouteUnits = "routeUnits"; } }
agpl-3.0
oopcell/openApotti
Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/domain/base/impl/BaseReferralDetailsComponentImpl.java
2744
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BaseReferralDetailsComponentImpl extends DomainImpl implements ims.RefMan.domain.ReferralDetailsComponent, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validatelistServiceFunctionsLite(ims.core.clinical.vo.ServiceRefVo service) { } @SuppressWarnings("unused") public void validategetCatsReferral(ims.RefMan.vo.CatsReferralRefVo catsReferral) { } @SuppressWarnings("unused") public void validatesave(ims.clinical.vo.ReferralLetterDetailsVo referralDetailsVo, ims.RefMan.vo.CatsReferralWizardVo catsReferralVo, Boolean bDiagnosticReferral) { } @SuppressWarnings("unused") public void validategetReferral(ims.core.clinical.vo.ReferralLetterDetailsRefVo referral) { } @SuppressWarnings("unused") public void validategetPatientGP(Integer patientId) { } @SuppressWarnings("unused") public void validatelistProcedures(String procedureName, ims.core.vo.ServiceLiteVo serviceLiteVo) { } @SuppressWarnings("unused") public void validatelistOrganisations(ims.core.vo.OrgShortVo filter) { } @SuppressWarnings("unused") public void validatesaveCatsReferral(ims.RefMan.vo.CatsReferralWizardVo record) { } @SuppressWarnings("unused") public void validatelistLocationByOrganisation(ims.core.resource.place.vo.OrganisationRefVo organisation, String name) { } @SuppressWarnings("unused") public void validatelistActiveContracts(ims.core.resource.place.vo.OrganisationRefVo voOrgRef) { } @SuppressWarnings("unused") public void validatelistAllContracts(ims.core.resource.place.vo.OrganisationRefVo voOrgRef) { } @SuppressWarnings("unused") public void validategetOrganisationByLocation(Integer locationId) { } @SuppressWarnings("unused") public void validatelistActiveContractsForLocation(ims.core.resource.place.vo.LocationRefVo location) { } @SuppressWarnings("unused") public void validatelistLocationServiceByContract(ims.core.configuration.vo.ContractConfigRefVo contract) { } @SuppressWarnings("unused") public void validatelistLocationServiceByContractAndService(ims.core.configuration.vo.ContractConfigRefVo contract, ims.core.clinical.vo.ServiceRefVo service) { } @SuppressWarnings("unused") public void validategetPatientSurgery(ims.core.patient.vo.PatientRefVo voPatientRef) { } @SuppressWarnings("unused") public void validategetCCGForPostCode(String szPostcode) { } }
agpl-3.0
hdweiss/qt-creator-visualizer
src/plugins/texteditor/generichighlighter/manager.cpp
18950
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "manager.h" #include "highlightdefinition.h" #include "highlightdefinitionhandler.h" #include "highlighterexception.h" #include "definitiondownloader.h" #include "highlightersettings.h" #include "plaintexteditorfactory.h" #include "texteditorconstants.h" #include "texteditorplugin.h" #include "texteditorsettings.h" #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <coreplugin/progressmanager/progressmanager.h> #include <utils/QtConcurrentTools> #include <QtAlgorithms> #include <QtPlugin> #include <QString> #include <QLatin1Char> #include <QLatin1String> #include <QStringList> #include <QFile> #include <QFileInfo> #include <QDir> #include <QRegExp> #include <QFuture> #include <QtConcurrentRun> #include <QtConcurrentMap> #include <QUrl> #include <QSet> #include <QXmlStreamReader> #include <QXmlStreamAttributes> #include <QDesktopServices> #include <QMessageBox> #include <QXmlSimpleReader> #include <QXmlInputSource> #include <QNetworkRequest> #include <QNetworkReply> #include <QtAlgorithms> using namespace TextEditor; using namespace Internal; Manager::Manager() : m_isDownloadingDefinitionsSpec(false), m_hasQueuedRegistration(false) { connect(&m_registeringWatcher, SIGNAL(finished()), this, SLOT(registerMimeTypesFinished())); connect(&m_downloadWatcher, SIGNAL(finished()), this, SLOT(downloadDefinitionsFinished())); } Manager::~Manager() { disconnect(&m_registeringWatcher); disconnect(&m_downloadWatcher); if (m_registeringWatcher.isRunning()) m_registeringWatcher.cancel(); if (m_downloadWatcher.isRunning()) m_downloadWatcher.cancel(); } Manager *Manager::instance() { static Manager manager; return &manager; } QString Manager::definitionIdByName(const QString &name) const { return m_register.m_idByName.value(name); } QString Manager::definitionIdByMimeType(const QString &mimeType) const { return m_register.m_idByMimeType.value(mimeType); } QString Manager::definitionIdByAnyMimeType(const QStringList &mimeTypes) const { QString definitionId; foreach (const QString &mimeType, mimeTypes) { definitionId = definitionIdByMimeType(mimeType); if (!definitionId.isEmpty()) break; } return definitionId; } QSharedPointer<HighlightDefinition> Manager::definition(const QString &id) { if (!id.isEmpty() && !m_definitions.contains(id)) { QFile definitionFile(id); if (!definitionFile.open(QIODevice::ReadOnly | QIODevice::Text)) return QSharedPointer<HighlightDefinition>(); QSharedPointer<HighlightDefinition> definition(new HighlightDefinition); HighlightDefinitionHandler handler(definition); QXmlInputSource source(&definitionFile); QXmlSimpleReader reader; reader.setContentHandler(&handler); m_isBuildingDefinition.insert(id); try { reader.parse(source); } catch (HighlighterException &) { definition.clear(); } m_isBuildingDefinition.remove(id); definitionFile.close(); m_definitions.insert(id, definition); } return m_definitions.value(id); } QSharedPointer<HighlightDefinitionMetaData> Manager::definitionMetaData(const QString &id) const { return m_register.m_definitionsMetaData.value(id); } bool Manager::isBuildingDefinition(const QString &id) const { return m_isBuildingDefinition.contains(id); } namespace TextEditor { namespace Internal { class ManagerProcessor : public QObject { Q_OBJECT public: ManagerProcessor(); void process(QFutureInterface<QPair<Manager::RegisterData, QList<Core::MimeType> > > &future); QStringList m_definitionsPaths; QSet<QString> m_knownMimeTypes; QSet<QString> m_knownSuffixes; QHash<QString, Core::MimeType> m_userModified; static const int kMaxProgress; struct PriorityComp { bool operator()(const QSharedPointer<HighlightDefinitionMetaData> &a, const QSharedPointer<HighlightDefinitionMetaData> &b) { return a->priority() > b->priority(); } }; }; const int ManagerProcessor::kMaxProgress = 200; ManagerProcessor::ManagerProcessor() : m_knownSuffixes(QSet<QString>::fromList(Core::ICore::mimeDatabase()->suffixes())) { const HighlighterSettings &settings = TextEditorSettings::instance()->highlighterSettings(); m_definitionsPaths.append(settings.definitionFilesPath()); if (settings.useFallbackLocation()) m_definitionsPaths.append(settings.fallbackDefinitionFilesPath()); Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase(); foreach (const Core::MimeType &userMimeType, mimeDatabase->readUserModifiedMimeTypes()) m_userModified.insert(userMimeType.type(), userMimeType); foreach (const Core::MimeType &mimeType, mimeDatabase->mimeTypes()) m_knownMimeTypes.insert(mimeType.type()); } void ManagerProcessor::process(QFutureInterface<QPair<Manager::RegisterData, QList<Core::MimeType> > > &future) { future.setProgressRange(0, kMaxProgress); // @TODO: Improve MIME database to handle the following limitation. // The generic highlighter only register its types after all other plugins // have populated Creator's MIME database (so it does not override anything). // When the generic highlighter settings change only its internal data is cleaned-up // and rebuilt. Creator's MIME database is not touched. So depending on how the // user plays around with the generic highlighter file definitions (changing // duplicated patterns, for example), some changes might not be reflected. // A definitive implementation would require some kind of re-load or update // (considering hierarchies, aliases, etc) of the MIME database whenever there // is a change in the generic highlighter settings. Manager::RegisterData data; QList<Core::MimeType> newMimeTypes; foreach (const QString &path, m_definitionsPaths) { if (path.isEmpty()) continue; QDir definitionsDir(path); QStringList filter(QLatin1String("*.xml")); definitionsDir.setNameFilters(filter); QList<QSharedPointer<HighlightDefinitionMetaData> > allMetaData; foreach (const QFileInfo &fileInfo, definitionsDir.entryInfoList()) { const QSharedPointer<HighlightDefinitionMetaData> &metaData = Manager::parseMetadata(fileInfo); if (!metaData.isNull()) allMetaData.append(metaData); } // Consider definitions with higher priority first. qSort(allMetaData.begin(), allMetaData.end(), PriorityComp()); foreach (const QSharedPointer<HighlightDefinitionMetaData> &metaData, allMetaData) { if (future.isCanceled()) return; if (future.progressValue() < kMaxProgress - 1) future.setProgressValue(future.progressValue() + 1); if (data.m_idByName.contains(metaData->name())) // Name already exists... This is a fallback item, do not consider it. continue; const QString &id = metaData->id(); data.m_idByName.insert(metaData->name(), id); data.m_definitionsMetaData.insert(id, metaData); static const QStringList textPlain(QLatin1String("text/plain")); // A definition can specify multiple MIME types and file extensions/patterns, // but all on a single string. So associate all patterns with all MIME types. QList<Core::MimeGlobPattern> globPatterns; foreach (const QString &type, metaData->mimeTypes()) { if (data.m_idByMimeType.contains(type)) continue; data.m_idByMimeType.insert(type, id); if (!m_knownMimeTypes.contains(type)) { m_knownMimeTypes.insert(type); Core::MimeType mimeType; mimeType.setType(type); mimeType.setSubClassesOf(textPlain); mimeType.setComment(metaData->name()); // If there's a user modification for this mime type, we want to use the // modified patterns and rule-based matchers. If not, just consider what // is specified in the definition file. QHash<QString, Core::MimeType>::const_iterator it = m_userModified.find(mimeType.type()); if (it == m_userModified.end()) { if (globPatterns.isEmpty()) { foreach (const QString &pattern, metaData->patterns()) { static const QLatin1String mark("*."); if (pattern.startsWith(mark)) { const QString &suffix = pattern.right(pattern.length() - 2); if (!m_knownSuffixes.contains(suffix)) m_knownSuffixes.insert(suffix); else continue; } QRegExp regExp(pattern, Qt::CaseSensitive, QRegExp::Wildcard); globPatterns.append(Core::MimeGlobPattern(regExp, 50)); } } mimeType.setGlobPatterns(globPatterns); } else { mimeType.setGlobPatterns(it.value().globPatterns()); mimeType.setMagicRuleMatchers(it.value().magicRuleMatchers()); } newMimeTypes.append(mimeType); } } } } future.reportResult(qMakePair(data, newMimeTypes)); } } // Internal } // TextEditor void Manager::registerMimeTypes() { if (!m_registeringWatcher.isRunning()) { clear(); ManagerProcessor *processor = new ManagerProcessor; QFuture<QPair<RegisterData, QList<Core::MimeType> > > future = QtConcurrent::run(&ManagerProcessor::process, processor); connect(&m_registeringWatcher, SIGNAL(finished()), processor, SLOT(deleteLater())); m_registeringWatcher.setFuture(future); Core::ICore::progressManager()->addTask(future, tr("Registering definitions"), QLatin1String(Constants::TASK_REGISTER_DEFINITIONS)); } else { m_hasQueuedRegistration = true; m_registeringWatcher.cancel(); } } void Manager::registerMimeTypesFinished() { if (m_hasQueuedRegistration) { m_hasQueuedRegistration = false; registerMimeTypes(); } else if (!m_registeringWatcher.isCanceled()) { const QPair<RegisterData, QList<Core::MimeType> > &result = m_registeringWatcher.result(); m_register = result.first; PlainTextEditorFactory *factory = TextEditorPlugin::instance()->editorFactory(); const QSet<QString> &inFactory = factory->mimeTypes().toSet(); foreach (const Core::MimeType &mimeType, result.second) { Core::ICore::mimeDatabase()->addMimeType(mimeType); if (!inFactory.contains(mimeType.type())) factory->addMimeType(mimeType.type()); } emit mimeTypesRegistered(); } } QSharedPointer<HighlightDefinitionMetaData> Manager::parseMetadata(const QFileInfo &fileInfo) { static const QLatin1Char kSemiColon(';'); static const QLatin1Char kSpace(' '); static const QLatin1Char kDash('-'); static const QLatin1String kLanguage("language"); static const QLatin1String kArtificial("text/x-artificial-"); QFile definitionFile(fileInfo.absoluteFilePath()); if (!definitionFile.open(QIODevice::ReadOnly | QIODevice::Text)) return QSharedPointer<HighlightDefinitionMetaData>(); QSharedPointer<HighlightDefinitionMetaData> metaData(new HighlightDefinitionMetaData); QXmlStreamReader reader(&definitionFile); while (!reader.atEnd() && !reader.hasError()) { if (reader.readNext() == QXmlStreamReader::StartElement && reader.name() == kLanguage) { const QXmlStreamAttributes &atts = reader.attributes(); metaData->setFileName(fileInfo.fileName()); metaData->setId(fileInfo.absoluteFilePath()); metaData->setName(atts.value(HighlightDefinitionMetaData::kName).toString()); metaData->setVersion(atts.value(HighlightDefinitionMetaData::kVersion).toString()); metaData->setPriority(atts.value(HighlightDefinitionMetaData::kPriority).toString() .toInt()); metaData->setPatterns(atts.value(HighlightDefinitionMetaData::kExtensions) .toString().split(kSemiColon, QString::SkipEmptyParts)); QStringList mimeTypes = atts.value(HighlightDefinitionMetaData::kMimeType). toString().split(kSemiColon, QString::SkipEmptyParts); if (mimeTypes.isEmpty()) { // There are definitions which do not specify a MIME type, but specify file // patterns. Creating an artificial MIME type is a workaround. QString artificialType(kArtificial); artificialType.append(metaData->name().trimmed().replace(kSpace, kDash)); mimeTypes.append(artificialType); } metaData->setMimeTypes(mimeTypes); break; } } reader.clear(); definitionFile.close(); return metaData; } QList<HighlightDefinitionMetaData> Manager::parseAvailableDefinitionsList(QIODevice *device) const { static const QLatin1Char kSlash('/'); static const QLatin1String kDefinition("Definition"); QList<HighlightDefinitionMetaData> metaDataList; QXmlStreamReader reader(device); while (!reader.atEnd() && !reader.hasError()) { if (reader.readNext() == QXmlStreamReader::StartElement && reader.name() == kDefinition) { const QXmlStreamAttributes &atts = reader.attributes(); HighlightDefinitionMetaData metaData; metaData.setName(atts.value(HighlightDefinitionMetaData::kName).toString()); metaData.setVersion(atts.value(HighlightDefinitionMetaData::kVersion).toString()); QString url(atts.value(HighlightDefinitionMetaData::kUrl).toString()); metaData.setUrl(QUrl(url)); const int slash = url.lastIndexOf(kSlash); if (slash != -1) metaData.setFileName(url.right(url.length() - slash - 1)); metaDataList.append(metaData); } } reader.clear(); return metaDataList; } void Manager::downloadAvailableDefinitionsMetaData() { QUrl url(QLatin1String("http://www.kate-editor.org/syntax/update-3.2.xml")); QNetworkRequest request(url); // Currently this takes a couple of seconds on Windows 7: QTBUG-10106. QNetworkReply *reply = m_networkManager.get(request); connect(reply, SIGNAL(finished()), this, SLOT(downloadAvailableDefinitionsListFinished())); } void Manager::downloadAvailableDefinitionsListFinished() { if (QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender())) { if (reply->error() == QNetworkReply::NoError) emit definitionsMetaDataReady(parseAvailableDefinitionsList(reply)); else emit errorDownloadingDefinitionsMetaData(); reply->deleteLater(); } } void Manager::downloadDefinitions(const QList<QUrl> &urls, const QString &savePath) { m_downloaders.clear(); foreach (const QUrl &url, urls) m_downloaders.append(new DefinitionDownloader(url, savePath)); m_isDownloadingDefinitionsSpec = true; QFuture<void> future = QtConcurrent::map(m_downloaders, DownloaderStarter()); m_downloadWatcher.setFuture(future); Core::ICore::progressManager()->addTask(future, tr("Downloading definitions"), QLatin1String(Constants::TASK_DOWNLOAD_DEFINITIONS)); } void Manager::downloadDefinitionsFinished() { int errors = 0; bool writeError = false; foreach (DefinitionDownloader *downloader, m_downloaders) { DefinitionDownloader::Status status = downloader->status(); if (status != DefinitionDownloader::Ok) { ++errors; if (status == DefinitionDownloader::WriteError && !writeError) writeError = true; } delete downloader; } if (errors > 0) { QString text; if (errors == m_downloaders.size()) text = tr("Error downloading selected definition(s)."); else text = tr("Error downloading one or more definitions."); if (writeError) text.append(tr("\nPlease check the directory's access rights.")); QMessageBox::critical(0, tr("Download Error"), text); } m_isDownloadingDefinitionsSpec = false; } bool Manager::isDownloadingDefinitions() const { return m_isDownloadingDefinitionsSpec; } void Manager::clear() { m_register.m_idByName.clear(); m_register.m_idByMimeType.clear(); m_register.m_definitionsMetaData.clear(); m_definitions.clear(); } #include "manager.moc"
lgpl-2.1
ikcalB/linuxcnc-mirror
src/hal/user_comps/xhc-hb04.cc
30639
/* XHC-HB04 Wireless MPG pendant LinuxCNC HAL module for LinuxCNC Copyright (C) 2013 Frederic Rible (frible@teaser.fr) Copyright (C) 2013 Rene Hopf (renehopf@mac.com) Copyright (C) 2014 Marius Alksnys (marius.alksnys@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include <signal.h> #include <string.h> #include <libusb.h> #include <unistd.h> #include <stdarg.h> #include <hal.h> #include <inifile.hh> #include "config.h" const char *modname = "xhc-hb04"; int hal_comp_id; const char *section = "XHC-HB04"; bool simu_mode = true; typedef struct { char pin_name[256]; unsigned int code; } xhc_button_t; typedef enum { axis_off = 0x00, axis_x = 0x11, axis_y = 0x12, axis_z = 0x13, axis_a = 0x18, axis_spindle = 0x14, axis_feed = 0x15 } xhc_axis_t; #define NB_MAX_BUTTONS 32 #define STEPSIZE_BYTE 35 #define FLAGS_BYTE 36 // the defines below were found for an 18 button device // bit 'or' patterns for STEPSIZE_BYTE #define DISPLAY_HOME_ICON 0x10 #define DISPLAY_HEIGHT_SETTING_ICON 0x20 #define DISPLAY_HEIGHT_UNKNOWN_40 0x40 #define DISPLAY_HEIGHT_UNKNOWN_80 0x80 #define STEPSIZE_DISPLAY_0 0x00 #define STEPSIZE_DISPLAY_1 0x01 #define STEPSIZE_DISPLAY_5 0x02 #define STEPSIZE_DISPLAY_10 0x03 #define STEPSIZE_DISPLAY_20 0x04 #define STEPSIZE_DISPLAY_30 0x05 #define STEPSIZE_DISPLAY_40 0x06 #define STEPSIZE_DISPLAY_50 0x07 #define STEPSIZE_DISPLAY_100 0x08 #define STEPSIZE_DISPLAY_500 0x09 #define STEPSIZE_DISPLAY_1000 0x0A #define STEPSIZE_DISPLAY_P6 0x0B #define STEPSIZE_DISPLAY_UNKNOWN_0C 0x0C #define STEPSIZE_DISPLAY_UNKNOWN_0D 0x0D #define STEPSIZE_DISPLAY_UNKNOWN_0E 0x0E #define STEPSIZE_DISPLAY_UNKNOWN_0F 0x0F // guard for maximum number of items in a stepsize_sequence #define MAX_STEPSIZE_SEQUENCE 10 // alternate stepsize sequences (use STEPSIZE_DISPLAY_*), terminate with 0: static const int stepsize_sequence_1[MAX_STEPSIZE_SEQUENCE +1] = {1,10,100,1000, 0}; // default static const int stepsize_sequence_2[MAX_STEPSIZE_SEQUENCE +1] = {1, 5, 10, 20, 0}; static const int stepsize_sequence_3[MAX_STEPSIZE_SEQUENCE +1] = {1,10,100, 0}; static const int stepsize_sequence_4[MAX_STEPSIZE_SEQUENCE +1] = {1, 5, 10, 20, 50,100,0}; static const int stepsize_sequence_5[MAX_STEPSIZE_SEQUENCE +1] = {1,10, 50,100,1000, 0}; static const int* stepsize_sequence = stepsize_sequence_1; // use the default static int stepsize_idx = 0; // start at initial (zeroth) sequence static int stepsize_last_idx = 0; //calculated` typedef struct { hal_float_t *x_wc, *y_wc, *z_wc, *a_wc; hal_float_t *x_mc, *y_mc, *z_mc, *a_mc; hal_float_t *feedrate_override, *feedrate; hal_float_t *spindle_override, *spindle_rps; hal_bit_t *button_pin[NB_MAX_BUTTONS]; hal_bit_t *jog_enable_off; hal_bit_t *jog_enable_x; hal_bit_t *jog_enable_y; hal_bit_t *jog_enable_z; hal_bit_t *jog_enable_a; hal_bit_t *jog_enable_feedrate; hal_bit_t *jog_enable_spindle; hal_float_t *jog_scale; hal_s32_t *jog_counts, *jog_counts_neg; hal_float_t *jog_velocity; hal_float_t *jog_max_velocity; hal_float_t *jog_increment; hal_bit_t *jog_plus_x, *jog_plus_y, *jog_plus_z, *jog_plus_a; hal_bit_t *jog_minus_x, *jog_minus_y, *jog_minus_z, *jog_minus_a; hal_bit_t *stepsize_up; hal_bit_t *stepsize_down; hal_s32_t *stepsize; hal_bit_t *sleeping; hal_bit_t *connected; hal_bit_t *require_pendant; hal_bit_t *inch_icon; hal_bit_t *zero_x; hal_bit_t *zero_y; hal_bit_t *zero_z; hal_bit_t *zero_a; hal_bit_t *gotozero_x; hal_bit_t *gotozero_y; hal_bit_t *gotozero_z; hal_bit_t *gotozero_a; hal_bit_t *half_x; hal_bit_t *half_y; hal_bit_t *half_z; hal_bit_t *half_a; } xhc_hal_t; #define STEP_UNDEFINED -1 #define STEP_NONE 0x0 #define STEP_UP 0x1 #define STEP_DOWN 0x2 typedef struct { xhc_hal_t *hal; xhc_axis_t axis; xhc_button_t buttons[NB_MAX_BUTTONS]; unsigned char button_code; char old_inc_step_status; unsigned char button_step; // Used in simulation mode to handle the STEP increment // Variables for velocity computation hal_s32_t last_jog_counts; struct timeval last_tv; struct timeval last_wakeup; } xhc_t; static xhc_t xhc; static int do_exit = 0; static int do_reconnect = 0; static bool wait_for_pendant_before_HAL = false; struct libusb_transfer *transfer_in = NULL; unsigned char in_buf[32]; void setup_asynch_transfer(libusb_device_handle *dev_handle); extern "C" const char * iniFind(FILE *fp, const char *tag, const char *section) { IniFile f(false, fp); return(f.Find(tag, section)); } void init_xhc(xhc_t *xhc) { memset(xhc, 0, sizeof(*xhc)); xhc->old_inc_step_status = STEP_UNDEFINED; gettimeofday(&xhc->last_wakeup, NULL); } int xhc_encode_float(float v, unsigned char *buf) { unsigned int int_v = round(fabs(v) * 10000.0); unsigned short int_part = int_v / 10000; unsigned short fract_part = int_v % 10000; if (v < 0) fract_part = fract_part | 0x8000; *(short *)buf = int_part; *((short *)buf+1) = fract_part; return 4; } int xhc_encode_s16(int v, unsigned char *buf) { *(short *)buf = v; return 2; } void xhc_display_encode(xhc_t *xhc, unsigned char *data, int len) { unsigned char buf[6*7]; unsigned char *p = buf; int i; int packet; assert(len == 6*8); memset(buf, 0, sizeof(buf)); *p++ = 0xFE; *p++ = 0xFD; *p++ = 0x0C; if (xhc->axis == axis_a) p += xhc_encode_float(round(1000 * *(xhc->hal->a_wc)) / 1000, p); else p += xhc_encode_float(round(1000 * *(xhc->hal->x_wc)) / 1000, p); p += xhc_encode_float(round(1000 * *(xhc->hal->y_wc)) / 1000, p); p += xhc_encode_float(round(1000 * *(xhc->hal->z_wc)) / 1000, p); if (xhc->axis == axis_a) p += xhc_encode_float(round(1000 * *(xhc->hal->a_mc)) / 1000, p); else p += xhc_encode_float(round(1000 * *(xhc->hal->x_mc)) / 1000, p); p += xhc_encode_float(round(1000 * *(xhc->hal->y_mc)) / 1000, p); p += xhc_encode_float(round(1000 * *(xhc->hal->z_mc)) / 1000, p); p += xhc_encode_s16(round(100.0 * *(xhc->hal->feedrate_override)), p); p += xhc_encode_s16(round(100.0 * *(xhc->hal->spindle_override)), p); p += xhc_encode_s16(round(60.0 * *(xhc->hal->feedrate)), p); p += xhc_encode_s16(round(60.0 * *(xhc->hal->spindle_rps)), p); switch (*(xhc->hal->stepsize)) { case 0: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_0; break; case 1: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_1; break; case 5: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_5; break; case 10: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_10; break; case 20: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_20; break; case 30: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_30; break; case 40: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_40; break; case 50: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_50; break; case 100: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_100; break; case 500: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_500; break; case 1000: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_1000; break; default: //stepsize not supported on the display: buf[STEPSIZE_BYTE] = STEPSIZE_DISPLAY_0; break; } buf[FLAGS_BYTE] = 0; if (*(xhc->hal->inch_icon)) { buf[FLAGS_BYTE] |= 0x80; } // Multiplex to 6 USB transactions p = buf; for (packet=0; packet<6; packet++) { for (i=0; i<8; i++) { if (i == 0) data[i+8*packet] = 6; else data[i+8*packet] = *p++; } } } void xhc_set_display(libusb_device_handle *dev_handle, xhc_t *xhc) { unsigned char data[6*8]; int packet; xhc_display_encode(xhc, data, sizeof(data)); for (packet=0; packet<6; packet++) { int r = libusb_control_transfer(dev_handle, LIBUSB_DT_HID, //bmRequestType 0x21 LIBUSB_REQUEST_SET_CONFIGURATION, //bRequest 0x09 0x0306, //wValue 0x00, //wIndex data+8*packet, //*data 8, //wLength 0); //timeout if (r < 0) { do_reconnect = 1; } } } void hexdump(unsigned char *data, int len) { int i; for (i=0; i<len; i++) printf("%02X ", data[i]); } void linuxcnc_simu(xhc_t *xhc) { static int last_jog_counts; xhc_hal_t *hal = xhc->hal; // for simu, always step up *(hal->stepsize_up) = (xhc->button_step && xhc->button_code == xhc->button_step); if (*(hal->jog_counts) != last_jog_counts) { int delta_int = *(hal->jog_counts) - last_jog_counts; float delta = delta_int * *(hal->jog_scale); if (*(hal->jog_enable_x)) { *(hal->x_mc) += delta; *(hal->x_wc) += delta; } if (*(hal->jog_enable_y)) { *(hal->y_mc) += delta; *(hal->y_wc) += delta; } if (*(hal->jog_enable_z)) { *(hal->z_mc) += delta; *(hal->z_wc) += delta; } if (*(hal->jog_enable_a)) { *(hal->a_mc) += delta; *(hal->a_wc) += delta; } if (*(hal->jog_enable_spindle)) { *(hal->spindle_override) += delta_int * 0.01; if (*(hal->spindle_override) > 1) *(hal->spindle_override) = 1; if (*(hal->spindle_override) < 0) *(hal->spindle_override) = 0; *(hal->spindle_rps) = 25000.0/60.0 * *(hal->spindle_override); } if (*(hal->jog_enable_feedrate)) { *(hal->feedrate_override) += delta_int * 0.01; if (*(hal->feedrate_override) > 1) *(hal->feedrate_override) = 1; if (*(hal->feedrate_override) < 0) *(hal->feedrate_override) = 0; *(hal->feedrate) = 3000.0/60.0 * *(hal->feedrate_override); } last_jog_counts = *(hal->jog_counts); } } void compute_velocity(xhc_t *xhc) { timeval now, delta_tv; gettimeofday(&now, NULL); if (xhc->last_tv.tv_sec == 0) xhc->last_tv = now; timersub(&now, &xhc->last_tv, &delta_tv); float elapsed = delta_tv.tv_sec + 1e-6f*delta_tv.tv_usec; if (elapsed <= 0) return; float delta_pos = (*(xhc->hal->jog_counts) - xhc->last_jog_counts) * *(xhc->hal->jog_scale); float velocity = *(xhc->hal->jog_max_velocity) * 60.0f * *(xhc->hal->jog_scale); float k = 0.05f; if (delta_pos) { *(xhc->hal->jog_velocity) = (1 - k) * *(xhc->hal->jog_velocity) + k * velocity; *(xhc->hal->jog_increment) = fabs(delta_pos); *(xhc->hal->jog_plus_x) = (delta_pos > 0) && *(xhc->hal->jog_enable_x); *(xhc->hal->jog_minus_x) = (delta_pos < 0) && *(xhc->hal->jog_enable_x); *(xhc->hal->jog_plus_y) = (delta_pos > 0) && *(xhc->hal->jog_enable_y); *(xhc->hal->jog_minus_y) = (delta_pos < 0) && *(xhc->hal->jog_enable_y); *(xhc->hal->jog_plus_z) = (delta_pos > 0) && *(xhc->hal->jog_enable_z); *(xhc->hal->jog_minus_z) = (delta_pos < 0) && *(xhc->hal->jog_enable_z); *(xhc->hal->jog_plus_a) = (delta_pos > 0) && *(xhc->hal->jog_enable_a); *(xhc->hal->jog_minus_a) = (delta_pos < 0) && *(xhc->hal->jog_enable_a); xhc->last_jog_counts = *(xhc->hal->jog_counts); xhc->last_tv = now; } else { *(xhc->hal->jog_velocity) = (1 - k) * *(xhc->hal->jog_velocity); if (elapsed > 0.25) { *(xhc->hal->jog_velocity) = 0; *(xhc->hal->jog_plus_x) = 0; *(xhc->hal->jog_minus_x) = 0; *(xhc->hal->jog_plus_y) = 0; *(xhc->hal->jog_minus_y) = 0; *(xhc->hal->jog_plus_z) = 0; *(xhc->hal->jog_minus_z) = 0; *(xhc->hal->jog_plus_a) = 0; *(xhc->hal->jog_minus_a) = 0; } } } void handle_step(xhc_t *xhc) { int _inc_step_status = STEP_NONE; int _stepsize = *(xhc->hal->stepsize); // Use a local variable to avoid STEP display as 0 on pendant during transitions if (*(xhc->hal->stepsize_up)) { _inc_step_status = STEP_UP; if (*(xhc->hal->stepsize_down)) { _inc_step_status = STEP_NONE; // none if both pressed } } else if (*(xhc->hal->stepsize_down)) { _inc_step_status = STEP_DOWN; } else { _inc_step_status = STEP_NONE; } if (_inc_step_status != xhc->old_inc_step_status) { if (_inc_step_status == STEP_UP) { stepsize_idx++; // restart idx when 0 terminator reached: if (stepsize_sequence[stepsize_idx] == 0) stepsize_idx = 0; } if (_inc_step_status == STEP_DOWN) { stepsize_idx--; // restart at stepsize_last_idx when stepsize_idx < 0 if (stepsize_idx < 0) stepsize_idx = stepsize_last_idx; } _stepsize = stepsize_sequence[stepsize_idx]; } xhc->old_inc_step_status = _inc_step_status; *(xhc->hal->stepsize) = _stepsize; *(xhc->hal->jog_scale) = *(xhc->hal->stepsize) * 0.001f; } void cb_response_in(struct libusb_transfer *transfer) { int i; if (transfer->actual_length > 0) { if (simu_mode) hexdump(in_buf, transfer->actual_length); xhc.button_code = in_buf[1]; xhc.axis = (xhc_axis_t)in_buf[3]; *(xhc.hal->jog_counts) += ((signed char)in_buf[4]); *(xhc.hal->jog_counts_neg) = - *(xhc.hal->jog_counts); *(xhc.hal->jog_enable_off) = (xhc.axis == axis_off); *(xhc.hal->jog_enable_x) = (xhc.axis == axis_x); *(xhc.hal->jog_enable_y) = (xhc.axis == axis_y); *(xhc.hal->jog_enable_z) = (xhc.axis == axis_z); *(xhc.hal->jog_enable_a) = (xhc.axis == axis_a); *(xhc.hal->jog_enable_feedrate) = (xhc.axis == axis_feed); *(xhc.hal->jog_enable_spindle) = (xhc.axis == axis_spindle); for (i=0; i<NB_MAX_BUTTONS; i++) { if (!xhc.hal->button_pin[i]) continue; *(xhc.hal->button_pin[i]) = (xhc.button_code == xhc.buttons[i].code); if (strcmp("button-zero", xhc.buttons[i].pin_name) == 0) { *(xhc.hal->zero_x) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x); *(xhc.hal->zero_y) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y); *(xhc.hal->zero_z) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z); *(xhc.hal->zero_a) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a); } if (strcmp("button-goto-zero", xhc.buttons[i].pin_name) == 0) { *(xhc.hal->gotozero_x) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x); *(xhc.hal->gotozero_y) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y); *(xhc.hal->gotozero_z) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z); *(xhc.hal->gotozero_a) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a); } if (strcmp("button-half", xhc.buttons[i].pin_name) == 0) { *(xhc.hal->half_x) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_x); *(xhc.hal->half_y) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_y); *(xhc.hal->half_z) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_z); *(xhc.hal->half_a) = (xhc.button_code == xhc.buttons[i].code) && (xhc.axis == axis_a); } if (simu_mode && *(xhc.hal->button_pin[i])) { printf("%s pressed", xhc.buttons[i].pin_name); } } if (simu_mode) { if ((signed char)in_buf[4] != 0) printf(" delta %+3d",(signed char)in_buf[4]); printf("\n"); } //detect pendant going to sleep (occurs for 18 button pendant) if ( in_buf[0]==0x04 && in_buf[1]==0 && in_buf[2]==0 && in_buf[3]==0 && in_buf[4]==0 && in_buf[5]==0) { *(xhc.hal->sleeping) = 1; if (simu_mode) { struct timeval now; gettimeofday(&now, NULL); fprintf(stderr,"Sleep, idle for %ld seconds\n", now.tv_sec - xhc.last_wakeup.tv_sec); } } else { gettimeofday(&xhc.last_wakeup, NULL); if (*(xhc.hal->sleeping)) { if (simu_mode) { fprintf(stderr,"Wake\n"); } } *(xhc.hal->sleeping) = 0; } } libusb_submit_transfer(transfer); } void setup_asynch_transfer(libusb_device_handle *dev_handle) { libusb_fill_bulk_transfer( transfer_in, dev_handle, (0x1 | LIBUSB_ENDPOINT_IN), in_buf, sizeof(in_buf), cb_response_in, NULL, 0); // no user data libusb_submit_transfer(transfer_in); } static void quit(int sig) { do_exit = 1; } static int hal_pin_simu(char *pin_name, void **ptr, int s) { printf("Creating pin: %s\n", pin_name); *ptr = calloc(s, 1); return 0; } int _hal_pin_float_newf(hal_pin_dir_t dir, hal_float_t ** data_ptr_addr, int comp_id, const char *fmt, ...) { char pin_name[256]; va_list args; va_start(args,fmt); vsprintf(pin_name, fmt, args); va_end(args); if (simu_mode) { return hal_pin_simu(pin_name, ( void**)data_ptr_addr, sizeof(*data_ptr_addr)); } else { return hal_pin_float_new(pin_name, dir, data_ptr_addr, comp_id); } } int _hal_pin_s32_newf(hal_pin_dir_t dir, hal_s32_t ** data_ptr_addr, int comp_id, const char *fmt, ...) { char pin_name[256]; va_list args; va_start(args,fmt); vsprintf(pin_name, fmt, args); va_end(args); if (simu_mode) { return hal_pin_simu(pin_name, ( void**)data_ptr_addr, sizeof(*data_ptr_addr)); } else { return hal_pin_s32_new(pin_name, dir, data_ptr_addr, comp_id); } } int _hal_pin_bit_newf(hal_pin_dir_t dir, hal_bit_t ** data_ptr_addr, int comp_id, const char *fmt, ...) { char pin_name[256]; va_list args; va_start(args,fmt); vsprintf(pin_name, fmt, args); va_end(args); if (simu_mode) { return hal_pin_simu(pin_name, ( void**)data_ptr_addr, sizeof(*data_ptr_addr)); } else { return hal_pin_bit_new(pin_name, dir, data_ptr_addr, comp_id); } } static void hal_setup() { int r, i; if (!simu_mode) { hal_comp_id = hal_init(modname); if (hal_comp_id < 1) { fprintf(stderr, "%s: ERROR: hal_init failed\n", modname); exit(1); } xhc.hal = (xhc_hal_t *)hal_malloc(sizeof(xhc_hal_t)); if (xhc.hal == NULL) { fprintf(stderr, "%s: ERROR: unable to allocate HAL shared memory\n", modname); exit(1); } } else { xhc.hal = (xhc_hal_t *)calloc(sizeof(xhc_hal_t), 1); } r = 0; r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->x_mc), hal_comp_id, "%s.x.pos-absolute", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->y_mc), hal_comp_id, "%s.y.pos-absolute", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->z_mc), hal_comp_id, "%s.z.pos-absolute", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->a_mc), hal_comp_id, "%s.a.pos-absolute", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->x_wc), hal_comp_id, "%s.x.pos-relative", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->y_wc), hal_comp_id, "%s.y.pos-relative", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->z_wc), hal_comp_id, "%s.z.pos-relative", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->a_wc), hal_comp_id, "%s.a.pos-relative", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->feedrate), hal_comp_id, "%s.feed-value", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->feedrate_override), hal_comp_id, "%s.feed-override", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->spindle_rps), hal_comp_id, "%s.spindle-rps", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->spindle_override), hal_comp_id, "%s.spindle-override", modname); for (i=0; i<NB_MAX_BUTTONS; i++) { if (!xhc.buttons[i].pin_name[0]) continue; r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->button_pin[i]), hal_comp_id, "%s.%s", modname, xhc.buttons[i].pin_name); if (strcmp("button-zero", xhc.buttons[i].pin_name) == 0) { r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->zero_x), hal_comp_id, "%s.%s-x", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->zero_y), hal_comp_id, "%s.%s-y", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->zero_z), hal_comp_id, "%s.%s-z", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->zero_a), hal_comp_id, "%s.%s-a", modname, xhc.buttons[i].pin_name); } if (strcmp("button-goto-zero", xhc.buttons[i].pin_name) == 0) { r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->gotozero_x), hal_comp_id, "%s.%s-x", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->gotozero_y), hal_comp_id, "%s.%s-y", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->gotozero_z), hal_comp_id, "%s.%s-z", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->gotozero_a), hal_comp_id, "%s.%s-a", modname, xhc.buttons[i].pin_name); } if (strcmp("button-half", xhc.buttons[i].pin_name) == 0) { r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->half_x), hal_comp_id, "%s.%s-x", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->half_y), hal_comp_id, "%s.%s-y", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->half_z), hal_comp_id, "%s.%s-z", modname, xhc.buttons[i].pin_name); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->half_a), hal_comp_id, "%s.%s-a", modname, xhc.buttons[i].pin_name); } if (strcmp("button-step", xhc.buttons[i].pin_name) == 0) xhc.button_step = xhc.buttons[i].code; } r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->sleeping), hal_comp_id, "%s.sleeping", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->connected), hal_comp_id, "%s.connected", modname); r |= _hal_pin_bit_newf(HAL_IN, &(xhc.hal->stepsize_up), hal_comp_id, "%s.stepsize-up", modname); r |= _hal_pin_bit_newf(HAL_IN, &(xhc.hal->stepsize_down), hal_comp_id, "%s.stepsize-down", modname); r |= _hal_pin_s32_newf(HAL_OUT, &(xhc.hal->stepsize), hal_comp_id, "%s.stepsize", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->require_pendant), hal_comp_id, "%s.require_pendant", modname); r |= _hal_pin_bit_newf(HAL_IN, &(xhc.hal->inch_icon), hal_comp_id, "%s.inch-icon", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_enable_off), hal_comp_id, "%s.jog.enable-off", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_enable_x), hal_comp_id, "%s.jog.enable-x", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_enable_y), hal_comp_id, "%s.jog.enable-y", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_enable_z), hal_comp_id, "%s.jog.enable-z", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_enable_a), hal_comp_id, "%s.jog.enable-a", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_enable_feedrate), hal_comp_id, "%s.jog.enable-feed-override", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_enable_spindle), hal_comp_id, "%s.jog.enable-spindle-override", modname); r |= _hal_pin_float_newf(HAL_OUT, &(xhc.hal->jog_scale), hal_comp_id, "%s.jog.scale", modname); r |= _hal_pin_s32_newf(HAL_OUT, &(xhc.hal->jog_counts), hal_comp_id, "%s.jog.counts", modname); r |= _hal_pin_s32_newf(HAL_OUT, &(xhc.hal->jog_counts_neg), hal_comp_id, "%s.jog.counts-neg", modname); r |= _hal_pin_float_newf(HAL_OUT, &(xhc.hal->jog_velocity), hal_comp_id, "%s.jog.velocity", modname); r |= _hal_pin_float_newf(HAL_IN, &(xhc.hal->jog_max_velocity), hal_comp_id, "%s.jog.max-velocity", modname); r |= _hal_pin_float_newf(HAL_OUT, &(xhc.hal->jog_increment), hal_comp_id, "%s.jog.increment", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_plus_x), hal_comp_id, "%s.jog.plus-x", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_minus_x), hal_comp_id, "%s.jog.minus-x", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_plus_y), hal_comp_id, "%s.jog.plus-y", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_minus_y), hal_comp_id, "%s.jog.minus-y", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_plus_z), hal_comp_id, "%s.jog.plus-z", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_minus_z), hal_comp_id, "%s.jog.minus-z", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_plus_a), hal_comp_id, "%s.jog.plus-a", modname); r |= _hal_pin_bit_newf(HAL_OUT, &(xhc.hal->jog_minus_a), hal_comp_id, "%s.jog.minus-a", modname); return; } int read_ini_file(char *filename) { FILE *fd = fopen(filename, "r"); const char *bt; int nb_buttons = 0; if (!fd) { perror(filename); return -1; } IniFile f(false, fd); while ( (bt = f.Find("BUTTON", section, nb_buttons+1)) && nb_buttons < NB_MAX_BUTTONS) { if (sscanf(bt, "%x:%s", &xhc.buttons[nb_buttons].code, xhc.buttons[nb_buttons].pin_name) !=2 ) { fprintf(stderr, "%s: syntax error\n", bt); return -1; } nb_buttons++; } return 0; } #define STRINGIFY_IMPL(S) #S #define STRINGIFY(s) STRINGIFY_IMPL(s) static void Usage(char *name) { fprintf(stderr, "%s version %s by Frederic RIBLE (frible@teaser.fr)\n", name, PACKAGE_VERSION); fprintf(stderr, "\n"); fprintf(stderr, "Usage: %s [-I button-cfg-file] [-h] [-H] [-s n]\n", name); fprintf(stderr, " -I button-cfg-file: configuration file defining the MPG keyboard layout\n"); fprintf(stderr, " -h: usage (this)\n"); fprintf(stderr, " -H: run in real-time HAL mode (run in simulation mode by default)\n"); fprintf(stderr, " -x: wait for pendant detection before creating HAL pins\n"); fprintf(stderr, " -s: step sequence (multiplied by 0.001 unit):\n"); fprintf(stderr, " 1: 1,10,100,1000 (default)\n"); fprintf(stderr, " 2: 1,5,10,20\n"); fprintf(stderr, " 3: 1,10,100\n"); fprintf(stderr, " 4: 1,5,10,20,50,100\n"); fprintf(stderr, " 5: 1,10,50,100,1000\n"); fprintf(stderr, "\n"); fprintf(stderr, "Configuration file section format:\n"); fprintf(stderr, "[XHC-HB04]\n"); fprintf(stderr, "BUTTON=XN:button-thenameN\n"); fprintf(stderr, "...\n"); fprintf(stderr, " where XN=hexcode, button-thenameN=nameforbutton\n"); } int main (int argc,char **argv) { libusb_device **devs; libusb_device_handle *dev_handle; libusb_context *ctx = NULL; int r,idx; ssize_t cnt; #define MAX_WAIT_SECS 10 int wait_secs = 0; int opt; bool hal_ready_done = false; init_xhc(&xhc); while ((opt = getopt(argc, argv, "HhI:xs:")) != -1) { switch (opt) { case 'I': if (read_ini_file(optarg)) { printf("Problem reading ini file: %s\n\n",optarg); Usage(argv[0]); exit(EXIT_FAILURE); } break; case 'H': simu_mode = false; break; case 's': switch (optarg[0]) { case '1': stepsize_sequence = stepsize_sequence_1;break; case '2': stepsize_sequence = stepsize_sequence_2;break; case '3': stepsize_sequence = stepsize_sequence_3;break; case '4': stepsize_sequence = stepsize_sequence_4;break; case '5': stepsize_sequence = stepsize_sequence_5;break; default: printf("Unknown sequence: %s\n\n",optarg); Usage(argv[0]); exit(EXIT_FAILURE); break; } break; case 'x': wait_for_pendant_before_HAL = true; break; default: Usage(argv[0]); exit(EXIT_FAILURE); } } // compute the last valid idx for use with stepsize-down for (idx=0; idx < MAX_STEPSIZE_SEQUENCE; idx++) { if (stepsize_sequence[idx] == 0) break; } stepsize_last_idx = idx - 1; hal_setup(); signal(SIGINT, quit); signal(SIGTERM, quit); if (!wait_for_pendant_before_HAL && !simu_mode) { hal_ready(hal_comp_id); hal_ready_done = true; } while (!do_exit) { //on reconnect wait for device to be gone if (do_reconnect == 1) { sleep(5); do_reconnect = 0; } r = libusb_init(&ctx); if(r < 0) { perror("libusb_init"); return 1; } libusb_set_debug(ctx, 2); // use environmental variable LIBUSB_DEBUG if needed printf("%s: waiting for XHC-HB04 device\n",modname); *(xhc.hal->connected) = 0; wait_secs = 0; *(xhc.hal->require_pendant) = wait_for_pendant_before_HAL; *(xhc.hal->stepsize) = stepsize_sequence[0]; do { cnt = libusb_get_device_list(ctx, &devs); if (cnt < 0) { perror("libusb_get_device_list"); return 1; } dev_handle = libusb_open_device_with_vid_pid(ctx, 0x10CE, 0xEB70); libusb_free_device_list(devs, 1); if (dev_handle == NULL) { if (wait_for_pendant_before_HAL) { wait_secs++; if (wait_secs >= MAX_WAIT_SECS/2) { printf("%s: waiting for XHC-HB04 device (%d)\n",modname,wait_secs); } if (wait_secs > MAX_WAIT_SECS) { printf("%s: MAX_WAIT_SECS exceeded, exiting\n",modname); exit(1); } } sleep(1); } } while(dev_handle == NULL && !do_exit); printf("%s: found XHC-HB04 device\n",modname); if (dev_handle) { if (libusb_kernel_driver_active(dev_handle, 0) == 1) { libusb_detach_kernel_driver(dev_handle, 0); } r = libusb_claim_interface(dev_handle, 0); if (r < 0) { perror("libusb_claim_interface"); return 1; } //allocate the transfer struct here only once after successful connection transfer_in = libusb_alloc_transfer(0); } *(xhc.hal->connected) = 1; if (!hal_ready_done && !simu_mode) { hal_ready(hal_comp_id); hal_ready_done = true; } if (dev_handle) { setup_asynch_transfer(dev_handle); xhc_set_display(dev_handle, &xhc); } if (dev_handle) { while (!do_exit && !do_reconnect) { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 30000; r = libusb_handle_events_timeout(ctx, &tv); compute_velocity(&xhc); if (simu_mode) linuxcnc_simu(&xhc); handle_step(&xhc); xhc_set_display(dev_handle, &xhc); } *(xhc.hal->connected) = 0; printf("%s: connection lost, cleaning up\n",modname); libusb_cancel_transfer(transfer_in); libusb_free_transfer(transfer_in); libusb_release_interface(dev_handle, 0); libusb_close(dev_handle); } else { while (!do_exit) usleep(70000); } libusb_exit(ctx); } }
lgpl-2.1
mbenz89/soot
src/soot/coffi/Instruction_Getstatic.java
2491
/* Soot - a J*va Optimization Framework * Copyright (C) 1997 Clark Verbrugge * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ package soot.coffi; /** Instruction subclasses are used to represent parsed bytecode; each * bytecode operation has a corresponding subclass of Instruction. * <p> * Each subclass is derived from one of * <ul><li>Instruction</li> * <li>Instruction_noargs (an Instruction with no embedded arguments)</li> * <li>Instruction_byte (an Instruction with a single byte data argument)</li> * <li>Instruction_bytevar (a byte argument specifying a local variable)</li> * <li>Instruction_byteindex (a byte argument specifying a constant pool index)</li> * <li>Instruction_int (an Instruction with a single short data argument)</li> * <li>Instruction_intvar (a short argument specifying a local variable)</li> * <li>Instruction_intindex (a short argument specifying a constant pool index)</li> * <li>Instruction_intbranch (a short argument specifying a code offset)</li> * <li>Instruction_longbranch (an int argument specifying a code offset)</li> * </ul> * @author Clark Verbrugge * @see Instruction * @see Instruction_noargs * @see Instruction_byte * @see Instruction_bytevar * @see Instruction_byteindex * @see Instruction_int * @see Instruction_intvar * @see Instruction_intindex * @see Instruction_intbranch * @see Instruction_longbranch * @see Instruction_Unknown */ class Instruction_Getstatic extends Instruction_intindex { public Instruction_Getstatic() { super((byte)ByteCode.GETSTATIC); name = "getstatic"; } }
lgpl-2.1
olvidalo/exist
exist-testkit/src/main/java/org/exist/test/runner/ExtTestIgnoredFunction.java
2047
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2018 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.test.runner; import org.exist.xquery.Annotation; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.Type; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import static org.exist.xquery.FunctionDSL.param; import static org.exist.xquery.FunctionDSL.params; public class ExtTestIgnoredFunction extends JUnitIntegrationFunction { public ExtTestIgnoredFunction(final XQueryContext context, final String parentName, final RunNotifier notifier) { super("ext-test-ignored-function", params(param("name", Type.STRING, "name of the test")), context, parentName, notifier); } @Override public Sequence eval(final Sequence contextSequence, final Item contextItem) throws XPathException { final Sequence arg1 = getCurrentArguments()[0]; final String name = arg1.itemAt(0).getStringValue(); // notify JUnit notifier.fireTestIgnored(Description.createTestDescription(suiteName, name, new Annotation[0])); return Sequence.EMPTY_SEQUENCE; } }
lgpl-2.1
wolfgangmm/exist
extensions/modules/cqlparser/src/main/java/org/exist/xquery/modules/cqlparser/CQLParserModule.java
2193
/* * eXist-db Open Source Native XML Database * Copyright (C) 2001 The eXist-db Authors * * info@exist-db.org * http://www.exist-db.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.xquery.modules.cqlparser; import java.util.List; import java.util.Map; import org.exist.xquery.AbstractInternalModule; import org.exist.xquery.FunctionDef; /** * Module function definitions for a Contextual Query Language (CQL) parser. * * @author matej * @author ljo * * */ public class CQLParserModule extends AbstractInternalModule { public final static String NAMESPACE_URI = "http://exist-db.org/xquery/cqlparser"; public final static String PREFIX = "cqlparser"; public final static String INCLUSION_DATE = "2012-06-18"; public final static String RELEASED_IN_VERSION = "eXist-2.1"; private final static FunctionDef[] functions = { new FunctionDef(ParseCQL.signature, ParseCQL.class) }; // , // new FunctionDef(CQL2XCQL.signature, CQL2XCQL.class), public CQLParserModule(Map<String, List<? extends Object>> parameters) { super(functions, parameters); } public String getNamespaceURI() { return NAMESPACE_URI; } public String getDefaultPrefix() { return PREFIX; } public String getDescription() { return "A module for a Contextual Query Language (CQL) parser"; } public String getReleaseVersion() { return RELEASED_IN_VERSION; } }
lgpl-2.1
fatihzkaratana/jofc2
src/jofc2/model/Text.java
1979
/* This file is part of JOFC2. JOFC2 is free software: you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JOFC2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See <http://www.gnu.org/licenses/lgpl-3.0.txt>. */ package jofc2.model; import java.io.Serializable; public class Text implements Serializable { public static final String TEXT_ALIGN_CENTER = "center"; public static final String TEXT_ALIGN_LEFT = "left"; public static final String TEXT_ALIGN_RIGHT = "right"; private static final long serialVersionUID = -2390229886841547192L; private String text; private String style = ""; // issue 29 public Text() {} public Text(String text) { setText(text); } public Text(String text, String style) { setText(text); setStyle(style); } public String getText() { return text; } public Text setText(String text) { this.text = text; return this; } public String getStyle() { return style; } public Text setStyle(String style) { this.style = style; return this; } public static String createStyle(int fontsize, String color, String textalign) { StringBuilder sb = new StringBuilder(); if (fontsize != 0) { sb.append("font-size: "); sb.append(fontsize); sb.append("px;"); } if (color != null) { sb.append("color: "); sb.append(color); sb.append(";"); } if (textalign != null) { sb.append("text-align: "); sb.append(textalign); sb.append(";"); } return sb.toString(); } public static String createStyle(int fontsize){ return createStyle(fontsize, null, null); } }
lgpl-3.0
billhj/Etoile
extern/rbdl/addons/benchmark/model_generator.cc
1543
#include "model_generator.h" #include "rbdl/rbdl.h" using namespace RigidBodyDynamics; using namespace RigidBodyDynamics::Math; void generate_planar_tree_recursive (Model *model, unsigned int parent_body_id, int depth, double length) { if (depth == 0) return; // create left child Joint joint_rot_z (JointTypeRevolute, Vector3d (0., 0., 1.)); Body body (length, Vector3d (0., -0.25 * length, 0.), Vector3d (length, length, length)); Vector3d displacement (-0.5 * length, -0.25 * length, 0.); unsigned int child_left = model->AddBody (parent_body_id, Xtrans (displacement), joint_rot_z, body); generate_planar_tree_recursive (model, child_left, depth - 1, length * 0.4); displacement.set (0.5 * length, -0.25 * length, 0.); unsigned int child_right = model->AddBody (parent_body_id, Xtrans (displacement), joint_rot_z, body); generate_planar_tree_recursive (model, child_right, depth - 1, length * 0.4); } void generate_planar_tree (Model *model, int depth) { // we first add a single body that is hanging straight down from // (0, 0, 0). After that we generate the tree recursively such that each // call adds two children. // double length = 1.; Joint joint_rot_z (JointTypeRevolute, Vector3d (0., 0., 1.)); Body body (length, Vector3d (0., -0.25 * length, 0.), Vector3d (length, length, length)); unsigned int base_child = model->AddBody (0, Xtrans (Vector3d (0., 0., 0.)), joint_rot_z, body); generate_planar_tree_recursive ( model, base_child, depth, length * 0.4); }
lgpl-3.0
fathi-hindi/oneplace
dev/tests/api-functional/framework/Magento/TestFramework/Authentication/Rest/CurlClient.php
682
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\TestFramework\Authentication\Rest; use OAuth\Common\Http\Uri\UriInterface; /** * Custom Client implementation for cURL */ class CurlClient extends \OAuth\Common\Http\Client\CurlClient { /** * {@inheritdoc} */ public function retrieveResponse( UriInterface $endpoint, $requestBody, array $extraHeaders = [], $method = 'POST' ) { $this->setCurlParameters([CURLOPT_FAILONERROR => true]); return parent::retrieveResponse($endpoint, $requestBody, $extraHeaders, $method); } }
unlicense
Vexatos/EnderIO
src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java
1688
/* * The MIT License (MIT) * * Copyright (c) 2013 AlgorithmX2 * * 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. */ package appeng.api.features; import net.minecraft.item.ItemStack; public interface IMatterCannonAmmoRegistry { /** * register a new ammo, generally speaking this is based off of atomic weight to make it easier to guess at * * @param ammo new ammo * @param weight atomic weight */ void registerAmmo(ItemStack ammo, double weight); /** * get the penetration value for a particular ammo, 0 indicates a non-ammo. * * @param is ammo * @return 0 or a valid penetration value. */ float getPenetration(ItemStack is); }
unlicense
danr/kakoune
src/shared_string.hh
1842
#ifndef shared_string_hh_INCLUDED #define shared_string_hh_INCLUDED #include "string.hh" #include "ref_ptr.hh" #include "utils.hh" #include "hash_map.hh" #include <numeric> namespace Kakoune { struct StringData : UseMemoryDomain<MemoryDomain::SharedString> { uint32_t refcount; const int length; [[gnu::always_inline]] const char* data() const { return reinterpret_cast<const char*>(this + 1); } [[gnu::always_inline]] StringView strview() const { return {data(), length}; } private: StringData(int len) : refcount(0), length(len) {} static constexpr uint32_t interned_flag = 1 << 31; static constexpr uint32_t refcount_mask = ~interned_flag; struct PtrPolicy { static void inc_ref(StringData* r, void*) noexcept { ++r->refcount; } static void dec_ref(StringData* r, void*) noexcept { if ((--r->refcount & refcount_mask) == 0) { if (r->refcount & interned_flag) Registry::instance().remove(r->strview()); StringData::operator delete(r, sizeof(StringData) + r->length + 1); } } static void ptr_moved(StringData*, void*, void*) noexcept {} }; public: using Ptr = RefPtr<StringData, PtrPolicy>; class Registry : public Singleton<Registry> { public: void debug_stats() const; Ptr intern(StringView str); void remove(StringView str); private: HashMap<StringView, StringData*, MemoryDomain::SharedString> m_strings; }; static Ptr create(ArrayView<const StringView> strs); }; using StringDataPtr = StringData::Ptr; using StringRegistry = StringData::Registry; inline StringDataPtr intern(StringView str) { return StringRegistry::instance().intern(str); } } #endif // shared_string_hh_INCLUDED
unlicense
KaranToor/MA450
google-cloud-sdk/.install/.backup/lib/googlecloudsdk/command_lib/service_management/completion_callbacks.py
2027
# Copyright 2016 Google Inc. All Rights Reserved. # # 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. """Callback functions for tab completion.""" from googlecloudsdk.core import exceptions def _ServiceFlagCompletionCallback(list_type, project): """Callback function for service tab-completion. Args: list_type: str, should be one of 'produced', 'enabled', or 'available' project: str, the name of the project for which to retrieve candidates Returns: The list of arguments that the gcloud infrastructure will use to retrieve candidate services. """ # Sanity check the type of list_type argument if not isinstance(list_type, basestring): raise exceptions.InternalError( 'Could not read list type in service flag completion callback.') # Sanity check the list_type contents if list_type not in ['produced', 'enabled']: raise exceptions.InternalError( 'Invalid list type in service flag completion callback.') result = ['service-management', 'list', '--%s' % list_type, '--format=value(serviceConfig.name)'] if project: result.extend(['--project', project]) return result def ProducerServiceFlagCompletionCallback(parsed_args): return _ServiceFlagCompletionCallback('produced', getattr(parsed_args, 'project', None)) def ConsumerServiceFlagCompletionCallback(parsed_args): return _ServiceFlagCompletionCallback('enabled', getattr(parsed_args, 'project', None))
apache-2.0
porcelli-forks/kie-wb-common
kie-wb-common-widgets/kie-wb-metadata-widget/src/test/java/org/kie/workbench/common/widgets/metadata/client/widget/ExternalLinkPresenterTest.java
2951
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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. */ package org.kie.workbench.common.widgets.metadata.client.widget; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.uberfire.client.callbacks.Callback; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ExternalLinkPresenterTest { @Mock private ExternalLinkView view; private ExternalLinkPresenter presenter; @Before public void setUp() throws Exception { presenter = new ExternalLinkPresenter(view); } @Test public void presenterSet() throws Exception { verify(view).init(presenter); } @Test public void setLink() throws Exception { presenter.setLink("http://www.drools.org"); verify(view).setLinkModeVisibility(true); verify(view).setEditModeVisibility(false); verify(view).setLink("http://www.drools.org"); verify(view).setText("http://www.drools.org"); } @Test public void setEmptyShowsEditModeAutomatically() throws Exception { presenter.setLink(""); verify(view).setLinkModeVisibility(false); verify(view).setEditModeVisibility(true); verify(view).setText(""); } @Test public void setNullShowsEditModeAutomaticallyWithEmptyText() throws Exception { presenter.setLink(null); verify(view).setLinkModeVisibility(false); verify(view).setEditModeVisibility(true); verify(view).setText(""); } @Test(expected = IllegalStateException.class) public void editNoCallbackSet() throws Exception { presenter.onTextChange("hello"); } @Test public void edit() throws Exception { final Callback callback = mock(Callback.class); presenter.addChangeCallback(callback); presenter.onTextChange("hello"); verify(callback).callback("hello"); } @Test public void editDone() throws Exception { when(view.getTextBoxText()).thenReturn("hi"); presenter.onTextChangeDone(); verify(view).setLink("hi"); verify(view).setLinkModeVisibility(true); verify(view).setEditModeVisibility(false); } }
apache-2.0
wiltonlazary/arangodb
3rdParty/velocypack/src/Utf8Helper.cpp
2610
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Max Neunhoeffer /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "velocypack/velocypack-common.h" #include "velocypack/Utf8Helper.h" using namespace arangodb::velocypack; namespace { static constexpr uint8_t ValidChar = 0; static constexpr uint8_t InvalidChar = 1; static const uint8_t states[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df 0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef 0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff 0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2 1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4 1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6 1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8 }; } bool Utf8Helper::isValidUtf8(uint8_t const* p, ValueLength len) { uint8_t const* end = p + len; uint8_t state = ValidChar; while (p < end) { state = states[256 + state * 16 + states[*p++]]; if (state == InvalidChar) { return false; } } return (state == ValidChar); }
apache-2.0
atomicjets/summingbird
summingbird-batch-hadoop/src/main/scala/com/twitter/summingbird/batch/state/FileVersionTracking.scala
2421
/* Copyright 2013 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.summingbird.batch.state import org.apache.hadoop.fs.FileSystem import org.apache.hadoop.fs.Path import scala.collection.JavaConverters._ import scala.util.{ Try, Success, Failure } import org.slf4j.LoggerFactory private[summingbird] object FileVersionTracking { @transient private val logger = LoggerFactory.getLogger(classOf[FileVersionTracking]) val FINISHED_VERSION_SUFFIX = ".version" implicit def path(strPath: String): Path = new Path(strPath) def path(basePath: String, fileName: String): Path = new Path(basePath, fileName) } private[summingbird] case class FileVersionTracking(root: String, fs: FileSystem) { import FileVersionTracking._ fs.mkdirs(root) def mostRecentVersion: Option[Long] = getAllVersions.headOption def failVersion(version: Long) = deleteVersion(version) def deleteVersion(version: Long) = fs.delete(tokenPath(version), false) def succeedVersion(version: Long) = fs.createNewFile(tokenPath(version)) private def getOnDiskVersions: List[Try[Long]] = listDir(root) .filter(p => !(p.getName.startsWith("_"))) .filter(_.getName().endsWith(FINISHED_VERSION_SUFFIX)) .map(f => parseVersion(f.toString())) private def logVersion(v: Try[Long]) = logger.debug("Version on disk : " + v.toString) def getAllVersions: List[Long] = getOnDiskVersions .map { v => logVersion(v) v } .collect { case Success(s) => s } .sorted .reverse def hasVersion(version: Long) = getAllVersions.contains(version) def tokenPath(version: Long): Path = path(root, version.toString + FINISHED_VERSION_SUFFIX) def parseVersion(p: String): Try[Long] = Try(p.getName().dropRight(FINISHED_VERSION_SUFFIX.length()).toLong) def listDir(dir: String): List[Path] = fs.listStatus(dir).map(_.getPath).toList }
apache-2.0
DeezCashews/spring-boot
spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnJndiTests.java
5541
/* * Copyright 2012-2017 the original author or authors. * * 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. */ package org.springframework.boot.autoconfigure.condition; import java.util.HashMap; import java.util.Map; import javax.naming.Context; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.boot.autoconfigure.jndi.JndiPropertiesHidingClassLoader; import org.springframework.boot.autoconfigure.jndi.TestableInitialContextFactory; import org.springframework.boot.test.util.EnvironmentTestUtils; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.type.AnnotatedTypeMetadata; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link ConditionalOnJndi} * * @author Stephane Nicoll * @author Phillip Webb * @author Andy Wilkinson */ public class ConditionalOnJndiTests { private ClassLoader threadContextClassLoader; private String initialContextFactory; private ConfigurableApplicationContext context; private MockableOnJndi condition = new MockableOnJndi(); @Before public void setupThreadContextClassLoader() { this.threadContextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( new JndiPropertiesHidingClassLoader(getClass().getClassLoader())); } @After public void close() { TestableInitialContextFactory.clearAll(); if (this.initialContextFactory != null) { System.setProperty(Context.INITIAL_CONTEXT_FACTORY, this.initialContextFactory); } else { System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); } if (this.context != null) { this.context.close(); } Thread.currentThread().setContextClassLoader(this.threadContextClassLoader); } @Test public void jndiNotAvailable() { load(JndiAvailableConfiguration.class); assertPresent(false); } @Test public void jndiAvailable() { setupJndi(); load(JndiAvailableConfiguration.class); assertPresent(true); } @Test public void jndiLocationNotBound() { setupJndi(); load(JndiConditionConfiguration.class); assertPresent(false); } @Test public void jndiLocationBound() { setupJndi(); TestableInitialContextFactory.bind("java:/FooManager", new Object()); load(JndiConditionConfiguration.class); assertPresent(true); } @Test public void jndiLocationNotFound() { ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a")); assertThat(outcome.isMatch()).isFalse(); } @Test public void jndiLocationFound() { this.condition.setFoundLocation("java:/b"); ConditionOutcome outcome = this.condition.getMatchOutcome(null, mockMetaData("java:/a", "java:/b")); assertThat(outcome.isMatch()).isTrue(); } private void setupJndi() { this.initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestableInitialContextFactory.class.getName()); } private void assertPresent(boolean expected) { assertThat(this.context.getBeansOfType(String.class)).hasSize(expected ? 1 : 0); } private void load(Class<?> config, String... environment) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(applicationContext, environment); applicationContext.register(config); applicationContext.register(JndiConditionConfiguration.class); applicationContext.refresh(); this.context = applicationContext; } private AnnotatedTypeMetadata mockMetaData(String... value) { AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.class); Map<String, Object> attributes = new HashMap<>(); attributes.put("value", value); given(metadata.getAnnotationAttributes(ConditionalOnJndi.class.getName())) .willReturn(attributes); return metadata; } @Configuration @ConditionalOnJndi static class JndiAvailableConfiguration { @Bean public String foo() { return "foo"; } } @Configuration @ConditionalOnJndi("java:/FooManager") static class JndiConditionConfiguration { @Bean public String foo() { return "foo"; } } private static class MockableOnJndi extends OnJndiCondition { private boolean jndiAvailable = true; private String foundLocation; @Override protected boolean isJndiAvailable() { return this.jndiAvailable; } @Override protected JndiLocator getJndiLocator(String[] locations) { return new JndiLocator(locations) { @Override public String lookupFirstLocation() { return MockableOnJndi.this.foundLocation; } }; } public void setFoundLocation(String foundLocation) { this.foundLocation = foundLocation; } } }
apache-2.0
bf8086/alluxio
core/server/common/src/main/java/alluxio/master/journal/StateChangeJournalContext.java
1996
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.master.journal; import alluxio.exception.status.UnavailableException; import alluxio.proto.journal.Journal.JournalEntry; import alluxio.resource.LockResource; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.concurrent.NotThreadSafe; /** * Context for correctly managing the state change lock for a wrapped journal context. */ @NotThreadSafe public final class StateChangeJournalContext implements JournalContext { private static final Logger LOG = LoggerFactory.getLogger(StateChangeJournalContext.class); private final JournalContext mJournalContext; private final LockResource mStateLockResource; /** * Constructs a {@link StateChangeJournalContext}. * * @param journalContext the journal context to wrap * @param stateLockResource the state lock resource to keep */ public StateChangeJournalContext(JournalContext journalContext, LockResource stateLockResource) { Preconditions.checkNotNull(journalContext, "journalContext"); mJournalContext = journalContext; mStateLockResource = stateLockResource; } @Override public void append(JournalEntry entry) { mJournalContext.append(entry); } @Override public void close() throws UnavailableException { try { mJournalContext.close(); } finally { // must release the state lock after the journal context is closed. mStateLockResource.close(); } } }
apache-2.0
matzew/keycloak
integration/adapter-core/src/main/java/org/keycloak/adapters/AdapterUtils.java
4336
package org.keycloak.adapters; import org.jboss.logging.Logger; import org.keycloak.KeycloakPrincipal; import org.keycloak.KeycloakSecurityContext; import org.keycloak.representations.AccessToken; import org.keycloak.util.UriUtils; import java.util.Collections; import java.util.Set; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class AdapterUtils { private static Logger log = Logger.getLogger(AdapterUtils.class); /** * Best effort to find origin for REST request calls from web UI application to REST application. In case of relative or absolute * "auth-server-url" is returned the URL from request. In case of "auth-server-url-for-backend-request" used in configuration, it returns * the origin of auth server. * * This may be the optimization in cluster, so if you have keycloak and applications on same host, the REST request doesn't need to * go through loadbalancer, but can be sent directly to same host. * * @param browserRequestURL * @param session * @return */ public static String getOriginForRestCalls(String browserRequestURL, KeycloakSecurityContext session) { if (session instanceof RefreshableKeycloakSecurityContext) { KeycloakDeployment deployment = ((RefreshableKeycloakSecurityContext)session).getDeployment(); switch (deployment.getRelativeUrls()) { case ALL_REQUESTS: case NEVER: // Resolve baseURI from the request return UriUtils.getOrigin(browserRequestURL); case BROWSER_ONLY: // Resolve baseURI from the codeURL (This is already non-relative and based on our hostname) return UriUtils.getOrigin(deployment.getTokenUrl()); default: return ""; } } else { return UriUtils.getOrigin(browserRequestURL); } } public static Set<String> getRolesFromSecurityContext(RefreshableKeycloakSecurityContext session) { Set<String> roles = null; AccessToken accessToken = session.getToken(); if (session.getDeployment().isUseResourceRoleMappings()) { if (log.isTraceEnabled()) { log.trace("useResourceRoleMappings"); } AccessToken.Access access = accessToken.getResourceAccess(session.getDeployment().getResourceName()); if (access != null) roles = access.getRoles(); } else { if (log.isTraceEnabled()) { log.trace("use realm role mappings"); } AccessToken.Access access = accessToken.getRealmAccess(); if (access != null) roles = access.getRoles(); } if (roles == null) roles = Collections.emptySet(); if (log.isTraceEnabled()) { log.trace("Setting roles: "); for (String role : roles) { log.trace(" role: " + role); } } return roles; } public static String getPrincipalName(KeycloakDeployment deployment, AccessToken token) { String attr = "sub"; if (deployment.getPrincipalAttribute() != null) attr = deployment.getPrincipalAttribute(); String name = null; if ("sub".equals(attr)) { name = token.getSubject(); } else if ("email".equals(attr)) { name = token.getEmail(); } else if ("preferred_username".equals(attr)) { name = token.getPreferredUsername(); } else if ("name".equals(attr)) { name = token.getName(); } else if ("given_name".equals(attr)) { name = token.getGivenName(); } else if ("family_name".equals(attr)) { name = token.getFamilyName(); } else if ("nickname".equals(attr)) { name = token.getNickName(); } if (name == null) name = token.getSubject(); return name; } public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> createPrincipal(KeycloakDeployment deployment, RefreshableKeycloakSecurityContext securityContext) { return new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(getPrincipalName(deployment, securityContext.getToken()), securityContext); } }
apache-2.0
walteryang47/ovirt-engine
backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/UserProfileDaoImpl.java
3428
package org.ovirt.engine.core.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.inject.Named; import javax.inject.Singleton; import org.ovirt.engine.core.common.businessentities.UserProfile; import org.ovirt.engine.core.compat.Guid; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; @Named @Singleton public class UserProfileDaoImpl extends BaseDao implements UserProfileDao { private static final class UserProfileRowMapper implements RowMapper<UserProfile> { public static final UserProfileRowMapper instance = new UserProfileRowMapper(); @Override public UserProfile mapRow(ResultSet rs, int rowNum) throws SQLException { UserProfile entity = new UserProfile(); entity.setId(getGuidDefaultEmpty(rs, "profile_id")); entity.setUserId(getGuidDefaultEmpty(rs, "user_id")); entity.setSshPublicKeyId(getGuidDefaultEmpty(rs, "ssh_public_key_id")); entity.setSshPublicKey(rs.getString("ssh_public_key")); entity.setLoginName(rs.getString("login_name")); return entity; } } @Override public UserProfile get(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("profile_id", id); return getCallsHandler().executeRead("GetUserProfileByProfileId", UserProfileRowMapper.instance, parameterSource); } @Override public UserProfile getByUserId(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("user_id", id); return getCallsHandler().executeRead("GetUserProfileByUserId", UserProfileRowMapper.instance, parameterSource); } @Override public List<UserProfile> getAll() { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource(); return getCallsHandler().executeReadList("GetAllFromUserProfiles", UserProfileRowMapper.instance, parameterSource); } private MapSqlParameterSource createIdParameterMapper(Guid id) { return getCustomMapSqlParameterSource().addValue("profile_id", id); } @Override public void save(UserProfile profile) { getCallsHandler().executeModification("InsertUserProfile", createIdParameterMapper(profile.getId()) .addValue("user_id", profile.getUserId()) .addValue("ssh_public_key_id", profile.getSshPublicKeyId()) .addValue("ssh_public_key", profile.getSshPublicKey())); } @Override public void update(UserProfile profile) { getCallsHandler().executeModification("UpdateUserProfile", createIdParameterMapper(profile.getId()) .addValue("user_id", profile.getUserId()) .addValue("ssh_public_key_id", profile.getSshPublicKeyId()) .addValue("ssh_public_key", profile.getSshPublicKey())); } @Override public void remove(Guid id) { MapSqlParameterSource parameterSource = createIdParameterMapper(id); getCallsHandler().executeModification("DeleteUserProfile", parameterSource); } }
apache-2.0
bright-sparks/enyo
source/ajax/Ajax.js
9555
(function (enyo, scope) { /** * A cache of response properties set on the {@link enyo.Ajax} instance once it has completed * its request. * * @typedef {Object} enyo.Ajax~xhrResponse * @property {Number} status - The response status. * @property {Object} headers - The headers used for the request. * @property {String} body - The request body. * @public */ /** * A [kind]{@glossary kind} designed to expose the native * [XMLHttpRequest]{@glossary XMLHttpRequest} API. Available configuration options * are exposed by {@link enyo.AjaxProperties}. * * This kind does not extend {@link enyo.Component} and cannot be used * in the [components block]{@link enyo.Component#components}. * * For more information, see the documentation on [Consuming Web * Services]{@linkplain $dev-guide/building-apps/managing-data/consuming-web-services.html} * in the Enyo Developer Guide. * * @class enyo.Ajax * @extends enyo.Async * @public */ enyo.kind( /** @lends enyo.Ajax.prototype */ { /** * @private */ name: 'enyo.Ajax', /** * @private */ kind: 'enyo.Async', /** * @private */ published: enyo.AjaxProperties, /** * @private */ constructor: enyo.inherit(function (sup) { return function (inParams) { enyo.mixin(this, inParams); sup.apply(this, arguments); }; }), /** * @private */ destroy: enyo.inherit(function (sup) { return function () { // explicilty release any XHR refs this.xhr = null; sup.apply(this, arguments); }; }), /** * This will be set once a request has completed (successfully or unsuccessfully). * It is a cache of the response values. * * @type enyo.Ajax~xhrResponse * @default null * @public */ xhrResponse: null, /** * Executes the request with the given options. The parameter may be a * [hash]{@glossary Object} of properties or a [string]{@glossary String}. Both * represent the query string, with the hash being serialized and the string * being used directly. * * ```javascript * var query = {q: 'searchTerm'}; // -> "?q=searchTerm" * ``` * * To provide a `POST` body, see {@link enyo.AjaxProperties.postBody}. * * When the request is completed, it will set the * [xhrResponse]{@link enyo.Ajax#xhrResponse} property. * * @see enyo.AjaxProperties * @see enyo.Ajax.xhrResponse * @see enyo.Ajax~xhrResponse * @param {(Object|String)} [params] - A [string]{@glossary String} or * [hash]{@glossary Object} to be used as the query string. * @returns {this} The callee for chaining. * @public */ go: function (params) { this.failed = false; this.startTimer(); this.request(params); return this; }, /** * @private */ request: function (params) { var parts = this.url.split('?'); var uri = parts.shift() || ''; var args = parts.length ? (parts.join('?').split('&')) : []; // var query = null; // if(enyo.isString(params)){ //If params parameter is a string, use it as request body query = params; } else{ //If params parameter is not a string, build a query from it if(params){ query = enyo.Ajax.objectToQuery(params); } } // if (query) { args.push(query); query = null; } if (this.cacheBust) { args.push(Math.random()); } // var url = args.length ? [uri, args.join('&')].join('?') : uri; // var xhr_headers = {}; var body; if (this.method != 'GET') { body = this.postBody; if (this.method === 'POST' && body instanceof enyo.FormData) { if (body.fake) { xhr_headers['Content-Type'] = body.getContentType(); body = body.toString(); } else { // Nothing to do as the // content-type will be // automagically set according // to the FormData } } else { xhr_headers['Content-Type'] = this.contentType; if (body instanceof Object) { if (this.contentType.match(/^application\/json(;.*)?$/) !== null) { body = JSON.stringify(body); } else if (this.contentType === 'application/x-www-form-urlencoded') { body = enyo.Ajax.objectToQuery(body); } else { body = body.toString(); } } } } enyo.mixin(xhr_headers, this.headers); // don't pass in headers structure if there are no headers defined as this messes // up CORS code for IE8-9 if (enyo.keys(xhr_headers).length === 0) { xhr_headers = undefined; } // try { this.xhr = enyo.xhr.request({ url: url, method: this.method, callback: this.bindSafely('receive'), body: body, headers: xhr_headers, sync: this.sync, username: this.username, password: this.password, xhrFields: enyo.mixin({onprogress: this.bindSafely(this.updateProgress)}, this.xhrFields), mimeType: this.mimeType }); } catch (e) { // IE can throw errors here if the XHR would fail CORS checks, // so catch and turn into a failure. this.fail(e); } }, /** * @private */ receive: function (inText, inXhr) { if (!this.failed && !this.destroyed) { var body; if (inXhr.responseType === 'arraybuffer') { body = inXhr.response; } else if (typeof inXhr.responseText === 'string') { body = inXhr.responseText; } else { // IE carrying a binary body = inXhr.responseBody; } this.xhrResponse = { status: inXhr.status, headers: enyo.Ajax.parseResponseHeaders(inXhr), body: body }; if (this.isFailure(inXhr)) { this.fail(inXhr.status); } else { this.respond(this.xhrToResponse(inXhr)); } } }, /** * @private */ fail: enyo.inherit(function (sup) { return function (inError) { // on failure, explicitly cancel the XHR to prevent // further responses. cancellation also resets the // response headers & body, if (this.xhr) { enyo.xhr.cancel(this.xhr); this.xhr = null; } sup.apply(this, arguments); }; }), /** * @private */ xhrToResponse: function (inXhr) { if (inXhr) { return this[(this.handleAs || 'text') + 'Handler'](inXhr); } }, /** * @private */ isFailure: function (inXhr) { // if any exceptions are thrown while checking fields in the xhr, // assume a failure. try { if (inXhr.responseType === 'arraybuffer') { // if we are loading binary data, don't try to access inXhr.responseText // because that throws an exception on webkit. Instead, just look for // the response. if (inXhr.status === 0 && !inXhr.response) { return true; } } else { var text = ''; // work around IE8-9 bug where accessing responseText will thrown error // for binary requests. if (typeof inXhr.responseText === 'string') { text = inXhr.responseText; } // Follow same failure policy as jQuery's Ajax code // CORS failures on FireFox will have status 0 and no responseText, // so treat that as failure. if (inXhr.status === 0 && text === '') { return true; } } // Otherwise, status 0 may be good for local file access. We treat the range // 1-199 and 300+ as failure (only 200-series code are OK). return (inXhr.status !== 0) && (inXhr.status < 200 || inXhr.status >= 300); } catch (e) { return true; } }, /** * @private */ xmlHandler: function (inXhr) { return inXhr.responseXML; }, /** * @private */ textHandler: function (inXhr) { return inXhr.responseText; }, /** * @private */ jsonHandler: function (inXhr) { var r = inXhr.responseText; try { return r && enyo.json.parse(r); } catch (x) { enyo.warn('Ajax request set to handleAs JSON but data was not in JSON format'); return r; } }, /** * @private */ binaryHandler: function (inXhr) { return inXhr.response; }, /** * @private */ updateProgress: function (event) { // IE8 doesn't properly support progress events and doesn't pass an object to the // handlers so we'll check that before continuing. if (event) { // filter out 'input' as it causes exceptions on some Firefox versions // due to unimplemented internal APIs var ev = {}; for (var k in event) { if (k !== 'input') { ev[k] = event[k]; } } this.sendProgress(event.loaded, 0, event.total, ev); } }, /** * @private */ statics: { objectToQuery: function (/*Object*/ map) { var enc = encodeURIComponent; var pairs = []; var backstop = {}; for (var name in map){ var value = map[name]; if (value != backstop[name]) { var assign = enc(name) + '='; if (enyo.isArray(value)) { for (var i=0; i < value.length; i++) { pairs.push(assign + enc(value[i])); } } else { pairs.push(assign + enc(value)); } } } return pairs.join('&'); } }, /** * @private */ protectedStatics: { parseResponseHeaders: function (xhr) { var headers = {}; var headersStr = []; if (xhr.getAllResponseHeaders) { headersStr = xhr.getAllResponseHeaders().split(/\r?\n/); } for (var i = 0; i < headersStr.length; i++) { var headerStr = headersStr[i]; var index = headerStr.indexOf(': '); if (index > 0) { var key = headerStr.substring(0, index).toLowerCase(); var val = headerStr.substring(index + 2); headers[key] = val; } } return headers; } } }); })(enyo, this);
apache-2.0
akoeplinger/roslyn
src/InteractiveWindow/Editor/Output/SortedSpans.cs
2861
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.InteractiveWindow { // TODO (tomat): could we avoid locking by using an ImmutableList? /// <summary> /// Thread safe sequence of disjoint spans ordered by start position. /// </summary> internal sealed class SortedSpans { private readonly object _mutex = new object(); private List<Span> _spans = new List<Span>(); public void Clear() { _spans = new List<Span>(); } public void Add(Span span) { Debug.Assert(_spans.Count == 0 || span.Start >= _spans.Last().End); Debug.Assert(span.Length > 0); lock (_mutex) { int last = _spans.Count - 1; if (last >= 0 && _spans[last].End == span.Start) { // merge adjacent spans: _spans[last] = new Span(_spans[last].Start, _spans[last].Length + span.Length); } else { _spans.Add(span); } } } public IEnumerable<Span> GetOverlap(Span span) { List<Span> result = null; var comparer = SpanStartComparer.Instance; lock (_mutex) { int startIndex = _spans.BinarySearch(span, comparer); if (startIndex < 0) { startIndex = ~startIndex - 1; } if (startIndex < 0) { return SpecializedCollections.EmptyEnumerable<Span>(); } int spanEnd = span.End; for (int i = startIndex; i < _spans.Count && _spans[i].Start < spanEnd; i++) { var overlap = span.Overlap(_spans[i]); if (overlap.HasValue) { if (result == null) { result = new List<Span>(); } result.Add(overlap.Value); } } } return result ?? SpecializedCollections.EmptyEnumerable<Span>(); } private sealed class SpanStartComparer : IComparer<Span> { internal static readonly SpanStartComparer Instance = new SpanStartComparer(); public int Compare(Span x, Span y) { return x.Start - y.Start; } } } }
apache-2.0
selrahal/jbpm
jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/commands/GetTaskByWorkItemIdCommand.java
1701
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. */ package org.jbpm.services.task.commands; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import org.kie.api.task.model.Task; import org.kie.internal.command.Context; @XmlRootElement(name="get-task-by-work-item-id-command") @XmlAccessorType(XmlAccessType.NONE) public class GetTaskByWorkItemIdCommand extends TaskCommand<Task> { private static final long serialVersionUID = 6296898155907765061L; @XmlElement @XmlSchemaType(name="long") private Long workItemId; public GetTaskByWorkItemIdCommand() { } public GetTaskByWorkItemIdCommand(Long workItemId) { this.workItemId = workItemId; } public Long getWorkItemId() { return workItemId; } public void setWorkItemId(Long workItemId) { this.workItemId = workItemId; } public Task execute(Context cntxt) { TaskContext context = (TaskContext) cntxt; return context.getTaskQueryService().getTaskByWorkItemId(workItemId); } }
apache-2.0
Xpray/flink
flink-libraries/flink-gelly-examples/src/main/java/org/apache/flink/graph/drivers/parameter/Parameter.java
1631
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.graph.drivers.parameter; import org.apache.flink.api.java.utils.ParameterTool; /** * Encapsulates the usage and configuration of a command-line parameter. * * @param <T> parameter value type */ public interface Parameter<T> { /** * An informal usage string. Parameter names are prefixed with "--". * * Optional parameters are enclosed by "[" and "]". * * Generic values are represented by all-caps with specific values enclosed * by "&lt;" and "&gt;". * * @return command-line usage string */ String getUsage(); /** * Read and parse the parameter value from command-line arguments. * * @param parameterTool parameter parser */ void configure(ParameterTool parameterTool); /** * Get the parameter value. * * @return parameter value */ T getValue(); }
apache-2.0
develar/netty
transport/src/main/java/io/netty/channel/ChannelConfig.java
8740
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.channel; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.socket.SocketChannelConfig; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.Map; /** * A set of configuration properties of a {@link Channel}. * <p> * Please down-cast to more specific configuration type such as * {@link SocketChannelConfig} or use {@link #setOptions(Map)} to set the * transport-specific properties: * <pre> * {@link Channel} ch = ...; * {@link SocketChannelConfig} cfg = <strong>({@link SocketChannelConfig}) ch.getConfig();</strong> * cfg.setTcpNoDelay(false); * </pre> * * <h3>Option map</h3> * * An option map property is a dynamic write-only property which allows * the configuration of a {@link Channel} without down-casting its associated * {@link ChannelConfig}. To update an option map, please call {@link #setOptions(Map)}. * <p> * All {@link ChannelConfig} has the following options: * * <table border="1" cellspacing="0" cellpadding="6"> * <tr> * <th>Name</th><th>Associated setter method</th> * </tr><tr> * <td>{@link ChannelOption#CONNECT_TIMEOUT_MILLIS}</td><td>{@link #setConnectTimeoutMillis(int)}</td> * </tr><tr> * <td>{@link ChannelOption#WRITE_SPIN_COUNT}</td><td>{@link #setWriteSpinCount(int)}</td> * </tr><tr> * <td>{@link ChannelOption#ALLOCATOR}</td><td>{@link #setAllocator(ByteBufAllocator)}</td> * </tr><tr> * <td>{@link ChannelOption#AUTO_READ}</td><td>{@link #setAutoRead(boolean)}</td> * </tr> * </table> * <p> * More options are available in the sub-types of {@link ChannelConfig}. For * example, you can configure the parameters which are specific to a TCP/IP * socket as explained in {@link SocketChannelConfig}. */ public interface ChannelConfig { /** * Return all set {@link ChannelOption}'s. */ Map<ChannelOption<?>, Object> getOptions(); /** * Sets the configuration properties from the specified {@link Map}. */ boolean setOptions(Map<ChannelOption<?>, ?> options); /** * Return the value of the given {@link ChannelOption} */ <T> T getOption(ChannelOption<T> option); /** * Sets a configuration property with the specified name and value. * To override this method properly, you must call the super class: * <pre> * public boolean setOption(ChannelOption&lt;T&gt; option, T value) { * if (super.setOption(option, value)) { * return true; * } * * if (option.equals(additionalOption)) { * .... * return true; * } * * return false; * } * </pre> * * @return {@code true} if and only if the property has been set */ <T> boolean setOption(ChannelOption<T> option, T value); /** * Returns the connect timeout of the channel in milliseconds. If the * {@link Channel} does not support connect operation, this property is not * used at all, and therefore will be ignored. * * @return the connect timeout in milliseconds. {@code 0} if disabled. */ int getConnectTimeoutMillis(); /** * Sets the connect timeout of the channel in milliseconds. If the * {@link Channel} does not support connect operation, this property is not * used at all, and therefore will be ignored. * * @param connectTimeoutMillis the connect timeout in milliseconds. * {@code 0} to disable. */ ChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis); /** * Returns the maximum number of messages to read per read loop. * a {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object) channelRead()} event. * If this value is greater than 1, an event loop might attempt to read multiple times to procure multiple messages. */ int getMaxMessagesPerRead(); /** * Sets the maximum number of messages to read per read loop. * If this value is greater than 1, an event loop might attempt to read multiple times to procure multiple messages. */ ChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead); /** * Returns the maximum loop count for a write operation until * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. * It is similar to what a spin lock is used for in concurrency programming. * It improves memory utilization and write throughput depending on * the platform that JVM runs on. The default value is {@code 16}. */ int getWriteSpinCount(); /** * Sets the maximum loop count for a write operation until * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. * It is similar to what a spin lock is used for in concurrency programming. * It improves memory utilization and write throughput depending on * the platform that JVM runs on. The default value is {@code 16}. * * @throws IllegalArgumentException * if the specified value is {@code 0} or less than {@code 0} */ ChannelConfig setWriteSpinCount(int writeSpinCount); /** * Returns {@link ByteBufAllocator} which is used for the channel * to allocate buffers. */ ByteBufAllocator getAllocator(); /** * Set the {@link ByteBufAllocator} which is used for the channel * to allocate buffers. */ ChannelConfig setAllocator(ByteBufAllocator allocator); /** * Returns {@link RecvByteBufAllocator} which is used for the channel * to allocate receive buffers. */ RecvByteBufAllocator getRecvByteBufAllocator(); /** * Set the {@link ByteBufAllocator} which is used for the channel * to allocate receive buffers. */ ChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator); /** * Returns {@code true} if and only if {@link ChannelHandlerContext#read()} will be invoked automatically so that * a user application doesn't need to call it at all. The default value is {@code true}. */ boolean isAutoRead(); /** * Sets if {@link ChannelHandlerContext#read()} will be invoked automatically so that a user application doesn't * need to call it at all. The default value is {@code true}. */ ChannelConfig setAutoRead(boolean autoRead); /** * Returns the high water mark of the write buffer. If the number of bytes * queued in the write buffer exceeds this value, {@link Channel#isWritable()} * will start to return {@code false}. */ int getWriteBufferHighWaterMark(); /** * Sets the high water mark of the write buffer. If the number of bytes * queued in the write buffer exceeds this value, {@link Channel#isWritable()} * will start to return {@code false}. */ ChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark); /** * Returns the low water mark of the write buffer. Once the number of bytes * queued in the write buffer exceeded the * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then * dropped down below this value, {@link Channel#isWritable()} will start to return * {@code true} again. */ int getWriteBufferLowWaterMark(); /** * Sets the low water mark of the write buffer. Once the number of bytes * queued in the write buffer exceeded the * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then * dropped down below this value, {@link Channel#isWritable()} will start to return * {@code true} again. */ ChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark); /** * Returns {@link MessageSizeEstimator} which is used for the channel * to detect the size of a message. */ MessageSizeEstimator getMessageSizeEstimator(); /** * Set the {@link ByteBufAllocator} which is used for the channel * to detect the size of a message. */ ChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator); }
apache-2.0
jeorme/OG-Platform
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/provider/description/interestrate/HullWhiteOneFactorProviderDiscount.java
6763
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.provider.description.interestrate; import com.opengamma.analytics.financial.instrument.index.IborIndex; import com.opengamma.analytics.financial.instrument.index.IndexON; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; import com.opengamma.analytics.financial.model.interestrate.definition.HullWhiteOneFactorPiecewiseConstantParameters; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; /** * Class describing a "market" with discounting, forward, price index and credit curves. * The forward rate are computed as the ratio of discount factors stored in YieldAndDiscountCurve. */ public class HullWhiteOneFactorProviderDiscount extends HullWhiteOneFactorProvider { /** * Constructor from existing multicurveProvider and Hull-White parameters. The given provider and parameters are used for the new provider (the same maps are used, not copied). * @param multicurves The multi-curves provider, not null * @param parameters The Hull-White one factor parameters, not null * @param ccyHW The currency for which the Hull-White parameters are valid (Hull-White on the discounting curve), not null */ public HullWhiteOneFactorProviderDiscount(final MulticurveProviderDiscount multicurves, final HullWhiteOneFactorPiecewiseConstantParameters parameters, final Currency ccyHW) { super(multicurves, parameters, ccyHW); } /** * Returns the MulticurveProvider from which the HullWhiteOneFactorProvider is composed. * @return The multi-curves provider. */ @Override public MulticurveProviderDiscount getMulticurveProvider() { return (MulticurveProviderDiscount) super.getMulticurveProvider(); } /** * Create a new copy of the provider. * @return The bundle. */ @Override public HullWhiteOneFactorProviderDiscount copy() { final MulticurveProviderDiscount multicurveProvider = getMulticurveProvider().copy(); return new HullWhiteOneFactorProviderDiscount(multicurveProvider, getHullWhiteParameters(), getHullWhiteCurrency()); } /** * Gets the discounting curve associated in a given currency in the market. * @param ccy The currency. * @return The curve. */ public YieldAndDiscountCurve getCurve(final Currency ccy) { return getMulticurveProvider().getCurve(ccy); } /** * Gets the forward curve associated to a given Ibor index in the market. * @param index The Ibor index. * @return The curve. */ public YieldAndDiscountCurve getCurve(final IborIndex index) { return getMulticurveProvider().getCurve(index); } /** * Gets the forward curve associated to a given ON index in the market. * @param index The ON index. * @return The curve. */ public YieldAndDiscountCurve getCurve(final IndexON index) { return getMulticurveProvider().getCurve(index); } /** * Sets the discounting curve for a given currency. * @param ccy The currency. * @param curve The yield curve used for discounting. */ public void setCurve(final Currency ccy, final YieldAndDiscountCurve curve) { getMulticurveProvider().setCurve(ccy, curve); } /** * Sets the curve associated to an Ibor index. * @param index The index. * @param curve The curve. */ public void setCurve(final IborIndex index, final YieldAndDiscountCurve curve) { getMulticurveProvider().setCurve(index, curve); } /** * Sets the curve associated to an ON index. * @param index The index. * @param curve The curve. */ public void setCurve(final IndexON index, final YieldAndDiscountCurve curve) { getMulticurveProvider().setCurve(index, curve); } /** * Set all the curves contains in another provider. If a currency or index is already present in the map, the associated curve is changed. * @param other The other provider. */ // TODO: REVIEW: Should we check that the curve are already present? Should we update the HW parameters. public void setAll(final HullWhiteOneFactorProviderDiscount other) { ArgumentChecker.notNull(other, "Inflation provider"); getMulticurveProvider().setAll(other.getMulticurveProvider()); } /** * Replaces the discounting curve for a given currency. * @param ccy The currency. * @param curve The yield curve used for discounting. * @throws IllegalArgumentException if curve name NOT already present */ public void replaceCurve(final Currency ccy, final YieldAndDiscountCurve curve) { getMulticurveProvider().replaceCurve(ccy, curve); } /** * Replaces the forward curve for a given index. * @param index The index. * @param curve The yield curve used for forward. * @throws IllegalArgumentException if curve name NOT already present */ public void replaceCurve(final IborIndex index, final YieldAndDiscountCurve curve) { getMulticurveProvider().replaceCurve(index, curve); } /** * Replaces a discounting curve for a currency. * @param ccy The currency * @param replacement The replacement curve * @return A new provider with the supplied discounting curve */ public HullWhiteOneFactorProviderDiscount withDiscountFactor(final Currency ccy, final YieldAndDiscountCurve replacement) { final MulticurveProviderDiscount decoratedMulticurve = getMulticurveProvider().withDiscountFactor(ccy, replacement); return new HullWhiteOneFactorProviderDiscount(decoratedMulticurve, getHullWhiteParameters(), getHullWhiteCurrency()); } /** * Replaces an ibor curve for an index. * @param index The index * @param replacement The replacement curve * @return A new provider with the supplied ibor curve */ public HullWhiteOneFactorProviderDiscount withForward(final IborIndex index, final YieldAndDiscountCurve replacement) { final MulticurveProviderDiscount decoratedMulticurve = getMulticurveProvider().withForward(index, replacement); return new HullWhiteOneFactorProviderDiscount(decoratedMulticurve, getHullWhiteParameters(), getHullWhiteCurrency()); } /** * Replaces an overnight curve for an index. * @param index The index * @param replacement The replacement curve * @return A new provider with the supplied overnight curve */ public HullWhiteOneFactorProviderDiscount withForward(final IndexON index, final YieldAndDiscountCurve replacement) { final MulticurveProviderDiscount decoratedMulticurve = getMulticurveProvider().withForward(index, replacement); return new HullWhiteOneFactorProviderDiscount(decoratedMulticurve, getHullWhiteParameters(), getHullWhiteCurrency()); } }
apache-2.0
jpkrohling/hawkular-btm
client/api/src/main/java/org/hawkular/apm/client/api/rest/AbstractRESTClient.java
11104
/* * Copyright 2015-2017 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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. */ package org.hawkular.apm.client.api.rest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.Base64; import java.util.function.Function; import java.util.stream.Collectors; import org.hawkular.apm.api.logging.Logger; import org.hawkular.apm.api.services.Criteria; import org.hawkular.apm.api.services.ServiceStatus; import org.hawkular.apm.api.utils.PropertyUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; /** * This class provides the abstract based class for REST client implementations. * * @author gbrown */ public class AbstractRESTClient implements ServiceStatus { private static final Logger log = Logger.getLogger(AbstractRESTClient.class.getName()); private static final String HAWKULAR_TENANT = "Hawkular-Tenant"; protected static final ObjectMapper mapper = new ObjectMapper(); private static final Base64.Encoder encoder = Base64.getEncoder(); private String username; private String authorization; private String uri; /** * By default rest client tries to find username and password in environmental variables. * @param uriProperty */ public AbstractRESTClient(String uriProperty) { this(PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_USERNAME), PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_PASSWORD), PropertyUtil.getProperty(uriProperty, PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_URI))); } public AbstractRESTClient(String username, String password, String url) { if (url != null && !url.isEmpty() && url.charAt(url.length() - 1) != '/') { url += '/'; } this.username = username; this.authorization = basicAuthorization(username, password); this.uri = url; } @Override public boolean isAvailable() { // Check URI is specified and starts with http, so either http: or https: return uri != null && uri.startsWith("http"); } public void setAuthorization(String username, String password) { this.authorization = basicAuthorization(username, password); } /** * Add the header values to the supplied connection. * * @param connection The connection * @param tenantId The optional tenant id */ protected void addHeaders(HttpURLConnection connection, String tenantId) { if (tenantId == null) { // Check if default tenant provided as property tenantId = PropertyUtil.getProperty(PropertyUtil.HAWKULAR_TENANT); } if (tenantId != null) { connection.setRequestProperty(HAWKULAR_TENANT, tenantId); } if (authorization != null) { connection.setRequestProperty("Authorization", authorization); } } public URL getUrl(String path, Object... args) { return getUrl(String.format(path, args)); } public URL getUrl(String path) { try { return new URL(uri + "hawkular/apm/" + path); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public <T> T withContext(String tenantId, URL url, Function<HttpURLConnection, T> function) { HttpURLConnection connection = null; try { connection = getConnectionForGetRequest(tenantId, url); return function.apply(connection); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if (connection != null) { connection.disconnect(); } } } public <T> T getResultsForUrl(String tenantId, TypeReference<T> typeReference, String path, Object... parameters) { return withContext(tenantId, getUrl(path, parameters), (connection) -> parseResultsIntoJson(connection, typeReference)); } public <T> T parseResultsIntoJson(HttpURLConnection connection, TypeReference<T> typeReference) { try { String response = getResponse(connection); if (connection.getResponseCode() == 200) { if (log.isLoggable(Logger.Level.FINEST)) { log.finest("Returned json=[" + response + "]"); } if (!response.trim().isEmpty()) { try { return mapper.readValue(response, typeReference); } catch (Throwable t) { log.log(Logger.Level.SEVERE, "Failed to deserialize", t); } } } else { if (log.isLoggable(Logger.Level.FINEST)) { log.finest("Failed to get results: status=[" + connection.getResponseCode() + "]:" + connection.getResponseMessage()); } } } catch (Exception e) { log.log(Logger.Level.SEVERE, "Failed to get results", e); } return null; } public <T> T getResultsForUrl(String tenantId, TypeReference<T> typeReference, String path, Criteria criteria) { return getResultsForUrl(tenantId, typeReference, path, encodedCriteria(criteria)); } public <T> T getResultsForUrl(String tenantId, TypeReference<T> typeReference, String path, Criteria criteria, Object arg) { return getResultsForUrl(tenantId, typeReference, path, encodedCriteria(criteria), arg); } public String encodedCriteria(Criteria criteria) { try { return URLEncoder.encode(mapper.writeValueAsString(criteria), "UTF-8"); } catch (UnsupportedEncodingException | JsonProcessingException e) { throw new RuntimeException(e); } } public HttpURLConnection getConnectionForGetRequest(String tenantId, URL url) throws IOException { return getConnectionForRequest(tenantId, url, "GET"); } public HttpURLConnection getConnectionForRequest(String tenantId, URL url, String method) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true); connection.setUseCaches(false); connection.setAllowUserInteraction(false); addHeaders(connection, tenantId); return connection; } public String getResponse(HttpURLConnection connection) throws IOException { InputStream is = connection.getInputStream(); String response; try (BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) { response = buffer.lines().collect(Collectors.joining("\n")); } return response; } public int postAsJsonTo(String tenantId, String path, Object toSerialize) { URL url = getUrl(path); return withJsonPayloadAndResults("POST", tenantId, url, toSerialize, (connection) -> { try { return connection.getResponseCode(); } catch (IOException e) { e.printStackTrace(); log.log(Logger.Level.SEVERE, String.format("Failed to post to [%s]", url), e); } return 0; }); } public <T> T withJsonPayloadAndResults(String method, String tenantId, URL url, Object toSerialize, Function<HttpURLConnection, T> function) { return withContext(tenantId, url, (connection) -> { try { connection.setRequestMethod(method); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setAllowUserInteraction(false); connection.setRequestProperty("Content-Type", "application/json"); OutputStream os = connection.getOutputStream(); os.write(mapper.writeValueAsBytes(toSerialize)); os.flush(); os.close(); return function.apply(connection); } catch (IOException e) { e.printStackTrace(); log.log(Logger.Level.SEVERE, String.format("Failed to post to [%s]", url), e); } return null; }); } public void clear(String tenantId, String path) { if (log.isLoggable(Logger.Level.FINEST)) { log.finest(String.format("Clear service at path [%s] for tenant [%s]", path, tenantId)); } URL url = getUrl(path); withContext(tenantId, url, (connection) -> { try { connection.setRequestMethod("DELETE"); if (connection.getResponseCode() == 200) { if (log.isLoggable(Logger.Level.FINEST)) { log.finest(String.format("Service at [%s] cleared", path)); } } else { if (log.isLoggable(Logger.Level.FINEST)) { log.warning("Failed to clear analytics: status=[" + connection.getResponseCode() + "]:" + connection.getResponseMessage()); } } } catch (IOException e) { e.printStackTrace(); log.log(Logger.Level.SEVERE, String.format("Failed to send 'clear' request to service [%s]", path), e); } return null; }); } private String basicAuthorization(String username, String password) { if (username == null || password == null) { return null; } return "Basic " + encoder.encodeToString((username + ":" + password).getBytes()); } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("REST client uri="); builder.append(uri); if (username != null) { builder.append(" username="); builder.append(username); } return builder.toString(); } }
apache-2.0
jeorme/OG-Platform
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/provider/calculator/blackforex/ForwardVegaForexBlackSmileCalculator.java
1741
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.provider.calculator.blackforex; import com.opengamma.analytics.financial.forex.derivative.ForexOptionVanilla; import com.opengamma.analytics.financial.forex.provider.ForexOptionVanillaBlackSmileMethod; import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitorAdapter; import com.opengamma.analytics.financial.provider.description.forex.BlackForexSmileProviderInterface; /** * Calculates the forward vega (first order derivative with respect to the implied volatility) for Forex derivatives in the Black (Garman-Kohlhagen) world. */ public class ForwardVegaForexBlackSmileCalculator extends InstrumentDerivativeVisitorAdapter<BlackForexSmileProviderInterface, Double> { /** * The unique instance of the calculator. */ private static final ForwardVegaForexBlackSmileCalculator INSTANCE = new ForwardVegaForexBlackSmileCalculator(); /** * Gets the calculator instance. * @return The calculator. */ public static ForwardVegaForexBlackSmileCalculator getInstance() { return INSTANCE; } /** * Constructor. */ ForwardVegaForexBlackSmileCalculator() { } /** * The methods used by the different instruments. */ private static final ForexOptionVanillaBlackSmileMethod METHOD_FXOPTIONVANILLA = ForexOptionVanillaBlackSmileMethod.getInstance(); @Override public Double visitForexOptionVanilla(final ForexOptionVanilla optionForex, final BlackForexSmileProviderInterface smileMulticurves) { return METHOD_FXOPTIONVANILLA.forwardVegaTheoretical(optionForex, smileMulticurves); } }
apache-2.0
lordjone/libgdx
tests/gdx-tests-android/src/com/badlogic/gdx/tests/android/FragmentTestStarter.java
4359
package com.badlogic.gdx.tests.android; import java.util.List; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.badlogic.gdx.backends.android.AndroidFragmentApplication; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.GdxTests; public class FragmentTestStarter extends FragmentActivity implements AndroidFragmentApplication.Callbacks { FrameLayout list; FrameLayout view; @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); GdxTests.tests.add(MatrixTest.class); LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.HORIZONTAL); list = new FrameLayout(this); list.setId(1); list.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); layout.addView(list); list.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1)); view = new FrameLayout(this); view.setId(2); view.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 2)); layout.addView(view); setContentView(layout); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction().add(1, new TestListFragment()).commit(); } } public void onTestSelected (String testName) { if(view != null) { getSupportFragmentManager().beginTransaction().replace(2, TestViewFragment.newInstance(testName)).commit(); } else { startActivity(new Intent(this, GdxTestActivity.class).putExtra("test", testName)); } } @Override public void exit () { } public static class TestListFragment extends ListFragment { private SharedPreferences prefs; private FragmentTestStarter activity; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); List<String> testNames = GdxTests.getNames(); setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, testNames)); prefs = getActivity().getSharedPreferences("libgdx-tests", Context.MODE_PRIVATE); } @Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); ((ListView)view.findViewById(android.R.id.list)).setSelectionFromTop(prefs.getInt("index", 0), prefs.getInt("top", 0)); return view; } @Override public void onListItemClick (ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); Object o = this.getListAdapter().getItem(position); String testName = o.toString(); if (activity != null) { activity.onTestSelected(testName); } } @Override public void onAttach (Activity activity) { super.onAttach(activity); if (activity instanceof FragmentTestStarter) { this.activity = (FragmentTestStarter)activity; } } } public static class TestViewFragment extends AndroidFragmentApplication { public static TestViewFragment newInstance(String testName) { Bundle arguments = new Bundle(); arguments.putString("test", testName); TestViewFragment fragment = new TestViewFragment(); fragment.setArguments(arguments); return fragment; } GdxTest test; @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); test = GdxTests.newTest(getArguments().getString("test")); } @Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return initializeForView(test, new AndroidApplicationConfiguration()); } } }
apache-2.0
igarashitm/camel
camel-core/src/main/java/org/apache/camel/model/dataformat/StringDataFormat.java
1748
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.model.dataformat; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import org.apache.camel.model.DataFormatDefinition; import org.apache.camel.spi.DataFormat; import org.apache.camel.spi.RouteContext; /** * Represents the String (text based) {@link DataFormat} * * @version */ @XmlRootElement(name = "string") @XmlAccessorType(XmlAccessType.FIELD) public class StringDataFormat extends DataFormatDefinition { @XmlAttribute private String charset; @Override protected DataFormat createDataFormat(RouteContext routeContext) { return new org.apache.camel.impl.StringDataFormat(charset); } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } }
apache-2.0
jamescdavis/ember-osf
tests/dummy/app/routes/collections/detail.js
2923
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; export default Ember.Route.extend(AuthenticatedRouteMixin, { model(params) { return this.store.findRecord('collection', params.collection_id); }, actions: { /** * Add node to a collection * * @method addNodeToCollection * @param {String} projectId, ID of node (linkedNode) to be added to the collection * @return {Promise} Returns a promise that resolves to the updated collection * with the new linkedNodes relationship */ addNodeToCollection(projectId) { this.store.findRecord('node', projectId).then(node => { var collection = this.modelFor(this.routeName); collection.get('linkedNodes').pushObject(node); return collection.save(); }); }, /** * Remove node from a collection * * @method removeNodeFromCollection * @param {Object} project Node(linkedNode) relationship to be removed from collection * @return {Promise} Returns a promise that resolves to the updated collection * with the linkedNode relationship removed. The node itself is not removed. */ removeNodeFromCollection(project) { var collection = this.modelFor(this.routeName); collection.get('linkedNodes').removeObject(project); return collection.save(); }, /** * Add registration to a collection * * @method addRegistrationToCollection * @param {String} registrationId, ID of registration (linkedRegistration) to be added to the collection * @return {Promise} Returns a promise that resolves to the updated collection * with the new linkedRegistration relationship */ addRegistrationToCollection(registrationId) { this.store.findRecord('registration', registrationId).then(registration => { var collection = this.modelFor(this.routeName); collection.get('linkedRegistrations').pushObject(registration); return collection.save(); }); }, /** * Remove registration from a collection * * @method removeRegistrationFromCollection * @param {Object} registration linkedRegistration to be removed from collection * @return {Promise} Returns a promise that resolves to the updated collection * with the linkedRegistration relationship removed. The registration itself is not deleted. */ removeRegistrationFromCollection(registration) { var collection = this.modelFor(this.routeName); collection.get('linkedRegistrations').removeObject(registration); return collection.save(); }, } });
apache-2.0
Metaswitch/calico-nova
nova/tests/unit/api/openstack/compute/contrib/test_flavor_swap.py
3627
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.serialization import jsonutils import webob from nova.compute import flavors from nova import test from nova.tests.unit.api.openstack import fakes FAKE_FLAVORS = { 'flavor 1': { "flavorid": '1', "name": 'flavor 1', "memory_mb": '256', "root_gb": '10', "swap": 512, "vcpus": 1, "ephemeral_gb": 1, "disabled": False, }, 'flavor 2': { "flavorid": '2', "name": 'flavor 2', "memory_mb": '512', "root_gb": '10', "swap": None, "vcpus": 1, "ephemeral_gb": 1, "disabled": False, }, } # TODO(jogo) dedup these across nova.api.openstack.contrib.test_flavor* def fake_flavor_get_by_flavor_id(flavorid, ctxt=None): return FAKE_FLAVORS['flavor %s' % flavorid] def fake_get_all_flavors_sorted_list(context=None, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None): return [ fake_flavor_get_by_flavor_id(1), fake_flavor_get_by_flavor_id(2) ] class FlavorSwapTestV21(test.NoDBTestCase): base_url = '/v2/fake/flavors' content_type = 'application/json' prefix = '' def setUp(self): super(FlavorSwapTestV21, self).setUp() ext = ('nova.api.openstack.compute.contrib' '.flavor_swap.Flavor_swap') self.flags(osapi_compute_extension=[ext]) fakes.stub_out_nw_api(self.stubs) self.stubs.Set(flavors, "get_all_flavors_sorted_list", fake_get_all_flavors_sorted_list) self.stubs.Set(flavors, "get_flavor_by_flavor_id", fake_flavor_get_by_flavor_id) def _make_request(self, url): req = webob.Request.blank(url) req.headers['Accept'] = self.content_type res = req.get_response(fakes.wsgi_app_v21(init_only=('flavors'))) return res def _get_flavor(self, body): return jsonutils.loads(body).get('flavor') def _get_flavors(self, body): return jsonutils.loads(body).get('flavors') def assertFlavorSwap(self, flavor, swap): self.assertEqual(str(flavor.get('%sswap' % self.prefix)), swap) def test_show(self): url = self.base_url + '/1' res = self._make_request(url) self.assertEqual(res.status_int, 200) self.assertFlavorSwap(self._get_flavor(res.body), '512') def test_detail(self): url = self.base_url + '/detail' res = self._make_request(url) self.assertEqual(res.status_int, 200) flavors = self._get_flavors(res.body) self.assertFlavorSwap(flavors[0], '512') self.assertFlavorSwap(flavors[1], '') class FlavorSwapTestV2(FlavorSwapTestV21): def _make_request(self, url): req = webob.Request.blank(url) req.headers['Accept'] = self.content_type res = req.get_response(fakes.wsgi_app()) return res
apache-2.0
jkandasa/hawkular-inventory
hawkular-inventory-rest-api/src/main/java/org/hawkular/inventory/rest/exception/mappers/NotAcceptableExceptionMapper.java
1477
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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. */ package org.hawkular.inventory.rest.exception.mappers; import javax.ws.rs.NotAcceptableException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * Exception mapper for any exception thrown by RESTEasy when HTTP Not Acceptable (406) is encountered. * <p> * This mapper let us reply to the user with a pre-determined message format if, for example, receive a * HTTP GET request with unsupported media type. * * @author Jeeva Kandasamy */ @Provider public class NotAcceptableExceptionMapper implements ExceptionMapper<NotAcceptableException> { @Override public Response toResponse(NotAcceptableException exception) { return ExceptionMapperUtils.buildResponse(exception, Response.Status.NOT_ACCEPTABLE); } }
apache-2.0
kebenxiaoming/owncloudRedis
apps/firstrunwizard/l10n/ro.php
964
<?php $TRANSLATIONS = array( "Your personal web services. All your files, contacts, calendar and more, in one place." => "Serviciile tale web personale. Toate fișierele, contactele, calendarele și multe altele într-un singur loc.", "Get the apps to sync your files" => "Obține aplicația pentru sincronizarea fișierelor", "Connect your Calendar" => "Conectează-ți calendarul", "Connect your Contacts" => "Conectează-ți contactele", "Access files via WebDAV" => "Accesează fișierele prin WebDAV", "Documentation" => "Documentație", "There’s more information in the <a target=\"_blank\" href=\"%s\">documentation</a> and on our <a target=\"_blank\" href=\"http://owncloud.org\">website</a>." => "Găsești mai multe informații în <a target=\"_blank\" href=\"%s\">documentație</a> și pe <a target=\"_blank\" href=\"http://owncloud.org\">saitul nostru</a>." ); $PLURAL_FORMS = "nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1));";
apache-2.0
newbeginningxzm/WeChatChoosen
ptrlibrary/src/main/java/com/handmark/pulltorefresh/library/PullToRefreshWebView.java
5223
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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. *******************************************************************************/ package com.handmark.pulltorefresh.library; import android.annotation.TargetApi; import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.util.AttributeSet; import android.util.FloatMath; import android.webkit.WebChromeClient; import android.webkit.WebView; public class PullToRefreshWebView extends PullToRefreshBase<WebView> { private static final OnRefreshListener<WebView> defaultOnRefreshListener = new OnRefreshListener<WebView>() { @Override public void onRefresh(PullToRefreshBase<WebView> refreshView) { refreshView.getRefreshableView().reload(); } }; private final WebChromeClient defaultWebChromeClient = new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { onRefreshComplete(); } } }; public PullToRefreshWebView(Context context) { super(context); /** * Added so that by default, Pull-to-Refresh refreshes the page */ setOnRefreshListener(defaultOnRefreshListener); mRefreshableView.setWebChromeClient(defaultWebChromeClient); } public PullToRefreshWebView(Context context, AttributeSet attrs) { super(context, attrs); /** * Added so that by default, Pull-to-Refresh refreshes the page */ setOnRefreshListener(defaultOnRefreshListener); mRefreshableView.setWebChromeClient(defaultWebChromeClient); } public PullToRefreshWebView(Context context, Mode mode) { super(context, mode); /** * Added so that by default, Pull-to-Refresh refreshes the page */ setOnRefreshListener(defaultOnRefreshListener); mRefreshableView.setWebChromeClient(defaultWebChromeClient); } public PullToRefreshWebView(Context context, Mode mode, AnimationStyle style) { super(context, mode, style); /** * Added so that by default, Pull-to-Refresh refreshes the page */ setOnRefreshListener(defaultOnRefreshListener); mRefreshableView.setWebChromeClient(defaultWebChromeClient); } @Override public final Orientation getPullToRefreshScrollDirection() { return Orientation.VERTICAL; } @Override protected WebView createRefreshableView(Context context, AttributeSet attrs) { WebView webView; if (VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD) { webView = new InternalWebViewSDK9(context, attrs); } else { webView = new WebView(context, attrs); } webView.setId(R.id.webview); return webView; } @Override protected boolean isReadyForPullStart() { return mRefreshableView.getScrollY() == 0; } @Override protected boolean isReadyForPullEnd() { float exactContentHeight = (float)Math.floor(mRefreshableView.getContentHeight() * mRefreshableView.getScale()); return mRefreshableView.getScrollY() >= (exactContentHeight - mRefreshableView.getHeight()); } @Override protected void onPtrRestoreInstanceState(Bundle savedInstanceState) { super.onPtrRestoreInstanceState(savedInstanceState); mRefreshableView.restoreState(savedInstanceState); } @Override protected void onPtrSaveInstanceState(Bundle saveState) { super.onPtrSaveInstanceState(saveState); mRefreshableView.saveState(saveState); } @TargetApi(9) final class InternalWebViewSDK9 extends WebView { // WebView doesn't always scroll back to it's edge so we add some // fuzziness static final int OVERSCROLL_FUZZY_THRESHOLD = 2; // WebView seems quite reluctant to overscroll so we use the scale // factor to scale it's value static final float OVERSCROLL_SCALE_FACTOR = 1.5f; public InternalWebViewSDK9(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) { final boolean returnValue = super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent); // Does all of the hard work... OverscrollHelper.overScrollBy(PullToRefreshWebView.this, deltaX, scrollX, deltaY, scrollY, getScrollRange(), OVERSCROLL_FUZZY_THRESHOLD, OVERSCROLL_SCALE_FACTOR, isTouchEvent); return returnValue; } private int getScrollRange() { return (int) Math.max(0, Math.floor(mRefreshableView.getContentHeight() * mRefreshableView.getScale()) - (getHeight() - getPaddingBottom() - getPaddingTop())); } } }
apache-2.0
wuzhaozhongguo/simpleimage
simpleimage.core/src/test/java/com/alibaba/simpleimage/view/ImagePanel.java
1590
/* * Copyright 1999-2004 Alibaba.com All right reserved. This software is the * confidential and proprietary information of Alibaba.com ("Confidential * Information"). You shall not disclose such Confidential Information and shall * use it only in accordance with the terms of the license agreement you entered * into with Alibaba.com. */ package com.alibaba.simpleimage.view; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; import com.alibaba.simpleimage.ImageWrapper; /** * 类ImagePanel.java的实现描述:TODO 类实现描述 * @author wendell 2011-7-21 下午04:52:11 */ public class ImagePanel extends JPanel { /** * */ private static final long serialVersionUID = 8942241691324980880L; BufferedImage image; public static void show(ImageWrapper imageWrapper) { JFrame frame = new JFrame(); frame.setContentPane(new ImagePanel(imageWrapper.getAsBufferedImage())); frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); while(frame.isVisible()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } ImagePanel(BufferedImage image) { this.image = image; this.setBackground(Color.RED); } public void paint(Graphics g) { super.paint(g); g.drawImage(image, 0, 0, null); } }
apache-2.0
nkinkade/operator
tools/fetch.py
9355
#!/usr/bin/env python import csv import sys import os import vxargs #from monitor import parser as parsermodule #from monitor import common #from automate import * import csv from glob import glob import os import time def usage(): return """ fetch.py -- run a short bash script across many machines. The list of nodes is taken to be all MLab nodes, unless otherwise specified. Most common parameters: --script <script name> This looks for a script named 'scripts/<script name>.sh' and writes logs to 'logs/<script name>'. You can also define a 'post' script to automatically run on all the output logs from <script name>. If this file 'scripts/<script name>-post.sh' exists, it is executed with the log directory as its only argument. --rerun <extension=content> Rerun a command using the log files as the source of the node list. This is helpful for rerunning commands on just a few nodes based on previous runs. status=255 matches all nodes with an error status=0 matches all nodes with a success Examples: ./fetch.py --script procs ./fetch.py --script procs --rerun status=255 --list ./fetch.py --script procs --rerun status=255 ./fetch.py --command "ps ax" --nodelist list.txt """ def csv_to_hash(r): ret = {} for line in r: (k,v) = (line[0], line[1]) if k not in ret: ret[k] = v else: # multiple values for the same key if isinstance(ret[k], list): ret[k].append(v) else: ret[k] = [ret[k], v] return ret def getcsv(file): return csv_to_hash(csv.reader(open(file,'r'))) def get_hostlist_from_dir(dirname, which): f = which.split("=") if len(f) > 1: suffix = f[0] value = f[1] else: suffix = f[0] value = None ret = glob(dirname + "/*.%s" % suffix) if value: ret_list = [] for fname in ret: v = open(fname, 'r').read().strip() if value in v: ret_list.append(fname) ret = ret_list ret_list = [] for fname in ret: ret_list.append([os.path.basename(fname)[:-(len(suffix)+1)], '']) return ret_list def build_vx_args_external(shell_cmd): args = shell_cmd.split() return args def vx_start_external(nodelist,outdir,cmd, timeout=0, threadcount=20): args = build_vx_args_external(cmd) vxargs.start(None, threadcount, nodelist, outdir, False, args, timeout) def build_vx_args(shell_cmd, user): ssh_options="-q -o UserKnownHostsFile=junkssh -o StrictHostKeyChecking=no" cmd="""ssh -p806 %s %s@[] """ % (ssh_options, user) args = cmd.split() args.append(shell_cmd) return args def vx_start(nodelist, outdir, cmd, user, timeout=0, threadcount=20): args = build_vx_args(cmd, user) vxargs.start(None, threadcount, nodelist, outdir, False, args, timeout) def update_latest_symlink(outdir, latest_symlink): """Updates the 'latest' symlink to point to the given outdir.""" if os.path.lexists(latest_symlink): try: os.remove(latest_symlink) except OSError as err: return err try: os.symlink(os.path.basename(auto_outdir), latest_symlink) except OSError as err: return err return None if __name__ == "__main__": from optparse import OptionParser parser = OptionParser(usage=usage()) parser.set_defaults(outdir=None, timeout=120, simple=False, threadcount=20, external=False, myopsfilter=None, nodelist=None, run=False, list=False, rerun=None, command=None, script=None,) parser.add_option("", "--script", dest="script", metavar="<script>", help=("This looks for a script named "+ "'scripts/<script>.sh' and writes logs to "+ "'logs/<script>'.")) parser.add_option( "", "--command", dest="command", metavar="<command line>", help=("The command to run. If --external is false, then the command " "runs on nodes after login. If --external is true, then the " "command is run on the local system. In both cases, the pattern " "[] is replaced with the hostname being acted on.")) parser.add_option("", "--rerun", dest="rerun", metavar="ext[=val]", help=("Rerun fetch with the files indicated by the "+ "extension given to --rerun. For example, "+ "--rerun status=255, would rerun fetch on all "+ "files in --outdir that end with .status and "+ "have a value of 255")) parser.add_option("", "--outdir", dest="outdir", metavar="dirname", help="Name of directory to place logs. If unset, "+ "automatically set to 'logs/<cmd>/'") parser.add_option("", "--nodelist", dest="nodelist", metavar="FILE", help=("Provide the input file for the list of objects,"+ " or explicit list 'host1,host2,host3' etc.")) parser.add_option("", "--list", dest="list", action="store_true", help=("List the nodes the command would use; do "+ "nothing else.")) parser.add_option("", "--timeout", dest="timeout", metavar="120", help="Stop trying to execute after <timeout> seconds.") parser.add_option("", "--threadcount", dest="threadcount", metavar="20", help="Number of simultaneous threads.") parser.add_option("", "--external", dest="external", action="store_true", help=("Run commands external to the server. The "+ "default is internal.")) parser.add_option( "", "--user", dest="user", metavar="username", default="site_admin", help="User name used to ssh into remote server.") (config, args) = parser.parse_args() if len(sys.argv) == 1: parser.print_help() sys.exit(1) auto_outdir=None auto_script=None auto_script_post=None if config.script: if os.path.exists(config.script): f = open(config.script, 'r') else: auto_script = "scripts/" + config.script + ".sh" auto_script_post = "scripts/" + config.script + "-post.sh" f = open(auto_script, 'r') cmd_str = f.read() suffix = time.strftime('-%Y-%m-%dT%H:%M:%S', time.gmtime(time.time())) auto_outdir = 'logs/' + config.script.split('.')[0] + suffix latest_symlink = 'logs/' + config.script.split('.')[0] + '-latest' err = update_latest_symlink(auto_outdir, latest_symlink) if err is not None: sys.stderr.write('Failed to update latest symlink: %s' % err) sys.exit(1) elif config.command: cmd_str = config.command else: parser.print_help() sys.exit(1) if config.outdir == None and auto_outdir is None: outdir="default_outdir" elif config.outdir == None and auto_outdir is not None: outdir=auto_outdir else: outdir=config.outdir if not os.path.exists(outdir): os.system('mkdir -p %s' % outdir) assert os.path.exists(outdir) if config.nodelist is None and config.rerun is None: os.system("./plcquery.py --action=checksession") filename="/tmp/nodelist.txt" cmd="./plcquery.py --action=get --type node --filter hostname=*.measurement-lab.org " + \ "--fields hostname > %s" % filename os.system(cmd) nodelist = vxargs.getListFromFile(open(filename,'r')) elif config.nodelist is not None: if os.path.exists(config.nodelist) and os.path.isfile(config.nodelist): nodelist = vxargs.getListFromFile(open(config.nodelist,'r')) elif not os.path.exists(str(config.nodelist)): # NOTE: explicit list on command line "host1,host2,host3" nodelist = [ (host,'') for host in config.nodelist.split(",") ] elif config.rerun is not None and os.path.isdir(outdir): if config.rerun: nodelist = get_hostlist_from_dir(outdir, config.rerun) else: nodelist = get_hostlist_from_dir(outdir, "out") else: # probably no such file. raise Exception("Please specifiy a nodelist or --rerun directory" % config.nodelist) if config.list: for n in sorted(nodelist, cmp, lambda x: x[0][::-1]): print n[0] sys.exit(0) if config.external: vx_start_external( nodelist, outdir, cmd_str, int(config.timeout), int(config.threadcount)) else: vx_start( nodelist, outdir, cmd_str, config.user, int(config.timeout), int(config.threadcount)) if auto_script_post is not None and os.path.isfile(auto_script_post): os.system("bash %s %s" % (auto_script_post, outdir))
apache-2.0
vincent99/ui
lib/shared/app/mixins/promise-to-cb.js
55
export { default } from 'shared/mixins/promise-to-cb';
apache-2.0
jml/flocker
flocker/node/_loop.py
15861
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Convergence loop for a node-specific dataset agent. In practice most of the code is generic, but a few bits assume this agent is node-specific. The convergence agent runs a loop that attempts to converge the local state with the desired configuration as transmitted by the control service. This involves two state machines: ClusterStatus and ConvergenceLoop. The ClusterStatus state machine receives inputs from the connection to the control service, and sends inputs to the ConvergenceLoop state machine. """ from zope.interface import implementer from eliot import ActionType, Field, writeFailure, MessageType from eliot.twisted import DeferredContext from characteristic import attributes from machinist import ( trivialInput, TransitionTable, constructFiniteStateMachine, MethodSuffixOutputer, ) from twisted.application.service import MultiService from twisted.python.constants import Names, NamedConstant from twisted.internet.protocol import ReconnectingClientFactory from twisted.protocols.tls import TLSMemoryBIOFactory from . import run_state_change from ..control import ( NodeStateCommand, IConvergenceAgent, AgentAMP, ) class ClusterStatusInputs(Names): """ Inputs to the cluster status state machine. """ # The client has connected to the control service: CONNECTED_TO_CONTROL_SERVICE = NamedConstant() # A status update has been received from the control service: STATUS_UPDATE = NamedConstant() # THe client has disconnected from the control service: DISCONNECTED_FROM_CONTROL_SERVICE = NamedConstant() # The system is shutting down: SHUTDOWN = NamedConstant() @attributes(["client"]) class _ConnectedToControlService( trivialInput(ClusterStatusInputs.CONNECTED_TO_CONTROL_SERVICE)): """ A rich input indicating the client has connected. :ivar AMP client: An AMP client connected to the control service. """ @attributes(["configuration", "state"]) class _StatusUpdate(trivialInput(ClusterStatusInputs.STATUS_UPDATE)): """ A rich input indicating the cluster status has been received from the control service. :ivar Deployment configuration: Desired cluster configuration. :ivar Deployment state: Actual cluster state. """ class ClusterStatusStates(Names): """ States of the cluster status state machine. """ # The client is currently disconnected: DISCONNECTED = NamedConstant() # The client is connected, we don't know cluster status: IGNORANT = NamedConstant() # The client is connected and we know the cluster status: KNOWLEDGEABLE = NamedConstant() # The system is shut down: SHUTDOWN = NamedConstant() class ClusterStatusOutputs(Names): """ Outputs of the cluster status state machine. """ # Store the AMP protocol instance connected to the server: STORE_CLIENT = NamedConstant() # Notify the convergence loop state machine of new cluster status: UPDATE_STATUS = NamedConstant() # Stop the convergence loop state machine: STOP = NamedConstant() # Disconnect the AMP client: DISCONNECT = NamedConstant() class ClusterStatus(object): """ World object for cluster state machine, executing the actions indicated by the outputs. :ivar AMP client: The latest AMP protocol instance to connect to the control service. Initially ``None``. """ def __init__(self, convergence_loop_fsm): """ :param convergence_loop_fsm: An convergence loop FSM as output by ``build_convergence_loop_fsm``. """ self.convergence_loop_fsm = convergence_loop_fsm self.client = None def output_STORE_CLIENT(self, context): self.client = context.client def output_UPDATE_STATUS(self, context): self.convergence_loop_fsm.receive( _ClientStatusUpdate(client=self.client, configuration=context.configuration, state=context.state)) def output_STOP(self, context): self.convergence_loop_fsm.receive(ConvergenceLoopInputs.STOP) def output_DISCONNECT(self, context): self.client.transport.loseConnection() self.client = None def build_cluster_status_fsm(convergence_loop_fsm): """ Create a new cluster status FSM. The automatic reconnection logic is handled by the ``AgentLoopService``; the world object here just gets notified of disconnects, it need schedule the reconnect itself. :param convergence_loop_fsm: A convergence loop FSM as output by ``build_convergence_loop_fsm``. """ S = ClusterStatusStates I = ClusterStatusInputs O = ClusterStatusOutputs table = TransitionTable() # We may be shut down in any state, in which case we disconnect if # necessary. table = table.addTransitions( S.DISCONNECTED, { # Store the client, then wait for cluster status to be sent # over AMP: I.CONNECTED_TO_CONTROL_SERVICE: ([O.STORE_CLIENT], S.IGNORANT), I.SHUTDOWN: ([], S.SHUTDOWN), }) table = table.addTransitions( S.IGNORANT, { # We never told agent to start, so no need to tell it to stop: I.DISCONNECTED_FROM_CONTROL_SERVICE: ([], S.DISCONNECTED), # Tell agent latest cluster status, implicitly starting it: I.STATUS_UPDATE: ([O.UPDATE_STATUS], S.KNOWLEDGEABLE), I.SHUTDOWN: ([O.DISCONNECT], S.SHUTDOWN), }) table = table.addTransitions( S.KNOWLEDGEABLE, { # Tell agent latest cluster status: I.STATUS_UPDATE: ([O.UPDATE_STATUS], S.KNOWLEDGEABLE), I.DISCONNECTED_FROM_CONTROL_SERVICE: ([O.STOP], S.DISCONNECTED), I.SHUTDOWN: ([O.STOP, O.DISCONNECT], S.SHUTDOWN), }) table = table.addTransitions( S.SHUTDOWN, { I.DISCONNECTED_FROM_CONTROL_SERVICE: ([], S.SHUTDOWN), I.STATUS_UPDATE: ([], S.SHUTDOWN), }) return constructFiniteStateMachine( inputs=I, outputs=O, states=S, initial=S.DISCONNECTED, table=table, richInputs=[_ConnectedToControlService, _StatusUpdate], inputContext={}, world=MethodSuffixOutputer(ClusterStatus(convergence_loop_fsm))) class ConvergenceLoopInputs(Names): """ Inputs for convergence loop FSM. """ # Updated references to latest AMP client, desired configuration and # cluster state: STATUS_UPDATE = NamedConstant() # Stop the convergence loop: STOP = NamedConstant() # Finished applying necessary changes to local state, a single # iteration of the convergence loop: ITERATION_DONE = NamedConstant() @attributes(["client", "configuration", "state"]) class _ClientStatusUpdate(trivialInput(ConvergenceLoopInputs.STATUS_UPDATE)): """ A rich input with a cluster status update - we are currently connected to the control service, and know latest desired configuration and cluster state. :ivar AMP client: An AMP client connected to the control service. :ivar Deployment configuration: Desired cluster configuration. :ivar Deployment state: Actual cluster state. """ class ConvergenceLoopStates(Names): """ Convergence loop FSM states. """ # The loop is stopped: STOPPED = NamedConstant() # Local state is being discovered and changes applied: CONVERGING = NamedConstant() # Local state is being converged, and once that is done we will # immediately stop: CONVERGING_STOPPING = NamedConstant() class ConvergenceLoopOutputs(Names): """ Converence loop FSM outputs. """ # Store AMP client, desired configuration and cluster state for later # use: STORE_INFO = NamedConstant() # Start an iteration of the covergence loop: CONVERGE = NamedConstant() _FIELD_CONNECTION = Field( u"connection", lambda client: repr(client), "The AMP connection to control service") _FIELD_LOCAL_CHANGES = Field( u"local_changes", repr, "Changes discovered in local state.") LOG_SEND_TO_CONTROL_SERVICE = ActionType( u"flocker:agent:send_to_control_service", [_FIELD_CONNECTION, _FIELD_LOCAL_CHANGES], [], "Send the local state to the control service.") _FIELD_CLUSTERSTATE = Field( u"cluster_state", repr, "The state of the cluster, according to control service.") _FIELD_CONFIGURATION = Field( u"desired_configuration", repr, "The configuration of the cluster according to the control service.") _FIELD_ACTIONS = Field( u"calculated_actions", repr, "The actions we decided to take to converge with configuration.") LOG_CONVERGE = ActionType( u"flocker:agent:converge", [_FIELD_CLUSTERSTATE, _FIELD_CONFIGURATION], [], "The convergence action within the loop.") LOG_CALCULATED_ACTIONS = MessageType( u"flocker:agent:converge:actions", [_FIELD_ACTIONS], "The actions we're going to attempt.") class ConvergenceLoop(object): """ World object for the convergence loop state machine, executing the actions indicated by the outputs from the state machine. :ivar AMP client: An AMP client connected to the control service. Initially ``None``. :ivar Deployment configuration: Desired cluster configuration. Initially ``None``. :ivar DeploymentState cluster_state: Actual cluster state. Initially ``None``. :ivar fsm: The finite state machine this is part of. """ def __init__(self, reactor, deployer): """ :param IReactorTime reactor: Used to schedule delays in the loop. :param IDeployer deployer: Used to discover local state and calculate necessary changes to match desired configuration. """ self.reactor = reactor self.deployer = deployer self.cluster_state = None def output_STORE_INFO(self, context): self.client, self.configuration, self.cluster_state = ( context.client, context.configuration, context.state) def output_CONVERGE(self, context): known_local_state = self.cluster_state.get_node( self.deployer.node_uuid, hostname=self.deployer.hostname) with LOG_CONVERGE(self.fsm.logger, cluster_state=self.cluster_state, desired_configuration=self.configuration).context(): d = DeferredContext( self.deployer.discover_state(known_local_state)) def got_local_state(state_changes): # Current cluster state is likely out of date as regards the local # state, so update it accordingly. for state in state_changes: self.cluster_state = state.update_cluster_state( self.cluster_state ) with LOG_SEND_TO_CONTROL_SERVICE( self.fsm.logger, connection=self.client, local_changes=list(state_changes)) as context: self.client.callRemote(NodeStateCommand, state_changes=state_changes, eliot_context=context) action = self.deployer.calculate_changes( self.configuration, self.cluster_state ) LOG_CALCULATED_ACTIONS(calculated_actions=action).write( self.fsm.logger) return run_state_change(action, self.deployer) d.addCallback(got_local_state) # If an error occurred we just want to log it and then try # converging again; hopefully next time we'll have more success. d.addErrback(writeFailure, self.fsm.logger, u"") # It would be better to have a "quiet time" state in the FSM and # transition to that next, then have a timeout input kick the machine # back around to the beginning of the loop in the FSM. However, we're # not going to keep this sleep-for-a-bit solution in the long term. # Instead, we'll be more event driven. So just going with the simple # solution and inserting a side-effect-y delay directly here. d.addCallback( lambda _: self.reactor.callLater( 1.0, self.fsm.receive, ConvergenceLoopInputs.ITERATION_DONE ) ) d.addActionFinish() def build_convergence_loop_fsm(reactor, deployer): """ Create a convergence loop FSM. :param IReactorTime reactor: Used to schedule delays in the loop. :param IDeployer deployer: Used to discover local state and calcualte necessary changes to match desired configuration. """ I = ConvergenceLoopInputs O = ConvergenceLoopOutputs S = ConvergenceLoopStates table = TransitionTable() table = table.addTransition( S.STOPPED, I.STATUS_UPDATE, [O.STORE_INFO, O.CONVERGE], S.CONVERGING) table = table.addTransitions( S.CONVERGING, { I.STATUS_UPDATE: ([O.STORE_INFO], S.CONVERGING), I.STOP: ([], S.CONVERGING_STOPPING), I.ITERATION_DONE: ([O.CONVERGE], S.CONVERGING), }) table = table.addTransitions( S.CONVERGING_STOPPING, { I.STATUS_UPDATE: ([O.STORE_INFO], S.CONVERGING), I.ITERATION_DONE: ([], S.STOPPED), }) loop = ConvergenceLoop(reactor, deployer) fsm = constructFiniteStateMachine( inputs=I, outputs=O, states=S, initial=S.STOPPED, table=table, richInputs=[_ClientStatusUpdate], inputContext={}, world=MethodSuffixOutputer(loop)) loop.fsm = fsm return fsm @implementer(IConvergenceAgent) @attributes(["reactor", "deployer", "host", "port"]) class AgentLoopService(object, MultiService): """ Service in charge of running the convergence loop. :ivar reactor: The reactor. :ivar IDeployer deployer: Deployer for discovering local state and then changing it. :ivar host: Host to connect to. :ivar port: Port to connect to. :ivar cluster_status: A cluster status FSM. :ivar factory: The factory used to connect to the control service. :ivar reconnecting_factory: The underlying factory used to connect to the control service, without the TLS wrapper. """ def __init__(self, context_factory): """ :param context_factory: TLS context factory for the AMP client. """ MultiService.__init__(self) convergence_loop = build_convergence_loop_fsm( self.reactor, self.deployer ) self.logger = convergence_loop.logger self.cluster_status = build_cluster_status_fsm(convergence_loop) self.reconnecting_factory = ReconnectingClientFactory.forProtocol( lambda: AgentAMP(self.reactor, self) ) self.factory = TLSMemoryBIOFactory(context_factory, True, self.reconnecting_factory) def startService(self): MultiService.startService(self) self.reactor.connectTCP(self.host, self.port, self.factory) def stopService(self): MultiService.stopService(self) self.reconnecting_factory.stopTrying() self.cluster_status.receive(ClusterStatusInputs.SHUTDOWN) # IConvergenceAgent methods: def connected(self, client): self.cluster_status.receive(_ConnectedToControlService(client=client)) def disconnected(self): self.cluster_status.receive( ClusterStatusInputs.DISCONNECTED_FROM_CONTROL_SERVICE) def cluster_updated(self, configuration, cluster_state): self.cluster_status.receive(_StatusUpdate(configuration=configuration, state=cluster_state))
apache-2.0
msbeta/apollo
modules/prediction/scenario/scenario_features/scenario_features.cc
1118
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * 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. *****************************************************************************/ /** * @file */ #include "modules/prediction/scenario/scenario_features/scenario_features.h" namespace apollo { namespace prediction { ScenarioFeatures::ScenarioFeatures() { scenario_.set_type(Scenario::UNKNOWN); } const Scenario& ScenarioFeatures::scenario() const { return scenario_; } } // namespace prediction } // namespace apollo
apache-2.0
wwjiang007/hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/audit/package-info.java
1133
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Public classes for adding information to any auditing information * picked up by filesystem clients. * */ @InterfaceAudience.Public @InterfaceStability.Unstable package org.apache.hadoop.fs.audit; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability;
apache-2.0
felipeg48/isf-book
ch06/src/main/java/com/apress/isf/spring/service/SearchEngineService.java
1632
/** * */ package com.apress.isf.spring.service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.apress.isf.java.model.Document; import com.apress.isf.java.model.Type; import com.apress.isf.java.service.SearchEngine; import com.apress.isf.spring.data.DocumentDAO; /** * @author Felipe Gutierrez * */ public class SearchEngineService implements SearchEngine { private static final Logger log = LoggerFactory.getLogger(SearchEngineService.class); private DocumentDAO documentDAO; public SearchEngineService(){ if(log.isDebugEnabled()) log.debug("SearchEngineService created: " + this); } public DocumentDAO getDocumentDAO() { return documentDAO; } public void setDocumentDAO(DocumentDAO documentDAO) { if(log.isDebugEnabled()) log.debug("Document DAO set: " + documentDAO); this.documentDAO = documentDAO; } public List<Document> findByType(Type documentType) { if(log.isDebugEnabled()) log.debug("Start <findByType> Params: " + documentType); List<Document> result = new ArrayList<Document>(); for(Document doc : listAll()){ if(doc.getType().getName().equals(documentType.getName())) result.add(doc); } if(log.isDebugEnabled()) log.debug("End <findByType> Result: " + result); return result; } public List<Document> listAll() { if(log.isDebugEnabled()) log.debug("Start <listAll> Params: "); List<Document> result = Arrays.asList(documentDAO.getAll()); if(log.isDebugEnabled()) log.debug("End <listAll> Result: " + result); return result; } }
apache-2.0
jeorme/OG-Platform
projects/OG-FinancialTypes/src/main/java/com/opengamma/financial/security/option/SwaptionSecurityFudgeBuilder.java
4690
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.security.option; import org.fudgemsg.FudgeMsg; import org.fudgemsg.MutableFudgeMsg; import org.fudgemsg.mapping.FudgeBuilder; import org.fudgemsg.mapping.FudgeBuilderFor; import org.fudgemsg.mapping.FudgeDeserializer; import org.fudgemsg.mapping.FudgeSerializer; import com.opengamma.financial.security.FinancialSecurityFudgeBuilder; import com.opengamma.financial.security.LongShort; import com.opengamma.id.ExternalIdFudgeBuilder; import com.opengamma.util.fudgemsg.AbstractFudgeBuilder; import com.opengamma.util.money.Currency; import com.opengamma.util.time.ExpiryFudgeBuilder; import com.opengamma.util.time.ZonedDateTimeFudgeBuilder; /** * A Fudge builder for {@code SwaptionSecurity}. */ @FudgeBuilderFor(SwaptionSecurity.class) public class SwaptionSecurityFudgeBuilder extends AbstractFudgeBuilder implements FudgeBuilder<SwaptionSecurity> { /** Field name. */ public static final String IS_PAYER_FIELD_NAME = "isPayer"; /** Field name. */ public static final String UNDERLYING_IDENTIFIER_FIELD_NAME = "underlyingIdentifier"; /** Field name. */ public static final String IS_LONG_FIELD_NAME = "isLong"; /** Field name. */ public static final String EXPIRY_FIELD_NAME = "expiry"; /** Field name. */ public static final String IS_CASH_SETTLED_FIELD_NAME = "isCashSettled"; /** Field name. */ public static final String CURRENCY_FIELD_NAME = "currency"; /** Field name. */ public static final String EXERCISE_TYPE_FIELD_NAME = "exerciseType"; /** Field name. */ public static final String NOTIONAL_FIELD_NAME = "notional"; /** Field name. */ public static final String SETTLEMENT_DATE_FIELD_NAME = "settlementDate"; @Override public MutableFudgeMsg buildMessage(FudgeSerializer serializer, SwaptionSecurity object) { final MutableFudgeMsg msg = serializer.newMessage(); SwaptionSecurityFudgeBuilder.toFudgeMsg(serializer, object, msg); return msg; } public static void toFudgeMsg(FudgeSerializer serializer, SwaptionSecurity object, final MutableFudgeMsg msg) { FinancialSecurityFudgeBuilder.toFudgeMsg(serializer, object, msg); addToMessage(msg, IS_PAYER_FIELD_NAME, object.isPayer()); addToMessage(msg, UNDERLYING_IDENTIFIER_FIELD_NAME, ExternalIdFudgeBuilder.toFudgeMsg(serializer, object.getUnderlyingId())); addToMessage(msg, IS_LONG_FIELD_NAME, object.isLong()); addToMessage(msg, EXPIRY_FIELD_NAME, ExpiryFudgeBuilder.toFudgeMsg(serializer, object.getExpiry())); addToMessage(msg, IS_CASH_SETTLED_FIELD_NAME, object.isCashSettled()); addToMessage(msg, CURRENCY_FIELD_NAME, object.getCurrency()); if (object.getExerciseType() != null) { addToMessage(msg, EXERCISE_TYPE_FIELD_NAME, ExerciseTypeFudgeBuilder.toFudgeMsg(serializer, object.getExerciseType())); } if (object.getSettlementDate() != null) { addToMessage(msg, SETTLEMENT_DATE_FIELD_NAME, ZonedDateTimeFudgeBuilder.toFudgeMsg(serializer, object.getSettlementDate())); } if (object.getNotional() != null) { addToMessage(msg, NOTIONAL_FIELD_NAME, object.getNotional()); } } @Override public SwaptionSecurity buildObject(FudgeDeserializer deserializer, FudgeMsg msg) { SwaptionSecurity object = new SwaptionSecurity(); SwaptionSecurityFudgeBuilder.fromFudgeMsg(deserializer, msg, object); return object; } public static void fromFudgeMsg(FudgeDeserializer deserializer, FudgeMsg msg, SwaptionSecurity object) { FinancialSecurityFudgeBuilder.fromFudgeMsg(deserializer, msg, object); object.setPayer(msg.getBoolean(IS_PAYER_FIELD_NAME)); object.setUnderlyingId(ExternalIdFudgeBuilder.fromFudgeMsg(deserializer, msg.getMessage(UNDERLYING_IDENTIFIER_FIELD_NAME))); object.setLongShort(LongShort.ofLong(msg.getBoolean(IS_LONG_FIELD_NAME))); object.setExpiry(ExpiryFudgeBuilder.fromFudgeMsg(deserializer, msg.getMessage(EXPIRY_FIELD_NAME))); object.setCashSettled(msg.getBoolean(IS_CASH_SETTLED_FIELD_NAME)); object.setCurrency(msg.getValue(Currency.class, CURRENCY_FIELD_NAME)); if (msg.hasField(EXERCISE_TYPE_FIELD_NAME)) { object.setExerciseType(ExerciseTypeFudgeBuilder.fromFudgeMsg(deserializer, msg.getMessage(EXERCISE_TYPE_FIELD_NAME))); } if (msg.hasField(SETTLEMENT_DATE_FIELD_NAME)) { object.setSettlementDate(ZonedDateTimeFudgeBuilder.fromFudgeMsg(deserializer, msg.getMessage(SETTLEMENT_DATE_FIELD_NAME))); } if (msg.hasField(NOTIONAL_FIELD_NAME)) { object.setNotional(msg.getDouble(NOTIONAL_FIELD_NAME)); } } }
apache-2.0
roberth/pitest
pitest/src/test/java/org/pitest/execute/ResultClassifierTest.java
2189
/** * */ package org.pitest.execute; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.pitest.DescriptionMother; import org.pitest.testapi.Description; import org.pitest.testapi.TestResult; import org.pitest.testapi.TestUnitState; /** * @author henry * */ public class ResultClassifierTest { private DefaultResultClassifier testee; private Description description; @Before public void createTestee() { this.testee = new DefaultResultClassifier(); this.description = DescriptionMother.createEmptyDescription("foo"); } @Test public void shouldClassifyTestResultsWithStatusOfStartedAsStarted() { final ResultType actual = this.testee.classify(new TestResult( this.description, null, TestUnitState.STARTED)); assertEquals(ResultType.STARTED, actual); } @Test public void shouldClassifyJavaAssertionsAsFailed() { final ResultType actual = this.testee.classify(new TestResult( this.description, new java.lang.AssertionError(), TestUnitState.FINISHED)); assertEquals(ResultType.FAIL, actual); } @Test public void shouldClassifyJUnitFrameworkAssertionFailedErrorsAsFailed() { final ResultType actual = this.testee.classify(new TestResult( this.description, new junit.framework.AssertionFailedError(), TestUnitState.FINISHED)); assertEquals(ResultType.FAIL, actual); } @Test public void shouldClassifyThrowablesAtErrors() { final ResultType actual = this.testee.classify(new TestResult( this.description, new NullPointerException(), TestUnitState.FINISHED)); assertEquals(ResultType.ERROR, actual); } @Test public void shouldClassifyResultsWithoutThrowablesAsPass() { final ResultType actual = this.testee.classify(new TestResult( this.description, null, TestUnitState.FINISHED)); assertEquals(ResultType.PASS, actual); } @Test public void shouldClassifyResultsThatWereNotRunAsSkipped() { final ResultType actual = this.testee.classify(new TestResult( this.description, null, TestUnitState.NOT_RUN)); assertEquals(ResultType.SKIPPED, actual); } }
apache-2.0