code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
namespace ZeroMQ { /// <summary> /// Specifies possible results for socket receive operations. /// </summary> public enum ReceiveStatus { /// <summary> /// No receive operation has been performed. /// </summary> None, /// <summary> /// The receive operation returned a message that contains data. /// </summary> Received, /// <summary> /// Non-blocking mode was requested and no messages are available at the moment. /// </summary> TryAgain, /// <summary> /// The receive operation was interrupted, likely by terminating the containing context. /// </summary> Interrupted } }
zeromq/clrzmq
src/ZeroMQ/ReceiveStatus.cs
C#
lgpl-3.0
734
<?php /** * @author jurgenhaas */ namespace GMJH\SQRL\Sample; use GMJH\SQRL\ClientException; /** * An override class for Sample SQRL account * * @author jurgenhaas * * @link */ class Account extends \GMJH\SQRL\Account { #region Command ============================================================== /** * @param Client $client * @param bool $additional * @return bool * @throws ClientException */ public function command_setkey($client, $additional = FALSE) { return FALSE; } /** * @param Client $client * @return bool * @throws ClientException */ public function command_setlock($client) { return FALSE; } /** * @param Client $client * @return bool * @throws ClientException */ public function command_disable($client) { return FALSE; } /** * @param Client $client * @return bool * @throws ClientException */ public function command_enable($client) { return FALSE; } /** * @param Client $client * @return bool * @throws ClientException */ public function command_delete($client) { return FALSE; } /** * @param Client $client * @return bool * @throws ClientException */ public function command_login($client) { return TRUE; } /** * @param Client $client * @return bool * @throws ClientException */ public function command_logme($client) { return FALSE; } /** * @param Client $client * @return bool * @throws ClientException */ public function command_logoff($client) { return FALSE; } #endregion }
GMJH/SQRL-PHP-Library
sample/includes/Account.php
PHP
lgpl-3.0
1,602
using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using System.Threading; namespace CoCoL { /// <summary> /// Static helper class to create channels /// </summary> public static class Channel { /// <summary> /// Gets or creates a named channel. /// </summary> /// <returns>The named channel.</returns> /// <param name="name">The name of the channel to find.</param> /// <param name="buffersize">The number of buffers in the channel.</param> /// <param name="scope">The scope to create a named channel in, defaults to null which means the current scope</param> /// <param name="maxPendingReaders">The maximum number of pending readers. A negative value indicates infinite</param> /// <param name="maxPendingWriters">The maximum number of pending writers. A negative value indicates infinite</param> /// <param name="pendingReadersOverflowStrategy">The strategy for dealing with overflow for read requests</param> /// <param name="pendingWritersOverflowStrategy">The strategy for dealing with overflow for write requests</param> /// <param name="broadcast"><c>True</c> will create the channel as a broadcast channel, the default <c>false</c> will create a normal channel</param> /// <param name="initialBroadcastBarrier">The number of readers required on the channel before sending the first broadcast, can only be used with broadcast channels</param> /// <param name="broadcastMinimum">The minimum number of readers required on the channel, before a broadcast can be performed, can only be used with broadcast channels</param> /// <typeparam name="T">The channel type.</typeparam> public static IChannel<T> Get<T>(string name, int buffersize = 0, ChannelScope scope = null, int maxPendingReaders = -1, int maxPendingWriters = -1, QueueOverflowStrategy pendingReadersOverflowStrategy = QueueOverflowStrategy.Reject, QueueOverflowStrategy pendingWritersOverflowStrategy = QueueOverflowStrategy.Reject, bool broadcast = false, int initialBroadcastBarrier = -1, int broadcastMinimum = -1) { return ChannelManager.GetChannel<T>(name, buffersize, scope, maxPendingReaders, maxPendingWriters, pendingReadersOverflowStrategy, pendingWritersOverflowStrategy, broadcast, initialBroadcastBarrier, broadcastMinimum); } /// <summary> /// Gets or creates a named channel. /// </summary> /// <returns>The named channel.</returns> /// <param name="attr">The attribute describing the channel.</param> /// <param name="scope">The scope to create a named channel in, defaults to null which means the current scope</param> /// <typeparam name="T">The channel type.</typeparam> public static IChannel<T> Get<T>(ChannelNameAttribute attr, ChannelScope scope = null) { return ChannelManager.GetChannel<T>(attr, scope); } /// <summary> /// Gets or creates a named channel from a marker setup /// </summary> /// <returns>The named channel.</returns> /// <param name="marker">The channel marker instance that describes the channel.</param> /// <typeparam name="T">The channel type.</typeparam> public static IChannel<T> Get<T>(ChannelMarkerWrapper<T> marker) { return ChannelManager.GetChannel<T>(marker); } /// <summary> /// Gets a write channel from a marker interface. /// </summary> /// <returns>The requested channel.</returns> /// <param name="channel">The marker interface, or a real channel instance.</param> /// <typeparam name="T">The channel type.</typeparam> public static IWriteChannelEnd<T> Get<T>(IWriteChannel<T> channel) { return ChannelManager.GetChannel<T>(channel); } /// <summary> /// Gets a read channel from a marker interface. /// </summary> /// <returns>The requested channel.</returns> /// <param name="channel">The marker interface, or a real channel instance.</param> /// <typeparam name="T">The channel type.</typeparam> public static IReadChannelEnd<T> Get<T>(IReadChannel<T> channel) { return ChannelManager.GetChannel<T>(channel); } /// <summary> /// Creates a channel, possibly unnamed. /// If a channel name is provided, the channel is created in the supplied scope. /// If a channel with the given name is already found in the supplied scope, the named channel is returned. /// </summary> /// <returns>The channel.</returns> /// <param name="name">The name of the channel, or null.</param> /// <param name="buffersize">The number of buffers in the channel.</param> /// <param name="scope">The scope to create a named channel in, defaults to null which means the current scope</param> /// <param name="maxPendingReaders">The maximum number of pending readers. A negative value indicates infinite</param> /// <param name="maxPendingWriters">The maximum number of pending writers. A negative value indicates infinite</param> /// <param name="pendingReadersOverflowStrategy">The strategy for dealing with overflow for read requests</param> /// <param name="pendingWritersOverflowStrategy">The strategy for dealing with overflow for write requests</param> /// <param name="broadcast"><c>True</c> will create the channel as a broadcast channel, the default <c>false</c> will create a normal channel</param> /// <param name="initialBroadcastBarrier">The number of readers required on the channel before sending the first broadcast, can only be used with broadcast channels</param> /// <param name="broadcastMinimum">The minimum number of readers required on the channel, before a broadcast can be performed, can only be used with broadcast channels</param> /// <typeparam name="T">The channel type.</typeparam> public static IChannel<T> Create<T>(string name = null, int buffersize = 0, ChannelScope scope = null, int maxPendingReaders = -1, int maxPendingWriters = -1, QueueOverflowStrategy pendingReadersOverflowStrategy = QueueOverflowStrategy.Reject, QueueOverflowStrategy pendingWritersOverflowStrategy = QueueOverflowStrategy.Reject, bool broadcast = false, int initialBroadcastBarrier = -1, int broadcastMinimum = -1) { return ChannelManager.CreateChannel<T>(name, buffersize, scope, maxPendingReaders, maxPendingWriters, pendingReadersOverflowStrategy, pendingWritersOverflowStrategy, broadcast, initialBroadcastBarrier, broadcastMinimum); } /// <summary> /// Creates a channel, possibly unnamed. /// If a channel name is provided, the channel is created in the supplied scope. /// If a channel with the given name is already found in the supplied scope, the named channel is returned. /// </summary> /// <returns>The named channel.</returns> /// <param name="attr">The attribute describing the channel.</param> /// <param name="scope">The scope to create a named channel in, defaults to null which means the current scope</param> /// <typeparam name="T">The channel type.</typeparam> public static IChannel<T> Create<T>(ChannelNameAttribute attr, ChannelScope scope = null) { return ChannelManager.CreateChannel<T>(attr, scope); } } /// <summary> /// A channel that uses continuation callbacks /// </summary> public class Channel<T> : IChannel<T>, IUntypedChannel, IJoinAbleChannel, INamedItem { /// <summary> /// The minium value for the cleanup threshold /// </summary> protected const int MIN_QUEUE_CLEANUP_THRESHOLD = 100; /// <summary> /// Interface for an offer /// </summary> protected interface IEntry { /// <summary> /// The two-phase offer instance /// </summary> /// <value>The offer.</value> ITwoPhaseOffer Offer { get; } } /// <summary> /// Structure for keeping a read request /// </summary> protected struct ReaderEntry : IEntry, IEquatable<ReaderEntry> { /// <summary> /// The offer handler for the request /// </summary> public readonly ITwoPhaseOffer Offer; /// <summary> /// The callback method for reporting progress /// </summary> public readonly TaskCompletionSource<T> Source; #if !NO_TASK_ASYNCCONTINUE /// <summary> /// A flag indicating if signalling task completion must be enqued on the task pool /// </summary> public readonly bool EnqueueContinuation; #endif /// <summary> /// Initializes a new instance of the <see cref="CoCoL.Channel&lt;T&gt;.ReaderEntry"/> struct. /// </summary> /// <param name="offer">The offer handler</param> public ReaderEntry(ITwoPhaseOffer offer) { Offer = offer; #if NO_TASK_ASYNCCONTINUE Source = new TaskCompletionSource<T>(); #else EnqueueContinuation = ExecutionScope.Current.IsLimitingPool; Source = new TaskCompletionSource<T>( EnqueueContinuation ? TaskCreationOptions.None : TaskCreationOptions.RunContinuationsAsynchronously); #endif } /// <summary> /// The offer handler for the request /// </summary> ITwoPhaseOffer IEntry.Offer { get { return Offer; } } /// <summary> /// Gets a value indicating whether this <see cref="T:CoCoL.Channel`1.ReaderEntry"/> is timed out. /// </summary> public bool IsTimeout => Offer is IExpiringOffer expOffer && expOffer.IsExpired; /// <summary> /// Gets a value indicating whether this <see cref="T:CoCoL.Channel`1.ReaderEntry"/> is cancelled. /// </summary> public bool IsCancelled => Offer is ICancelAbleOffer canOffer && canOffer.CancelToken.IsCancellationRequested; /// <summary> /// Gets a value representing the expiration time of this entry /// </summary> public DateTime Expires => Offer is IExpiringOffer expOffer ? expOffer.Expires : new DateTime(0); /// <summary> /// Signals that the probe phase has finished /// </summary> public void ProbeCompleted() { if (Offer is IExpiringOffer offer) offer.ProbeComplete(); } /// <summary> /// Explict disable of compares /// </summary> /// <param name="other">The item to compare with</param> /// <returns>Always throws an exception to avoid compares</returns> public bool Equals(ReaderEntry other) { throw new NotImplementedException(); } } /// <summary> /// Structure for keeping a write request /// </summary> protected struct WriterEntry : IEntry, IEquatable<WriterEntry> { /// <summary> /// The offer handler for the request /// </summary> public readonly ITwoPhaseOffer Offer; /// <summary> /// The callback method for reporting progress /// </summary> public readonly TaskCompletionSource<bool> Source; /// <summary> /// The cancellation token /// </summary> public readonly CancellationToken CancelToken; /// <summary> /// The value being written /// </summary> public readonly T Value; #if !NO_TASK_ASYNCCONTINUE /// <summary> /// A flag indicating if signalling task completion must be enqued on the task pool /// </summary> public readonly bool EnqueueContinuation; #endif /// <summary> /// Initializes a new instance of the <see cref="CoCoL.Channel&lt;T&gt;.WriterEntry"/> struct. /// </summary> /// <param name="offer">The offer handler</param> /// <param name="value">The value being written.</param> public WriterEntry(ITwoPhaseOffer offer, T value) { Offer = offer; #if NO_TASK_ASYNCCONTINUE Source = new TaskCompletionSource<bool>(); #else EnqueueContinuation = ExecutionScope.Current.IsLimitingPool; Source = new TaskCompletionSource<bool>( EnqueueContinuation ? TaskCreationOptions.None : TaskCreationOptions.RunContinuationsAsynchronously); #endif Value = value; } /// <summary> /// Initializes a new empty instance of the <see cref="CoCoL.Channel&lt;T&gt;.WriterEntry"/> struct. /// </summary> /// <param name="value">The value being written.</param> public WriterEntry(T value) { Offer = null; Source = null; Value = value; #if !NO_TASK_ASYNCCONTINUE EnqueueContinuation = false; #endif } /// <summary> /// The offer handler for the request /// </summary> ITwoPhaseOffer IEntry.Offer { get { return Offer; } } /// <summary> /// Gets a value indicating whether this <see cref="T:CoCoL.Channel`1.ReaderEntry"/> is timed out. /// </summary> public bool IsTimeout => Offer is IExpiringOffer && ((IExpiringOffer)Offer).IsExpired; /// <summary> /// Gets a value indicating whether this <see cref="T:CoCoL.Channel`1.ReaderEntry"/> is cancelled. /// </summary> public bool IsCancelled => Offer is ICancelAbleOffer && ((ICancelAbleOffer)Offer).CancelToken.IsCancellationRequested; /// <summary> /// Gets a value representing the expiration time of this entry /// </summary> public DateTime Expires => Offer is IExpiringOffer ? ((IExpiringOffer)Offer).Expires : new DateTime(0); /// <summary> /// Signals that the probe phase has finished /// </summary> public void ProbeCompleted() { if (Offer is IExpiringOffer offer) offer.ProbeComplete(); } /// <summary> /// Explict disable of compares /// </summary> /// <param name="other">The item to compare with</param> /// <returns>Always throws an exception to avoid compares</returns> public bool Equals(WriterEntry other) { throw new NotImplementedException(); } } /// <summary> /// The queue with pending readers /// </summary> protected List<ReaderEntry> m_readerQueue = new List<ReaderEntry>(1); /// <summary> /// The queue with pending writers /// </summary> protected List<WriterEntry> m_writerQueue = new List<WriterEntry>(1); /// <summary> /// The maximal size of the queue /// </summary> protected readonly int m_bufferSize; /// <summary> /// The lock object protecting access to the queues /// </summary> protected readonly AsyncLock m_asynclock = new AsyncLock(); /// <summary> /// Gets or sets the name of the channel /// </summary> /// <value>The name.</value> public string Name { get; private set; } /// <summary> /// Gets a value indicating whether this instance is retired. /// </summary> /// <value><c>true</c> if this instance is retired; otherwise, <c>false</c>.</value> public Task<bool> IsRetiredAsync { get { return GetIsRetiredAsync(); } } /// <summary> /// Gets a value indicating whether this instance is retired. /// </summary> protected bool m_isRetired; /// <summary> /// The number of messages to process before marking the channel as retired /// </summary> protected int m_retireCount = -1; /// <summary> /// The number of reader processes having joined the channel /// </summary> protected int m_joinedReaderCount = 0; /// <summary> /// The number of writer processes having joined the channel /// </summary> protected int m_joinedWriterCount = 0; /// <summary> /// The threshold for performing writer queue cleanup /// </summary> protected int m_writerQueueCleanup = MIN_QUEUE_CLEANUP_THRESHOLD; /// <summary> /// The threshold for performing reader queue cleanup /// </summary> protected int m_readerQueueCleanup = MIN_QUEUE_CLEANUP_THRESHOLD; /// <summary> /// The maximum number of pending readers to allow /// </summary> protected readonly int m_maxPendingReaders; /// <summary> /// The strategy for selecting pending readers to discard on overflow /// </summary> protected readonly QueueOverflowStrategy m_pendingReadersOverflowStrategy; /// <summary> /// The maximum number of pending writers to allow /// </summary> protected readonly int m_maxPendingWriters; /// <summary> /// The strategy for selecting pending writers to discard on overflow /// </summary> protected readonly QueueOverflowStrategy m_pendingWritersOverflowStrategy; /// <summary> /// Initializes a new instance of the <see cref="CoCoL.Channel&lt;T&gt;"/> class. /// </summary> /// <param name="attribute">The attribute describing the channel</param> internal Channel(ChannelNameAttribute attribute) { if (attribute == null) throw new ArgumentNullException(nameof(attribute)); if (attribute.BufferSize < 0) throw new ArgumentOutOfRangeException(nameof(attribute), "The size parameter must be greater than or equal to zero"); this.Name = attribute.Name; m_bufferSize = attribute.BufferSize; m_maxPendingReaders = attribute.MaxPendingReaders; m_maxPendingWriters = attribute.MaxPendingWriters; m_pendingReadersOverflowStrategy = attribute.PendingReadersOverflowStrategy; m_pendingWritersOverflowStrategy = attribute.PendingWritersOverflowStrategy; } /// <summary> /// Helper method for accessor to get the retired state /// </summary> /// <returns>The is retired async.</returns> protected async Task<bool> GetIsRetiredAsync() { using (await m_asynclock.LockAsync()) return m_isRetired; } /// <summary> /// Offers a transaction to the write end /// </summary> /// <param name="wr">The writer entry.</param> protected async Task<bool> Offer(WriterEntry wr) { Exception tex = null; bool accept = false; System.Diagnostics.Debug.Assert(wr.Source == m_writerQueue[0].Source); try { accept = (wr.Source == null || wr.Source.Task.Status == TaskStatus.WaitingForActivation) && (wr.Offer == null || await wr.Offer.OfferAsync(this).ConfigureAwait(false)); } catch (Exception ex) { tex = ex; // Workaround to support C# 5.0, with no await in catch clause } if (tex != null) { TrySetException(wr, tex); m_writerQueue.RemoveAt(0); return false; } if (!accept) { TrySetCancelled(wr); m_writerQueue.RemoveAt(0); return false; } return true; } /// <summary> /// Offersa transaction to the read end /// </summary> /// <param name="rd">The reader entry.</param> protected async Task<bool> Offer(ReaderEntry rd) { Exception tex = null; bool accept = false; System.Diagnostics.Debug.Assert(rd.Source == m_readerQueue[0].Source); try { accept = (rd.Source == null || rd.Source.Task.Status == TaskStatus.WaitingForActivation) && (rd.Offer == null || await rd.Offer.OfferAsync(this).ConfigureAwait(false)); } catch (Exception ex) { tex = ex; // Workaround to support C# 5.0, with no await in catch clause } if (tex != null) { TrySetException(rd, tex); m_readerQueue.RemoveAt(0); return false; } if (!accept) { TrySetCancelled(rd); m_readerQueue.RemoveAt(0); return false; } return true; } /// <summary> /// Method that examines the queues and matches readers with writers /// </summary> /// <returns>An awaitable that signals if the caller has been accepted or rejected.</returns> /// <param name="asReader"><c>True</c> if the caller method is a reader, <c>false</c> otherwise.</param> /// <param name="caller">The caller task.</param> protected virtual async Task<bool> MatchReadersAndWriters(bool asReader, Task caller) { var processed = false; while (m_writerQueue != null && m_readerQueue != null && m_writerQueue.Count > 0 && m_readerQueue.Count > 0) { var wr = m_writerQueue[0]; var rd = m_readerQueue[0]; bool offerWriter; bool offerReader; // If the caller is a reader, we assume that the // read call will always proceed, and start emptying // the write queue, and vice versa if the caller // is a writer if (asReader) { offerWriter = await Offer(wr).ConfigureAwait(false); if (!offerWriter) continue; offerReader = await Offer(rd).ConfigureAwait(false); } else { offerReader = await Offer(rd).ConfigureAwait(false); if (!offerReader) continue; offerWriter = await Offer(wr).ConfigureAwait(false); } // We flip the first entry, so we do not repeatedly // offer the side that agrees, and then discover // that the other side denies asReader = !asReader; // If the ends disagree, the declining end // has been removed from the queue, so we just // withdraw the offer from the other end if (!(offerReader && offerWriter)) { if (wr.Offer != null && offerWriter) await wr.Offer.WithdrawAsync(this).ConfigureAwait(false); if (rd.Offer != null && offerReader) await rd.Offer.WithdrawAsync(this).ConfigureAwait(false); } else { // transaction complete m_writerQueue.RemoveAt(0); m_readerQueue.RemoveAt(0); if (wr.Offer != null) await wr.Offer.CommitAsync(this).ConfigureAwait(false); if (rd.Offer != null) await rd.Offer.CommitAsync(this).ConfigureAwait(false); if (caller == rd.Source.Task || (wr.Source != null && caller == wr.Source.Task)) processed = true; SetResult(rd, wr.Value); SetResult(wr, true); // Release items if there is space in the buffer await ProcessWriteQueueBufferAfterReadAsync(true).ConfigureAwait(false); // Adjust the cleanup threshold if (m_writerQueue.Count <= m_writerQueueCleanup - MIN_QUEUE_CLEANUP_THRESHOLD) m_writerQueueCleanup = Math.Max(MIN_QUEUE_CLEANUP_THRESHOLD, m_writerQueue.Count + MIN_QUEUE_CLEANUP_THRESHOLD); // Adjust the cleanup threshold if (m_readerQueue.Count <= m_readerQueueCleanup - MIN_QUEUE_CLEANUP_THRESHOLD) m_readerQueueCleanup = Math.Max(MIN_QUEUE_CLEANUP_THRESHOLD, m_readerQueue.Count + MIN_QUEUE_CLEANUP_THRESHOLD); // If this was the last item before the retirement, // flush all following and set the retired flag await EmptyQueueIfRetiredAsync(true).ConfigureAwait(false); } } return processed || caller.Status != TaskStatus.WaitingForActivation; } /// <summary> /// Registers a desire to read from the channel /// </summary> public Task<T> ReadAsync() { return ReadAsync(null); } /// <summary> /// Registers a desire to read from the channel /// </summary> /// <param name="offer">A callback method for offering an item, use null to unconditionally accept</param> public async Task<T> ReadAsync(ITwoPhaseOffer offer) { var rd = new ReaderEntry(offer); if (rd.IsCancelled) throw new TaskCanceledException(); using (await m_asynclock.LockAsync()) { if (m_isRetired) { TrySetException(rd, new RetiredException(this.Name)); return await rd.Source.Task.ConfigureAwait(false); } m_readerQueue.Add(rd); if (!await MatchReadersAndWriters(true, rd.Source.Task).ConfigureAwait(false)) { rd.ProbeCompleted(); System.Diagnostics.Debug.Assert(m_readerQueue[m_readerQueue.Count - 1].Source == rd.Source); // If this was a probe call, return a timeout now if (rd.IsTimeout) { m_readerQueue.RemoveAt(m_readerQueue.Count - 1); TrySetException(rd, new TimeoutException()); } else if (rd.IsCancelled) { m_readerQueue.RemoveAt(m_readerQueue.Count - 1); TrySetException(rd, new TaskCanceledException()); } else { // Make room if we have too many if (m_maxPendingReaders > 0 && (m_readerQueue.Count - 1) >= m_maxPendingReaders) { switch (m_pendingReadersOverflowStrategy) { case QueueOverflowStrategy.FIFO: { var exp = m_readerQueue[0]; m_readerQueue.RemoveAt(0); TrySetException(exp, new ChannelOverflowException(this.Name)); } break; case QueueOverflowStrategy.LIFO: { var exp = m_readerQueue[m_readerQueue.Count - 2]; m_readerQueue.RemoveAt(m_readerQueue.Count - 2); TrySetException(exp, new ChannelOverflowException(this.Name)); } break; //case QueueOverflowStrategy.Reject: default: { var exp = m_readerQueue[m_readerQueue.Count - 1]; m_readerQueue.RemoveAt(m_readerQueue.Count - 1); TrySetException(exp, new ChannelOverflowException(this.Name)); } break; } } // If we have expanded the queue with a new batch, see if we can purge old entries m_readerQueueCleanup = await PerformQueueCleanupAsync(m_readerQueue, true, m_readerQueueCleanup).ConfigureAwait(false); if (rd.Offer is IExpiringOffer && ((IExpiringOffer)rd.Offer).Expires != Timeout.InfiniteDateTime) ExpirationManager.AddExpirationCallback(((IExpiringOffer)rd.Offer).Expires, () => ExpireItemsAsync().FireAndForget()); } } } return await rd.Source.Task.ConfigureAwait(false); } /// <summary> /// Registers a desire to write to the channel /// </summary> /// <param name="value">The value to write to the channel.</param> public Task WriteAsync(T value) { return WriteAsync(value, null); } /// <summary> /// Registers a desire to write to the channel /// </summary> /// <param name="offer">A callback method for offering an item, use null to unconditionally accept</param> /// <param name="value">The value to write to the channel.</param> public async Task WriteAsync(T value, ITwoPhaseOffer offer) { var wr = new WriterEntry(offer, value); if (wr.IsCancelled) throw new TaskCanceledException(); using (await m_asynclock.LockAsync()) { if (m_isRetired) { TrySetException(wr, new RetiredException(this.Name)); await wr.Source.Task.ConfigureAwait(false); return; } m_writerQueue.Add(wr); if (!await MatchReadersAndWriters(false, wr.Source.Task).ConfigureAwait(false)) { System.Diagnostics.Debug.Assert(m_writerQueue[m_writerQueue.Count - 1].Source == wr.Source); // If we have a buffer slot to use if (m_writerQueue.Count <= m_bufferSize && m_retireCount < 0) { if (offer == null || await offer.OfferAsync(this)) { if (offer != null) await offer.CommitAsync(this).ConfigureAwait(false); m_writerQueue[m_writerQueue.Count - 1] = new WriterEntry(value); TrySetResult(wr, true); } else { TrySetCancelled(wr); } // For good measure, we also make sure the probe phase is completed wr.ProbeCompleted(); } else { wr.ProbeCompleted(); // If this was a probe call, return a timeout now if (wr.IsTimeout) { m_writerQueue.RemoveAt(m_writerQueue.Count - 1); TrySetException(wr, new TimeoutException()); } else if (wr.IsCancelled) { m_writerQueue.RemoveAt(m_writerQueue.Count - 1); TrySetException(wr, new TaskCanceledException()); } else { // Make room if we have too many if (m_maxPendingWriters > 0 && (m_writerQueue.Count - m_bufferSize - 1) >= m_maxPendingWriters) { switch (m_pendingWritersOverflowStrategy) { case QueueOverflowStrategy.FIFO: { var exp = m_writerQueue[m_bufferSize]; m_writerQueue.RemoveAt(m_bufferSize); TrySetException(exp, new ChannelOverflowException(this.Name)); } break; case QueueOverflowStrategy.LIFO: { var exp = m_writerQueue[m_writerQueue.Count - 2]; m_writerQueue.RemoveAt(m_writerQueue.Count - 2); TrySetException(exp, new ChannelOverflowException(this.Name)); } break; //case QueueOverflowStrategy.Reject: default: { var exp = m_writerQueue[m_writerQueue.Count - 1]; m_writerQueue.RemoveAt(m_writerQueue.Count - 1); TrySetException(exp, new ChannelOverflowException(this.Name)); } break; } } // If we have expanded the queue with a new batch, see if we can purge old entries m_writerQueueCleanup = await PerformQueueCleanupAsync(m_writerQueue, true, m_writerQueueCleanup).ConfigureAwait(false); if (wr.Offer is IExpiringOffer && ((IExpiringOffer)wr.Offer).Expires != Timeout.InfiniteDateTime) ExpirationManager.AddExpirationCallback(((IExpiringOffer)wr.Offer).Expires, () => ExpireItemsAsync().FireAndForget()); } } } } await wr.Source.Task.ConfigureAwait(false); return; } /// <summary> /// Purges items in the queue that are no longer active /// </summary> /// <param name="queue">The queue to remove from.</param> /// <param name="queueCleanup">The threshold parameter.</param> /// <param name="isLocked"><c>True</c> if we are already holding the lock, <c>false</c> otherwise</param> /// <typeparam name="Tx">The type of list data.</typeparam> private async Task<int> PerformQueueCleanupAsync<Tx>(List<Tx> queue, bool isLocked, int queueCleanup) where Tx : IEntry { var res = queueCleanup; using(isLocked ? default(AsyncLock.Releaser) : await m_asynclock.LockAsync()) { if (queue.Count > queueCleanup) { for (var i = queue.Count - 1; i >= 0; i--) { if (queue[i].Offer != null) if (await queue[i].Offer.OfferAsync(this).ConfigureAwait(false)) await queue[i].Offer.WithdrawAsync(this).ConfigureAwait(false); else { TrySetCancelled(queue[i]); queue.RemoveAt(i); } } // Prevent repeated cleanup requests res = Math.Max(MIN_QUEUE_CLEANUP_THRESHOLD, queue.Count + MIN_QUEUE_CLEANUP_THRESHOLD); } } return res; } /// <summary> /// Helper method for dequeueing write requests after space has been allocated in the writer queue /// </summary> /// <param name="isLocked"><c>True</c> if we are already holding the lock, <c>false</c> otherwise</param> private async Task ProcessWriteQueueBufferAfterReadAsync(bool isLocked) { using(isLocked ? default(AsyncLock.Releaser) : await m_asynclock.LockAsync()) { // If there is now a buffer slot in the queue, trigger a callback to a waiting item while (m_retireCount < 0 && m_bufferSize > 0 && m_writerQueue.Count >= m_bufferSize) { var nextItem = m_writerQueue[m_bufferSize - 1]; if (nextItem.Offer == null || await nextItem.Offer.OfferAsync(this).ConfigureAwait(false)) { if (nextItem.Offer != null) await nextItem.Offer.CommitAsync(this).ConfigureAwait(false); SetResult(nextItem, true); // Now that the transaction has completed for the writer, record it as waiting forever m_writerQueue[m_bufferSize - 1] = new WriterEntry(nextItem.Value); // We can have at most one, since we process at most one read break; } else m_writerQueue.RemoveAt(m_bufferSize - 1); } } } /// <summary> /// Stops this channel from processing messages /// </summary> public Task RetireAsync() { return RetireAsync(false, false); } /// <summary> /// Stops this channel from processing messages /// </summary> /// <param name="immediate">Retires the channel without processing the queue, which may cause lost messages</param> public Task RetireAsync(bool immediate) { return RetireAsync(immediate, false); } /// <summary> /// Stops this channel from processing messages /// </summary> /// <param name="immediate">Retires the channel without processing the queue, which may cause lost messages</param> /// <param name="isLocked"><c>True</c> if we are already holding the lock, <c>false</c> otherwise</param> private async Task RetireAsync(bool immediate, bool isLocked) { using (isLocked ? default(AsyncLock.Releaser) : await m_asynclock.LockAsync()) { if (m_isRetired) return; if (m_retireCount < 0) { // If we have responded to buffered writes, // make sure we pair those before retiring m_retireCount = Math.Min(m_writerQueue.Count, m_bufferSize) + 1; // For immediate retire, remove buffered writes if (immediate) while (m_retireCount > 1) { if (m_writerQueue[0].Source != null) TrySetException(m_writerQueue[0], new RetiredException(this.Name)); m_writerQueue.RemoveAt(0); m_retireCount--; } } await EmptyQueueIfRetiredAsync(true).ConfigureAwait(false); } } /// <summary> /// Join the channel /// </summary> /// <param name="asReader"><c>true</c> if joining as a reader, <c>false</c> otherwise</param> public virtual async Task JoinAsync(bool asReader) { using (await m_asynclock.LockAsync()) { // Do not allow anyone to join after we retire the channel if (m_isRetired) throw new RetiredException(this.Name); if (asReader) m_joinedReaderCount++; else m_joinedWriterCount++; } } /// <summary> /// Leave the channel. /// </summary> /// <param name="asReader"><c>true</c> if leaving as a reader, <c>false</c> otherwise</param> public virtual async Task LeaveAsync(bool asReader) { using (await m_asynclock.LockAsync()) { // If we are already retired, skip this call if (m_isRetired) return; // Countdown if (asReader) m_joinedReaderCount--; else m_joinedWriterCount--; // Retire if required if ((asReader && m_joinedReaderCount <= 0) || (!asReader && m_joinedWriterCount <= 0)) await RetireAsync(false, true).ConfigureAwait(false); } } /// <summary> /// Empties the queue if the channel is retired. /// </summary> /// <param name="isLocked"><c>True</c> if we are already holding the lock, <c>false</c> otherwise</param> private async Task EmptyQueueIfRetiredAsync(bool isLocked) { List<ReaderEntry> readers = null; List<WriterEntry> writers = null; using (isLocked ? default(AsyncLock.Releaser) : await m_asynclock.LockAsync()) { // Countdown as required if (m_retireCount > 0) { m_retireCount--; if (m_retireCount == 0) { // Empty the queues, as we are now retired readers = m_readerQueue; writers = m_writerQueue; // Make sure nothing new enters the queues m_isRetired = true; m_readerQueue = null; m_writerQueue = null; } } } // If there are pending retire messages, send them if (readers != null || writers != null) { if (readers != null) foreach (var r in readers) TrySetException(r, new RetiredException(this.Name)); if (writers != null) foreach (var w in writers) TrySetException(w, new RetiredException(this.Name)); } } /// <summary> /// Callback method used to signal timeout on expired items /// </summary> private async Task ExpireItemsAsync() { KeyValuePair<int, ReaderEntry>[] expiredReaders; KeyValuePair<int, WriterEntry>[] expiredWriters; // Extract all expired items from their queues using (await m_asynclock.LockAsync()) { // If the channel is retired, there is nothing to do here if (m_readerQueue == null || m_writerQueue == null) return; var now = DateTime.Now; expiredReaders = m_readerQueue.Zip(Enumerable.Range(0, m_readerQueue.Count), (n, i) => new KeyValuePair<int, ReaderEntry>(i, n)).Where(x => x.Value.Expires.Ticks != 0 && (x.Value.Expires - now).Ticks <= ExpirationManager.ALLOWED_ADVANCE_EXPIRE_TICKS).ToArray(); expiredWriters = m_writerQueue.Zip(Enumerable.Range(0, m_writerQueue.Count), (n, i) => new KeyValuePair<int, WriterEntry>(i, n)).Where(x => x.Value.Expires.Ticks != 0 && (x.Value.Expires - now).Ticks <= ExpirationManager.ALLOWED_ADVANCE_EXPIRE_TICKS).ToArray(); foreach (var r in expiredReaders.OrderByDescending(x => x.Key)) m_readerQueue.RemoveAt(r.Key); foreach (var r in expiredWriters.OrderByDescending(x => x.Key)) m_writerQueue.RemoveAt(r.Key); } // Send the notifications foreach (var r in expiredReaders.OrderBy(x => x.Value.Expires)) TrySetException(r.Value, new TimeoutException()); // Send the notifications foreach (var w in expiredWriters.OrderBy(x => x.Value.Expires)) TrySetException(w.Value, new TimeoutException()); } #region Task continuation support methods /// <summary> /// Sets the task to be failed /// </summary> /// <param name="entry">The task to set</param> /// <param name="ex">The exception to set</param> private static void TrySetException(ReaderEntry entry, Exception ex) { #if NO_TASK_ASYNCCONTINUE ThreadPool.QueueItem(() => entry.Source.TrySetException(ex)); #else if (entry.EnqueueContinuation) ThreadPool.QueueItem(() => entry.Source.TrySetException(ex)); else entry.Source.TrySetException(ex); #endif } /// <summary> /// Sets the task to be failed /// </summary> /// <param name="entry">The task to set</param> /// <param name="ex">The exception to set</param> private static void TrySetException(WriterEntry entry, Exception ex) { if (entry.Source != null) { #if NO_TASK_ASYNCCONTINUE ThreadPool.QueueItem(() => entry.Source.TrySetException(ex)); #else if (entry.EnqueueContinuation) ThreadPool.QueueItem(() => entry.Source.TrySetException(ex)); else entry.Source.TrySetException(ex); #endif } } /// <summary> /// Tries to set the source to Cancelled /// </summary> /// <param name="entry">The entry to signal</param> private static void TrySetCancelled(IEntry entry) { if (entry is ReaderEntry re) TrySetCancelled(re); else if (entry is WriterEntry we) TrySetCancelled(we); else throw new InvalidOperationException("No such type"); } /// <summary> /// Tries to set the source to Cancelled /// </summary> /// <param name="entry">The entry to signal</param> private static void TrySetCancelled(ReaderEntry entry) { #if NO_TASK_ASYNCCONTINUE ThreadPool.QueueItem(() => entry.Source.TrySetCanceled()); #else if (entry.EnqueueContinuation) ThreadPool.QueueItem(() => entry.Source.TrySetCanceled()); else entry.Source.TrySetCanceled(); #endif } /// <summary> /// Tries to set the source to Cancelled /// </summary> /// <param name="entry">The entry to signal</param> private static void TrySetCancelled(WriterEntry entry) { if (entry.Source != null) { #if NO_TASK_ASYNCCONTINUE ThreadPool.QueueItem(() => entry.Source.TrySetCanceled()); #else if (entry.EnqueueContinuation) ThreadPool.QueueItem(() => entry.Source.TrySetCanceled()); else entry.Source.TrySetCanceled(); #endif } } /// <summary> /// Tries to set the source result /// </summary> /// <param name="entry">The entry to signal</param> /// <param name="value">The value to signal</param> private static void TrySetResult(WriterEntry entry, bool value) { if (entry.Source != null) { #if NO_TASK_ASYNCCONTINUE ThreadPool.QueueItem(() => entry.Source.TrySetResult(value)); #else if (entry.EnqueueContinuation) ThreadPool.QueueItem(() => entry.Source.TrySetResult(value)); else entry.Source.TrySetResult(value); #endif } } /// <summary> /// Sets the source result /// </summary> /// <param name="entry">The entry to signal</param> /// <param name="value">The value to signal</param> private static void SetResult(WriterEntry entry, bool value) { if (entry.Source != null) { #if NO_TASK_ASYNCCONTINUE ThreadPool.QueueItem(() => entry.Source.SetResult(value)); #else if (entry.EnqueueContinuation) ThreadPool.QueueItem(() => entry.Source.SetResult(value)); else entry.Source.SetResult(value); #endif } } /// <summary> /// Sets the source result /// </summary> /// <param name="entry">The entry to signal</param> /// <param name="value">The value to signal</param> private static void SetResult(ReaderEntry entry, T value) { #if NO_TASK_ASYNCCONTINUE ThreadPool.QueueItem(() => entry.Source.SetResult(value)); #else if (entry.EnqueueContinuation) ThreadPool.QueueItem(() => entry.Source.SetResult(value)); else entry.Source.SetResult(value); #endif } #endregion } }
kenkendk/cocol
src/CoCoL/Channel.cs
C#
lgpl-3.0
43,301
<?php class CsvTest extends \PHPUnit_Framework_TestCase { use ExcelFileTestCase; protected $class = '\Maatwebsite\Clerk\Files\Csv'; protected $ext = 'csv'; }
Maatwebsite/Clerk
tests/Files/CsvTest.php
PHP
lgpl-3.0
173
#region Dapplo 2017 - GNU Lesser General Public License // Dapplo - building blocks for .NET applications // Copyright (C) 2017 Dapplo // // For more information see: http://dapplo.net/ // Dapplo repositories are hosted on GitHub: https://github.com/dapplo // // This file is part of Dapplo.Jira // // Dapplo.Jira 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. // // Dapplo.Jira 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 a copy of the GNU Lesser General Public License // along with Dapplo.Jira. If not, see <http://www.gnu.org/licenses/lgpl.txt>. #endregion namespace Dapplo.Jira.Domains { /// <summary> /// The marker interface of the user domain /// </summary> public interface IUserDomain : IJiraDomain { } }
alfadormx/Dapplo.Jira
src/Dapplo.Jira/Domains/IUserDomain.cs
C#
lgpl-3.0
1,161
package tk.teemocode.module.base.vo; import java.io.Serializable; public class Vo implements Serializable, Cloneable { private Long id; private String uuid; private Integer tag; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Integer getTag() { return tag; } public void setTag(Integer tag) { this.tag = tag; } }
yangylsky/teemocode
teemocode-modulebase/src/main/java/tk/teemocode/module/base/vo/Vo.java
Java
lgpl-3.0
520
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_14) on Tue Aug 12 15:38:40 EDT 2008 --> <TITLE> BlockingInfo (NITRO 2.0-RC1 API) </TITLE> <META NAME="keywords" CONTENT="nitf.BlockingInfo class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="BlockingInfo (NITRO 2.0-RC1 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="BlockingInfo.html#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/BlockingInfo.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="BandSource.html" title="class in nitf"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="CloneableObject.html" title="class in nitf"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?nitf%252FBlockingInfo.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="BlockingInfo.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="BlockingInfo.html#fields_inherited_from_class_nitf.NITFObject">FIELD</A>&nbsp;|&nbsp;<A HREF="BlockingInfo.html#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="BlockingInfo.html#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="BlockingInfo.html#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="BlockingInfo.html#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> nitf</FONT> <BR> Class BlockingInfo</H2> <PRE> java.lang.Object <IMG SRC="../resources/inherit.gif" ALT="extended by "><A HREF="NITFObject.html" title="class in nitf">nitf.NITFObject</A> <IMG SRC="../resources/inherit.gif" ALT="extended by "><A HREF="DestructibleObject.html" title="class in nitf">nitf.DestructibleObject</A> <IMG SRC="../resources/inherit.gif" ALT="extended by "><B>nitf.BlockingInfo</B> </PRE> <HR> <DL> <DT><PRE>public final class <B>BlockingInfo</B><DT>extends <A HREF="DestructibleObject.html" title="class in nitf">DestructibleObject</A></DL> </PRE> <P> A representation of the blocking information used in the library. <P> <P> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_nitf.NITFObject"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Fields inherited from class nitf.<A HREF="NITFObject.html" title="class in nitf">NITFObject</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="NITFObject.html#address">address</A>, <A HREF="NITFObject.html#INVALID_ADDRESS">INVALID_ADDRESS</A>, <A HREF="NITFObject.html#NITF_LIBRARY_NAME">NITF_LIBRARY_NAME</A></CODE></TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="BlockingInfo.html#BlockingInfo()">BlockingInfo</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#destructMemory()">destructMemory</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Destruct the underlying memory</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#getLength()">getLength</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the length</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#getNumBlocksPerCol()">getNumBlocksPerCol</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the number of blocks per column</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#getNumBlocksPerRow()">getNumBlocksPerRow</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the number of blocks per row</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#getNumColsPerBlock()">getNumColsPerBlock</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the number of columns per block</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#getNumRowsPerBlock()">getNumRowsPerBlock</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the number of rows per block</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#print(java.io.PrintStream)">print</A></B>(java.io.PrintStream&nbsp;out)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Prints the data pertaining to this object to an OutputStream</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#setLength(int)">setLength</A></B>(int&nbsp;length)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the length</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#setNumBlocksPerCol(int)">setNumBlocksPerCol</A></B>(int&nbsp;numBlocksPerCol)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the number of blocks per column</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#setNumBlocksPerRow(int)">setNumBlocksPerRow</A></B>(int&nbsp;numBlocksPerRow)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the number of blocks per row</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#setNumColsPerBlock(int)">setNumColsPerBlock</A></B>(int&nbsp;numColsPerBlock)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the number of columns per block</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="BlockingInfo.html#setNumRowsPerBlock(int)">setNumRowsPerBlock</A></B>(int&nbsp;numRowsPerBlock)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the number of rows per block</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_nitf.DestructibleObject"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class nitf.<A HREF="DestructibleObject.html" title="class in nitf">DestructibleObject</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="DestructibleObject.html#destruct()">destruct</A>, <A HREF="DestructibleObject.html#finalize()">finalize</A>, <A HREF="DestructibleObject.html#getInfo()">getInfo</A>, <A HREF="DestructibleObject.html#isManaged()">isManaged</A>, <A HREF="DestructibleObject.html#setManaged(boolean)">setManaged</A>, <A HREF="DestructibleObject.html#toString()">toString</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_nitf.NITFObject"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class nitf.<A HREF="NITFObject.html" title="class in nitf">NITFObject</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="NITFObject.html#equals(java.lang.Object)">equals</A>, <A HREF="NITFObject.html#isValid()">isValid</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="BlockingInfo()"><!-- --></A><H3> BlockingInfo</H3> <PRE> public <B>BlockingInfo</B>() throws <A HREF="NITFException.html" title="class in nitf">NITFException</A></PRE> <DL> <DL> <DT><B>Throws:</B> <DD><CODE><A HREF="NITFException.html" title="class in nitf">NITFException</A></CODE></DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="destructMemory()"><!-- --></A><H3> destructMemory</H3> <PRE> protected void <B>destructMemory</B>()</PRE> <DL> <DD>Destruct the underlying memory <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="DestructibleObject.html#destructMemory()">destructMemory</A></CODE> in class <CODE><A HREF="DestructibleObject.html" title="class in nitf">DestructibleObject</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getNumBlocksPerRow()"><!-- --></A><H3> getNumBlocksPerRow</H3> <PRE> public int <B>getNumBlocksPerRow</B>()</PRE> <DL> <DD>Returns the number of blocks per row <P> <DD><DL> <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="setNumBlocksPerRow(int)"><!-- --></A><H3> setNumBlocksPerRow</H3> <PRE> public void <B>setNumBlocksPerRow</B>(int&nbsp;numBlocksPerRow)</PRE> <DL> <DD>Sets the number of blocks per row <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>numBlocksPerRow</CODE> - </DL> </DD> </DL> <HR> <A NAME="getNumBlocksPerCol()"><!-- --></A><H3> getNumBlocksPerCol</H3> <PRE> public int <B>getNumBlocksPerCol</B>()</PRE> <DL> <DD>Returns the number of blocks per column <P> <DD><DL> <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="setNumBlocksPerCol(int)"><!-- --></A><H3> setNumBlocksPerCol</H3> <PRE> public void <B>setNumBlocksPerCol</B>(int&nbsp;numBlocksPerCol)</PRE> <DL> <DD>Sets the number of blocks per column <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>numBlocksPerCol</CODE> - </DL> </DD> </DL> <HR> <A NAME="getNumRowsPerBlock()"><!-- --></A><H3> getNumRowsPerBlock</H3> <PRE> public int <B>getNumRowsPerBlock</B>()</PRE> <DL> <DD>Returns the number of rows per block <P> <DD><DL> <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="setNumRowsPerBlock(int)"><!-- --></A><H3> setNumRowsPerBlock</H3> <PRE> public void <B>setNumRowsPerBlock</B>(int&nbsp;numRowsPerBlock)</PRE> <DL> <DD>Sets the number of rows per block <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>numRowsPerBlock</CODE> - </DL> </DD> </DL> <HR> <A NAME="getNumColsPerBlock()"><!-- --></A><H3> getNumColsPerBlock</H3> <PRE> public int <B>getNumColsPerBlock</B>()</PRE> <DL> <DD>Returns the number of columns per block <P> <DD><DL> <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="setNumColsPerBlock(int)"><!-- --></A><H3> setNumColsPerBlock</H3> <PRE> public void <B>setNumColsPerBlock</B>(int&nbsp;numColsPerBlock)</PRE> <DL> <DD>Sets the number of columns per block <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>numColsPerBlock</CODE> - </DL> </DD> </DL> <HR> <A NAME="getLength()"><!-- --></A><H3> getLength</H3> <PRE> public int <B>getLength</B>()</PRE> <DL> <DD>Returns the length <P> <DD><DL> <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="setLength(int)"><!-- --></A><H3> setLength</H3> <PRE> public void <B>setLength</B>(int&nbsp;length)</PRE> <DL> <DD>Sets the length <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>length</CODE> - </DL> </DD> </DL> <HR> <A NAME="print(java.io.PrintStream)"><!-- --></A><H3> print</H3> <PRE> public void <B>print</B>(java.io.PrintStream&nbsp;out) throws java.io.IOException</PRE> <DL> <DD>Prints the data pertaining to this object to an OutputStream <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>out</CODE> - <DT><B>Throws:</B> <DD><CODE>java.io.IOException</CODE></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="BlockingInfo.html#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/BlockingInfo.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Created: 08/12/2008 03:38:34 PM</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="BandSource.html" title="class in nitf"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="CloneableObject.html" title="class in nitf"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?nitf%252FBlockingInfo.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="BlockingInfo.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="BlockingInfo.html#fields_inherited_from_class_nitf.NITFObject">FIELD</A>&nbsp;|&nbsp;<A HREF="BlockingInfo.html#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="BlockingInfo.html#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="BlockingInfo.html#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="BlockingInfo.html#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &#169; 2004-2008 General Dynamics All Rights Reserved.</i> <div style="float:left;"><a href="http://sourceforge.net/" target="_blank"><img style="width: 151px; height: 38px;" src="http://web.sourceforge.com/images/footer/source.gif" alt="SourceForge.net" border="0" height="38" width="151"></a></div> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-3779761-1"); pageTracker._initData(); pageTracker._trackPageview(); </script> </BODY> </HTML>
mdaus/nitro
docs/nitro-nitf.sourceforge.net/apidocs/java/2.0/nitf/BlockingInfo.html
HTML
lgpl-3.0
20,203
/******************************************************************************* * Copyright (c) 2011 Dipanjan Das * Language Technologies Institute, * Carnegie Mellon University, * All Rights Reserved. * * IntCounter.java is part of SEMAFOR 2.0. * * SEMAFOR 2.0 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. * * SEMAFOR 2.0 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 SEMAFOR 2.0. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package edu.cmu.cs.lti.ark.util.ds.map; import gnu.trove.TObjectIntHashMap; import gnu.trove.TObjectIntIterator; import gnu.trove.TObjectIntProcedure; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Simple integer counter: stores integer values for keys; lookup on nonexistent keys returns 0. * Stores the sum of all values and provides methods for normalizing them. * * A {@code null} key is allowed, although the Iterator returned by {@link #getIterator()} * will not include an entry whose key is {@code null}. * * @author Nathan Schneider (nschneid) * @since 2009-03-19 * @param <T> Type for keys */ public class IntCounter<T> extends AbstractCounter<T, Integer> implements java.io.Serializable { private static final long serialVersionUID = -5622820446958578575L; protected TObjectIntHashMap<T> m_map; protected int m_sum = 0; public final int DEFAULT_VALUE = 0; public IntCounter() { m_map = new TObjectIntHashMap<T>(); } public IntCounter(TObjectIntHashMap<T> map) { m_map = map; int vals[] = map.getValues(); for (int val : vals) { m_sum += val; } } /** * @param key * @return The value stored for a particular key (if present), or 0 otherwise */ public int getT(T key) { if (m_map.containsKey(key)) return m_map.get(key); return DEFAULT_VALUE; } /** Calls {@link #getT(T)}; required for compliance with {@link Map} */ @SuppressWarnings("unchecked") public Integer get(Object key) { return getT((T)key); } /** * @param key * @param newValue * @return Previous value for the key */ public int set(T key, int newValue) { int preval = getT(key); m_map.put(key, newValue); m_sum += newValue - preval; return preval; } /** * Increments a value in the counter by 1. * @param key * @return The new value */ public int increment(T key) { return incrementBy(key, 1); } /** * Changes a value in the counter by adding the specified delta to its current value. * @param key * @param delta * @return The new value */ public int incrementBy(T key, int delta) { int curval = getT(key); int newValue = curval+delta; set(key, newValue); return newValue; } /** * Returns a new counter containing only keys with nonzero values in * at least one of the provided counters. Each key's value is the * number of counters in which it occurs. */ public static <T> IntCounter<T> or(Collection<IntCounter<? extends T>> counters) { IntCounter<T> result = new IntCounter<T>(); for (IntCounter<? extends T> counter : counters) { for (TObjectIntIterator<? extends T> iter = counter.getIterator(); iter.hasNext();) { iter.advance(); if (iter.value()!=0) result.increment(iter.key()); } } return result; } /** * @return Sum of all values currently in the Counter */ public int getSum() { return m_sum; } public IntCounter<T> add(final int val) { final IntCounter<T> result = new IntCounter<T>(); m_map.forEachEntry(new TObjectIntProcedure<T>() { private boolean first = true; public boolean execute(T key, int value) { if ( first ) first = false; int newValue = value + val; result.set(key, newValue); return true; } }); return result; } /** * @return Iterator for the counter. Ignores the {@code null} key (if present). */ public TObjectIntIterator<T> getIterator() { return m_map.iterator(); } @SuppressWarnings("unchecked") public Set<T> keySet() { Object[] okeys = m_map.keys(); HashSet<T> keyset = new HashSet<T>(); for(Object o:okeys) { keyset.add((T)o); } return keyset; } /** * @param valueThreshold * @return New IntCounter containing only entries whose value equals or exceeds the given threshold */ public IntCounter<T> filter(int valueThreshold) { IntCounter<T> result = new IntCounter<T>(); for (TObjectIntIterator<T> iter = getIterator(); iter.hasNext();) { iter.advance(); T key = iter.key(); int value = getT(key); if (value >= valueThreshold) { result.set(key, value); } } int nullValue = getT(null); if (containsKey(null) && nullValue >= valueThreshold) result.set(null, nullValue); return result; } /** Calls {@link #containsKeyT(T)}; required for compliance with {@link Map} */ @SuppressWarnings("unchecked") public boolean containsKey(Object key) { return containsKeyT((T)key); } public boolean containsKeyT(T key) { return m_map.containsKey(key); } public int size() { return m_map.size(); } public String toString() { return toString(Integer.MIN_VALUE, null); } public String toString(int valueThreshold) { return toString(valueThreshold, null); } /** * @param sep Array with two Strings: an entry separator ("," by default, if this is {@code null}), and a key-value separator ("=" by default) */ public String toString(String[] sep) { return toString(Integer.MIN_VALUE, sep); } /** * @param valueThreshold * @param sep Array with two Strings: an entry separator ("," by default, if this is {@code null}), and a key-value separator ("=" by default) * @return A string representation of all (key, value) pairs such that the value equals or exceeds the given threshold */ public String toString(final int valueThreshold, String[] sep) { String entrySep = ","; // default String kvSep = "="; // default if (sep!=null && sep.length>0) { if (sep[0]!=null) entrySep = sep[0]; if (sep.length>1 && sep[1]!=null) kvSep = sep[1]; } final String ENTRYSEP = entrySep; final String KVSEP = kvSep; final StringBuilder buf = new StringBuilder("{"); m_map.forEachEntry(new TObjectIntProcedure<T>() { private boolean first = true; public boolean execute(T key, int value) { if (value >= valueThreshold) { if ( first ) first = false; else buf.append(ENTRYSEP); buf.append(key); buf.append(KVSEP); buf.append(value); } return true; } }); buf.append("}"); return buf.toString(); } public IntCounter<T> clone() { return new IntCounter<T>(m_map.clone()); } // Other methods implemented by the Map interface @Override public void clear() { throw new UnsupportedOperationException("IntCounter.clear() unsupported"); } @Override public boolean containsValue(Object value) { return m_map.containsValue((Integer)value); } @Override public Set<java.util.Map.Entry<T, Integer>> entrySet() { throw new UnsupportedOperationException("IntCounter.entrySet() unsupported"); } @Override public boolean isEmpty() { return m_map.isEmpty(); } @Override public Integer put(T key, Integer value) { return set(key,value); } @Override public void putAll(Map<? extends T, ? extends Integer> m) { throw new UnsupportedOperationException("IntCounter.putAll() unsupported"); } @Override public Integer remove(Object key) { throw new UnsupportedOperationException("IntCounter.remove() unsupported"); } @Override public Collection<Integer> values() { throw new UnsupportedOperationException("IntCounter.values() unsupported"); } }
jtraviesor/semafor-parser
semafor/src/main/java/edu/cmu/cs/lti/ark/util/ds/map/IntCounter.java
Java
lgpl-3.0
8,362
/************************************************************************/ /* */ /* FramepaC -- frame manipulation in C++ */ /* Version 2.01 */ /* by Ralf Brown <[email protected]> */ /* */ /* File frsymbol.h class FrSymbol */ /* LastEdit: 08nov2015 */ /* */ /* (c) Copyright 1994,1995,1996,1997,1998,2000,2001,2009,2012,2015 */ /* Ralf Brown/Carnegie Mellon University */ /* 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, */ /* version 3. */ /* */ /* 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 (file COPYING) and General Public License (file */ /* GPL.txt) along with this program. If not, see */ /* http://www.gnu.org/licenses/ */ /* */ /************************************************************************/ #ifndef __FRSYMBOL_H_INCLUDED #define __FRSYMBOL_H_INCLUDED #ifndef __FRLIST_H_INCLUDED #include "frlist.h" #endif #include <string.h> #if defined(__GNUC__) # pragma interface #endif /**********************************************************************/ /* Optional Demon support */ /**********************************************************************/ typedef bool FrDemonFunc(const FrSymbol *frame, const FrSymbol *slot, const FrSymbol *facet, const FrObject *value, va_list args) ; enum FrDemonType { DT_IfCreated, DT_IfAdded, DT_IfRetrieved, DT_IfMissing, DT_IfDeleted } ; struct FrDemonList ; struct FrDemons { FrDemonList *if_created ; // demons to call just after creating facet FrDemonList *if_added ; // demons to call just before adding filler FrDemonList *if_missing ; // demons to call before attempting inheritance FrDemonList *if_retrieved ; // demons to call just before returning filler FrDemonList *if_deleted ; // demons to call just after deleting filler void *operator new(size_t size) { return FrMalloc(size) ; } void operator delete(void *obj) { FrFree(obj) ; } } ; /**********************************************************************/ /**********************************************************************/ #ifdef FrSYMBOL_RELATION # define if_FrSYMBOL_RELATION(x) x #else # define if_FrSYMBOL_RELATION(x) #endif #ifdef FrSYMBOL_VALUE # define if_FrSYMBOL_VALUE(x) x #else # define if_FrSYMBOL_VALUE(x) #endif #ifdef FrDEMONS # define if_FrDEMONS(x) x #else # define if_FrDEMONS(x) #endif FrSymbol *findSymbol(const char *name) ; class FrSymbol : public FrAtom { private: FrFrame *m_frame ; // in lieu of a full property list, if_FrSYMBOL_RELATION(FrSymbol *m_inv_relation) ;// we have these 2 ptrs if_FrSYMBOL_VALUE(FrObject *m_value) ; if_FrDEMONS(FrDemons *theDemons) ; char m_name[1] ; //__attribute__((bnd_variable_size)) ; private: // methods void setInvRelation(FrSymbol *inv) { (void)inv ; if_FrSYMBOL_RELATION(m_inv_relation = inv) ; } void setDemons(FrDemons *d) { (void)d ; if_FrDEMONS(theDemons = d) ; } void *operator new(size_t size,void *where) { (void)size; return where ; } FrSymbol(const char *symname,int len) // private use for FramepaC only // { memcpy(m_name,(char *)symname,len) ; if_FrSYMBOL_VALUE(m_value = &UNBOUND) ; setFrame(0) ; setInvRelation(0) ; setDemons(0) ; } public: FrSymbol() _fnattr_noreturn ; virtual ~FrSymbol() _fnattr_noreturn ; void *operator new(size_t size) { return FrMalloc(size) ; } void operator delete(void *sym, size_t) { FrFree(sym) ; } virtual FrObjectType objType() const ; virtual const char *objTypeName() const ; virtual FrObjectType objSuperclass() const ; virtual ostream &printValue(ostream &output) const ; virtual char *displayValue(char *buffer) const ; virtual size_t displayLength() const ; virtual void freeObject() {} // can never free a FrSymbol virtual long int intValue() const ; virtual const char *printableName() const ; virtual FrSymbol *coerce2symbol(FrCharEncoding) const { return (FrSymbol*)this ; } virtual bool symbolp() const ; virtual size_t length() const ; virtual int compare(const FrObject *obj) const ; FrSymbol *makeSymbol(const char *nam) const ; FrSymbol *findSymbol(const char *nam) const ; const char *symbolName() const { return m_name ; } static bool nameNeedsQuoting(const char *name) ; FrFrame *symbolFrame() const { return m_frame ; } ostream &printBinding(ostream &output) const ; #ifdef FrSYMBOL_VALUE void setValue(const FrObject *newval) { m_value = (FrObject *)newval; } FrObject *symbolValue() const { return m_value ; } #else void setValue(const FrObject *newval) ; FrObject *symbolValue() const ; #endif /* FrSYMBOL_VALUE */ #ifdef FrDEMONS FrDemons *demons() const { return theDemons ; } bool addDemon(FrDemonType type,FrDemonFunc *func, va_list args = 0) ; bool removeDemon(FrDemonType type, FrDemonFunc *func) ; #else FrDemons *demons() const { return 0 ; } bool addDemon(FrDemonType,FrDemonFunc,va_list=0) { return false ; } bool removeDemon(FrDemonType,FrDemonFunc) { return false ; } #endif /* FrDEMONS */ void setFrame(const FrFrame *fr) { m_frame = (FrFrame *)fr ; } void defineRelation(const FrSymbol *inverse) ; void undefineRelation() ; #ifdef FrSYMBOL_RELATION FrSymbol *inverseRelation() const { return m_inv_relation ; } #else FrSymbol *inverseRelation() const { return 0 ; } #endif /* FrSYMBOL_RELATION */ //functions to support VFrames FrFrame *createFrame() ; FrFrame *createVFrame() ; FrFrame *createInstanceFrame() ; bool isFrame() ; bool isDeletedFrame() ; FrFrame *findFrame() ; int startTransaction() ; int endTransaction(int transaction) ; int abortTransaction(int transaction) ; FrFrame *lockFrame() ; static bool lockFrames(FrList *locklist) ; bool unlockFrame() ; static bool unlockFrames(FrList *locklist) ; bool isLocked() const ; bool emptyFrame() ; bool dirtyFrame() ; int commitFrame() ; int discardFrame() ; int deleteFrame() ; FrFrame *oldFrame(int generation) ; FrFrame *copyFrame(FrSymbol *newframe, bool temporary = false) ; bool renameFrame(FrSymbol *newname) ; FrSlot *createSlot(const FrSymbol *slotname) ; void createFacet(const FrSymbol *slotname, const FrSymbol *facetname) ; void addFiller(const FrSymbol *slotname,const FrSymbol *facet, const FrObject *filler) ; void addValue(const FrSymbol *slotname, const FrObject *filler) ; void addSem(const FrSymbol *slotname, const FrObject *filler) ; void addFillers(const FrSymbol *slotname,const FrSymbol *facet, const FrList *fillers); void addValues(const FrSymbol *slotname, const FrList *fillers) ; void addSems(const FrSymbol *slotname, const FrList *fillers) ; void pushFiller(const FrSymbol *slotname,const FrSymbol *facet, const FrObject *filler) ; FrObject *popFiller(const FrSymbol *slotname, const FrSymbol *facet) ; void replaceFiller(const FrSymbol *slotname, const FrSymbol *facetname, const FrObject *old, const FrObject *newfiller) ; void replaceFiller(const FrSymbol *slotname, const FrSymbol *facetname, const FrObject *old, const FrObject *newfiller, FrCompareFunc cmp) ; void replaceFacet(const FrSymbol *slotname, const FrSymbol *facet, const FrList *newfillers) ; void eraseFrame() ; void eraseCopyFrame() ; void eraseSlot(const char *slotname) ; void eraseSlot(const FrSymbol *slotname) ; void eraseFacet(const FrSymbol *slotname,const FrSymbol *facetname) ; void eraseFiller(const FrSymbol *slotname,const FrSymbol *facetname, const FrObject *filler) ; void eraseFiller(const FrSymbol *slotname,const FrSymbol *facetname, const FrObject *filler,FrCompareFunc cmp) ; void eraseSem(const FrSymbol *slotname, const FrObject *filler) ; void eraseSem(const FrSymbol *slotname, const FrObject *filler, FrCompareFunc cmp) ; void eraseValue(const FrSymbol *slotname, const FrObject *filler) ; void eraseValue(const FrSymbol *slotname, const FrObject *filler, FrCompareFunc cmp) ; // const FrList *getImmedFillers(const FrSymbol *slotname, // const FrSymbol *facet) const ; const FrList *getFillers(const FrSymbol *slotname, const FrSymbol *facet, bool inherit = true) ; FrObject *firstFiller(const FrSymbol *slotname,const FrSymbol *facet, bool inherit = true) ; const FrList *getValues(const FrSymbol *slotname,bool inherit = true) ; FrObject *getValue(const FrSymbol *slotname,bool inherit=true) ; const FrList *getSem(const FrSymbol *slotname,bool inherit = true) ; bool isA_p(FrSymbol *poss_parent) ; bool partOf_p(FrSymbol *poss_container) ; FrList *collectSlots(FrInheritanceType inherit,FrList *allslots=0, bool include_names = false) ; void inheritAll() ; void inheritAll(FrInheritanceType inherit) ; FrList *allSlots() const ; FrList *slotFacets(const FrSymbol *slotname) const ; bool doSlots(bool (*func)(const FrFrame *frame, const FrSymbol *slot, va_list args), va_list args) ; bool doFacets(const FrSymbol *slotname, bool (*func)(const FrFrame *frame, const FrSymbol *slot, const FrSymbol *facet, va_list args), va_list args) ; bool doAllFacets(bool (*func)(const FrFrame *frame, const FrSymbol *slot, const FrSymbol *facet, va_list args), va_list args) ; //overloaded operators int operator == (const char *symname) const { return (FrSymbol *)this == findSymbol(symname) ; } int operator != (const char *symname) const { return (FrSymbol *)this != findSymbol(symname) ; } operator char* () const { return (char*)symbolName() ; } //friends friend class FrSymbolTable ; } ; //---------------------------------------------------------------------- // non-member functions related to class FrSymbol FrSymbol *read_Symbol(istream &input) ; FrSymbol *string_to_Symbol(const char *&input) ; bool verify_Symbol(const char *&input, bool strict = false) ; FrSymbol *makeSymbol(const FrSymbol *sym) ; // copy from another symbol table FrSymbol *gensym(const char *basename = 0, const char *suffix = 0) ; FrSymbol *gensym(const FrSymbol *basename) ; void define_relation(const char *relname,const char *invname) ; void undefine_relation(const char *relname) ; /**********************************************************************/ /* Optional Demon support */ /**********************************************************************/ #ifdef FrDEMONS inline bool add_demon(FrSymbol *sym, FrDemonType type, FrDemonFunc *func,va_list args) { return (sym) ? sym->addDemon(type,func,args) : false ; } inline bool remove_demon(FrSymbol *sym, FrDemonType type, FrDemonFunc *func) { return (sym) ? sym->removeDemon(type,func) : false ; } #endif /* FrDEMONS */ /**********************************************************************/ /* overloaded operators (non-member functions) */ /**********************************************************************/ inline istream &operator >> (istream &input,FrSymbol *&obj) { FramepaC_bgproc() ; obj = read_Symbol(input) ; return input ; } #endif /* !__FRSYMBOL_H_INCLUDED */ // end of file frsymbol.h //
ralfbrown/framepac
src/frsymbol.h
C
lgpl-3.0
12,136
<?php /** * Custom factory for photos with method to get next sort order * * @package Modules * @subpackage PhotoGallery * @author Peter Epp * @version $Id: photo_factory.php 13843 2011-07-27 19:45:49Z teknocat $ */ class PhotoFactory extends ModelFactory { /** * Find and return the next sort order to use * * @return void * @author Peter Epp */ public function next_sort_order($album_id) { return parent::next_highest('sort_order',1,"`album_id` = {$album_id}"); } }
theteknocat/Biscuit-PhotoGallery
factories/photo_factory.php
PHP
lgpl-3.0
490
/* * Copyright (C) 2010 Tieto Czech, s.r.o. * All rights reserved. * Contact: Tomáš Hanák <[email protected]> * Radek Valášek <[email protected]> * Martin Kampas <[email protected]> * Jiří Litomyský <[email protected]> * * This file is part of sfd [Simple Form Designer]. * * SFD 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. * * 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 program. If not, see <http://www.gnu.org/licenses/>. * */ /*! \file * \brief This is an automatically included header file. * * This file should mostly contain imports of things defined somewhere else. * Usual piece of code put in this file is supposed to looks like * * \code #include "path/to/some/header/file.hpp" namespace sfd { using some::symbol; using some::other_symbol; } * \endcode * * \author Martin Kampas <[email protected]>, 01/2010 */ #pragma once ////////////////////////////////////////////////////////////////////////////// // IMPORTS #include "tools/PIMPL.hpp" namespace sfd { using tools::p_ptr; } ////////////////////////////////////////////////////////////////////////////// // OTHER STUFF //! Redefinition to make use of GCC's __PRETTY_FUNCTION__ #define __func__ __PRETTY_FUNCTION__ //! Use it to mark deprecated symbols #define SFD_DEPRECATED __attribute__((deprecated)) #include <QtCore/QDebug>
tomhanak/form-designer
src/common.hpp
C++
lgpl-3.0
1,967
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_STARTONDEMANDAPPREPLICATIONRESPONSE_P_H #define QTAWS_STARTONDEMANDAPPREPLICATIONRESPONSE_P_H #include "smsresponse_p.h" namespace QtAws { namespace SMS { class StartOnDemandAppReplicationResponse; class StartOnDemandAppReplicationResponsePrivate : public SmsResponsePrivate { public: explicit StartOnDemandAppReplicationResponsePrivate(StartOnDemandAppReplicationResponse * const q); void parseStartOnDemandAppReplicationResponse(QXmlStreamReader &xml); private: Q_DECLARE_PUBLIC(StartOnDemandAppReplicationResponse) Q_DISABLE_COPY(StartOnDemandAppReplicationResponsePrivate) }; } // namespace SMS } // namespace QtAws #endif
pcolby/libqtaws
src/sms/startondemandappreplicationresponse_p.h
C
lgpl-3.0
1,400
/* * Project: NextGIS Mobile * Purpose: Mobile GIS for Android. * Author: Dmitry Baryshnikov (aka Bishop), [email protected] * Author: NikitaFeodonit, [email protected] * Author: Stanislav Petriakov, [email protected] * ***************************************************************************** * Copyright (c) 2015-2017, 2019 NextGIS, [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser 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 Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextgis.maplib.util; import android.accounts.Account; import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.Context; import android.content.SyncInfo; import android.os.Build; import android.util.Base64; import com.nextgis.maplib.api.IGISApplication; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import static com.nextgis.maplib.util.Constants.JSON_END_DATE_KEY; import static com.nextgis.maplib.util.Constants.JSON_SIGNATURE_KEY; import static com.nextgis.maplib.util.Constants.JSON_START_DATE_KEY; import static com.nextgis.maplib.util.Constants.JSON_SUPPORTED_KEY; import static com.nextgis.maplib.util.Constants.JSON_USER_ID_KEY; import static com.nextgis.maplib.util.Constants.SUPPORT; public class AccountUtil { public static boolean isProUser(Context context) { File support = context.getExternalFilesDir(null); if (support == null) support = new File(context.getFilesDir(), SUPPORT); else support = new File(support, SUPPORT); try { String jsonString = FileUtil.readFromFile(support); JSONObject json = new JSONObject(jsonString); if (json.optBoolean(JSON_SUPPORTED_KEY)) { final String id = json.getString(JSON_USER_ID_KEY); final String start = json.getString(JSON_START_DATE_KEY); final String end = json.getString(JSON_END_DATE_KEY); final String data = id + start + end + "true"; final String signature = json.getString(JSON_SIGNATURE_KEY); return verifySignature(data, signature); } } catch (JSONException | IOException ignored) { } return false; } private static boolean verifySignature(String data, String signature) { try { // add public key KeyFactory keyFactory = KeyFactory.getInstance("RSA"); String key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzbmnrTLjTLxqCnIqXgIJ\n" + "jebXVOn4oV++8z5VsBkQwK+svDkGK/UcJ4YjXUuPqyiZwauHGy1wizGCgVIRcPNM\n" + "I0n9W6797NMFaC1G6Rp04ISv7DAu0GIZ75uDxE/HHDAH48V4PqQeXMp01Uf4ttti\n" + "XfErPKGio7+SL3GloEqtqGbGDj6Yx4DQwWyIi6VvmMsbXKmdMm4ErczWFDFHIxpV\n" + "ln/VfX43r/YOFxqt26M7eTpaBIvAU6/yWkIsvidMNL/FekQVTiRCl/exPgioDGrf\n" + "06z5a0sd3NDbS++GMCJstcKxkzk5KLQljAJ85Jciiuy2vv14WU621ves8S9cMISO\n" + "HwIDAQAB"; byte[] keyBytes = Base64.decode(key.getBytes("UTF-8"), Base64.DEFAULT); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); PublicKey publicKey = keyFactory.generatePublic(spec); // verify signature Signature signCheck = Signature.getInstance("SHA256withRSA"); signCheck.initVerify(publicKey); signCheck.update(data.getBytes("UTF-8")); byte[] sigBytes = Base64.decode(signature, Base64.DEFAULT); return signCheck.verify(sigBytes); } catch (Exception e) { return false; } } public static boolean isSyncActive(Account account, String authority) { return isSyncActiveHoneycomb(account, authority); } public static boolean isSyncActiveHoneycomb(Account account, String authority) { for (SyncInfo syncInfo : ContentResolver.getCurrentSyncs()) { if (syncInfo.account.equals(account) && syncInfo.authority.equals(authority)) { return true; } } return false; } public static AccountData getAccountData(Context context, String accountName) throws IllegalStateException { IGISApplication app = (IGISApplication) context.getApplicationContext(); Account account = app.getAccount(accountName); if (null == account) { throw new IllegalStateException("Account is null"); } AccountData accountData = new AccountData(); accountData.url = app.getAccountUrl(account); accountData.login = app.getAccountLogin(account); accountData.password = app.getAccountPassword(account); return accountData; } public static class AccountData { public String url; public String login; public String password; } }
nextgis/android_maplib
src/main/java/com/nextgis/maplib/util/AccountUtil.java
Java
lgpl-3.0
5,591
package edu.ucsd.arcum.interpreter.ast; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import edu.ucsd.arcum.exceptions.ArcumError; import edu.ucsd.arcum.exceptions.SourceLocation; import edu.ucsd.arcum.interpreter.ast.expressions.ConstraintExpression; import edu.ucsd.arcum.interpreter.query.EntityDataBase; import edu.ucsd.arcum.interpreter.query.OptionMatchTable; import edu.ucsd.arcum.util.StringUtil; public class MapTraitArgument extends MapNameValueBinding { private RequireMap map; private ConstraintExpression patternExpr; private List<FormalParameter> formals; // TODO: paramNames should be allowed to have the types explicit, just like // any other realize statement public MapTraitArgument(SourceLocation location, RequireMap map, String traitName, List<FormalParameter> formals, ConstraintExpression patternExpr) { super(location, traitName); this.map = map; this.patternExpr = patternExpr; this.formals = formals; } public void initializeValue(EntityDataBase edb, Option option, OptionMatchTable table) throws CoreException { StaticRealizationStatement pseudoStmt; OptionInterface optionIntf = option.getOptionInterface(); List<FormalParameter> allParams = optionIntf.getSingletonParameters(); List<FormalParameter> formals = null; for (FormalParameter param : allParams) { if (param.getIdentifier().equals(getName())) { formals = param.getTraitArguments(); break; } } if (formals == null) { ArcumError.fatalUserError(getLocation(), "Couldn't find %s", getName()); } pseudoStmt = StaticRealizationStatement.makeNested(map, getName(), patternExpr, formals, this.getLocation()); pseudoStmt.typeCheckAndValidate(optionIntf); List<StaticRealizationStatement> stmts = Lists.newArrayList(pseudoStmt); try { EntityDataBase.pushCurrentDataBase(edb); RealizationStatement.collectivelyRealizeStatements(stmts, edb, table); } finally { EntityDataBase.popMostRecentDataBase(); } } @Override public Object getValue() { return this; } @Override public String toString() { return String.format("%s(%s): %s", getName(), StringUtil.separate(formals), patternExpr.toString()); } public void checkUserDefinedPredicates(List<TraitSignature> tupleSets) { Set<String> names = Sets.newHashSet(); names.addAll(Lists.transform(formals, FormalParameter.getIdentifier)); patternExpr.checkUserDefinedPredicates(tupleSets, names); } }
mshonle/Arcum
src/edu/ucsd/arcum/interpreter/ast/MapTraitArgument.java
Java
lgpl-3.0
2,934
package edu.hm.gamedev.server.packets.client2server; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonProperty; import edu.hm.gamedev.server.packets.Packet; import edu.hm.gamedev.server.packets.Type; public class JoinGame extends Packet { private final String gameName; @JsonCreator public JoinGame(@JsonProperty("gameName") String gameName) { super(Type.JOIN_GAME); this.gameName = gameName; } public String getGameName() { return gameName; } @Override public String toString() { return "JoinGame{" + "gameName='" + gameName + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } JoinGame joinGame = (JoinGame) o; if (gameName != null ? !gameName.equals(joinGame.gameName) : joinGame.gameName != null) { return false; } return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (gameName != null ? gameName.hashCode() : 0); return result; } }
phxql/gamedev-server
src/main/java/edu/hm/gamedev/server/packets/client2server/JoinGame.java
Java
lgpl-3.0
1,227
#!/usr/bin/env python import sys, argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file") args = parser.parse_args() stats = dict() if args.input is None: print "Error: No input file" with open(args.input) as in_file: for line in in_file.readlines(): time = int(line.split()[0]) tx_bytes = int(line.split()[1]) stats[time] = tx_bytes stats = sorted(stats.items()) start_time = stats[0][0] prev_tx = stats[0][1] no_traffic_flag = True for time, tx_bytes in stats: if no_traffic_flag: if tx_bytes > (prev_tx+100000): no_traffic_flag = False start_time, prev_tx = time, tx_bytes else: print (time-start_time), (tx_bytes-prev_tx) prev_tx = tx_bytes if __name__ == "__main__": main()
merlin-lang/kulfi
experiments/testbed/results/plot/sort.py
Python
lgpl-3.0
989
// Copyright 2017 The AriseID Authors // This file is part AriseID. // // AriseID 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. // // AriseID 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 AriseID. If not, see <http://www.gnu.org/licenses/>. package main import ( "bytes" "fmt" "math/big" "math/rand" "time" "github.com/ariseid/ariseid-core/common" "github.com/ariseid/ariseid-core/core" "github.com/ariseid/ariseid-core/log" "github.com/ariseid/ariseid-core/params" ) // makeGenesis creates a new genesis struct based on some user input. func (w *wizard) makeGenesis() { // Construct a default genesis block genesis := &core.Genesis{ Timestamp: uint64(time.Now().Unix()), LifeLimit: 4700000, Difficulty: big.NewInt(1048576), Alloc: make(core.GenesisAlloc), Config: &params.ChainConfig{ HomesteadBlock: big.NewInt(1), EIP150Block: big.NewInt(2), EIP155Block: big.NewInt(3), EIP158Block: big.NewInt(3), }, } // Figure out which consensus engine to choose fmt.Println() fmt.Println("Which consensus engine to use? (default = clique)") fmt.Println(" 1. Idhash - proof-of-work") fmt.Println(" 2. Clique - proof-of-authority") choice := w.read() switch { case choice == "1": // In case of idhash, we're pretty much done genesis.Config.Idhash = new(params.IdhashConfig) genesis.ExtraData = make([]byte, 32) case choice == "" || choice == "2": // In the case of clique, configure the consensus parameters genesis.Difficulty = big.NewInt(1) genesis.Config.Clique = &params.CliqueConfig{ Period: 15, Epoch: 30000, } fmt.Println() fmt.Println("How many seconds should blocks take? (default = 15)") genesis.Config.Clique.Period = uint64(w.readDefaultInt(15)) // We also need the initial list of signers fmt.Println() fmt.Println("Which accounts are allowed to seal? (mandatory at least one)") var signers []common.Address for { if address := w.readAddress(); address != nil { signers = append(signers, *address) continue } if len(signers) > 0 { break } } // Sort the signers and embed into the extra-data section for i := 0; i < len(signers); i++ { for j := i + 1; j < len(signers); j++ { if bytes.Compare(signers[i][:], signers[j][:]) > 0 { signers[i], signers[j] = signers[j], signers[i] } } } genesis.ExtraData = make([]byte, 32+len(signers)*common.AddressLength+65) for i, signer := range signers { copy(genesis.ExtraData[32+i*common.AddressLength:], signer[:]) } default: log.Crit("Invalid consensus engine choice", "choice", choice) } // Consensus all set, just ask for initial funds and go fmt.Println() fmt.Println("Which accounts should be pre-funded? (advisable at least one)") for { // Read the address of the account to fund if address := w.readAddress(); address != nil { genesis.Alloc[*address] = core.GenesisAccount{ Balance: new(big.Int).Lsh(big.NewInt(1), 256-7), // 2^256 / 128 (allow many pre-funds without balance overflows) } continue } break } // Add a batch of precompile balances to avoid them getting deleted for i := int64(0); i < 256; i++ { genesis.Alloc[common.BigToAddress(big.NewInt(i))] = core.GenesisAccount{Balance: big.NewInt(1)} } fmt.Println() // Query the user for some custom extras fmt.Println() fmt.Println("Specify your chain/network ID if you want an explicit one (default = random)") genesis.Config.ChainId = new(big.Int).SetUint64(uint64(w.readDefaultInt(rand.Intn(65536)))) fmt.Println() fmt.Println("Anything fun to embed into the genesis block? (max 32 bytes)") extra := w.read() if len(extra) > 32 { extra = extra[:32] } genesis.ExtraData = append([]byte(extra), genesis.ExtraData[len(extra):]...) // All done, store the genesis and flush to disk w.conf.genesis = genesis }
AriseID/ariseid-core
cmd/puppeth/wizard_genesis.go
GO
lgpl-3.0
4,285
@echo off rem HTMLParser Library - A java-based parser for HTML rem http:remhtmlparser.org rem Copyright (C) 2006 Derrick Oswald rem rem Revision Control Information rem rem $URL: file:///svn/p/htmlparser/code/tags/HTMLParserProject-2.1/src/main/bin/beanybaby.cmd $ rem $Author: derrickoswald $ rem $Date: 2006-09-16 14:44:17 +0000 (Sat, 16 Sep 2006) $ rem $Revision: 4 $ rem rem This library is free software; you can redistribute it and/or rem modify it under the terms of the Common Public License; either rem version 1.0 of the License, or (at your option) any later version. rem rem This library is distributed in the hope that it will be useful, rem but WITHOUT ANY WARRANTY; without even the implied warranty of rem MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the rem Common Public License for more details. rem rem You should have received a copy of the Common Public License rem along with this library; if not, the license is available from rem the Open Source Initiative (OSI) website: rem http://opensource.org/licenses/cpl1.0.php rem setlocal enableextensions if errorlevel 1 goto no_extensions_error for %%i in ("%0") do set cmd_path=%%~dpi for /D %%i in ("%cmd_path%..\lib\") do set lib_path=%%~dpi if not exist "%lib_path%htmllexer.jar" goto no_htmllexer_jar_error if not exist "%lib_path%htmlparser.jar" goto no_htmlparser_jar_error for %%i in (java.exe) do set java_executable=%%~$PATH:i if "%java_executable%"=="" goto no_java_error @echo on %java_executable% -classpath "%lib_path%htmlparser.jar;%lib_path%htmllexer.jar" org.htmlparser.beans.BeanyBaby %1 %2 @echo off goto end :no_extensions_error echo Unable to use CMD extensions goto end :no_htmllexer_jar_error echo Unable to find htmllexer.jar goto end :no_htmlparser_jar_error echo Unable to find htmlparser.jar goto end :no_java_error echo Unable to find java.exe goto end :end
socialwareinc/html-parser
src/main/bin/beanybaby.cmd
Batchfile
lgpl-3.0
1,921
package uk.co.wehavecookies56.kk.common.container.slot; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.SlotItemHandler; import uk.co.wehavecookies56.kk.common.item.ItemSynthesisBagS; import uk.co.wehavecookies56.kk.common.item.base.ItemSynthesisMaterial; public class SlotSynthesisBag extends SlotItemHandler { public SlotSynthesisBag (IItemHandler inventory, int index, int x, int y) { super(inventory, index, x, y); } @Override public boolean isItemValid (ItemStack stack) { return !(stack.getItem() instanceof ItemSynthesisBagS) && stack.getItem() instanceof ItemSynthesisMaterial; } }
Wehavecookies56/Kingdom-Keys-Re-Coded
src/main/java/uk/co/wehavecookies56/kk/common/container/slot/SlotSynthesisBag.java
Java
lgpl-3.0
697
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ package org.sonar.duplications.statement; import org.sonar.duplications.statement.matcher.AnyTokenMatcher; import org.sonar.duplications.statement.matcher.BridgeTokenMatcher; import org.sonar.duplications.statement.matcher.ExactTokenMatcher; import org.sonar.duplications.statement.matcher.ForgetLastTokenMatcher; import org.sonar.duplications.statement.matcher.OptTokenMatcher; import org.sonar.duplications.statement.matcher.TokenMatcher; import org.sonar.duplications.statement.matcher.UptoTokenMatcher; public final class TokenMatcherFactory { private TokenMatcherFactory() { } public static TokenMatcher from(String token) { return new ExactTokenMatcher(token); } public static TokenMatcher to(String... tokens) { return new UptoTokenMatcher(tokens); } public static TokenMatcher bridge(String lToken, String rToken) { return new BridgeTokenMatcher(lToken, rToken); } public static TokenMatcher anyToken() { // TODO Godin: we can return singleton instance return new AnyTokenMatcher(); } public static TokenMatcher opt(TokenMatcher optMatcher) { return new OptTokenMatcher(optMatcher); } public static TokenMatcher forgetLastToken() { // TODO Godin: we can return singleton instance return new ForgetLastTokenMatcher(); } public static TokenMatcher token(String token) { return new ExactTokenMatcher(token); } }
SonarSource/sonarqube
sonar-duplications/src/main/java/org/sonar/duplications/statement/TokenMatcherFactory.java
Java
lgpl-3.0
2,239
package com.farevee.groceries; public class BulkItem implements Item { //+--------+------------------------------------------------------ // | Fields | // +--------+ /** * The type of food of the bulk item */ BulkFood food; /** * The unit of the bulk item */ Units unit; /** * The amount of bulk item */ int amount; // +--------------+------------------------------------------------ // | Constructor | // +--------------+ public BulkItem(BulkFood food, Units unit, int amount) { this.food = food; this.unit = unit; this.amount = amount; } // BulkItem (BulkFood, Units, int) //+-----------+--------------------------------------------------- // | Methods | // +-----------+ /** * Retrieve the Weight of BulkItem, including unit and amount */ public Weight getWeight() { return new Weight(this.unit, this.amount); }//getWeight() /** * Retrieve the amount of Weight of BulkItem */ @Override public int getWeightAmount() { return this.getWeight().amount; }//getWeightAmount() //Get the unit of weight @Override public Units getWeightUnit() { return this.unit; }//getWeightUnit() //Get the price public int getPrice() { return this.food.pricePerUnit * this.amount; }//getPrice() //Creates a string for the name public String toString() { return (amount + " " + unit.name + " of " + food.name); }//toString() //Gets the name @Override public String getName() { return this.food.name; }//getName() //Get the type of BulkFood public BulkFood getBulkFoodType() { return this.food; }//getBulkFoodType() //Get the amount of BulkItem public int getBulkItemAmount() { return this.amount; }//getBulkItemAmount() //Compares two BulkItem public boolean equalZ(Object thing) { if (thing instanceof BulkItem) { BulkItem anotherBulkItem = (BulkItem) thing; return ((this.food.name.equals(anotherBulkItem.food.name)) && (this.unit.name.equals(anotherBulkItem.unit.name))); } else { return Boolean.FALSE; } }//equals(Object) public void increaseAmount(int x) { this.amount += x; }//increaseAmount(int) }
lordzason/csc207-hw07-combined-with-hw06
src/com/farevee/groceries/BulkItem.java
Java
lgpl-3.0
2,267
/******************************************************************** ** Image Component Library (ICL) ** ** ** ** Copyright (C) 2006-2013 CITEC, University of Bielefeld ** ** Neuroinformatics Group ** ** Website: www.iclcv.org and ** ** http://opensource.cit-ec.de/projects/icl ** ** ** ** File : ICLFilter/src/ICLFilter/InplaceLogicalOp.h ** ** Module : ICLFilter ** ** Authors: Christof Elbrechter ** ** ** ** ** ** GNU LESSER GENERAL PUBLIC LICENSE ** ** This file may be used under the terms of the GNU Lesser General ** ** Public License version 3.0 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 license requirements will ** ** be met: http://www.gnu.org/licenses/lgpl-3.0.txt ** ** ** ** The development of this software was supported by the ** ** Excellence Cluster EXC 277 Cognitive Interaction Technology. ** ** The Excellence Cluster EXC 277 is a grant of the Deutsche ** ** Forschungsgemeinschaft (DFG) in the context of the German ** ** Excellence Initiative. ** ** ** ********************************************************************/ #pragma once #include <ICLUtils/CompatMacros.h> #include <ICLFilter/InplaceOp.h> namespace icl{ namespace filter{ /// Filter class for logical in-place operations \ingroup INPLACE /** The InplaceLogicalOp class provides functionalities for arbitrary logical in-place operations on images. The operator can be set to implement a certain operation using a given optype value. Logical (non-bit-wise) operations result in images of value 0 or 255.\n Operation list can be split into two sections: - pure logical operations (AND OR XOR and NOT) - bit-wise operations (bit-wise-AND bit-wise-OR bit-wise-XOR and bit-wise-NOT) Pure Logical operations are available for all types; bit-wise operations make no sense on floating point data, hence these operations are available for integer types only. Supported operator types (implementation on pixel value P and operator value V in braces) - <b>andOp</b> "logical and" ((P&&V)*255) - <b>orOp</b> "logical or" ((P||V)*255) - <b>xorOp</b> "logical and" ((!!P xor !!V)*255) - <b>notOp</b> "logical not" ((!P)*255) operator value is not used in this case - <b>binAndOp</b> "binary and" (P&V) [integer types only] - <b>binOrOp</b> "binary or" ((P|V) [integer types only] - <b>binXorOp</b> "binary and" (P^V) [integer types only] - <b>binNotOp</b> "binary not" (~P) operator value is not used in this case [integer types only] \section IPP-Optimization IPP-Optimization is possible, but not yet implemented. */ class ICLFilter_API InplaceLogicalOp : public InplaceOp{ public: enum optype{ andOp=0, ///< logical "and" orOp=1, ///< logical "or" xorOp=2, ///< logical "xor" notOp=3, ///< logical "not" binAndOp=4,///< binary "and" (for integer types only) binOrOp=5, ///< binary "or" (for integer types only) binXorOp=6,///< binary "xor" (for integer types only) binNotOp=7 ///< binary "not" (for integer types only) }; /// Creates a new InplaceLogicalOp instance with given optype and value InplaceLogicalOp(optype t, icl64f value=0): m_eOpType(t),m_dValue(value){} /// applies this operation in-place on given source image virtual core::ImgBase *apply(core::ImgBase *src); /// returns current value icl64f getValue() const { return m_dValue; } /// set current value void setValue(icl64f val){ m_dValue = val; } /// returns current optype optype getOpType() const { return m_eOpType; } /// set current optype void setOpType(optype t) { m_eOpType = t; } private: /// optype optype m_eOpType; /// value icl64f m_dValue; }; } // namespace filter }
iclcv/icl
ICLFilter/src/ICLFilter/InplaceLogicalOp.h
C
lgpl-3.0
4,939
#ifndef __TESTNGPPST_TEST_HIERARCHY_SANDBOX_RUNNER_H #define __TESTNGPPST_TEST_HIERARCHY_SANDBOX_RUNNER_H #include <testngppst/testngppst.h> #include <testngppst/runner/TestHierarchyRunner.h> TESTNGPPST_NS_START struct TestCaseRunner; struct TestHierarchySandboxRunnerImpl; struct TestHierarchySandboxRunner : public TestHierarchyRunner { TestHierarchySandboxRunner ( unsigned int maxCurrentProcess , TestCaseRunner*); ~TestHierarchySandboxRunner(); void run ( TestHierarchyHandler* , TestFixtureResultCollector*); private: TestHierarchySandboxRunnerImpl* This; }; TESTNGPPST_NS_END #endif
aprovy/test-ng-pp
tests/3rdparty/testngppst/include/testngppst/runner/TestHierarchySandboxRunner.h
C
lgpl-3.0
644
package org.logicobjects.converter.old; import java.util.Arrays; import java.util.List; import org.jpc.term.Term; import org.jpc.util.ParadigmLeakUtil; import org.logicobjects.converter.IncompatibleAdapterException; import org.logicobjects.converter.context.old.AdaptationContext; import org.logicobjects.converter.context.old.AnnotatedElementAdaptationContext; import org.logicobjects.converter.context.old.BeanPropertyAdaptationContext; import org.logicobjects.converter.context.old.ClassAdaptationContext; import org.logicobjects.converter.descriptor.LogicObjectDescriptor; import org.logicobjects.core.LogicObject; import org.logicobjects.methodadapter.LogicAdapter; import org.minitoolbox.reflection.BeansUtil; public class AnnotatedObjectToTermConverter<From> extends LogicAdapter<From, Term> { @Override public Term adapt(From object) { return adapt(object, null); } public Term adapt(From object, AdaptationContext context) { AnnotatedElementAdaptationContext annotatedContext; if(context != null) { if(understandsContext(context)) annotatedContext = (AnnotatedElementAdaptationContext)context; else throw new UnrecognizedAdaptationContextException(this.getClass(), context); } else { annotatedContext = new ClassAdaptationContext(object.getClass()); //the current context is null, then create default context } if(annotatedContext.hasObjectToTermConverter()) { //first check if there is an explicit adapter, in the current implementation, an Adapter annotation overrides any method invoker description return adaptToTermWithAdapter(object, annotatedContext); } else if(annotatedContext.hasLogicObjectDescription()) { return adaptToTermFromDescription(object, annotatedContext); } throw new IncompatibleAdapterException(this.getClass(), object); } protected Term adaptToTermWithAdapter(From object, AnnotatedElementAdaptationContext annotatedContext) { ObjectToTermConverter termAdapter = annotatedContext.getObjectToTermConverter(); return termAdapter.adapt(object); } protected Term adaptToTermFromDescription(From object, AnnotatedElementAdaptationContext annotatedContext) { LogicObjectDescriptor logicObjectDescription = annotatedContext.getLogicObjectDescription(); String logicObjectName = logicObjectDescription.name(); if(logicObjectName.isEmpty()) logicObjectName = infereLogicObjectName(annotatedContext); List<Term> arguments; String argsListPropertyName = logicObjectDescription.argsList(); if(argsListPropertyName != null && !argsListPropertyName.isEmpty()) { BeanPropertyAdaptationContext adaptationContext = new BeanPropertyAdaptationContext(object.getClass(), argsListPropertyName); Object argsListObject = BeansUtil.getProperty(object, argsListPropertyName, adaptationContext.getGuidingClass()); List argsList = null; if(List.class.isAssignableFrom(argsListObject.getClass())) argsList = (List) argsListObject; else if(Object[].class.isAssignableFrom(argsListObject.getClass())) argsList = Arrays.asList((Object[])argsListObject); else throw new RuntimeException("Property " + argsListPropertyName + " is neither a list nor an array"); arguments = new ObjectToTermConverter().adaptObjects(argsList, adaptationContext); } else { arguments = LogicObject.propertiesAsTerms(object, logicObjectDescription.args()); } return new LogicObject(logicObjectName, arguments).asTerm(); } /** * In case the id is not explicitly specified (e.g., with an annotation), it will have to be inferred * It can be inferred from a class id (if the transformation context is a class instance to a logic object), from a field id (if the context is the transformation of a field), etc * Different context override this method to specify how they infer the logic id of the object * @return */ public String infereLogicObjectName(AnnotatedElementAdaptationContext annotatedContext) { return ParadigmLeakUtil.javaClassNameToProlog(annotatedContext.getGuidingClass().getSimpleName()); } public static boolean understandsContext(AdaptationContext context) { return context != null && context instanceof AnnotatedElementAdaptationContext; } }
java-prolog-connectivity/logicobjects
src/main/java/org/logicobjects/converter/old/AnnotatedObjectToTermConverter.java
Java
lgpl-3.0
4,202
<?php /** * @copyright Copyright (c) Metaways Infosystems GmbH, 2011 * @license LGPLv3, http://www.arcavias.com/en/license */ return array( 'item' => array( 'delete' => ' DELETE FROM "mshop_product" WHERE :cond AND siteid = ? ', 'insert' => ' INSERT INTO "mshop_product" ( "siteid", "typeid", "code", "suppliercode", "label", "status", "start", "end", "mtime", "editor", "ctime" ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ', 'update' => ' UPDATE "mshop_product" SET "siteid" = ?, "typeid" = ?, "code" = ?, "suppliercode" = ?, "label" = ?, "status" = ?, "start" = ?, "end" = ?, "mtime" = ?, "editor" = ? WHERE "id" = ? ', 'search' => ' SELECT DISTINCT mpro."id", mpro."siteid", mpro."typeid", mpro."label", mpro."status", mpro."start", mpro."end", mpro."code", mpro."suppliercode", mpro."ctime", mpro."mtime", mpro."editor" FROM "mshop_product" AS mpro :joins WHERE :cond /*-orderby*/ ORDER BY :order /*orderby-*/ LIMIT :size OFFSET :start ', 'count' => ' SELECT COUNT(*) AS "count" FROM ( SELECT DISTINCT mpro."id" FROM "mshop_product" AS mpro :joins WHERE :cond LIMIT 10000 OFFSET 0 ) AS list ', ), );
Arcavias/arcavias-core
lib/mshoplib/config/common/mshop/product/manager/default.php
PHP
lgpl-3.0
1,235
/* Copyright (C) 2007 <SWGEmu> This File is part of Core3. 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 program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking Engine3 statically or dynamically with other modules is making a combined work based on Engine3. Thus, the terms and conditions of the GNU Lesser General Public License cover the whole combination. In addition, as a special exception, the copyright holders of Engine3 give you permission to combine Engine3 program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Core3 under the GNU LGPL license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU LGPL for Engine3 and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU LGPL requires distribution of source code. Note that people who make modified versions of Engine3 are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #ifndef STEADYAIMCOMMAND_H_ #define STEADYAIMCOMMAND_H_ #include "server/zone/objects/scene/SceneObject.h" #include "SquadLeaderCommand.h" class SteadyaimCommand : public SquadLeaderCommand { public: SteadyaimCommand(const String& name, ZoneProcessServer* server) : SquadLeaderCommand(name, server) { } int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) { if (!checkStateMask(creature)) return INVALIDSTATE; if (!checkInvalidLocomotions(creature)) return INVALIDLOCOMOTION; if (!creature->isPlayerCreature()) return GENERALERROR; ManagedReference<CreatureObject*> player = cast<CreatureObject*>(creature); ManagedReference<GroupObject*> group = player->getGroup(); if (!checkGroupLeader(player, group)) return GENERALERROR; float skillMod = (float) creature->getSkillMod("steadyaim"); int hamCost = (int) (100.0f * (1.0f - (skillMod / 100.0f))) * calculateGroupModifier(group); int healthCost = creature->calculateCostAdjustment(CreatureAttribute::STRENGTH, hamCost); int actionCost = creature->calculateCostAdjustment(CreatureAttribute::QUICKNESS, hamCost); int mindCost = creature->calculateCostAdjustment(CreatureAttribute::FOCUS, hamCost); if (!inflictHAM(player, healthCost, actionCost, mindCost)) return GENERALERROR; // shoutCommand(player, group); int amount = 5 + skillMod; if (!doSteadyAim(player, group, amount)) return GENERALERROR; if (player->isPlayerCreature() && player->getPlayerObject()->getCommandMessageString(String("steadyaim").hashCode()).isEmpty()==false) { UnicodeString shout(player->getPlayerObject()->getCommandMessageString(String("steadyaim").hashCode())); server->getChatManager()->broadcastMessage(player, shout, 0, 0, 80); } return SUCCESS; } bool doSteadyAim(CreatureObject* leader, GroupObject* group, int amount) { if (leader == NULL || group == NULL) return false; for (int i = 0; i < group->getGroupSize(); i++) { ManagedReference<SceneObject*> member = group->getGroupMember(i); if (!member->isPlayerCreature() || member == NULL || member->getZone() != leader->getZone()) continue; ManagedReference<CreatureObject*> memberPlayer = cast<CreatureObject*>( member.get()); Locker clocker(memberPlayer, leader); sendCombatSpam(memberPlayer); ManagedReference<WeaponObject*> weapon = memberPlayer->getWeapon(); if (!weapon->isRangedWeapon()) continue; int duration = 300; ManagedReference<Buff*> buff = new Buff(memberPlayer, actionCRC, duration, BuffType::SKILL); buff->setSkillModifier("private_aim", amount); memberPlayer->addBuff(buff); } return true; } }; #endif //STEADYAIMCOMMAND_H_
kidaa/Awakening-Core3
src/server/zone/objects/creature/commands/SteadyaimCommand.h
C
lgpl-3.0
4,686
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ package org.sonar.api.utils; import org.apache.commons.io.FileUtils; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class TempFileUtilsTest { @Test public void createTempDirectory() throws IOException { File dir = TempFileUtils.createTempDirectory(); try { assertThat(dir.exists(), is(true)); assertThat(dir.isDirectory(), is(true)); assertThat(dir.listFiles().length, is(0)); } finally { FileUtils.deleteDirectory(dir); } } }
lbndev/sonarqube
sonar-plugin-api/src/test/java/org/sonar/api/utils/TempFileUtilsTest.java
Java
lgpl-3.0
1,443
package net.anthavio.sewer.test; import net.anthavio.sewer.ServerInstance; import net.anthavio.sewer.ServerInstanceManager; import net.anthavio.sewer.ServerMetadata; import net.anthavio.sewer.ServerMetadata.CacheScope; import net.anthavio.sewer.ServerType; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * * public class MyCoolTests { * * @Rule * private SewerRule sewer = new SewerRule(ServerType.JETTY, "src/test/jetty8", 0); * * @Test * public void test() { * int port = sewer.getServer().getLocalPorts()[0]; * } * * } * * Can interact with method annotations - http://www.codeaffine.com/2012/09/24/junit-rules/ * * @author martin.vanek * */ public class SewerRule implements TestRule { private final ServerInstanceManager manager = ServerInstanceManager.INSTANCE; private final ServerMetadata metadata; private ServerInstance server; public SewerRule(ServerType type, String home) { this(type, home, -1, null, CacheScope.JVM); } public SewerRule(ServerType type, String home, int port) { this(type, home, port, null, CacheScope.JVM); } public SewerRule(ServerType type, String home, int port, CacheScope cache) { this(type, home, port, null, cache); } public SewerRule(ServerType type, String home, int port, String[] configs, CacheScope cache) { this.metadata = new ServerMetadata(type, home, port, configs, cache); } public ServerInstance getServer() { return server; } @Override public Statement apply(Statement base, Description description) { return new SewerStatement(base); } public class SewerStatement extends Statement { private final Statement base; public SewerStatement(Statement base) { this.base = base; } @Override public void evaluate() throws Throwable { server = manager.borrowServer(metadata); try { base.evaluate(); } finally { manager.returnServer(metadata); } } } }
anthavio/anthavio-sewer
src/main/java/net/anthavio/sewer/test/SewerRule.java
Java
lgpl-3.0
1,989
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ package org.sonar.api.ce.posttask; /** * @since 5.5 */ public interface CeTask { /** * Id of the Compute Engine task. * <p> * This is the id under which the processing of the project analysis report has been added to the Compute Engine * queue. * */ String getId(); /** * Indicates whether the Compute Engine task ended successfully or not. */ Status getStatus(); enum Status { SUCCESS, FAILED } }
lbndev/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/ce/posttask/CeTask.java
Java
lgpl-3.0
1,287
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "applypendingmaintenanceactionrequest.h" #include "applypendingmaintenanceactionrequest_p.h" #include "applypendingmaintenanceactionresponse.h" #include "rdsrequest_p.h" namespace QtAws { namespace RDS { /*! * \class QtAws::RDS::ApplyPendingMaintenanceActionRequest * \brief The ApplyPendingMaintenanceActionRequest class provides an interface for RDS ApplyPendingMaintenanceAction requests. * * \inmodule QtAwsRDS * * <fullname>Amazon Relational Database Service</fullname> * * * </p * * Amazon Relational Database Service (Amazon RDS) is a web service that makes it easier to set up, operate, and scale a * relational database in the cloud. It provides cost-efficient, resizeable capacity for an industry-standard relational * database and manages common database administration tasks, freeing up developers to focus on what makes their * applications and businesses * * unique> * * Amazon RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, Microsoft SQL Server, Oracle, or Amazon * Aurora database server. These capabilities mean that the code, applications, and tools you already use today with your * existing databases work with Amazon RDS without modification. Amazon RDS automatically backs up your database and * maintains the database software that powers your DB instance. Amazon RDS is flexible: you can scale your DB instance's * compute resources and storage capacity to meet your application's demand. As with all Amazon Web Services, there are no * up-front investments, and you pay only for the resources you * * use> * * This interface reference for Amazon RDS contains documentation for a programming or command line interface you can use * to manage Amazon RDS. Amazon RDS is asynchronous, which means that some interfaces might require techniques such as * polling or callback functions to determine when a command has been applied. In this reference, the parameter * descriptions indicate whether a command is applied immediately, on the next instance reboot, or during the maintenance * window. The reference structure is as follows, and we list following some related topics from the user * * guide> * * <b>Amazon RDS API Reference</b> * * </p <ul> <li> * * For the alphabetical list of API actions, see <a * href="https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Operations.html">API * * Actions</a>> </li> <li> * * For the alphabetical list of data types, see <a * href="https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Types.html">Data * * Types</a>> </li> <li> * * For a list of common query parameters, see <a * href="https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonParameters.html">Common * * Parameters</a>> </li> <li> * * For descriptions of the error codes, see <a * href="https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonErrors.html">Common * * Errors</a>> </li> </ul> * * <b>Amazon RDS User Guide</b> * * </p <ul> <li> * * For a summary of the Amazon RDS interfaces, see <a * href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html#Welcome.Interfaces">Available RDS * * Interfaces</a>> </li> <li> * * For more information about how to use the Query API, see <a * href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Using_the_Query_API.html">Using the Query * * \sa RdsClient::applyPendingMaintenanceAction */ /*! * Constructs a copy of \a other. */ ApplyPendingMaintenanceActionRequest::ApplyPendingMaintenanceActionRequest(const ApplyPendingMaintenanceActionRequest &other) : RdsRequest(new ApplyPendingMaintenanceActionRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a ApplyPendingMaintenanceActionRequest object. */ ApplyPendingMaintenanceActionRequest::ApplyPendingMaintenanceActionRequest() : RdsRequest(new ApplyPendingMaintenanceActionRequestPrivate(RdsRequest::ApplyPendingMaintenanceActionAction, this)) { } /*! * \reimp */ bool ApplyPendingMaintenanceActionRequest::isValid() const { return false; } /*! * Returns a ApplyPendingMaintenanceActionResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * ApplyPendingMaintenanceActionRequest::response(QNetworkReply * const reply) const { return new ApplyPendingMaintenanceActionResponse(*this, reply); } /*! * \class QtAws::RDS::ApplyPendingMaintenanceActionRequestPrivate * \brief The ApplyPendingMaintenanceActionRequestPrivate class provides private implementation for ApplyPendingMaintenanceActionRequest. * \internal * * \inmodule QtAwsRDS */ /*! * Constructs a ApplyPendingMaintenanceActionRequestPrivate object for Rds \a action, * with public implementation \a q. */ ApplyPendingMaintenanceActionRequestPrivate::ApplyPendingMaintenanceActionRequestPrivate( const RdsRequest::Action action, ApplyPendingMaintenanceActionRequest * const q) : RdsRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the ApplyPendingMaintenanceActionRequest * class' copy constructor. */ ApplyPendingMaintenanceActionRequestPrivate::ApplyPendingMaintenanceActionRequestPrivate( const ApplyPendingMaintenanceActionRequestPrivate &other, ApplyPendingMaintenanceActionRequest * const q) : RdsRequestPrivate(other, q) { } } // namespace RDS } // namespace QtAws
pcolby/libqtaws
src/rds/applypendingmaintenanceactionrequest.cpp
C++
lgpl-3.0
6,272
var KevoreeEntity = require('./KevoreeEntity'); /** * AbstractChannel entity * * @type {AbstractChannel} extends KevoreeEntity */ module.exports = KevoreeEntity.extend({ toString: 'AbstractChannel', construct: function () { this.remoteNodes = {}; this.inputs = {}; }, internalSend: function (portPath, msg) { var remoteNodeNames = this.remoteNodes[portPath]; for (var remoteNodeName in remoteNodeNames) { this.onSend(remoteNodeName, msg); } }, /** * * @param remoteNodeName * @param msg */ onSend: function (remoteNodeName, msg) { }, remoteCallback: function (msg) { for (var name in this.inputs) { this.inputs[name].getCallback().call(this, msg); } }, addInternalRemoteNodes: function (portPath, remoteNodes) { this.remoteNodes[portPath] = remoteNodes; }, addInternalInputPort: function (port) { this.inputs[port.getName()] = port; } });
barais/kevoree-js
library/kevoree-entities/lib/AbstractChannel.js
JavaScript
lgpl-3.0
938
package calc.lib; /** Class (POJO) used to store Uninhabited Solar System JSON objects * * @author Carlin Robertson * @version 1.0 * */ public class SolarSystemUninhabited { private String[] information; private String requirePermit; private Coords coords; private String name; public String[] getInformation () { return information; } public void setInformation (String[] information) { this.information = information; } public String getRequirePermit () { return requirePermit; } public void setRequirePermit (String requirePermit) { this.requirePermit = requirePermit; } public Coords getCoords () { return coords; } public void setCoords (Coords coords) { this.coords = coords; } public String getName () { return name; } public void setName (String name) { this.name = name; } }
TheJavaMagician/CalculusBot
src/main/java/calc/lib/SolarSystemUninhabited.java
Java
lgpl-3.0
977
<?php require_once '../../../config.php'; require_once $config['root_path'] . '/system/functions.php'; include_once $config['system_path'] . '/start_system.php'; admin_login(); if (isset($_POST['delete']) && isset($_POST['id']) && isset($_SESSION['member']['access']['countries'])) { require_once ROOT_PATH . '/applications/news/modeles/news.class.php'; $cms = new news(); $cms->delete(intval($_POST['id'])); die ( json_encode( array_merge( $_POST, array ( 'status' => 'true' ) ) ) ); } echo json_encode ( array_merge ( $_POST, array ( 'status' => 'unknown error' ) ) ); die (); ?>
UniPixen/Niradrien
applications/news/ajax/delete.php
PHP
lgpl-3.0
681
// Catalano Fuzzy Library // The Catalano Framework // // Copyright © Diego Catalano, 2013 // diego.catalano at live.com // // Copyright © Andrew Kirillov, 2007-2008 // andrew.kirillov at gmail.com // // 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 St, Fifth Floor, Boston, MA 02110-1301 USA // package Catalano.Fuzzy; /** * Interface with the common methods of Fuzzy Unary Operator. * @author Diego Catalano */ public interface IUnaryOperator { /** * Calculates the numerical result of a Unary operation applied to one fuzzy membership value. * @param membership A fuzzy membership value, [0..1]. * @return The numerical result of the operation applied to <paramref name="membership"/>. */ float Evaluate( float membership ); }
accord-net/java
Catalano.Fuzzy/src/Catalano/Fuzzy/IUnaryOperator.java
Java
lgpl-3.0
1,453
<?php namespace Google\AdsApi\Dfp\v201708; /** * This file was generated from WSDL. DO NOT EDIT. */ class ReportQueryAdUnitView { const TOP_LEVEL = 'TOP_LEVEL'; const FLAT = 'FLAT'; const HIERARCHICAL = 'HIERARCHICAL'; }
advanced-online-marketing/AOM
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201708/ReportQueryAdUnitView.php
PHP
lgpl-3.0
240
package flabs.mods.magitech.aura; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.WorldSavedData; public class AuraSavedData extends WorldSavedData{ public static final String nbtName="MagiAura"; public AuraSavedData(String name) { super(name); } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { System.out.println("Reading Aura Data"); } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { System.out.println("Writing Aura Data"); } }
froschi3b/Magitech
magitech_common/flabs/mods/magitech/aura/AuraSavedData.java
Java
lgpl-3.0
532
.iwl-height-full { height: 100%; } /*# sourceMappingURL=!design.css.map */
iwhp/IwStyle
IwStyle/IwStyle.Ui.Web/!Design/theme/!design.css
CSS
lgpl-3.0
80
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --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 program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. object_tangible_lair_womp_rat_shared_lair_womp_rat = SharedTangibleObjectTemplate:new { appearanceFilename = "appearance/poi_all_skeleton_human_headandbody.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 25, clientDataFile = "clientdata/lair/shared_poi_all_lair_bones.cdf", collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@lair_d:womp_rat", gameObjectType = 4, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 64, objectName = "@lair_n:womp_rat", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, useStructureFootprintOutline = 0 } ObjectTemplates:addTemplate(object_tangible_lair_womp_rat_shared_lair_womp_rat, 2053935761) object_tangible_lair_womp_rat_shared_lair_womp_rat_desert = SharedTangibleObjectTemplate:new { appearanceFilename = "appearance/poi_all_skeleton_human_headandbody.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 25, clientDataFile = "clientdata/lair/shared_poi_all_lair_bones.cdf", collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@lair_d:womp_rat_desert", gameObjectType = 4, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 64, objectName = "@lair_n:womp_rat_desert", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, useStructureFootprintOutline = 0 } ObjectTemplates:addTemplate(object_tangible_lair_womp_rat_shared_lair_womp_rat_desert, 703016558)
TheAnswer/FirstTest
bin/scripts/object/tangible/lair/womp_rat/objects.lua
Lua
lgpl-3.0
4,715
package edu.ut.mobile.network; public class NetInfo{ //public static byte[] IPAddress = {Integer.valueOf("54").byteValue(),Integer.valueOf("73").byteValue(),Integer.valueOf("28").byteValue(),Integer.valueOf("236").byteValue()}; static byte[] IPAddress = {Integer.valueOf("192").byteValue(),Integer.valueOf("168").byteValue(),Integer.valueOf("1").byteValue(),Integer.valueOf("67").byteValue()}; static int port = 6000; static int waitTime = 100000; }
huberflores/BenchmarkingAndroidx86
Simulator/MobileOffloadSimulator/src/main/java/edu/ut/mobile/network/NetInfo.java
Java
lgpl-3.0
473
/* Copyright 2009 Semantic Discovery, Inc. (www.semanticdiscovery.com) This file is part of the Semantic Discovery Toolkit. The Semantic Discovery Toolkit 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. The Semantic Discovery Toolkit 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 Semantic Discovery Toolkit. If not, see <http://www.gnu.org/licenses/>. */ package org.sd.text; import org.sd.io.FileUtil; import org.sd.nlp.AbstractLexicon; import org.sd.nlp.AbstractNormalizer; import org.sd.nlp.Break; import org.sd.nlp.BreakStrategy; import org.sd.nlp.Categories; import org.sd.nlp.Category; import org.sd.nlp.CategoryFactory; import org.sd.nlp.GeneralNormalizer; import org.sd.nlp.GenericLexicon; import org.sd.nlp.Lexicon; import org.sd.nlp.LexiconPipeline; import org.sd.nlp.TokenizationStrategy; import org.sd.nlp.TokenizerWrapper; import org.sd.nlp.StringWrapper; import org.sd.util.PropertiesParser; import org.sd.util.tree.Tree; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; /** * Utility to find meaningful words in strings. * <p> * @author Spence Koehler */ public class MungedWordFinder { private static final String UNDETERMINED_LETTER = "X"; private static final String UNDETERMINED_WORD = "U"; private static final String WORD = "W"; private static final String NUMBER = "N"; private static final String SEQUENCE = "S"; private static final String CONSTITUENT = "C"; private static final String[] CATEGORIES = new String[] { UNDETERMINED_LETTER, UNDETERMINED_WORD, WORD, NUMBER, SEQUENCE, CONSTITUENT, }; private static final AbstractNormalizer NORMALIZER = GeneralNormalizer.getCaseInsensitiveInstance(); private static final BreakStrategy BREAK_STRATEGY = new MyBreakStrategy(); private static final Comparator<WordSequence> SEQUENCE_COMPARATOR = new Comparator<WordSequence>() { public int compare(WordSequence ws1, WordSequence ws2) { return ws1.size() - ws2.size(); } public boolean equals(Object o) { return this == o; } }; private CategoryFactory categoryFactory; private Map<String, File> wordFiles; private Map<String, String[]> wordSets; private List<Lexicon> lexicons; private TokenizerWrapper _tokenizerWrapper; /** * Construct without any dictionaries. * <p> * Add dictionaries to use for finding munged words using the * addWordFile, addWordSet, and addLexicon methods. */ public MungedWordFinder() { this.categoryFactory = new CategoryFactory(CATEGORIES); this.wordFiles = new HashMap<String, File>(); this.wordSets = new HashMap<String, String[]>(); this.lexicons = new ArrayList<Lexicon>(); this._tokenizerWrapper = null; } /** * Add a word file defining words to recognize. */ public final void addWordFile(String name, File wordFile) { this.wordFiles.put(name, wordFile); this._tokenizerWrapper = null; // force rebuild. } /** * Add a word set defining words to recognize. */ public final void addWordSet(String name, String[] words) { this.wordSets.put(name, words); this._tokenizerWrapper = null; // force rebuild. } /** * Add a lexicon defining words to recognize. */ public final void addLexicon(Lexicon lexicon) { this.lexicons.add(lexicon); this._tokenizerWrapper = null; // force rebuild. } protected final TokenizerWrapper getTokenizerWrapper() { if (_tokenizerWrapper == null) { try { final Lexicon lexicon = new LexiconPipeline(buildLexicons()); _tokenizerWrapper = new TokenizerWrapper( lexicon, categoryFactory, TokenizationStrategy.Type.LONGEST_TO_SHORTEST, NORMALIZER, BREAK_STRATEGY, false, 0, false); //NOTE: lexicon should classify every token } catch (IOException e) { throw new IllegalStateException(e); } } return _tokenizerWrapper; } private final Lexicon[] buildLexicons() throws IOException { final List<Lexicon> result = new ArrayList<Lexicon>(); final Category wordCategory = categoryFactory.getCategory(WORD); // add a lexicon that identifies/recognizes number sequences. result.add(new NumberLexicon(categoryFactory.getCategory(NUMBER))); // add a lexicon for each wordSet for (Map.Entry<String, String[]> wordSetEntry : wordSets.entrySet()) { final String name = wordSetEntry.getKey(); final String[] terms = wordSetEntry.getValue(); final GenericLexicon genericLexicon = new GenericLexicon(terms, NORMALIZER, wordCategory, false, true, false, "name=" + name); genericLexicon.setMaxNumWords(0); // disable "word" limit. each char counts as a word with our break strategy. result.add(genericLexicon); } // add a lexicon for each wordFile for (Map.Entry<String, File> wordFileEntry : wordFiles.entrySet()) { final String name = wordFileEntry.getKey(); final File wordFile = wordFileEntry.getValue(); final GenericLexicon genericLexicon = new GenericLexicon(FileUtil.getInputStream(wordFile), NORMALIZER, wordCategory, false, true, false, "name=" + name); genericLexicon.setMaxNumWords(0); // disable "word" limit. each char counts as a word with our break strategy. result.add(genericLexicon); } // add each lexicon for (Lexicon lexicon : lexicons) { result.add(lexicon); } // add a lexicon that identifies a single letter as unknown. result.add(new UnknownLexicon(categoryFactory.getCategory(UNDETERMINED_LETTER))); return result.toArray(new Lexicon[result.size()]); //todo: what about conjugations? } public List<WordSequence> getBestSplits(String string) { List<WordSequence> result = new ArrayList<WordSequence>(); final TokenizerWrapper tokenizerWrapper = getTokenizerWrapper(); final Tree<StringWrapper.SubString> tokenTree = tokenizerWrapper.tokenize(string); final List<Tree<StringWrapper.SubString>> leaves = tokenTree.gatherLeaves(); int maxScore = -1; for (Tree<StringWrapper.SubString> leaf : leaves) { final WordSequence wordSequence = new WordSequence(leaf); final int curScore = wordSequence.getScore(); if (curScore >= maxScore) { if (curScore > maxScore) { result.clear(); maxScore = curScore; } result.add(wordSequence); } } if (result.size() > 0) { Collections.sort(result, SEQUENCE_COMPARATOR); } return result; } public List<WordSequence> getBestDomainSplits(String domain) { final int dotPos = domain.indexOf('.'); if (dotPos > 0 && dotPos < domain.length() - 1) { final DetailedUrl dUrl = new DetailedUrl(domain); domain = dUrl.getHost(false, false, false); } return getBestSplits(domain); } public String getSplitsAsString(List<WordSequence> splits) { final StringBuilder result = new StringBuilder(); if (splits != null) { for (Iterator<WordSequence> splitIter = splits.iterator(); splitIter.hasNext(); ) { final WordSequence split = splitIter.next(); result.append(split.toString()); if (splitIter.hasNext()) result.append('|'); } } return result.toString(); } // symbols are hard breaks... letters are soft breaks... consecutive digits aren't (don't break numbers) private static final class MyBreakStrategy implements BreakStrategy { public Break[] computeBreaks(int[] codePoints) { final Break[] result = new Break[codePoints.length]; boolean inNumber = false; for (int i = 0; i < codePoints.length; ++i) { Break curBreak = Break.NONE; final int cp = codePoints[i]; if (Character.isDigit(cp)) { if (i > 0 && !inNumber && result[i - 1] != Break.HARD) { curBreak = Break.SOFT_SPLIT; } else { curBreak = Break.NONE; } inNumber = true; } else if (Character.isLetter(cp)) { // first letter after a hard break (or at start) isn't a break if (i == 0 || result[i - 1] == Break.HARD) { curBreak = Break.NONE; } else { curBreak = Break.SOFT_SPLIT; } inNumber = false; } else { // if following a digit or with-digit-symbol, then consider the number parts as a whole if (inNumber) { curBreak = Break.NONE; } // else if a digit or digit-symbol follows, then consider the number parts as a whole else if (i + 1 < codePoints.length && (Character.isDigit(codePoints[i + 1]) || (i + 2 < codePoints.length && Character.isDigit(codePoints[i + 2])))) { curBreak = Break.NONE; inNumber = true; } else { curBreak = Break.HARD; inNumber = false; } } result[i] = curBreak; } return result; } } private static final class NumberLexicon extends AbstractLexicon { private Category category; public NumberLexicon(Category category) { super(null); this.category = category; } /** * Define applicable categories in the subString. * <p> * In this case, if a digit is found in the subString, then the NUMBER category is added. * * @param subString The substring to define. * @param normalizer The normalizer to use. */ protected void define(StringWrapper.SubString subString, AbstractNormalizer normalizer) { if (!subString.hasDefinitiveDefinition()) { boolean isNumber = true; int lastNumberPos = -1; for (int i = subString.startPos; i < subString.endPos; ++i) { final int cp = subString.stringWrapper.getCodePoint(i); if (cp > '9' || cp < '0') { isNumber = false; break; } lastNumberPos = i; } if (!isNumber) { // check for "text" numbers if (lastNumberPos >= 0 && lastNumberPos == subString.endPos - 3) { // check for number suffix isNumber = TextNumber.isNumberEnding(subString.originalSubString.substring(lastNumberPos + 1).toLowerCase()); } else if (lastNumberPos < 0) { // check for number word isNumber = TextNumber.isNumber(subString.originalSubString.toLowerCase()); } } if (isNumber) { subString.setAttribute("name", NUMBER); subString.addCategory(category); subString.setDefinitive(true); } } } /** * Determine whether the categories container already has category type(s) * that this lexicon would add. * <p> * NOTE: this is used to avoid calling "define" when categories already exist * for the substring. * * @return true if this lexicon's category type(s) are already present. */ protected boolean alreadyHasTypes(Categories categories) { return categories.hasType(category); } } private static final class UnknownLexicon extends AbstractLexicon { private Category category; public UnknownLexicon(Category category) { super(null); this.category = category; } /** * Define applicable categories in the subString. * <p> * In this case, if a digit is found in the subString, then the NUMBER category is added. * * @param subString The substring to define. * @param normalizer The normalizer to use. */ protected void define(StringWrapper.SubString subString, AbstractNormalizer normalizer) { if (!subString.hasDefinitiveDefinition() && subString.length() == 1) { subString.addCategory(category); subString.setAttribute("name", UNDETERMINED_WORD); } } /** * Determine whether the categories container already has category type(s) * that this lexicon would add. * <p> * NOTE: this is used to avoid calling "define" when categories already exist * for the substring. * * @return true if this lexicon's category type(s) are already present. */ protected boolean alreadyHasTypes(Categories categories) { return categories.hasType(category); } } /** * Container class for a word. */ public static final class Word { public final StringWrapper.SubString word; public final String type; private Integer _score; public Word(StringWrapper.SubString word, String type) { this.word = word; this.type = type; this._score = null; } /** * Get this word's score. * <p> * A word's score is its number of defined letters. */ public int getScore() { if (_score == null) { _score = UNDETERMINED_WORD.equals(type) ? 0 : word.length() * word.length(); } return _score; } public String toString() { final StringBuilder result = new StringBuilder(); result.append(type).append('=').append(word.originalSubString); return result.toString(); } } /** * Container for a sequence of words for a string. */ public static final class WordSequence { public final String string; public final List<Word> words; private int score; public WordSequence(Tree<StringWrapper.SubString> leaf) { final LinkedList<Word> theWords = new LinkedList<Word>(); this.words = theWords; this.score = 0; String theString = null; while (leaf != null) { final StringWrapper.SubString subString = leaf.getData(); if (subString == null) break; // hit root. final String nameValue = subString.getAttribute("name"); final Word word = new Word(subString, nameValue == null ? UNDETERMINED_WORD : nameValue); theWords.addFirst(word); score += word.getScore(); if (theString == null) theString = subString.stringWrapper.string; leaf = leaf.getParent(); } this.string = theString; } /** * Get this sequence's score. * <p> * The score is the total number of defined letters in the sequence's words. */ public int getScore() { return score; } public int size() { return words.size(); } public String toString() { return asString(","); } public String asString(String delim) { final StringBuilder result = new StringBuilder(); for (Iterator<Word> wordIter = words.iterator(); wordIter.hasNext(); ) { final Word word = wordIter.next(); result.append(word.toString()); if (wordIter.hasNext()) result.append(delim); } // result.append('(').append(getScore()).append(')'); return result.toString(); } } //java -Xmx640m org.sd.nlp.MungedWordFinder wordSet="foo,bar,baz" wordSetName="fbb" foobarbaz "foo-bar-baz" "foobArbaz" gesundheit public static final void main(String[] args) throws IOException { // properties: // wordFiles="file1,file2,..." // wordSet="word1,word2,..." // wordSetName="name" // non-property arguments are munged strings to split. // STDIN has other munged strings or domains to split. final PropertiesParser propertiesParser = new PropertiesParser(args); final Properties properties = propertiesParser.getProperties(); final String wordFileNames = properties.getProperty("wordFiles"); final String wordSet = properties.getProperty("wordSet"); final String wordSetName = properties.getProperty("wordSetName"); final MungedWordFinder mungedWordFinder = new MungedWordFinder(); if (wordFileNames != null) { for (String wordFile : wordFileNames.split("\\s*,\\s*")) { final File file = new File(wordFile); mungedWordFinder.addWordFile(file.getName().split("\\.")[0], file); } } if (wordSet != null) { mungedWordFinder.addWordSet(wordSetName, wordSet.split("\\s*,\\s*")); } final String[] mungedWords = propertiesParser.getArgs(); for (String mungedWord : mungedWords) { final List<WordSequence> splits = mungedWordFinder.getBestDomainSplits(mungedWord); final String splitsString = mungedWordFinder.getSplitsAsString(splits); System.out.println(mungedWord + "|" + splitsString); } final BufferedReader reader = FileUtil.getReader(System.in); String line = null; while ((line = reader.readLine()) != null) { final List<WordSequence> splits = mungedWordFinder.getBestDomainSplits(line); final String splitsString = mungedWordFinder.getSplitsAsString(splits); System.out.println(line + "|" + splitsString); } reader.close(); } }
jtsay362/semanticdiscoverytoolkit-text
src/main/java/org/sd/text/MungedWordFinder.java
Java
lgpl-3.0
17,721
/******************************************************************************* * Copyright (c) 2015 Open Software Solutions GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.html * * Contributors: * Open Software Solutions GmbH ******************************************************************************/ package org.oss.pdfreporter.sql.factory; import java.io.InputStream; import java.util.Date; import org.oss.pdfreporter.sql.IBlob; import org.oss.pdfreporter.sql.IConnection; import org.oss.pdfreporter.sql.IDate; import org.oss.pdfreporter.sql.IDateTime; import org.oss.pdfreporter.sql.ITime; import org.oss.pdfreporter.sql.ITimestamp; import org.oss.pdfreporter.sql.SQLException; /** * Sql connectivity factory. * The interface supports queries with prepared statements. * No DDL or modifying operations are supported, neither transactions or cursors. * @author donatmuller, 2013, last change 5:39:58 PM */ public interface ISqlFactory { /** * Returns a connection for the connection parameter. * It is up to the implementor to define the syntax of the connection parameter.<br> * The parameter could include a driver class name or just an url and assume that a driver * was already loaded. * @param url * @param user * @param password * @return */ IConnection newConnection(String url, String user, String password) throws SQLException; /** * used by dynamic loading of specific database driver and JDBC-URL, when the implementation don't know about the specific driver-implementation. * @param jdbcUrl * @param user * @param password * @return * @throws SQLException */ IConnection createConnection(String jdbcUrl, String user, String password) throws SQLException; /** * Creates a Date. * @param date * @return */ IDate newDate(Date date); /** * Creates a Time. * @param time * @return */ ITime newTime(Date time); /** * Creates a Timestamp. * @param timestamp * @return */ ITimestamp newTimestamp(long milliseconds); /** * Creates a DateTime. * @param datetime * @return */ IDateTime newDateTime(Date datetime); /** * Creates a Blob. * @param is * @return */ IBlob newBlob(InputStream is); /** * Creates a Blob. * @param bytes * @return */ IBlob newBlob(byte[] bytes); }
OpenSoftwareSolutions/PDFReporter
pdfreporter-core/src/org/oss/pdfreporter/sql/factory/ISqlFactory.java
Java
lgpl-3.0
2,507
/* * Copyright (C) 2005-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.admin.registry; import java.io.Serializable; import java.util.Collection; /** * Interface for service providing access to key-value pairs for storage * of system-controlled metadata. * * @author Derek Hulley */ public interface RegistryService { /** * Assign a value to the registry key, which must be of the form <b>/a/b/c</b>. * * @param key the registry key. * @param value any value that can be stored in the repository. */ void addProperty(RegistryKey key, Serializable value); /** * @param key the registry key. * @return Returns the value stored in the key or <tt>null</tt> if * no value exists at the path and name provided * * @see #addProperty(String, Serializable) */ Serializable getProperty(RegistryKey key); /** * Fetches all child elements for the given path. The key's property should be * <tt>null</tt> as it is completely ignored. * <code><pre> * ... * registryService.addValue(KEY_A_B_C_1, VALUE_ONE); * registryService.addValue(KEY_A_B_C_2, VALUE_TWO); * ... * assertTrue(registryService.getChildElements(KEY_A_B_null).contains("C")); * ... * </pre></code> * * @param key the registry key with the path. The last element in the path * will be ignored, and can be any acceptable value localname or <tt>null</tt>. * @return Returns all child elements (not values) for the given key, ignoring * the last element in the key. * * @see RegistryKey#getPath() */ Collection<String> getChildElements(RegistryKey key); /** * Copies the path or value from the source to the target location. The source and target * keys <b>must</b> be both either path-specific or property-specific. If the source doesn't * exist, then nothing will be done; there is no guarantee that the target will exist after * the call. * <p> * This is essentially a merge operation. Use {@link #delete(RegistryKey) delete} first * if the target must be cleaned. * * @param sourceKey the source registry key to take values from * @param targetKey the target registyr key to move the path or value to */ void copy(RegistryKey sourceKey, RegistryKey targetKey); /** * Delete the path element or value described by the key. If the key points to nothing, * then nothing is done. * <code>delete(/a/b/c)</code> will remove value <b>c</b> from path <b>/a/b</b>.<br/> * <code>delete(/a/b/null)</code> will remove node <b>/a/b</b> along with all values and child * elements. * * @param key the path or value to delete */ void delete(RegistryKey key); }
loftuxab/community-edition-old
projects/repository/source/java/org/alfresco/repo/admin/registry/RegistryService.java
Java
lgpl-3.0
3,781
Simple-CFG-Compiler =================== A simple syntax directed translator
Jay-Krish/Simple-CFG-Compiler
README.md
Markdown
lgpl-3.0
78
import java.util.*; import Jakarta.util.FixDosOutputStream; import java.io.*; //------------------------ j2jBase layer ------------------- //------ mixin-layer for dealing with Overrides and New Modifier //------ offhand, I wonder why we can't let j2j map these modifiers //------ to nothing, instead of letting PJ do some of this mapping // it would make more sense for PJ and Mixin to have similar // output. public class ModOverrides { public void reduce2java( AstProperties props ) { // Step 1: the overrides modifier should not be present, UNLESS // there is a SoUrCe property. It's an error otherwise. if ( props.getProperty( "SoUrCe" ) == null ) { AstNode.error( tok[0], "overrides modifier should not be present" ); return; } // Step 2: it's OK to be present. If so, the reduction is to // print the white-space in front for pretty-printing props.print( getComment() ); } }
SergiyKolesnikov/fuji
examples/AHEAD/j2jBase/ModOverrides.java
Java
lgpl-3.0
1,048
# -*- coding: utf-8 -*- """digitalocean API to manage droplets""" __version__ = "1.16.0" __author__ = "Lorenzo Setale ( http://who.is.lorenzo.setale.me/? )" __author_email__ = "[email protected]" __license__ = "LGPL v3" __copyright__ = "Copyright (c) 2012-2020 Lorenzo Setale" from .Manager import Manager from .Droplet import Droplet, DropletError, BadKernelObject, BadSSHKeyFormat from .Region import Region from .Size import Size from .Image import Image from .Action import Action from .Account import Account from .Balance import Balance from .Domain import Domain from .Record import Record from .SSHKey import SSHKey from .Kernel import Kernel from .FloatingIP import FloatingIP from .Volume import Volume from .baseapi import Error, EndPointError, TokenError, DataReadError, NotFoundError from .Tag import Tag from .LoadBalancer import LoadBalancer from .LoadBalancer import StickySessions, ForwardingRule, HealthCheck from .Certificate import Certificate from .Snapshot import Snapshot from .Project import Project from .Firewall import Firewall, InboundRule, OutboundRule, Destinations, Sources from .VPC import VPC
koalalorenzo/python-digitalocean
digitalocean/__init__.py
Python
lgpl-3.0
1,128
/* * Copyright (C) 2003-2014 eXo Platform SAS. * * 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 org.exoplatform.social.core.storage.proxy; import java.lang.reflect.Proxy; import org.exoplatform.social.core.activity.model.ExoSocialActivity; /** * Created by The eXo Platform SAS * Author : eXoPlatform * [email protected] * Apr 28, 2014 */ public class ActivityProxyBuilder { @SuppressWarnings("unchecked") static <T> T of(ProxyInvocation invocation) { Class<?> targetClass = invocation.getTargetClass(); //1. loader - the class loader to define the proxy class //2. the list of interfaces for the proxy class to implement //3. the invocation handler to dispatch method invocations to return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), new Class<?>[]{targetClass}, invocation); } public static <T> T of(Class<T> aClass, ExoSocialActivity activity) { return of(new ProxyInvocation(aClass, activity)); } }
thanhvc/poc-sam
services/src/main/java/org/exoplatform/social/core/storage/proxy/ActivityProxyBuilder.java
Java
lgpl-3.0
1,655
<?php namespace Tests\Browser\Pages\Admin; use Laravel\Dusk\Browser; use Laravel\Dusk\Page as BasePage; class FilterAdd extends BasePage { /** * Get the URL for the page. * * @return string */ public function url() { return '/admin/filter/create'; } /** * Assert that the browser is on the page. * * @param Browser $browser * @return void */ public function assert(Browser $browser) { $browser->assertPathIs($this->url()); } /** * Get the element shortcuts for the page. * * @return array */ public function elements() { return [ '@status' => 'select[name="properties[status]"]', '@display' => 'select[name="properties[display]"]', '@displayCount' => 'input[name="properties[display_count]"]', '@roundTo' => 'input[name="properties[other][round_to]"]', '@title' => 'input[name="properties[title]"]', '@type' => 'select[name="properties[type]"]', '@feature' => 'select[name="properties[feature_id]"]', '@categories' => 'select[name="categories[]"]', '@submit' => '#submit' ]; } }
myindexd/laravelcms
tests/Browser/Pages/Admin/FilterAdd.php
PHP
lgpl-3.0
1,239
/* * XAdES4j - A Java library for generation and verification of XAdES signatures. * Copyright (C) 2010 Luis Goncalves. * * XAdES4j 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 any later version. * * XAdES4j 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 XAdES4j. If not, see <http://www.gnu.org/licenses/>. */ package xades4j.xml.unmarshalling; import xades4j.algorithms.Algorithm; import xades4j.properties.SignatureTimeStampProperty; import xades4j.properties.data.SignatureTimeStampData; import xades4j.xml.bind.xades.XmlUnsignedSignaturePropertiesType; /** * * @author Luís */ class FromXmlSignatureTimeStampConverter extends FromXmlBaseTimeStampConverter<SignatureTimeStampData> implements UnsignedSigPropFromXmlConv { FromXmlSignatureTimeStampConverter() { super(SignatureTimeStampProperty.PROP_NAME); } @Override public void convertFromObjectTree( XmlUnsignedSignaturePropertiesType xmlProps, QualifyingPropertiesDataCollector propertyDataCollector) throws PropertyUnmarshalException { super.convertTimeStamps(xmlProps.getSignatureTimeStamp(), propertyDataCollector); } @Override protected SignatureTimeStampData createTSData(Algorithm c14n) { return new SignatureTimeStampData(c14n); } @Override protected void setTSData( SignatureTimeStampData tsData, QualifyingPropertiesDataCollector propertyDataCollector) { propertyDataCollector.addSignatureTimeStamp(tsData); } }
entaksi/xades4j
src/main/java/xades4j/xml/unmarshalling/FromXmlSignatureTimeStampConverter.java
Java
lgpl-3.0
1,991
/* * Unitex * * Copyright (C) 2001-2014 Université Paris-Est Marne-la-Vallée <[email protected]> * * 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. * */ package fr.umlv.unitex.cassys; public class ConfigurationFileAnalyser { private String fileName; private boolean mergeMode; private boolean replaceMode; private boolean disabled; private boolean star; private boolean commentFound; /** * @return the fileName */ public String getFileName() { return fileName; } /** * @return the mergeMode */ public boolean isMergeMode() { return mergeMode; } /** * @return the replaceMode */ public boolean isReplaceMode() { return replaceMode; } /** * @return the commentFound */ public boolean isCommentFound() { return commentFound; } /** * * @return disabled */ public boolean isDisabled(){ return disabled; } public boolean isStar(){ return star; } public ConfigurationFileAnalyser(String line) throws EmptyLineException, InvalidLineException { // extract line comment final String lineSubstring[] = line.split("#", 2); if (lineSubstring.length > 1) { commentFound = true; } if (lineSubstring[0] == null || lineSubstring[0].equals("")) { throw new EmptyLineException(); } final String lineCore[] = lineSubstring[0].split(" "); if (!lineCore[0].startsWith("\"") || !lineCore[0].endsWith("\"")) { throw new InvalidLineException(lineSubstring[0] + " --> FileName must start and end with quote\n"); } lineCore[0] = lineCore[0].substring(1, lineCore[0].length() - 1); if (lineCore.length > 1) { fileName = lineCore[0]; if (lineCore[1].equals("M") || lineCore[1].equals("Merge") || lineCore[1].equals("merge")) { mergeMode = true; replaceMode = false; } else if (lineCore[1].equals("R") || lineCore[1].equals("Replace") || lineCore[1].equals("replace")) { mergeMode = false; replaceMode = true; } else { throw new InvalidLineException(lineSubstring[0] + " --> Second argument should be Merge or Replace\n"); } } else { throw new InvalidLineException( lineSubstring[0] + " --> FileName should be followed by a white space and Merge or Replace\n"); } if(lineCore.length>2){ if(lineCore[2].equals("Disabled")||lineCore[2].equals("Disabled")){ disabled = true; } else if(lineCore[2].equals("Enabled")){ disabled = false; } else { throw new InvalidLineException(lineSubstring[0] + " --> Third argument should be Disabled or Enabled\n"); } if(lineCore.length>3){ if(lineCore[3].equals("*")){ star = true; } else if(lineCore[3].equals("1")){ star = false; } else { throw new InvalidLineException(lineSubstring[0] + " --> Fourth argument should be 1 or *\n"); } } else { star = false; } } else { disabled = false; star = false; } } public class InvalidLineException extends Exception { public InvalidLineException(String s) { super(s); } public InvalidLineException() { /* NOP */ } } public class EmptyLineException extends Exception { public EmptyLineException() { /* NOP */ } } }
mdamis/unilabIDE
Unitex-Java/src/fr/umlv/unitex/cassys/ConfigurationFileAnalyser.java
Java
lgpl-3.0
3,912
# Copyright (c) 2010 by Yaco Sistemas <[email protected]> # # 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 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this programe. If not, see <http://www.gnu.org/licenses/>. from django.conf.urls.defaults import patterns, url urlpatterns = patterns('autoreports.views', url(r'^ajax/fields/tree/$', 'reports_ajax_fields', name='reports_ajax_fields'), url(r'^ajax/fields/options/$', 'reports_ajax_fields_options', name='reports_ajax_fields_options'), url(r'^(category/(?P<category_key>[\w-]+)/)?$', 'reports_list', name='reports_list'), url(r'^(?P<registry_key>[\w-]+)/$', 'reports_api', name='reports_api'), url(r'^(?P<registry_key>[\w-]+)/(?P<report_id>\d+)/$', 'reports_api', name='reports_api'), url(r'^(?P<registry_key>[\w-]+)/reports/$', 'reports_api_list', name='reports_api_list'), url(r'^(?P<registry_key>[\w-]+)/wizard/$', 'reports_api_wizard', name='reports_api_wizard'), url(r'^(?P<registry_key>[\w-]+)/wizard/(?P<report_id>\d+)/$', 'reports_api_wizard', name='reports_api_wizard'), url(r'^(?P<app_name>[\w-]+)/(?P<model_name>[\w-]+)/$', 'reports_view', name='reports_view'), )
Yaco-Sistemas/django-autoreports
autoreports/urls.py
Python
lgpl-3.0
1,686
<?php /*! * Schedule builder * * Copyright (c) 2011, Edwin Choi * * Licensed under LGPL 3.0 * http://www.gnu.org/licenses/lgpl-3.0.txt */ //ini_set("display_errors", 1); //ini_set("display_startup_errors", 1); date_default_timezone_set("GMT"); $timezone = date_default_timezone_get(); if ( !isset($_GET['p'])) { header("HTTP/1.1 400 Bad Request"); header("Status: Bad Request"); exit; } $t_start = microtime(true); $data = array(); require_once "./dbconnect.php"; require_once "./terminfo.php"; if ( !$conn ) { header("HTTP/1.1 400 Bad Request"); header("Status: Bad Request"); echo "Failed to connect to DB: $conn->connect_error\n"; exit; } $headers = getallheaders(); if (isset($headers["If-Modified-Since"])) { $lastmodcheck = strtotime($headers["If-Modified-Since"]); if ($lastmodcheck >= $last_run_timestamp) { header("HTTP/1.0 304 Not Modified"); exit; } } if ( strpos($_GET['p'], '/') !== 0 ) { header("HTTP/1.1 400 Bad Request"); header("Status: Bad Request"); echo "Invalid path spec"; exit; } $paths = explode(';', $_GET['p']); if (count($paths) == 1) { $path = explode('/', $paths[0]); array_shift($path); if (count($path) > 1 && $path[0] != "") { $cond = "course = '" . implode("", $path) . "'"; } else { $cond = "TRUE"; } } else { $names = array(); $cond = ""; foreach ($paths as $p) { $path = explode('/', $p); array_shift($path); if (count($path) == 1 && $path[0] == "") { continue; } if ($cond !== "") $cond .= " OR\n"; $cond .= "course = '" . implode("", $path) . "'"; } } $result_array = array(); if (true) { define("CF_SUBJECT" ,0); define("CF_COURSE" ,0); define("CF_TITLE" ,1); define("CF_CREDITS" ,2); //define("CF_SECTIONS" ,3); //define("CF_CRSID" ,0); /* struct { const char* course; const char* title; float credits; struct { const char* course; const char* section; short callnr; const char* seats; const char* instructor; bool online; bool honors; const char* comments; const char* alt_title; const void* slots; } sections[1]; }; */ define("SF_COURSE" ,0); define("SF_SECTION" ,1); define("SF_CALLNR" ,2); //define("SF_ENROLLED" ,3); //define("SF_CAPACITY" ,4); define("SF_SEATS" ,3); define("SF_INSTRUCTOR" ,4); define("SF_ONLINE" ,5); define("SF_HONORS" ,6); //define("SF_FLAGS" ,7); define("SF_COMMENTS" ,7); define("SF_ALT_TITLE" ,8); define("SF_SLOTS" ,9); define("SF_SUBJECT" ,10); } else { define("CF_CRSID", "_id"); define("CF_COURSE", "course"); define("CF_TITLE","title"); define("CF_CREDITS","credits"); define("CF_SECTIONS","sections"); define("SF_SUBJECT","subject"); define("SF_COURSE","course"); define("SF_SECTION","section"); define("SF_CALLNR","callnr"); define("SF_ENROLLED", "enrolled"); define("SF_CAPACITY", "capacity"); define("SF_SEATS","seats"); define("SF_INSTRUCTOR","instructor"); define("SF_ONLINE","online"); define("SF_HONORS","honors"); define("SF_FLAGS","flags"); define("SF_COMMENTS","comments"); define("SF_ALT_TITLE","alt_title"); define("SF_SLOTS", "slots"); } $query = <<<_ SELECT course, title, credits, callnr, flags, section, enrolled, capacity, instructor, comments FROM NX_COURSE WHERE ($cond) _; $res = $conn->query($query); if ( !$res ) { header("HTTP/1.1 400 Bad Request"); header("Status: Bad Request"); echo "MySQL Query Failed: $conn->error"; exit; } $num_sects = $res->num_rows; class Flags { const ONLINE = 1; const HONORS = 2; const ST = 4; const CANCELLED = 8; }; $map = array(); $ctable = array(); $result = array(); $secFields = array(SF_INSTRUCTOR, SF_COMMENTS, SF_ALT_TITLE); $callnrToSlots = array(); while ($row = $res->fetch_row()) { if (!isset($ctable[$row[0]])) { $ctable[$row[0]] = array(); $arr = &$ctable[$row[0]]; $arr[CF_COURSE] = $row[0]; $arr[CF_TITLE] = $row[1]; $arr[CF_CREDITS] = floatval($row[2]); if (defined("CF_SECTIONS")) $arr[CF_SECTIONS] = array(); } else { $arr = &$ctable[$row[0]]; } if (defined("CF_SECTIONS")) { $map[$row[3]] = array($row[0], count($arr[CF_SECTIONS])); } else { $map[$row[3]] = array($row[0], count($arr) - 3); } $sec = array(); $sec[SF_COURSE] = $row[0]; $sec[SF_SECTION] = $row[5]; $sec[SF_CALLNR] = intval($row[3]); if (defined("SF_ENROLLED")) { $sec[SF_ENROLLED] = intval($row[6]); $sec[SF_CAPACITY] = intval($row[7]); } else { $sec[SF_SEATS] = "$row[6] / $row[7]"; } $sec[SF_INSTRUCTOR] = $row[8]; if (defined("SF_FLAGS")) { $sec[SF_FLAGS] = intval($row[4]); } else { $sec[SF_ONLINE] = ($row[4] & Flags::ONLINE) != 0; $sec[SF_HONORS] = ($row[4] & Flags::HONORS) != 0; } $sec[SF_COMMENTS] = $row[9]; $sec[SF_ALT_TITLE] = $row[1]; $sec[SF_SLOTS] = array(); $callnrToSlots[$sec[SF_CALLNR]] = &$sec[SF_SLOTS]; if (defined("CF_SECTIONS")) $arr[CF_SECTIONS][] = $sec; else $arr[] = $sec; //$data[] = &$arr; } if (count($map) > 0) { //$in_cond = 'callnr=' . implode(' OR callnr=', array_keys($map)); $in_cond = implode(',', array_keys($map)); $query = <<<_ SELECT DISTINCT callnr, day, TIME_TO_SEC(start), TIME_TO_SEC(end), room FROM TIMESLOT WHERE callnr IN ($in_cond) _; $res = $conn->query($query) or die("abc: $conn->error\nQuery: $query"); while ($row = $res->fetch_row()) { $callnrToSlots[$row[0]][] = array( /*"day" => */intval($row[1]), /*"start" => */intval($row[2]), /*"end" => */intval($row[3]), /*"location" => */trim($row[4]) ); } } $data = array_values($ctable); unset($ctable); unset($map); if (!defined("INTERNAL")) { header("Content-Type: application/x-javascript"); header("Cache-Control: no-cache, private, must-revalidate"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", $last_run_timestamp). " GMT"); if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) { echo "var COURSE_DATA = "; } // echo json_encode(array("data" => &$data, "t" => microtime(true) - $t_start, "n" => $num_sects)); echo json_encode($data); /* foreach($data as $row) { $sects = $row[CF_SECTIONS]; $row[CF_SECTIONS] = array(); //unset($row[CF_SECTIONS]); echo "db.courses.insert( " . json_encode($row) . " );\n"; echo "db.courses.ensureIndex({course:1});\n"; foreach($sects as $sec) { foreach ($secFields as $nullable) { if (!$sec[$nullable]) { unset($sec[$nullable]); } } if (count($sec[SF_SLOTS]) == 0) unset($sec[SF_SLOTS]); else foreach($sec[SF_SLOTS] as &$slot) { if ($slot["location"] == "") { unset($slot["location"]); } } echo "db.courses.update( { course:'" . $row[CF_COURSE] . "'}, { \$push: { " . CF_SECTIONS . ":". json_encode($sec) . " } } );\n"; } } */ } ?>
JoeParrinello/schedule-builder
datasvc.php
PHP
lgpl-3.0
6,667
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_DELETEBOTREQUEST_P_H #define QTAWS_DELETEBOTREQUEST_P_H #include "lexmodelbuildingservicerequest_p.h" #include "deletebotrequest.h" namespace QtAws { namespace LexModelBuildingService { class DeleteBotRequest; class DeleteBotRequestPrivate : public LexModelBuildingServiceRequestPrivate { public: DeleteBotRequestPrivate(const LexModelBuildingServiceRequest::Action action, DeleteBotRequest * const q); DeleteBotRequestPrivate(const DeleteBotRequestPrivate &other, DeleteBotRequest * const q); private: Q_DECLARE_PUBLIC(DeleteBotRequest) }; } // namespace LexModelBuildingService } // namespace QtAws #endif
pcolby/libqtaws
src/lexmodelbuildingservice/deletebotrequest_p.h
C
lgpl-3.0
1,445
#include <rlib/rbinfmt.h> static void dump_opt_hdr (RPeOptHdr * opt) { r_print ("\tLinkerVer: %u.%u\n", opt->major_linker_ver, opt->minor_linker_ver); r_print ("\tEntrypoint: 0x%.8x\n", opt->addr_entrypoint); r_print ("\tCode addr: 0x%.8x\n", opt->base_code); r_print ("\tCode size: 0x%.8x\n", opt->size_code); } static void dump_pe32_image (RPe32ImageHdr * img) { dump_opt_hdr (&img->opt); r_print ("\tImage base: 0x%.8x\n", img->winopt.image_base); r_print ("\tSect align: 0x%.8x\n", img->winopt.section_alignment); r_print ("\tFile align: 0x%.8x\n", img->winopt.file_alignment); r_print ("\tImage size: 0x%.8x\n", img->winopt.size_image); r_print ("\tHeaders size: 0x%.8x\n", img->winopt.size_headers); r_print ("\tOS ver: %u.%u\n", img->winopt.major_os_ver, img->winopt.minor_os_ver); r_print ("\tImage ver: %u.%u\n", img->winopt.major_image_ver, img->winopt.minor_image_ver); r_print ("\tSubSys ver: %u.%u\n", img->winopt.major_subsystem_ver, img->winopt.minor_subsystem_ver); r_print ("\tSubSys: %.4x\n", img->winopt.subsystem); r_print ("\tChecksum: 0x%.8x\n", img->winopt.checksum); r_print ("\tDLL flags: 0x%.4x\n", img->winopt.dll_characteristics); r_print ("\tLoader flags: 0x%.8x\n", img->winopt.loader_flags); r_print ("\tStack: 0x%.8x (res) 0x%.8x (commit)\n", img->winopt.size_stack_reserve, img->winopt.size_stack_commit); r_print ("\tHeap: 0x%.8x (res) 0x%.8x (commit)\n", img->winopt.size_stack_reserve, img->winopt.size_stack_commit); } static void dump_pe32p_image (RPe32PlusImageHdr * img) { dump_opt_hdr (&img->opt); r_print ("\tImage base: 0x%.12"RINT64_MODIFIER"x\n", img->winopt.image_base); r_print ("\tSect align: 0x%.8x\n", img->winopt.section_alignment); r_print ("\tFile align: 0x%.8x\n", img->winopt.file_alignment); r_print ("\tImage size: 0x%.8x\n", img->winopt.size_image); r_print ("\tHeaders size: 0x%.8x\n", img->winopt.size_headers); r_print ("\tOS ver: %u.%u\n", img->winopt.major_os_ver, img->winopt.minor_os_ver); r_print ("\tImage ver: %u.%u\n", img->winopt.major_image_ver, img->winopt.minor_image_ver); r_print ("\tSubSys ver: %u.%u\n", img->winopt.major_subsystem_ver, img->winopt.minor_subsystem_ver); r_print ("\tSubSys: %.4x\n", img->winopt.subsystem); r_print ("\tChecksum: 0x%.8x\n", img->winopt.checksum); r_print ("\tDLL flags: 0x%.4x\n", img->winopt.dll_characteristics); r_print ("\tLoader flags: 0x%.8x\n", img->winopt.loader_flags); r_print ("\tStack: 0x%.12"RINT64_MODIFIER"x (res) 0x%.12"RINT64_MODIFIER"x (commit)\n", img->winopt.size_stack_reserve, img->winopt.size_stack_commit); r_print ("\tHeap: 0x%.12"RINT64_MODIFIER"x (res) 0x%.12"RINT64_MODIFIER"x (commit)\n", img->winopt.size_stack_reserve, img->winopt.size_stack_commit); } static void dump_section (RPeParser * parser, RPeSectionHdr * sec) { r_print ("\tSection: '%s'\n", sec->name); r_print ("\t\tvmsize: 0x%.8x\n", sec->vmsize); r_print ("\t\tvmaddr: 0x%.8x\n", sec->vmaddr); r_print ("\t\tSize: 0x%.8x\n", sec->size_raw_data); r_print ("\t\tOffset: 0x%.8x\n", sec->ptr_raw_data); r_print ("\t\tReloc: 0x%.8x\n", sec->ptr_relocs); r_print ("\t\tReloc#: %u\n", sec->nrelocs); r_print ("\t\tLinenum: 0x%.8x\n", sec->ptr_linenos); r_print ("\t\tLinenum#: %u\n", sec->nlinenos); r_print ("\t\tFlags: 0x%.8x\n", sec->characteristics); } int main (int argc, char ** argv) { RPeParser * parser; RPeSectionHdr * sec; RPe32ImageHdr * pe32; RPe32PlusImageHdr * pe32p; ruint16 i; if (argc < 2) { r_printerr ("Usage: %s <filename>\n", argv[0]); return -1; } else if ((parser = r_pe_parser_new (argv[1])) == NULL) { r_printerr ("Unable to parse '%s' as Mach-O\n", argv[1]); return -1; } switch (r_pe_parser_get_pe32_magic (parser)) { case R_PE_PE32_MAGIC: r_print ("PE32\n"); break; case R_PE_PE32PLUS_MAGIC: r_print ("PE32+\n"); break; default: r_print ("Unknown PE format\n"); return -1; } r_print ("\tMachine: %s\n", r_pe_machine_str (r_pe_parser_get_machine (parser))); r_print ("\tSections: %u\n", r_pe_parser_get_section_count (parser)); r_print ("\tSymbols: %u\n", r_pe_parser_get_symbol_count (parser)); r_print ("\tFlags: 0x%.4x\n\n", r_pe_parser_get_characteristics (parser)); if ((pe32 = r_pe_parser_get_pe32_image_hdr (parser)) != NULL) dump_pe32_image (pe32); if ((pe32p = r_pe_parser_get_pe32p_image_hdr (parser)) != NULL) dump_pe32p_image (pe32p); r_print ("\nSections\n"); for (i = 0; (sec = r_pe_parser_get_section_hdr_by_idx (parser, i)) != NULL; i++) dump_section (parser, sec); return 0; }
ieei/rlib
example/rpedump.c
C
lgpl-3.0
4,789
<?php return array( 'code' => 'ANG', 'sign' => 'f', 'sign_position' => 0, 'sign_delim' => '', 'title' => 'Netherlands Antillean guilder', 'name' => array( array('', ''), 'NAƒ', 'NAf', 'ƒ', ), 'frac_name' => array( array('cent', 'cents'), ) );
dmitriyzhdankin/avantmarketcomua
wa-system/currency/data/ANG.php
PHP
lgpl-3.0
338
# encoding: utf-8 from __future__ import absolute_import, unicode_literals from apiview.model import AbstractUserMixin, BaseModel from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractUserMixin, BaseModel, AbstractBaseUser): is_staff = False def get_short_name(self): return self.name def get_full_name(self): return self.nickname USERNAME_FIELD = 'username' username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False) password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True) nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False) class Meta: db_table = 'example_user' app_label = 'example_app' verbose_name = verbose_name_plural = "用户"
007gzs/django_restframework_apiview
example/example_app/models.py
Python
lgpl-3.0
925
-- SETTINGS BLINKY_PLANT_INTERVAL = 3 NEW_STYLE_WIRES = true -- true = new nodebox wires, false = old raillike wires PRESSURE_PLATE_INTERVAL = 0.1 OBJECT_DETECTOR_RADIUS = 6 PISTON_MAXIMUM_PUSH = 15 MOVESTONE_MAXIMUM_PUSH = 100
jojoa1997/overcraft_origins
mods/redstone/mesecons/settings.lua
Lua
lgpl-3.0
237
/** * Copyright(C) 2009-2012 * @author Jing HUANG * @file EtoileImageToTexturePlugin.cpp * @brief * @date 1/2/2011 */ #include "EtoileImageToTexturePlugin.h" #include "util/File.h" #include "QtTextureLoader.h" /** * @brief For tracking memory leaks under windows using the crtdbg */ #if ( defined( _DEBUG ) || defined( DEBUG ) ) && defined( _MSC_VER ) #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif Etoile::EPlugin* loadEtoileImageToTexturePlugin() { return new Etoile::EtoileImageToTexturePlugin("ImageToTexture"); } namespace Etoile { ImageToTextureStringInputSocket::ImageToTextureStringInputSocket(const std::string& name) : StringInputSocket(name) { } void ImageToTextureStringInputSocket::perform(std::string* signal) { if(signal == NULL) return; EtoileImageToTexturePlugin* plugin = (EtoileImageToTexturePlugin*)(this->getNode()); plugin->openFile(*signal); } void ImageToTextureStringInputSocket::retrieve(std::string* signal) { EtoileImageToTexturePlugin* plugin = (EtoileImageToTexturePlugin*)(this->getNode()); plugin->openFile(""); } ImageToTextureOutputSocket::ImageToTextureOutputSocket(const std::string& name) : TextureOutputSocket(name) { } EtoileImageToTexturePlugin::EtoileImageToTexturePlugin(const std::string& name): EPlugin(), SocketNode() { this->getType()._description = "ImageToTexture"; this->getType()._name = name; this->getType()._w = 80; this->getType()._h = 60; this->getType()._color._r = 120; this->getType()._color._g = 240; this->getType()._color._b = 250; this->getType()._color._a = 240; _pInput = new ImageToTextureStringInputSocket(); this->addInputSocket(_pInput); _pOutput = new ImageToTextureOutputSocket(); this->addOutputSocket(_pOutput); } EtoileImageToTexturePlugin::~EtoileImageToTexturePlugin() { } void EtoileImageToTexturePlugin::openFile(const std::string& filename) { if(filename.empty()) return; std::string ext = File::getFileExtension(filename); Mesh *mesh = new Mesh(filename); QtTextureLoader textureloader; Texture* t = textureloader.loadFromFile(filename); _pOutput->set(t); _pOutput->signalEmit(t); } }
billhj/Etoile
applications/EtoileQtRendererPlugins/EtoileImageToTexturePlugin.cpp
C++
lgpl-3.0
2,341
/* * #-------------------------------------------------------------------------- * # Copyright (c) 2013 VITRO FP7 Consortium. * # All rights reserved. This program and the accompanying materials * # are made available under the terms of the GNU Lesser Public License v3.0 which accompanies this distribution, and is available at * # http://www.gnu.org/licenses/lgpl-3.0.html * # * # Contributors: * # Antoniou Thanasis (Research Academic Computer Technology Institute) * # Paolo Medagliani (Thales Communications & Security) * # D. Davide Lamanna (WLAB SRL) * # Alessandro Leoni (WLAB SRL) * # Francesco Ficarola (WLAB SRL) * # Stefano Puglia (WLAB SRL) * # Panos Trakadas (Technological Educational Institute of Chalkida) * # Panagiotis Karkazis (Technological Educational Institute of Chalkida) * # Andrea Kropp (Selex ES) * # Kiriakos Georgouleas (Hellenic Aerospace Industry) * # David Ferrer Figueroa (Telefonica Investigación y Desarrollo S.A.) * # * #-------------------------------------------------------------------------- */ package vitro.vspEngine.service.common.abstractservice.dao; import javax.persistence.EntityManager; import vitro.vspEngine.logic.model.Gateway; import vitro.vspEngine.service.common.abstractservice.model.ServiceInstance; import vitro.vspEngine.service.persistence.DBRegisteredGateway; import java.util.List; public class GatewayDAO { private static GatewayDAO instance = new GatewayDAO(); private GatewayDAO(){ super(); } public static GatewayDAO getInstance(){ return instance; } /** * * @param manager * @param incId the incremental auto id in the db * @return */ public DBRegisteredGateway getGatewayByIncId(EntityManager manager, int incId){ DBRegisteredGateway dbRegisteredGateway = manager.find(DBRegisteredGateway.class, incId); return dbRegisteredGateway; } /** * * @param manager * @param name the gateway (registered) name * @return */ public DBRegisteredGateway getGateway(EntityManager manager, String name){ StringBuffer sb = new StringBuffer(); sb.append("SELECT g "); sb.append("FROM DBRegisteredGateway g "); sb.append("WHERE g.registeredName = :gname "); DBRegisteredGateway result = manager.createQuery(sb.toString(), DBRegisteredGateway.class). setParameter("gname", name). getSingleResult(); return result; } public List<DBRegisteredGateway> getInstanceList(EntityManager manager){ List<DBRegisteredGateway> result = manager.createQuery("SELECT instance FROM DBRegisteredGateway instance", DBRegisteredGateway.class).getResultList(); return result; } }
vitrofp7/vitro
source/trunk/Demo/vitroUI/vspEngine/src/main/java/vitro/vspEngine/service/common/abstractservice/dao/GatewayDAO.java
Java
lgpl-3.0
2,739
package org.teaminfty.math_dragon.view.math.source.operation; import static org.teaminfty.math_dragon.view.math.Expression.lineWidth; import org.teaminfty.math_dragon.view.math.Empty; import org.teaminfty.math_dragon.view.math.source.Expression; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; /** A class that represents a source for new {@link Root}s in the drag-and-drop interface */ public class Root extends Expression { /** The paint we use to draw the operator */ private Paint paintOperator = new Paint(); /** Default constructor */ public Root() { // Initialise the paint paintOperator.setStyle(Paint.Style.STROKE); paintOperator.setAntiAlias(true); } @Override public org.teaminfty.math_dragon.view.math.Expression createMathObject() { return new org.teaminfty.math_dragon.view.math.operation.binary.Root(); } @Override public void draw(Canvas canvas, int w, int h) { // The width of the gap between the big box and the small box final int gapWidth = (int) (3 * lineWidth); // Get a boxes that fit the given width and height (we'll use it to draw the empty boxes) // We'll want one big and one small (2/3 times the big one) box Rect bigBox = getRectBoundingBox(3 * (w - gapWidth) / 5, 3 * h / 4, Empty.RATIO); Rect smallBox = getRectBoundingBox(2 * (w - gapWidth) / 5, 2 * h / 4, Empty.RATIO); // Position the boxes smallBox.offsetTo((w - bigBox.width() - smallBox.width() - gapWidth) / 2, (h - bigBox.height() - smallBox.height() / 2) / 2); bigBox.offsetTo(smallBox.right + gapWidth, smallBox.centerY()); // Draw the boxes drawEmptyBox(canvas, bigBox); drawEmptyBox(canvas, smallBox); // Create a path for the operator Path path = new Path(); path.moveTo(smallBox.left, smallBox.bottom + 2 * lineWidth); path.lineTo(smallBox.right - 2 * lineWidth, smallBox.bottom + 2 * lineWidth); path.lineTo(smallBox.right + 1.5f * lineWidth, bigBox.bottom - lineWidth / 2); path.lineTo(smallBox.right + 1.5f * lineWidth, bigBox.top - 2 * lineWidth); path.lineTo(bigBox.right, bigBox.top - 2 * lineWidth); // Draw the operator paintOperator.setStrokeWidth(lineWidth); canvas.drawPath(path, paintOperator); } }
Divendo/math-dragon
mathdragon/src/main/java/org/teaminfty/math_dragon/view/math/source/operation/Root.java
Java
lgpl-3.0
2,494
js.Offset = function(rawptr) { this.rawptr = rawptr; } js.Offset.prototype = new konoha.Object(); js.Offset.prototype._new = function(rawptr) { this.rawptr = rawptr; } js.Offset.prototype.getTop = function() { return this.rawptr.top; } js.Offset.prototype.getLeft = function() { return this.rawptr.left; } js.jquery = {}; var initJQuery = function() { var verifyArgs = function(args) { for (var i = 0; i < args.length; i++) { if (args[i].rawptr) { args[i] = args[i].rawptr; } } return args; } var jquery = function(rawptr) { this.rawptr = rawptr; } jquery.prototype = new konoha.Object(); jquery.konohaclass = "js.jquery.JQuery"; /* Selectors */ jquery.prototype.each_ = function(callback) { this.rawptr.each(callback.rawptr); } jquery.prototype.size = function() { return this.rawptr.size(); } jquery.prototype.getSelector = function() { return new konoha.String(this.rawptr.getSelector()); } jquery.prototype.getContext = function() { return new js.dom.Node(this.rawptr.getContext()); } jquery.prototype.getNodeList = function() { return new js.dom.NodeList(this.rawptr.get()); } jquery.prototype.getNode = function(index) { return new js.dom.Node(this.rawptr.get(index)); } /* Attributes */ jquery.prototype.getAttr = function(arg) { return new konoha.String(this.rawptr.attr(arg.rawptr)); } jquery.prototype.attr = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.attr.apply(this.rawptr, args)); } jquery.prototype.removeAttr = function(name) { return new jquery(this.rawptr.removeAttr(name.rawptr)); } jquery.prototype.addClass = function(className) { return new jquery(this.rawptr.addClass(className.rawptr)); } jquery.prototype.removeClass = function(className) { return new jquery(this.rawptr.removeClass(className.rawptr)); } jquery.prototype.toggleClass = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.toggleClass.apply(this.rawptr, args)); } jquery.prototype.getHTML = function() { return new konoha.String(this.rawptr.html()); } jquery.prototype.html = function(val) { return new jquery(this.rawptr.html(val.rawptr)); } jquery.prototype.getText = function() { return new konoha.String(this.rawptr.text()); } jquery.prototype.text = function(val) { return new jquery(this.rawptr.text(val.rawptr)); } jquery.prototype.getVal = function() { return new konoha.Array(this.rawptr.val()) } jquery.prototype.val = function(val) { return new jquery(this.rawptr.val(val.rawptr)); } /* Traversing */ jquery.prototype.eq = function(position) { return new jquery(this.rawptr.eq(position)); } jquery.prototype.filter = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.filter.apply(this.rawptr, args)); } jquery.prototype.is = function(expr) { return this.rawptr.is(expr.rawptr); } jquery.prototype.opnot = function(expr) { return this.rawptr.not(expr.rawptr); } jquery.prototype.slice = function() { return new jquery(this.rawptr.slice.apply(this.rawptr, Array.prototype.slice.call(arguments))); } jquery.prototype.add = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.add.apply(this.rawptr, args)); } jquery.prototype.children = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.children.apply(this.rawptr, args)); } jquery.prototype.closest = function() { var args =verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.closest.apply(this.rawptr, args)); } jquery.prototype.contents = function() { return new jquery(this.rawptr.contents()); } jquery.prototype.find = function(expr) { return new jquery(this.rawptr.find(expr.rawptr)); } jquery.prototype.next = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.next.apply(this.rawptr, args)); } jquery.prototype.nextAll = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.nextAll.apply(this.rawptr, args)); } jquery.prototype.parent = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.parent.apply(this.rawptr, args)); } jquery.prototype.parents = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.parents.apply(this.rawptr, args)); } jquery.prototype.prev = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.prev.apply(this.rawptr, args)); } jquery.prototype.prevAll = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.prevAll.apply(this.rawptr, args)); } jquery.prototype.siblings = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.siblings.apply(this.rawptr, args)); } jquery.prototype.andSelf = function() { return new jquery(this.rawptr.andSelf()); } jquery.prototype.end = function() { return new jquery(this.rawptr.end()); } /* Manipulation */ jquery.prototype.append = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.append.apply(this.rawptr, args)); } jquery.prototype.appendTo = function(content) { return new jquery(this.rawptr.appendTo(content.rawptr)); } jquery.prototype.prepend = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.prepend.apply(this.rawptr, args)); } jquery.prototype.prependTo = function(content) { return new jquery(this.rawptr.prependTo(content.rawptr)); } jquery.prototype.after = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.after.apply(this.rawptr, args)); } jquery.prototype.before = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.before.apply(this.rawptr, args)); } jquery.prototype.insertAfter = function(content) { return new jquery(this.rawptr.insertAfter(content.rawptr)); } jquery.prototype.insertBefore = function(content) { return new jquery(this.rawptr.insertBefore(content.rawptr)); } jquery.prototype.wrap = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.wrap.apply(this.rawptr, args)); } jquery.prototype.wrapAll = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.wrapAll.apply(this.rawptr, args)); } jquery.prototype.wrapInner = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.wrapInner.apply(this.rawptr, args)); } jquery.prototype.replaceWith = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.replaceWith.apply(this.rawptr, args)); } jquery.prototype.replaceAll = function(selector) { return new jquery(this.rawptr.replaceAll(selector.rawptr)); } jquery.prototype.empty = function() { return new jquery(this.rawptr.empty()); } jquery.prototype.remove = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.remove.apply(this.rawptr, args)); } jquery.prototype.clone = function() { return new jquery(this.rawptr.clone.apply(this.rawptr, Array.prototype.slice.call(arguments))); } /* CSS */ jquery.prototype.getCss = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new konoha.String(this.rawptr.css.apply(this.rawptr, args)); } jquery.prototype.css = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.css.apply(this.rawptr, args)); } jquery.prototype.offset = function() { return new js.Offset(this.rawptr.offset()); } jquery.prototype.position = function() { return new js.Offset(this.rawptr.position()); } jquery.prototype.scrollTop = function() { return this.rawptr.scrollTop.apply(this.rawptr, Array.prototype.slice.call(arguments)); } jquery.prototype.scrollLeft = function() { return this.rawptr.scrollLeft.apply(this.rawptr, Array.prototype.slice.call(arguments)); } jquery.prototype.height = function() { return this.rawptr.height.apply(this.rawptr, Array.prototype.slice.call(arguments)); } jquery.prototype.width = function() { return this.rawptr.width.apply(this.rawptr, Array.prototype.slice.call(arguments)); } jquery.prototype.innerHeight = function() { return this.rawptr.innerHeight(); } jquery.prototype.innerWidth = function() { return this.rawptr.innerWidth(); } jquery.prototype.outerHeight = function() { return this.rawptr.outerHeight(); } jquery.prototype.outerWidth = function() { return this.rawptr.outerWidth(); } /* Events */ jquery.prototype.ready = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.ready.apply(this.rawptr, args)); } jquery.prototype.bind = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.bind.apply(this.rawptr, args)); } jquery.prototype.one = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.one.apply(this.rawptr, args)); } jquery.prototype.trigger = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.trigger.apply(this.rawptr, args)); } jquery.prototype.triggerHandler = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.triggerHandler.apply(this.rawptr, args)); } jquery.prototype.unbind = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.unbind.apply(this.rawptr, args)); } jquery.prototype.hover = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.hover.apply(this.rawptr, args)); } jquery.prototype.toggleEvent = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); args = verifyArgs(args[0]); return new jquery(this.rawptr.toggle.apply(this.rawptr, args)); } jquery.prototype.live = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.live.apply(this.rawptr, args)); } jquery.prototype.die = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.die.apply(this.rawptr, args)); } jquery.prototype.blur = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.blur.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.blur(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.change = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.change.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.change(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.click = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.click.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.click(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.dblclick = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.dblclick.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.dblclick(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.error = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.error.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.error(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.focus = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.focus.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.focus(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.keydown = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.keydown.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.keydown(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.keypress = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.keypress.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.keypress(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.keyup = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.keyup.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.keyup(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.load = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.load.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.load(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mousedown = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mousedown.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mousedown(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mousemove = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mousemove.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mousemove(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mouseout = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mouseout.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mouseout(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mouseover = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mouseover.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mouseover(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mouseup = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mouseup.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mouseup(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.resize = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.resize.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.resize(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.scroll = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.scroll.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.scroll(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.select = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.select.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.select(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.submit = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.submit.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.select(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.unload = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.unload.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.unload(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } /* Effects */ jquery.prototype.show = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.show.apply(this.rawptr, args)); } jquery.prototype.hide = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.hide.apply(this.rawptr, args)); } jquery.prototype.toggle = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.toggle.apply(this.rawptr, args)); } jquery.prototype.slideDown = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.slideDown.apply(this.rawptr, args)); } jquery.prototype.slideUp = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.slideUp.apply(this.rawptr, args)); } jquery.prototype.slideToggle = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.slideToggle.apply(this.rawptr, args)); } jquery.prototype.fadeIn = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.fadeIn.apply(this.rawptr, args)); } jquery.prototype.fadeOut = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.fadeOut.apply(this.rawptr, args)); } jquery.prototype.fadeTo = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.fadeTo.apply(this.rawptr, args)); } jquery.prototype._new = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (arguments.length == 1) { this.rawptr = new $(args[0]); } else if (arguments.length == 2) { this.rawptr = new $(args[0], args[1]); } else { throw ("Script !!"); } return this; } return jquery; } js.jquery.JQuery = new initJQuery(); js.jquery.JEvent = new function() { var jevent = function(rawptr) { this.rawptr = rawptr; } jevent.prototype = new konoha.Object(); jevent.konohaclass = "js.jquery.JEvent"; jevent.prototype.type = function() { return new konoha.String(this.rawptr.type); } jevent.prototype.target = function() { return new konoha.dom.Element(this.rawptr.target); } jevent.prototype.relatedTarget = function() { return new konoha.dom.Element(this.rawptr.relatedTarget); } jevent.prototype.currentTarget = function() { return new konoha.dom.Element(this.rawptr.currentTarget); } jevent.prototype.pageX = function() { return this.rawptr.pageX; } jevent.prototype.pageY = function() { return this.rawptr.pageY; } jevent.prototype.timeStamp = function() { return this.rawptr.timeStamp; } jevent.prototype.preventDefault = function() { return new jevent(this.rawptr.preventDefault()); } jevent.prototype.isDefaultPrevented = function() { return this.rawptr.isDefaultPrevented(); } jevent.prototype.stopPropagation = function() { return new jevent(this.rawptr.stopPropagation()); } jevent.prototype.isPropagationStopped = function() { return this.rawptr.isPropagationStopped(); } jevent.prototype.stopImmediatePropagation = function() { return new jevent(this.rawptr.stopImmediatePropagation()); } jevent.prototype.isImmediatePropagationStopped = function() { return this.rawptr.isImmediatePropagationStopped(); } jevent.prototype._new = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (arguments.length == 1) { this.rawptr = new $(args[0]); } else if (arguments.length == 2) { this.rawptr = new $(args[0], args[1]); } else { throw ("Script !!"); } return this; } return jevent; }();
imasahiro/konohascript
package/konoha.compiler.js/runtime/js.jquery.js
JavaScript
lgpl-3.0
24,892
package br.gov.serpro.infoconv.proxy.businesscontroller; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import br.gov.frameworkdemoiselle.stereotype.BusinessController; import br.gov.serpro.infoconv.proxy.exception.AcessoNegadoException; import br.gov.serpro.infoconv.proxy.exception.CNPJNaoEncontradoException; import br.gov.serpro.infoconv.proxy.exception.CpfNaoEncontradoException; import br.gov.serpro.infoconv.proxy.exception.DadosInvalidosException; import br.gov.serpro.infoconv.proxy.exception.InfraException; import br.gov.serpro.infoconv.proxy.exception.PerfilInvalidoException; import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil1CNPJ; import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil2CNPJ; import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil3CNPJ; import br.gov.serpro.infoconv.proxy.util.InfoconvConfig; import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil1; import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil2; import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil3; import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil1; import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil2; import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil3; /** * Classe responsável por interagir com o componente infoconv-ws para obter as * consultas de cnpj e transformar os erros previstos em exceções. * */ @BusinessController public class ConsultaCNPJBC { /** Classe de configuração do infoconv. */ @Inject InfoconvConfig infoconv; private static final String CPF_CONSULTANTE = "79506240949"; /** * Verifica a propriedade ERRO para saber se houve algum problema na * consulta. * * Como se trata de um webservice sempre retorna com codigo http 200 e * dentro da msg de retorno o campo "erro" informa se teve algum problema. * * Alguns "erros" são na verdade avisos por isso não levantam exceção. segue * os erros que levantam exceção: * * - AcessoNegadoException: Todos os erros que começãm com ACS - Erro. Podem * ser por falta de permissão ou algum problema com certificado. A mensagem * explica qual o problema. * * - CNPJNaoEncontradoException: Quando o cpf não está na base. Erros: CPJ * 04 * * - DadosInvalidosException: Qualquer problema de validação no servidor. * Erros: CPJ 02,06 e 11 * * - InfraException: Erros no lado do servidor (WS) Erros: CPF 00 , 01, 03, * 08, 09 * * Documentação dos códigos de Erros: * https://github.com/infoconv/infoconv-ws * * @param response * @throws AcessoNegadoException * @throws DadosInvalidosException * @throws InfraException * @throws CNPJNaoEncontradoException */ private void verificarErros(final Object retorno) throws AcessoNegadoException, DadosInvalidosException, InfraException, CNPJNaoEncontradoException { try { Class<?> c = retorno.getClass(); Field erroField = c.getDeclaredField("erro"); erroField.setAccessible(true); String erroMsg = (String) erroField.get(retorno); if (erroMsg.indexOf("ACS - Erro") > -1) { throw new AcessoNegadoException(erroMsg); } else if (erroMsg.indexOf("CPJ - Erro 04") > -1) { throw new CNPJNaoEncontradoException(erroMsg); } else if (erroMsg.indexOf("CPJ - Erro 02") > -1 || erroMsg.indexOf("CPJ - Erro 06") > -1 || erroMsg.indexOf("CPJ - Erro 11") > -1) { throw new DadosInvalidosException(erroMsg); } else if (erroMsg.indexOf("CPJ - Erro 01") > -1 || erroMsg.indexOf("CPJ - Erro 03") > -1 || erroMsg.indexOf("CPJ - Erro 00") > -1 || erroMsg.indexOf("CPJ - Erro 08") > -1 || erroMsg.indexOf("CPJ - Erro 09") > -1) { throw new InfraException(erroMsg); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } /** * Baseado no perfil indicado monta uma lista generia com o tipo de CNPJ do * perfil como Object. * * @param listaCNPJs * @param perfil * @return * @throws PerfilInvalidoException * @throws InfraException * @throws DadosInvalidosException * @throws AcessoNegadoException * @throws CNPJNaoEncontradoException */ public List<Object> consultarListaDeCnpjPorPerfil(final String listaCNPJs, final String perfil) throws PerfilInvalidoException, AcessoNegadoException, DadosInvalidosException, InfraException, CNPJNaoEncontradoException { List<Object> lista = new ArrayList<Object>(); String perfilUpper = perfil.toUpperCase(); if (perfil == null || "P1".equals(perfilUpper)) { ArrayOfCNPJPerfil1 p = infoconv.consultarCNPJSoap.consultarCNPJP1(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil1()); } else if ("P1T".equals(perfilUpper)) { ArrayOfCNPJPerfil1 p = infoconv.consultarCNPJSoap.consultarCNPJP1T(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil1()); } else if ("P2".equals(perfilUpper)) { ArrayOfCNPJPerfil2 p = infoconv.consultarCNPJSoap.consultarCNPJP2(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil2()); } else if ("P2T".equals(perfilUpper)) { ArrayOfCNPJPerfil2 p = infoconv.consultarCNPJSoap.consultarCNPJP2T(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil2()); } else if ("P3".equals(perfilUpper)) { ArrayOfCNPJPerfil3 p = infoconv.consultarCNPJSoap.consultarCNPJP3(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil3()); } else if ("P3T".equals(perfilUpper)) { ArrayOfCNPJPerfil3 p = infoconv.consultarCNPJSoap.consultarCNPJP3T(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil3()); } else { throw new PerfilInvalidoException(); } verificarErros(lista.get(0)); return lista; } /** * Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP1 * * @param listaCNPJs * @return * @throws AcessoNegadoException * @throws CpfNaoEncontradoException * @throws DadosInvalidosException * @throws InfraException */ public List<Perfil1CNPJ> listarPerfil1(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{ ArrayOfCNPJPerfil1 result = infoconv.consultarCNPJSoap.consultarCNPJP1(listaCNPJs, CPF_CONSULTANTE); verificarErros(result.getCNPJPerfil1().get(0)); List<Perfil1CNPJ> lista = new ArrayList<Perfil1CNPJ>(); for (CNPJPerfil1 perfil1 : result.getCNPJPerfil1()) { lista.add(new Perfil1CNPJ(perfil1)); } return lista; } /** * Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP2 * * @param listaCNPJs * @return * @throws AcessoNegadoException * @throws CpfNaoEncontradoException * @throws DadosInvalidosException * @throws InfraException */ public List<Perfil2CNPJ> listarPerfil2(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{ ArrayOfCNPJPerfil2 result = infoconv.consultarCNPJSoap.consultarCNPJP2(listaCNPJs, CPF_CONSULTANTE); verificarErros(result.getCNPJPerfil2().get(0)); List<Perfil2CNPJ> lista = new ArrayList<Perfil2CNPJ>(); for (CNPJPerfil2 perfil1 : result.getCNPJPerfil2()) { lista.add(new Perfil2CNPJ(perfil1)); } return lista; } /** * Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP3 * * @param listaCNPJs * @return * @throws AcessoNegadoException * @throws CpfNaoEncontradoException * @throws DadosInvalidosException * @throws InfraException */ public List<Perfil3CNPJ> listarPerfil3(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{ ArrayOfCNPJPerfil3 result = infoconv.consultarCNPJSoap.consultarCNPJP3(listaCNPJs, CPF_CONSULTANTE); verificarErros(result.getCNPJPerfil3().get(0)); List<Perfil3CNPJ> lista = new ArrayList<Perfil3CNPJ>(); for (CNPJPerfil3 perfil1 : result.getCNPJPerfil3()) { lista.add(new Perfil3CNPJ(perfil1)); } return lista; } }
infoconv/infoconv-proxy
src/main/java/br/gov/serpro/infoconv/proxy/businesscontroller/ConsultaCNPJBC.java
Java
lgpl-3.0
8,058
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.18052 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace ClickBot.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
thedava/dh-clickbot
ClickBot/Properties/Settings.Designer.cs
C#
lgpl-3.0
1,129
/* * This file is part of Codecrypt. * * Copyright (C) 2013-2016 Mirek Kratochvil <[email protected]> * * Codecrypt 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. * * Codecrypt 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 Codecrypt. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _ccr_algorithm_h_ #define _ccr_algorithm_h_ #include "algo_suite.h" #include "bvector.h" #include "prng.h" #include "sencode.h" /* * virtual interface definition for all cryptographic algorithm instances. * * Note that the whole class could be defined static, but we really enjoy * having the tiny virtual pointers stored in some cool structure along with * the handy algorithm name. */ class algorithm { public: virtual bool provides_signatures() = 0; virtual bool provides_encryption() = 0; virtual std::string get_alg_id() = 0; void register_into_suite (algorithm_suite&s) { s[this->get_alg_id()] = this; } /* * note that these functions should be ready for different * plaintext/ciphertext/message lengths, usually padding them somehow. */ virtual int encrypt (const bvector&plain, bvector&cipher, sencode* pubkey, prng&rng) { return -1; } virtual int decrypt (const bvector&cipher, bvector&plain, sencode* privkey) { return -1; } virtual int sign (const bvector&msg, bvector&sig, sencode** privkey, bool&dirty, prng&rng) { return -1; } virtual int verify (const bvector&sig, const bvector&msg, sencode* pubkey) { return -1; } virtual int create_keypair (sencode**pub, sencode**priv, prng&rng) { return -1; } }; #endif
exaexa/codecrypt
src/algorithm.h
C
lgpl-3.0
2,137
/** * This file is part of the CRISTAL-iSE kernel. * Copyright (c) 2001-2015 The CRISTAL Consortium. All rights reserved. * * 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 3 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; with out 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. * * http://www.fsf.org/licensing/licenses/lgpl.html */ package org.cristalise.kernel.lifecycle.instance.stateMachine; import lombok.Getter; import lombok.Setter; @Getter @Setter public class TransitionQuery { /** * Name & version of the query to be run by the agent during this transition */ String name, version; public TransitionQuery() {} public TransitionQuery(String n, String v) { name = n; version = v; } }
cristal-ise/kernel
src/main/java/org/cristalise/kernel/lifecycle/instance/stateMachine/TransitionQuery.java
Java
lgpl-3.0
1,327
<?php namespace rocket\si\content\impl\iframe; use n2n\util\type\attrs\DataSet; use n2n\util\type\ArgUtils; use rocket\si\content\impl\InSiFieldAdapter; class IframeInSiField extends InSiFieldAdapter { private $iframeData; private $params = []; public function __construct(IframeData $iframeData) { $this->iframeData = $iframeData; } /** * @return string */ function getType(): string { return 'iframe-in'; } /** * @return array */ function getParams(): array { return $this->params; } /** * @param array $params * @return IframeInSiField */ function setParams(array $params) { ArgUtils::valArray($params, ['scalar', 'null']); $this->params = $params; return $this; } /** * {@inheritDoc} * @see \rocket\si\content\SiField::getData() */ function getData(): array { $data = $this->iframeData->toArray(); $data['params'] = $this->getParams(); $data['messages'] = $this->getMessageStrs(); return $data; } /** * {@inheritDoc} * @see \rocket\si\content\SiField::handleInput() */ function handleInput(array $data) { $ds = new DataSet($data); $this->params = $ds->reqScalarArray('params', false, true); } }
n2n/rocket
src/app/rocket/si/content/impl/iframe/IframeInSiField.php
PHP
lgpl-3.0
1,178
using System.Collections; using System.Linq; using System.Reflection; namespace System.ComponentModel.DataAnnotations { public class EnsureNoDuplicatesAttribute : ValidationAttribute { public EnsureNoDuplicatesAttribute(Type type, string comparassionMethodName) { this.type = type; method = type.GetMethod(comparassionMethodName, BindingFlags.Static | BindingFlags.Public); if (method != null) { if (method.ReturnType == typeof(bool)) { var pars = method.GetParameters(); if (pars.Count() != 2) throw new ArgumentException($"Method '{comparassionMethodName}' in type '{type.Name}' specified for this '{nameof(EnsureNoDuplicatesAttribute)}' must has 2 parameters. Both of them must be of type of property."); } else throw new ArgumentException($"Method '{comparassionMethodName}' in type '{type.Name}' specified for this '{nameof(EnsureNoDuplicatesAttribute)}' must return 'bool'."); } else throw new ArgumentException($"Method '{comparassionMethodName}' in type '{type.Name}' specified for this '{nameof(EnsureNoDuplicatesAttribute)}' was not found. This method must be public and static."); } Type type; MethodInfo? method; string? lastDuplicateValue; public override string FormatErrorMessage(string name) { return string.Format(ErrorMessageString, name, lastDuplicateValue); } public override bool IsValid(object? value) { if (value is IList list) { if (list.Count < 2) return true; for (int i = 1; i < list.Count; i++) { if ((bool?)method?.Invoke(null, new[] { list[i - 1], list[i] }) ?? false) { lastDuplicateValue = list[i]?.ToString(); return false; } } return true; } return false; } //public override bool RequiresValidationContext => true; //protected override ValidationResult IsValid(object value, ValidationContext context) //{ // if (value is IList list) // { // if (list.Count < 2) return ValidationResult.Success; // for (int i = 1; i < list.Count; i++) // { // if ((bool)method.Invoke(null, new[] { list[i - 1], list[i] })) // { // lastDuplicateValue = list[i].ToString(); // return new ValidationResult(string.Format(ErrorMessageString, context.DisplayName, list[i])); // } // } // return ValidationResult.Success; // } // return new ValidationResult("Value isn't IList"); //} } }
osjimenez/fuxion
src/core/Fuxion/ComponentModel/DataAnnotations/EnsureNoDuplicatesAttribute.cs
C#
lgpl-3.0
2,398
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Henon Map</title> <style type="text/css"> h1 {text-align: center} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <meta name="author" content="Mark Hale"> </head> <body> <h1>Henon Map</h1> <div align="center"> <object codetype="application/java" classid="java:HenonPlot.class" width=400 height=400> <param name="code" value="HenonPlot.class"> <param name="type" value="application/x-java-applet;version=1.3"> </object> </div> </body> </html> 
SOCR/HTML5_WebSite
SOCR2.8/src/JSci/Demos/Chaos/Henon.html
HTML
lgpl-3.0
668
#include "NodoTipo.h" NodoTipo::NodoTipo(Tipo* obj) { setTipo(obj); setDer(NULL); setIzq(NULL); _listaISBN = new ListaISBN(); } NodoTipo*&NodoTipo::getIzq() { return _izq; } void NodoTipo::setIzq(NodoTipo* _izq) { this->_izq = _izq; } NodoTipo*& NodoTipo::getDer() { return _der; } void NodoTipo::setDer(NodoTipo* _der) { this->_der = _der; } Tipo* NodoTipo::getTipo()const { return _Tipo; } void NodoTipo::setTipo(Tipo* _Tipo) { this->_Tipo = _Tipo; } NodoTipo::~NodoTipo() { _listaISBN->destruir(); delete _listaISBN; delete _Tipo; } ListaISBN* NodoTipo::getListaISBN(){ return _listaISBN; } void NodoTipo::setListaISBN(ListaISBN* l){ _listaISBN = l; } void NodoTipo::agregarISBN(int isbn){ _listaISBN->Inserta(isbn); } bool NodoTipo::borrarISBN(int isbn){ return _listaISBN->borrar(isbn); } void NodoTipo::destruirISBN(){ _listaISBN->destruir(); } string NodoTipo::MostrarListaISBN(){ return _listaISBN->toString(); }
jloriag/Bibliotc
NodoTipo.cpp
C++
lgpl-3.0
958
#!/bin/bash # # RktCopyHosts # # Function: RktCopyHosts # Params: $1 - Host's '/etc/hosts' location # $2 - Container's '/etc/hosts' location # Output: (Normal acbuild output) function RktCopyHosts { local HOSTS="/etc/hosts" local RKT_HOSTS="/etc/hosts" if [ "${1}" != "" ]; then HOSTS="${1}" fi if [ "${2}" != "" ]; then RKT_HOSTS="${2}" fi sudo ${ACBUILD} copy "${HOSTS}" "${RKT_HOSTS}" if [ "${?}" != "0" ]; then Error "Rkt_CopyHosts: Failed to copy '${HOSTS}' to 'rkt:${RKT_HOSTS}'." return 1 fi return 0 } # vim: tabstop=4 shiftwidth=4
nicrohobak/BashLib
Functions/Rkt/CopyHosts.sh
Shell
lgpl-3.0
584
// -*- Mode:C++ -*- /************************************************************************\ * * * This file is part of Avango. * * * * Copyright 1997 - 2008 Fraunhofer-Gesellschaft zur Foerderung der * * angewandten Forschung (FhG), Munich, Germany. * * * * Avango 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, version 3. * * * * Avango 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 Lesser General Public * * License along with Avango. If not, see <http://www.gnu.org/licenses/>. * * * * Avango is a trademark owned by FhG. * * * \************************************************************************/ #ifndef AV_PYTHON_OSG_SHADER #define AV_PYTHON_OSG_SHADER void init_OSGShader(void); #endif
vrsys/avango
attic/avango-osg/python/avango/osg/OSGShader.h
C
lgpl-3.0
1,766
<?php /**************************************************************************** * Name: quiverext.php * * Project: Cambusa/ryQuiver * * Version: 1.69 * * Description: Arrows-oriented Library * * Copyright (C): 2015 Rodolfo Calzetti * * License GNU LESSER GENERAL PUBLIC LICENSE Version 3 * * Contact: https://github.com/cambusa * * [email protected] * ****************************************************************************/ function qv_extension($maestro, $data, $prefix, $SYSID, $TYPOLOGYID, $oper){ global $babelcode, $babelparams, $global_cache; if($oper!=2){ // 0 insert, 1 update, 2 virtual delete, 3 delete $tabletypes=$prefix."TYPES"; $tableviews=$prefix."VIEWS"; if($t=_qv_cacheloader($maestro, $tabletypes, $TYPOLOGYID)){ $TABLENAME=$t["TABLENAME"]; $DELETABLE=$t["DELETABLE"]; unset($t); if($TABLENAME!=""){ if($oper==3){ if($DELETABLE) $sql="DELETE FROM $TABLENAME WHERE SYSID='$SYSID'"; else $sql="UPDATE $TABLENAME SET SYSID=NULL WHERE SYSID='$SYSID'"; if(!maestro_execute($maestro, $sql, false)){ $babelcode="QVERR_EXECUTE"; $trace=debug_backtrace(); $b_params=array("FUNCTION" => $trace[0]["function"] ); $b_pattern=$maestro->errdescr; throw new Exception( qv_babeltranslate($b_pattern, $b_params) ); } } elseif($DELETABLE || $oper==1){ if(isset($global_cache["$tableviews-$TYPOLOGYID"])){ // REPERISCO LE INFO DALLA CACHE $infos=$global_cache["$tableviews-$TYPOLOGYID"]; } else{ // REPERISCO LE INFO DAL DATABASE $infos=array(); maestro_query($maestro,"SELECT * FROM $tableviews WHERE TYPOLOGYID='$TYPOLOGYID'",$r); for($i=0;$i<count($r);$i++){ $FIELDTYPE=$r[$i]["FIELDTYPE"]; $TABLEREF=""; $NOTEMPTY=false; if(substr($FIELDTYPE,0,5)=="SYSID"){ $TABLEREF=substr($FIELDTYPE, 6, -1); if(substr($TABLEREF,0,1)=="#"){ $NOTEMPTY=true; $TABLEREF=substr($TABLEREF,1); } } $infos[$i]["FIELDNAME"]=$r[$i]["FIELDNAME"]; $infos[$i]["FIELDTYPE"]=$FIELDTYPE; $infos[$i]["FORMULA"]=$r[$i]["FORMULA"]; $infos[$i]["WRITABLE"]=intval($r[$i]["WRITABLE"]); $infos[$i]["TABLEREF"]=$TABLEREF; $infos[$i]["NOTEMPTY"]=$NOTEMPTY; } // INSERISCO LE INFO NELLA CACHE $global_cache["$tableviews-$TYPOLOGYID"]=$infos; } if(count($infos)>0 || $oper==0){ // Ci sono campi estensione oppure solo il SYSID in inserimento if($oper==0){ $columns="SYSID"; $values="'$SYSID'"; $helpful=true; } else{ $sets=""; $where="SYSID='$SYSID'"; $helpful=false; } $clobs=false; for($i=0;$i<count($infos);$i++){ $FIELDNAME=$infos[$i]["FIELDNAME"]; $FIELDTYPE=$infos[$i]["FIELDTYPE"]; $FORMULA=$infos[$i]["FORMULA"]; $WRITABLE=$infos[$i]["WRITABLE"]; $TABLEREF=$infos[$i]["TABLEREF"]; $NOTEMPTY=$infos[$i]["NOTEMPTY"]; if($WRITABLE){ // IL CAMPO PUO' ESSERE AGGIORNATO // DETERMINO IL NOME DEL CAMPO if($FORMULA=="") $ACTUALNAME=$FIELDNAME; else $ACTUALNAME=str_replace("$TABLENAME.", "", $FORMULA); // DETERMINO IL VALORE DEL CAMPO if(isset($data[$ACTUALNAME])){ // FORMATTAZIONE IN BASE AL TIPO if($TABLEREF!=""){ // SYSID(Tabella referenziata) $value=ryqEscapize($data[$ACTUALNAME]); if($value!=""){ // Controllo che esista l'oggetto con SYSID=$value nella tabella $TABLEREF qv_linkable($maestro, $TABLEREF, $value); } elseif($NOTEMPTY){ $babelcode="QVERR_EMPTYSYSID"; $trace=debug_backtrace(); $b_params=array("FUNCTION" => $trace[0]["function"], "ACTUALNAME" => $ACTUALNAME ); $b_pattern="Campo [{2}] obbligatorio"; throw new Exception( qv_babeltranslate($b_pattern, $b_params) ); } $value="'$value'"; } elseif($FIELDTYPE=="TEXT"){ $value=ryqNormalize($data[$ACTUALNAME]); qv_setclob($maestro, $ACTUALNAME, $value, $value, $clobs); } elseif(substr($FIELDTYPE, 0, 4)=="JSON"){ $value=ryqNormalize($data[$ACTUALNAME]); if(substr($FIELDTYPE, 0, 5)=="JSON("){ $len=intval(substr($FIELDTYPE, 5)); $value=substr($value, 0, $len); } if($value!=""){ if(!json_decode($value)){ $babelcode="QVERR_JSON"; $trace=debug_backtrace(); $b_params=array("FUNCTION" => $trace[0]["function"], "ACTUALNAME" => $ACTUALNAME ); $b_pattern="Documento JSON [{2}] non corretto o troppo esteso"; throw new Exception( qv_babeltranslate($b_pattern, $b_params) ); } } qv_setclob($maestro, $ACTUALNAME, $value, $value, $clobs); } else{ $value=ryqEscapize($data[$ACTUALNAME]); $value=qv_sqlize($value, $FIELDTYPE); } if($oper==0){ qv_appendcomma($columns, $ACTUALNAME); qv_appendcomma($values, $value); } else{ qv_appendcomma($sets,"$ACTUALNAME=$value"); $helpful=true; } } else{ if($oper==0){ if($NOTEMPTY){ $babelcode="QVERR_EMPTYSYSID"; $trace=debug_backtrace(); $b_params=array("FUNCTION" => $trace[0]["function"], "ACTUALNAME" => $ACTUALNAME ); $b_pattern="Campo [{2}] obbligatorio"; throw new Exception( qv_babeltranslate($b_pattern, $b_params) ); } $value=qv_sqlize("", $FIELDTYPE); qv_appendcomma($columns, $ACTUALNAME); qv_appendcomma($values, $value); } } } } unset($r); if($helpful){ if($oper==0) $sql="INSERT INTO $TABLENAME ($columns) VALUES($values)"; else $sql="UPDATE $TABLENAME SET $sets WHERE $where"; if(!maestro_execute($maestro, $sql, false, $clobs)){ $babelcode="QVERR_EXECUTE"; $trace=debug_backtrace(); $b_params=array("FUNCTION" => $trace[0]["function"] ); $b_pattern=$maestro->errdescr; throw new Exception( qv_babeltranslate($b_pattern, $b_params) ); } } } } } } } } function qv_sqlize($value, $FIELDTYPE){ $FIELDTYPE=strtoupper($FIELDTYPE); switch($FIELDTYPE){ case "INTEGER": $value=strval(intval($value)); break; case "RATIONAL": $value=strval(round(floatval($value),7)); break; case "DATE": if(strlen($value)<8) $value=LOWEST_DATE; $value="[:DATE($value)]"; break; case "TIMESTAMP": if(strlen($value)<8) $value=LOWEST_TIME; $value="[:TIME($value)]"; break; case "BOOLEAN": if(intval($value)!=0) $value="1"; else $value="0"; break; default: if(substr($FIELDTYPE, 0, 9)=="RATIONAL("){ $dec=intval(substr($FIELDTYPE, 9)); $value=strval(round(floatval($value), $dec)); } elseif(substr($FIELDTYPE, 0, 5)=="CHAR("){ $len=intval(substr($FIELDTYPE, 5)); $value="'".substr(qv_inputUTF8($value), 0, $len)."'"; } elseif(substr($value, 0, 2)!="[:" || substr($value, -1, 1)!="]"){ $value="'$value'"; } break; } return $value; } function _qv_historicizing($maestro, $prefix, $SYSID, $TYPOLOGYID, $oper){ global $global_quiveruserid, $global_quiverroleid; global $babelcode, $babelparams; $tablebase=$prefix."S"; $tabletypes=$prefix."TYPES"; if($t=_qv_cacheloader($maestro, $tabletypes, $TYPOLOGYID)){ if( intval($t["HISTORICIZING"]) ){ $TABLE=$t["VIEWNAME"]; if($TABLE==""){ $TABLE=$tablebase; } if($r=_qv_cacheloader($maestro, $TABLE, $SYSID)){ $clobs=false; $DATABAG=json_encode($r); qv_setclob($maestro, "DATABAG", $DATABAG, $DATABAG, $clobs); $HISTORYID=qv_createsysid($maestro); $DESCRIPTION=ryqEscapize($r["DESCRIPTION"]); $TIMEINSERT=qv_strtime($r["TIMEINSERT"]); $RECORDTIME=qv_strtime($r["TIMEUPDATE"]); if($RECORDTIME<$TIMEINSERT){ $RECORDTIME=$TIMEINSERT; } $RECORDTIME="[:TIME($RECORDTIME)]"; $EVENTTIME="[:NOW()]"; // PREDISPONGO COLONNE E VALORI DA REGISTRARE $columns="SYSID,RECORDID,DESCRIPTION,RECORDTIME,TABLEBASE,TYPOLOGYID,OPERTYPE,ROLEID,USERID,EVENTTIME,DATABAG"; $values="'$HISTORYID','$SYSID','$DESCRIPTION',$RECORDTIME,'$tablebase','$TYPOLOGYID','$oper','$global_quiverroleid','$global_quiveruserid',$EVENTTIME,$DATABAG"; $sql="INSERT INTO QVHISTORY($columns) VALUES($values)"; if(!maestro_execute($maestro, $sql, false, $clobs)){ $babelcode="QVERR_EXECUTE"; $trace=debug_backtrace(); $b_params=array("FUNCTION" => $trace[0]["function"] ); $b_pattern=$maestro->errdescr; throw new Exception( qv_babeltranslate($b_pattern, $b_params) ); } } } } } ?>
cambusa/corsaro
_master/cambusa/ryquiver/quiverext.php
PHP
lgpl-3.0
13,735
/* * SupplyTask.h - Tasks issued to SupplyManager. Basically, just * produce Supply Depots while nearing capacity. */ #pragma once #include "Task.h" class BuildTask: public Task { };
go2starr/CS-638-BWAPI
BasicAIModule/include/Managers/Tasks/SupplyTask.h
C
lgpl-3.0
193
# -*- coding: utf-8 -*- # Copyright(C) 2014 smurail # # This file is part of a weboob module. # # This weboob module 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. # # This weboob module 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 weboob module. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import re from weboob.exceptions import BrowserIncorrectPassword from weboob.browser.pages import HTMLPage, JsonPage, pagination, LoggedPage from weboob.browser.elements import ListElement, ItemElement, TableElement, method from weboob.browser.filters.standard import CleanText, CleanDecimal, DateGuesser, Env, Field, Filter, Regexp, Currency, Date from weboob.browser.filters.html import Link, Attr, TableCell from weboob.capabilities.bank import Account, Investment from weboob.capabilities.base import NotAvailable from weboob.tools.capabilities.bank.transactions import FrenchTransaction from weboob.tools.compat import urljoin from weboob.tools.capabilities.bank.investments import is_isin_valid __all__ = ['LoginPage'] class UselessPage(HTMLPage): pass class PasswordCreationPage(HTMLPage): def get_message(self): xpath = '//div[@class="bienvenueMdp"]/following-sibling::div' return '%s%s' % (CleanText(xpath + '/strong')(self.doc), CleanText(xpath, children=False)(self.doc)) class ErrorPage(HTMLPage): pass class SubscriptionPage(LoggedPage, JsonPage): pass class LoginPage(HTMLPage): pass class CMSOPage(HTMLPage): @property def logged(self): if len(self.doc.xpath('//b[text()="Session interrompue"]')) > 0: return False return True class AccountsPage(CMSOPage): TYPES = {'COMPTE CHEQUES': Account.TYPE_CHECKING, 'COMPTE TITRES': Account.TYPE_MARKET, "ACTIV'EPARGNE": Account.TYPE_SAVINGS, "TRESO'VIV": Account.TYPE_SAVINGS, } @method class iter_accounts(ListElement): item_xpath = '//div[has-class("groupe-comptes")]//li' class item(ItemElement): klass = Account class Type(Filter): def filter(self, label): for pattern, actype in AccountsPage.TYPES.items(): if label.startswith(pattern): return actype return Account.TYPE_UNKNOWN obj__history_url = Link('.//a[1]') obj_id = CleanText('.//span[has-class("numero-compte")]') & Regexp(pattern=r'(\d{3,}[\w]+)', default='') obj_label = CleanText('.//span[has-class("libelle")][1]') obj_currency = Currency('//span[has-class("montant")]') obj_balance = CleanDecimal('.//span[has-class("montant")]', replace_dots=True) obj_type = Type(Field('label')) # Last numbers replaced with XX... or we have to send sms to get RIB. obj_iban = NotAvailable # some accounts may appear on multiple areas, but the area where they come from is indicated obj__owner = CleanText('(./preceding-sibling::tr[@class="LnMnTiers"])[last()]') def validate(self, obj): if obj.id is None: obj.id = obj.label.replace(' ', '') return True def on_load(self): if self.doc.xpath('//p[contains(text(), "incident technique")]'): raise BrowserIncorrectPassword("Vous n'avez aucun compte sur cet espace. " \ "Veuillez choisir un autre type de compte.") class InvestmentPage(CMSOPage): def has_error(self): return CleanText('//span[@id="id_error_msg"]')(self.doc) @method class iter_accounts(ListElement): item_xpath = '//table[@class="Tb" and tr[1][@class="LnTit"]]/tr[@class="LnA" or @class="LnB"]' class item(ItemElement): klass = Account def obj_id(self): area_id = Regexp(CleanText('(./preceding-sibling::tr[@class="LnMnTiers"][1])//span[@class="CelMnTiersT1"]'), r'\((\d+)\)', default='')(self) acc_id = Regexp(CleanText('./td[1]'), r'(\d+)\s*(\d+)', r'\1\2')(self) if area_id: return '%s.%s' % (area_id, acc_id) return acc_id def obj__formdata(self): js = Attr('./td/a[1]', 'onclick', default=None)(self) if js is None: return args = re.search(r'\((.*)\)', js).group(1).split(',') form = args[0].strip().split('.')[1] idx = args[2].strip() idroot = args[4].strip().replace("'", "") return (form, idx, idroot) obj_url = Link('./td/a[1]', default=None) def go_account(self, form, idx, idroot): form = self.get_form(name=form) form['indiceCompte'] = idx form['idRacine'] = idroot form.submit() class CmsoTableElement(TableElement): head_xpath = '//table[has-class("Tb")]/tr[has-class("LnTit")]/td' item_xpath = '//table[has-class("Tb")]/tr[has-class("LnA") or has-class("LnB")]' class InvestmentAccountPage(CMSOPage): @method class iter_investments(CmsoTableElement): col_label = 'Valeur' col_code = 'Code' col_quantity = 'Qté' col_unitvalue = 'Cours' col_valuation = 'Valorisation' col_vdate = 'Date cours' class item(ItemElement): klass = Investment obj_label = CleanText(TableCell('label')) obj_quantity = CleanDecimal(TableCell('quantity'), replace_dots=True) obj_unitvalue = CleanDecimal(TableCell('unitvalue'), replace_dots=True) obj_valuation = CleanDecimal(TableCell('valuation'), replace_dots=True) obj_vdate = Date(CleanText(TableCell('vdate')), dayfirst=True, default=NotAvailable) def obj_code(self): if Field('label')(self) == "LIQUIDITES": return 'XX-liquidity' code = CleanText(TableCell('code'))(self) return code if is_isin_valid(code) else NotAvailable def obj_code_type(self): return Investment.CODE_TYPE_ISIN if is_isin_valid(Field('code')(self)) else NotAvailable class Transaction(FrenchTransaction): PATTERNS = [(re.compile(r'^RET DAB (?P<dd>\d{2})/?(?P<mm>\d{2})(/?(?P<yy>\d{2}))? (?P<text>.*)'), FrenchTransaction.TYPE_WITHDRAWAL), (re.compile(r'CARTE (?P<dd>\d{2})/(?P<mm>\d{2}) (?P<text>.*)'), FrenchTransaction.TYPE_CARD), (re.compile(r'^(?P<category>VIR(EMEN)?T? (SEPA)?(RECU|FAVEUR)?)( /FRM)?(?P<text>.*)'), FrenchTransaction.TYPE_TRANSFER), (re.compile(r'^PRLV (?P<text>.*)( \d+)?$'), FrenchTransaction.TYPE_ORDER), (re.compile(r'^(CHQ|CHEQUE) .*$'), FrenchTransaction.TYPE_CHECK), (re.compile(r'^(AGIOS /|FRAIS) (?P<text>.*)'), FrenchTransaction.TYPE_BANK), (re.compile(r'^(CONVENTION \d+ |F )?COTIS(ATION)? (?P<text>.*)'), FrenchTransaction.TYPE_BANK), (re.compile(r'^REMISE (?P<text>.*)'), FrenchTransaction.TYPE_DEPOSIT), (re.compile(r'^(?P<text>.*)( \d+)? QUITTANCE .*'), FrenchTransaction.TYPE_ORDER), (re.compile(r'^.* LE (?P<dd>\d{2})/(?P<mm>\d{2})/(?P<yy>\d{2})$'), FrenchTransaction.TYPE_UNKNOWN), (re.compile(r'^.* PAIEMENT (?P<dd>\d{2})/(?P<mm>\d{2}) (?P<text>.*)'), FrenchTransaction.TYPE_UNKNOWN), ] class CmsoTransactionElement(ItemElement): klass = Transaction def condition(self): return len(self.el) >= 5 and not self.el.get('id', '').startswith('libelleLong') class HistoryPage(CMSOPage): def get_date_range_list(self): return [d for d in self.doc.xpath('//select[@name="date"]/option/@value') if d] @pagination @method class iter_history(ListElement): item_xpath = '//div[contains(@class, "master-table")]//ul/li' def next_page(self): pager = self.page.doc.xpath('//div[@class="pager"]') if pager: # more than one page if only enough transactions assert len(pager) == 1 next_links = pager[0].xpath('./span/following-sibling::a[@class="page"]') if next_links: url_next_page = Link('.')(next_links[0]) url_next_page = urljoin(self.page.url, url_next_page) return self.page.browser.build_request(url_next_page) class item(CmsoTransactionElement): def date(selector): return DateGuesser(Regexp(CleanText(selector), r'\w+ (\d{2}/\d{2})'), Env('date_guesser')) | Transaction.Date(selector) # CAUTION: this website write a 'Date valeur' inside a div with a class == 'c-ope' # and a 'Date opération' inside a div with a class == 'c-val' # so actually i assume 'c-val' class is the real operation date and 'c-ope' is value date obj_date = date('./div[contains(@class, "c-val")]') obj_vdate = date('./div[contains(@class, "c-ope")]') obj_raw = Transaction.Raw(Regexp(CleanText('./div[contains(@class, "c-libelle-long")]'), r'Libellé étendu (.+)')) obj_amount = Transaction.Amount('./div[contains(@class, "c-credit")]', './div[contains(@class, "c-debit")]') class UpdateTokenMixin(object): def on_load(self): if 'Authentication' in self.response.headers: self.browser.token = self.response.headers['Authentication'].split(' ')[-1] class SSODomiPage(JsonPage, UpdateTokenMixin): def get_sso_url(self): return self.doc['urlSSO'] class AuthCheckUser(HTMLPage): pass
laurentb/weboob
modules/cmso/pro/pages.py
Python
lgpl-3.0
10,804
// Created file "Lib\src\Uuid\tapi3if_i" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_ITStreamControl, 0xee3bd604, 0x3868, 0x11d2, 0xa0, 0x45, 0x00, 0xc0, 0x4f, 0xb6, 0x80, 0x9f);
Frankie-PellesC/fSDK
Lib/src/Uuid/tapi3if_i0000004D.c
C
lgpl-3.0
453
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Sigfox lib")] [assembly: AssemblyDescription("RPi Sigfox shield support library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Pospa.NET")] [assembly: AssemblyProduct("Sigfox lib")] [assembly: AssemblyCopyright("Copyright © Pospa.NET 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
pospanet/TurrisGadgets
Sigfox lib/Properties/AssemblyInfo.cs
C#
lgpl-3.0
1,091
// Copyright 2016 Canonical Ltd. // Licensed under the LGPLv3, see LICENCE file for details. package gomaasapi import "github.com/juju/utils/set" const ( // Capability constants. NetworksManagement = "networks-management" StaticIPAddresses = "static-ipaddresses" IPv6DeploymentUbuntu = "ipv6-deployment-ubuntu" DevicesManagement = "devices-management" StorageDeploymentUbuntu = "storage-deployment-ubuntu" NetworkDeploymentUbuntu = "network-deployment-ubuntu" ) // Controller represents an API connection to a MAAS Controller. Since the API // is restful, there is no long held connection to the API server, but instead // HTTP calls are made and JSON response structures parsed. type Controller interface { // Capabilities returns a set of capabilities as defined by the string // constants. Capabilities() set.Strings BootResources() ([]BootResource, error) // Fabrics returns the list of Fabrics defined in the MAAS controller. Fabrics() ([]Fabric, error) // Spaces returns the list of Spaces defined in the MAAS controller. Spaces() ([]Space, error) // Zones lists all the zones known to the MAAS controller. Zones() ([]Zone, error) // Machines returns a list of machines that match the params. Machines(MachinesArgs) ([]Machine, error) // AllocateMachine will attempt to allocate a machine to the user. // If successful, the allocated machine is returned. AllocateMachine(AllocateMachineArgs) (Machine, ConstraintMatches, error) // ReleaseMachines will stop the specified machines, and release them // from the user making them available to be allocated again. ReleaseMachines(ReleaseMachinesArgs) error // Devices returns a list of devices that match the params. Devices(DevicesArgs) ([]Device, error) // CreateDevice creates and returns a new Device. CreateDevice(CreateDeviceArgs) (Device, error) // Files returns all the files that match the specified prefix. Files(prefix string) ([]File, error) // Return a single file by its filename. GetFile(filename string) (File, error) // AddFile adds or replaces the content of the specified filename. // If or when the MAAS api is able to return metadata about a single // file without sending the content of the file, we can return a File // instance here too. AddFile(AddFileArgs) error } // File represents a file stored in the MAAS controller. type File interface { // Filename is the name of the file. No path, just the filename. Filename() string // AnonymousURL is a URL that can be used to retrieve the conents of the // file without credentials. AnonymousURL() string // Delete removes the file from the MAAS controller. Delete() error // ReadAll returns the content of the file. ReadAll() ([]byte, error) } // Fabric represents a set of interconnected VLANs that are capable of mutual // communication. A fabric can be thought of as a logical grouping in which // VLANs can be considered unique. // // For example, a distributed network may have a fabric in London containing // VLAN 100, while a separate fabric in San Francisco may contain a VLAN 100, // whose attached subnets are completely different and unrelated. type Fabric interface { ID() int Name() string ClassType() string VLANs() []VLAN } // VLAN represents an instance of a Virtual LAN. VLANs are a common way to // create logically separate networks using the same physical infrastructure. // // Managed switches can assign VLANs to each port in either a “tagged” or an // “untagged” manner. A VLAN is said to be “untagged” on a particular port when // it is the default VLAN for that port, and requires no special configuration // in order to access. // // “Tagged” VLANs (traditionally used by network administrators in order to // aggregate multiple networks over inter-switch “trunk” lines) can also be used // with nodes in MAAS. That is, if a switch port is configured such that // “tagged” VLAN frames can be sent and received by a MAAS node, that MAAS node // can be configured to automatically bring up VLAN interfaces, so that the // deployed node can make use of them. // // A “Default VLAN” is created for every Fabric, to which every new VLAN-aware // object in the fabric will be associated to by default (unless otherwise // specified). type VLAN interface { ID() int Name() string Fabric() string // VID is the VLAN ID. eth0.10 -> VID = 10. VID() int // MTU (maximum transmission unit) is the largest size packet or frame, // specified in octets (eight-bit bytes), that can be sent. MTU() int DHCP() bool PrimaryRack() string SecondaryRack() string } // Zone represents a physical zone that a Machine is in. The meaning of a // physical zone is up to you: it could identify e.g. a server rack, a network, // or a data centre. Users can then allocate nodes from specific physical zones, // to suit their redundancy or performance requirements. type Zone interface { Name() string Description() string } // BootResource is the bomb... find something to say here. type BootResource interface { ID() int Name() string Type() string Architecture() string SubArchitectures() set.Strings KernelFlavor() string } // Device represents some form of device in MAAS. type Device interface { // TODO: add domain SystemID() string Hostname() string FQDN() string IPAddresses() []string Zone() Zone // Parent returns the SystemID of the Parent. Most often this will be a // Machine. Parent() string // Owner is the username of the user that created the device. Owner() string // InterfaceSet returns all the interfaces for the Device. InterfaceSet() []Interface // CreateInterface will create a physical interface for this machine. CreateInterface(CreateInterfaceArgs) (Interface, error) // Delete will remove this Device. Delete() error } // Machine represents a physical machine. type Machine interface { SystemID() string Hostname() string FQDN() string Tags() []string OperatingSystem() string DistroSeries() string Architecture() string Memory() int CPUCount() int IPAddresses() []string PowerState() string // Devices returns a list of devices that match the params and have // this Machine as the parent. Devices(DevicesArgs) ([]Device, error) // Consider bundling the status values into a single struct. // but need to check for consistent representation if exposed on other // entities. StatusName() string StatusMessage() string // BootInterface returns the interface that was used to boot the Machine. BootInterface() Interface // InterfaceSet returns all the interfaces for the Machine. InterfaceSet() []Interface // Interface returns the interface for the machine that matches the id // specified. If there is no match, nil is returned. Interface(id int) Interface // PhysicalBlockDevices returns all the physical block devices on the machine. PhysicalBlockDevices() []BlockDevice // PhysicalBlockDevice returns the physical block device for the machine // that matches the id specified. If there is no match, nil is returned. PhysicalBlockDevice(id int) BlockDevice // BlockDevices returns all the physical and virtual block devices on the machine. BlockDevices() []BlockDevice Zone() Zone // Start the machine and install the operating system specified in the args. Start(StartArgs) error // CreateDevice creates a new Device with this Machine as the parent. // The device will have one interface that is linked to the specified subnet. CreateDevice(CreateMachineDeviceArgs) (Device, error) } // Space is a name for a collection of Subnets. type Space interface { ID() int Name() string Subnets() []Subnet } // Subnet refers to an IP range on a VLAN. type Subnet interface { ID() int Name() string Space() string VLAN() VLAN Gateway() string CIDR() string // dns_mode // DNSServers is a list of ip addresses of the DNS servers for the subnet. // This list may be empty. DNSServers() []string } // Interface represents a physical or virtual network interface on a Machine. type Interface interface { ID() int Name() string // The parents of an interface are the names of interfaces that must exist // for this interface to exist. For example a parent of "eth0.100" would be // "eth0". Parents may be empty. Parents() []string // The children interfaces are the names of those that are dependent on this // interface existing. Children may be empty. Children() []string Type() string Enabled() bool Tags() []string VLAN() VLAN Links() []Link MACAddress() string EffectiveMTU() int // Params is a JSON field, and defaults to an empty string, but is almost // always a JSON object in practice. Gleefully ignoring it until we need it. // Update the name, mac address or VLAN. Update(UpdateInterfaceArgs) error // Delete this interface. Delete() error // LinkSubnet will attempt to make this interface available on the specified // Subnet. LinkSubnet(LinkSubnetArgs) error // UnlinkSubnet will remove the Link to the subnet, and release the IP // address associated if there is one. UnlinkSubnet(Subnet) error } // Link represents a network link between an Interface and a Subnet. type Link interface { ID() int Mode() string Subnet() Subnet // IPAddress returns the address if one has been assigned. // If unavailble, the address will be empty. IPAddress() string } // FileSystem represents a formatted filesystem mounted at a location. type FileSystem interface { // Type is the format type, e.g. "ext4". Type() string MountPoint() string Label() string UUID() string } // Partition represents a partition of a block device. It may be mounted // as a filesystem. type Partition interface { ID() int Path() string // FileSystem may be nil if not mounted. FileSystem() FileSystem UUID() string // UsedFor is a human readable string. UsedFor() string // Size is the number of bytes in the partition. Size() uint64 } // BlockDevice represents an entire block device on the machine. type BlockDevice interface { ID() int Name() string Model() string Path() string UsedFor() string Tags() []string BlockSize() uint64 UsedSize() uint64 Size() uint64 Partitions() []Partition // There are some other attributes for block devices, but we can // expose them on an as needed basis. }
voidspace/gomaasapi
interfaces.go
GO
lgpl-3.0
10,327
/*+@@file@@----------------------------------------------------------------*//*! \file MMCObj.h \par Description Extension and update of headers for PellesC compiler suite. \par Project: PellesC Headers extension \date Created on Sun Aug 7 22:15:35 2016 \date Modified on Sun Aug 7 22:15:35 2016 \author frankie \*//*-@@file@@----------------------------------------------------------------*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include <rpc.h> #include <rpcndr.h> #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif #ifndef COM_NO_WINDOWS_H #include <windows.h> #include <ole2.h> #endif #ifndef __mmcobj_h__ #define __mmcobj_h__ #if __POCC__ >= 500 #pragma once #endif #ifndef __ISnapinProperties_FWD_DEFINED__ #define __ISnapinProperties_FWD_DEFINED__ typedef interface ISnapinProperties ISnapinProperties; #endif #ifndef __ISnapinPropertiesCallback_FWD_DEFINED__ #define __ISnapinPropertiesCallback_FWD_DEFINED__ typedef interface ISnapinPropertiesCallback ISnapinPropertiesCallback; #endif #ifndef ___Application_FWD_DEFINED__ #define ___Application_FWD_DEFINED__ typedef interface _Application _Application; #endif #ifndef ___AppEvents_FWD_DEFINED__ #define ___AppEvents_FWD_DEFINED__ typedef interface _AppEvents _AppEvents; #endif #ifndef __AppEvents_FWD_DEFINED__ #define __AppEvents_FWD_DEFINED__ typedef interface AppEvents AppEvents; #endif #ifndef __Application_FWD_DEFINED__ #define __Application_FWD_DEFINED__ typedef struct Application Application; #endif #ifndef ___EventConnector_FWD_DEFINED__ #define ___EventConnector_FWD_DEFINED__ typedef interface _EventConnector _EventConnector; #endif #ifndef __AppEventsDHTMLConnector_FWD_DEFINED__ #define __AppEventsDHTMLConnector_FWD_DEFINED__ typedef struct AppEventsDHTMLConnector AppEventsDHTMLConnector; #endif #ifndef __Frame_FWD_DEFINED__ #define __Frame_FWD_DEFINED__ typedef interface Frame Frame; #endif #ifndef __Node_FWD_DEFINED__ #define __Node_FWD_DEFINED__ typedef interface Node Node; #endif #ifndef __ScopeNamespace_FWD_DEFINED__ #define __ScopeNamespace_FWD_DEFINED__ typedef interface ScopeNamespace ScopeNamespace; #endif #ifndef __Document_FWD_DEFINED__ #define __Document_FWD_DEFINED__ typedef interface Document Document; #endif #ifndef __SnapIn_FWD_DEFINED__ #define __SnapIn_FWD_DEFINED__ typedef interface SnapIn SnapIn; #endif #ifndef __SnapIns_FWD_DEFINED__ #define __SnapIns_FWD_DEFINED__ typedef interface SnapIns SnapIns; #endif #ifndef __Extension_FWD_DEFINED__ #define __Extension_FWD_DEFINED__ typedef interface Extension Extension; #endif #ifndef __Extensions_FWD_DEFINED__ #define __Extensions_FWD_DEFINED__ typedef interface Extensions Extensions; #endif #ifndef __Columns_FWD_DEFINED__ #define __Columns_FWD_DEFINED__ typedef interface Columns Columns; #endif #ifndef __Column_FWD_DEFINED__ #define __Column_FWD_DEFINED__ typedef interface Column Column; #endif #ifndef __Views_FWD_DEFINED__ #define __Views_FWD_DEFINED__ typedef interface Views Views; #endif #ifndef __View_FWD_DEFINED__ #define __View_FWD_DEFINED__ typedef interface View View; #endif #ifndef __Nodes_FWD_DEFINED__ #define __Nodes_FWD_DEFINED__ typedef interface Nodes Nodes; #endif #ifndef __ContextMenu_FWD_DEFINED__ #define __ContextMenu_FWD_DEFINED__ typedef interface ContextMenu ContextMenu; #endif #ifndef __MenuItem_FWD_DEFINED__ #define __MenuItem_FWD_DEFINED__ typedef interface MenuItem MenuItem; #endif #ifndef __Properties_FWD_DEFINED__ #define __Properties_FWD_DEFINED__ typedef interface Properties Properties; #endif #ifndef __Property_FWD_DEFINED__ #define __Property_FWD_DEFINED__ typedef interface Property Property; #endif #include <oaidl.h> #ifndef MMC_VER #define MMC_VER 0x0200 #endif #if (MMC_VER >= 0x0200) typedef _Application *PAPPLICATION; typedef _Application **PPAPPLICATION; typedef Column *PCOLUMN; typedef Column **PPCOLUMN; typedef Columns *PCOLUMNS; typedef Columns **PPCOLUMNS; typedef ContextMenu *PCONTEXTMENU; typedef ContextMenu **PPCONTEXTMENU; typedef Document *PDOCUMENT; typedef Document **PPDOCUMENT; typedef Frame *PFRAME; typedef Frame **PPFRAME; typedef MenuItem *PMENUITEM; typedef MenuItem **PPMENUITEM; typedef Node *PNODE; typedef Node **PPNODE; typedef Nodes *PNODES; typedef Nodes **PPNODES; typedef Properties *PPROPERTIES; typedef Properties **PPPROPERTIES; typedef Property *PPROPERTY; typedef Property **PPPROPERTY; typedef ScopeNamespace *PSCOPENAMESPACE; typedef ScopeNamespace **PPSCOPENAMESPACE; typedef SnapIn *PSNAPIN; typedef SnapIn **PPSNAPIN; typedef SnapIns *PSNAPINS; typedef SnapIns **PPSNAPINS; typedef Extension *PEXTENSION; typedef Extension **PPEXTENSION; typedef Extensions *PEXTENSIONS; typedef Extensions **PPEXTENSIONS; typedef View *PVIEW; typedef View **PPVIEW; typedef Views *PVIEWS; typedef Views **PPVIEWS; typedef ISnapinProperties *LPSNAPINPROPERTIES; typedef ISnapinPropertiesCallback *LPSNAPINPROPERTIESCALLBACK; typedef BOOL *PBOOL; typedef int *PINT; typedef BSTR *PBSTR; typedef VARIANT *PVARIANT; typedef long *PLONG; typedef IDispatch *PDISPATCH; typedef IDispatch **PPDISPATCH; extern RPC_IF_HANDLE __MIDL_itf_mmcobj_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_mmcobj_0000_0000_v0_0_s_ifspec; #ifndef __ISnapinProperties_INTERFACE_DEFINED__ #define __ISnapinProperties_INTERFACE_DEFINED__ typedef enum _MMC_PROPERTY_ACTION { MMC_PROPACT_DELETING = 1, MMC_PROPACT_CHANGING = (MMC_PROPACT_DELETING + 1), MMC_PROPACT_INITIALIZED = (MMC_PROPACT_CHANGING + 1) } MMC_PROPERTY_ACTION; typedef struct _MMC_SNAPIN_PROPERTY { LPCOLESTR pszPropName; VARIANT varValue; MMC_PROPERTY_ACTION eAction; } MMC_SNAPIN_PROPERTY; extern const IID IID_ISnapinProperties; typedef struct ISnapinPropertiesVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (ISnapinProperties * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (ISnapinProperties * This); ULONG(STDMETHODCALLTYPE * Release) (ISnapinProperties * This); HRESULT(STDMETHODCALLTYPE * Initialize) (ISnapinProperties * This, Properties * pProperties); HRESULT(STDMETHODCALLTYPE * QueryPropertyNames) (ISnapinProperties * This, ISnapinPropertiesCallback * pCallback); HRESULT(STDMETHODCALLTYPE * PropertiesChanged) (ISnapinProperties * This, long cProperties, MMC_SNAPIN_PROPERTY * pProperties); END_INTERFACE } ISnapinPropertiesVtbl; interface ISnapinProperties { CONST_VTBL struct ISnapinPropertiesVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISnapinProperties_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ISnapinProperties_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define ISnapinProperties_Release(This) ( (This)->lpVtbl -> Release(This) ) #define ISnapinProperties_Initialize(This,pProperties) ( (This)->lpVtbl -> Initialize(This,pProperties) ) #define ISnapinProperties_QueryPropertyNames(This,pCallback) ( (This)->lpVtbl -> QueryPropertyNames(This,pCallback) ) #define ISnapinProperties_PropertiesChanged(This,cProperties,pProperties) ( (This)->lpVtbl -> PropertiesChanged(This,cProperties,pProperties) ) #endif #endif #ifndef __ISnapinPropertiesCallback_INTERFACE_DEFINED__ #define __ISnapinPropertiesCallback_INTERFACE_DEFINED__ #define MMC_PROP_CHANGEAFFECTSUI ( 0x1 ) #define MMC_PROP_MODIFIABLE ( 0x2 ) #define MMC_PROP_REMOVABLE ( 0x4 ) #define MMC_PROP_PERSIST ( 0x8 ) extern const IID IID_ISnapinPropertiesCallback; typedef struct ISnapinPropertiesCallbackVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (ISnapinPropertiesCallback * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (ISnapinPropertiesCallback * This); ULONG(STDMETHODCALLTYPE * Release) (ISnapinPropertiesCallback * This); HRESULT(STDMETHODCALLTYPE * AddPropertyName) (ISnapinPropertiesCallback * This, LPCOLESTR pszPropName, DWORD dwFlags); END_INTERFACE } ISnapinPropertiesCallbackVtbl; interface ISnapinPropertiesCallback { CONST_VTBL struct ISnapinPropertiesCallbackVtbl *lpVtbl; }; #ifdef COBJMACROS #define ISnapinPropertiesCallback_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ISnapinPropertiesCallback_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define ISnapinPropertiesCallback_Release(This) ( (This)->lpVtbl -> Release(This) ) #define ISnapinPropertiesCallback_AddPropertyName(This,pszPropName,dwFlags) ( (This)->lpVtbl -> AddPropertyName(This,pszPropName,dwFlags) ) #endif #endif #ifndef __MMC20_LIBRARY_DEFINED__ #define __MMC20_LIBRARY_DEFINED__ typedef enum DocumentMode { DocumentMode_Author = 0, DocumentMode_User = (DocumentMode_Author + 1), DocumentMode_User_MDI = (DocumentMode_User + 1), DocumentMode_User_SDI = (DocumentMode_User_MDI + 1) } _DocumentMode; typedef enum DocumentMode DOCUMENTMODE; typedef enum DocumentMode *PDOCUMENTMODE; typedef enum DocumentMode **PPDOCUMENTMODE; typedef enum ListViewMode { ListMode_Small_Icons = 0, ListMode_Large_Icons = (ListMode_Small_Icons + 1), ListMode_List = (ListMode_Large_Icons + 1), ListMode_Detail = (ListMode_List + 1), ListMode_Filtered = (ListMode_Detail + 1) } _ListViewMode; typedef enum ListViewMode LISTVIEWMODE; typedef enum ListViewMode *PLISTVIEWMODE; typedef enum ListViewMode **PPLISTVIEWMODE; typedef enum ViewOptions { ViewOption_Default = 0, ViewOption_ScopeTreeHidden = 0x1, ViewOption_NoToolBars = 0x2, ViewOption_NotPersistable = 0x4, ViewOption_ActionPaneHidden = 0x8 } _ViewOptions; typedef enum ViewOptions VIEWOPTIONS; typedef enum ViewOptions *PVIEWOPTIONS; typedef enum ViewOptions **PPVIEWOPTIONS; typedef enum ExportListOptions { ExportListOptions_Default = 0, ExportListOptions_Unicode = 0x1, ExportListOptions_TabDelimited = 0x2, ExportListOptions_SelectedItemsOnly = 0x4 } _ExportListOptions; typedef enum ExportListOptions EXPORTLISTOPTIONS; extern const IID LIBID_MMC20; #ifndef ___Application_INTERFACE_DEFINED__ #define ___Application_INTERFACE_DEFINED__ extern const IID IID__Application; typedef struct _ApplicationVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (_Application * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (_Application * This); ULONG(STDMETHODCALLTYPE * Release) (_Application * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (_Application * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (_Application * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (_Application * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (_Application * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); void (STDMETHODCALLTYPE * Help) (_Application * This); void (STDMETHODCALLTYPE * Quit) (_Application * This); HRESULT(STDMETHODCALLTYPE * get_Document) (_Application * This, PPDOCUMENT Document); HRESULT(STDMETHODCALLTYPE * Load) (_Application * This, BSTR Filename); HRESULT(STDMETHODCALLTYPE * get_Frame) (_Application * This, PPFRAME Frame); HRESULT(STDMETHODCALLTYPE * get_Visible) (_Application * This, PBOOL Visible); HRESULT(STDMETHODCALLTYPE * Show) (_Application * This); HRESULT(STDMETHODCALLTYPE * Hide) (_Application * This); HRESULT(STDMETHODCALLTYPE * get_UserControl) (_Application * This, PBOOL UserControl); HRESULT(STDMETHODCALLTYPE * put_UserControl) (_Application * This, BOOL UserControl); HRESULT(STDMETHODCALLTYPE * get_VersionMajor) (_Application * This, PLONG VersionMajor); HRESULT(STDMETHODCALLTYPE * get_VersionMinor) (_Application * This, PLONG VersionMinor); END_INTERFACE } _ApplicationVtbl; interface _Application { CONST_VTBL struct _ApplicationVtbl *lpVtbl; }; #ifdef COBJMACROS #define _Application_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define _Application_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define _Application_Release(This) ( (This)->lpVtbl -> Release(This) ) #define _Application_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define _Application_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define _Application_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define _Application_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define _Application_Help(This) ( (This)->lpVtbl -> Help(This) ) #define _Application_Quit(This) ( (This)->lpVtbl -> Quit(This) ) #define _Application_get_Document(This,Document) ( (This)->lpVtbl -> get_Document(This,Document) ) #define _Application_Load(This,Filename) ( (This)->lpVtbl -> Load(This,Filename) ) #define _Application_get_Frame(This,Frame) ( (This)->lpVtbl -> get_Frame(This,Frame) ) #define _Application_get_Visible(This,Visible) ( (This)->lpVtbl -> get_Visible(This,Visible) ) #define _Application_Show(This) ( (This)->lpVtbl -> Show(This) ) #define _Application_Hide(This) ( (This)->lpVtbl -> Hide(This) ) #define _Application_get_UserControl(This,UserControl) ( (This)->lpVtbl -> get_UserControl(This,UserControl) ) #define _Application_put_UserControl(This,UserControl) ( (This)->lpVtbl -> put_UserControl(This,UserControl) ) #define _Application_get_VersionMajor(This,VersionMajor) ( (This)->lpVtbl -> get_VersionMajor(This,VersionMajor) ) #define _Application_get_VersionMinor(This,VersionMinor) ( (This)->lpVtbl -> get_VersionMinor(This,VersionMinor) ) #endif #endif #ifndef ___AppEvents_INTERFACE_DEFINED__ #define ___AppEvents_INTERFACE_DEFINED__ extern const IID IID__AppEvents; typedef struct _AppEventsVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (_AppEvents * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (_AppEvents * This); ULONG(STDMETHODCALLTYPE * Release) (_AppEvents * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (_AppEvents * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (_AppEvents * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (_AppEvents * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (_AppEvents * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * OnQuit) (_AppEvents * This, PAPPLICATION Application); HRESULT(STDMETHODCALLTYPE * OnDocumentOpen) (_AppEvents * This, PDOCUMENT Document, BOOL New); HRESULT(STDMETHODCALLTYPE * OnDocumentClose) (_AppEvents * This, PDOCUMENT Document); HRESULT(STDMETHODCALLTYPE * OnSnapInAdded) (_AppEvents * This, PDOCUMENT Document, PSNAPIN SnapIn); HRESULT(STDMETHODCALLTYPE * OnSnapInRemoved) (_AppEvents * This, PDOCUMENT Document, PSNAPIN SnapIn); HRESULT(STDMETHODCALLTYPE * OnNewView) (_AppEvents * This, PVIEW View); HRESULT(STDMETHODCALLTYPE * OnViewClose) (_AppEvents * This, PVIEW View); HRESULT(STDMETHODCALLTYPE * OnViewChange) (_AppEvents * This, PVIEW View, PNODE NewOwnerNode); HRESULT(STDMETHODCALLTYPE * OnSelectionChange) (_AppEvents * This, PVIEW View, PNODES NewNodes); HRESULT(STDMETHODCALLTYPE * OnContextMenuExecuted) (_AppEvents * This, PMENUITEM MenuItem); HRESULT(STDMETHODCALLTYPE * OnToolbarButtonClicked) (_AppEvents * This); HRESULT(STDMETHODCALLTYPE * OnListUpdated) (_AppEvents * This, PVIEW View); END_INTERFACE } _AppEventsVtbl; interface _AppEvents { CONST_VTBL struct _AppEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define _AppEvents_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define _AppEvents_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define _AppEvents_Release(This) ( (This)->lpVtbl -> Release(This) ) #define _AppEvents_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define _AppEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define _AppEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define _AppEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define _AppEvents_OnQuit(This,Application) ( (This)->lpVtbl -> OnQuit(This,Application) ) #define _AppEvents_OnDocumentOpen(This,Document,New) ( (This)->lpVtbl -> OnDocumentOpen(This,Document,New) ) #define _AppEvents_OnDocumentClose(This,Document) ( (This)->lpVtbl -> OnDocumentClose(This,Document) ) #define _AppEvents_OnSnapInAdded(This,Document,SnapIn) ( (This)->lpVtbl -> OnSnapInAdded(This,Document,SnapIn) ) #define _AppEvents_OnSnapInRemoved(This,Document,SnapIn) ( (This)->lpVtbl -> OnSnapInRemoved(This,Document,SnapIn) ) #define _AppEvents_OnNewView(This,View) ( (This)->lpVtbl -> OnNewView(This,View) ) #define _AppEvents_OnViewClose(This,View) ( (This)->lpVtbl -> OnViewClose(This,View) ) #define _AppEvents_OnViewChange(This,View,NewOwnerNode) ( (This)->lpVtbl -> OnViewChange(This,View,NewOwnerNode) ) #define _AppEvents_OnSelectionChange(This,View,NewNodes) ( (This)->lpVtbl -> OnSelectionChange(This,View,NewNodes) ) #define _AppEvents_OnContextMenuExecuted(This,MenuItem) ( (This)->lpVtbl -> OnContextMenuExecuted(This,MenuItem) ) #define _AppEvents_OnToolbarButtonClicked(This) ( (This)->lpVtbl -> OnToolbarButtonClicked(This) ) #define _AppEvents_OnListUpdated(This,View) ( (This)->lpVtbl -> OnListUpdated(This,View) ) #endif #endif #ifndef __AppEvents_DISPINTERFACE_DEFINED__ #define __AppEvents_DISPINTERFACE_DEFINED__ extern const IID DIID_AppEvents; typedef struct AppEventsVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (AppEvents * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (AppEvents * This); ULONG(STDMETHODCALLTYPE * Release) (AppEvents * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (AppEvents * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (AppEvents * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (AppEvents * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (AppEvents * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); END_INTERFACE } AppEventsVtbl; interface AppEvents { CONST_VTBL struct AppEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define AppEvents_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define AppEvents_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define AppEvents_Release(This) ( (This)->lpVtbl -> Release(This) ) #define AppEvents_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define AppEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define AppEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define AppEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif #endif extern const CLSID CLSID_Application; #ifndef ___EventConnector_INTERFACE_DEFINED__ #define ___EventConnector_INTERFACE_DEFINED__ extern const IID IID__EventConnector; typedef struct _EventConnectorVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (_EventConnector * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (_EventConnector * This); ULONG(STDMETHODCALLTYPE * Release) (_EventConnector * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (_EventConnector * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (_EventConnector * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (_EventConnector * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (_EventConnector * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * ConnectTo) (_EventConnector * This, PAPPLICATION Application); HRESULT(STDMETHODCALLTYPE * Disconnect) (_EventConnector * This); END_INTERFACE } _EventConnectorVtbl; interface _EventConnector { CONST_VTBL struct _EventConnectorVtbl *lpVtbl; }; #ifdef COBJMACROS #define _EventConnector_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define _EventConnector_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define _EventConnector_Release(This) ( (This)->lpVtbl -> Release(This) ) #define _EventConnector_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define _EventConnector_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define _EventConnector_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define _EventConnector_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define _EventConnector_ConnectTo(This,Application) ( (This)->lpVtbl -> ConnectTo(This,Application) ) #define _EventConnector_Disconnect(This) ( (This)->lpVtbl -> Disconnect(This) ) #endif #endif extern const CLSID CLSID_AppEventsDHTMLConnector; #ifndef __Frame_INTERFACE_DEFINED__ #define __Frame_INTERFACE_DEFINED__ extern const IID IID_Frame; typedef struct FrameVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Frame * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Frame * This); ULONG(STDMETHODCALLTYPE * Release) (Frame * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Frame * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Frame * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Frame * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Frame * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * Maximize) (Frame * This); HRESULT(STDMETHODCALLTYPE * Minimize) (Frame * This); HRESULT(STDMETHODCALLTYPE * Restore) (Frame * This); HRESULT(STDMETHODCALLTYPE * get_Top) (Frame * This, PINT Top); HRESULT(STDMETHODCALLTYPE * put_Top) (Frame * This, int top); HRESULT(STDMETHODCALLTYPE * get_Bottom) (Frame * This, PINT Bottom); HRESULT(STDMETHODCALLTYPE * put_Bottom) (Frame * This, int bottom); HRESULT(STDMETHODCALLTYPE * get_Left) (Frame * This, PINT Left); HRESULT(STDMETHODCALLTYPE * put_Left) (Frame * This, int left); HRESULT(STDMETHODCALLTYPE * get_Right) (Frame * This, PINT Right); HRESULT(STDMETHODCALLTYPE * put_Right) (Frame * This, int right); END_INTERFACE } FrameVtbl; interface Frame { CONST_VTBL struct FrameVtbl *lpVtbl; }; #ifdef COBJMACROS #define Frame_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Frame_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Frame_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Frame_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Frame_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Frame_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Frame_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Frame_Maximize(This) ( (This)->lpVtbl -> Maximize(This) ) #define Frame_Minimize(This) ( (This)->lpVtbl -> Minimize(This) ) #define Frame_Restore(This) ( (This)->lpVtbl -> Restore(This) ) #define Frame_get_Top(This,Top) ( (This)->lpVtbl -> get_Top(This,Top) ) #define Frame_put_Top(This,top) ( (This)->lpVtbl -> put_Top(This,top) ) #define Frame_get_Bottom(This,Bottom) ( (This)->lpVtbl -> get_Bottom(This,Bottom) ) #define Frame_put_Bottom(This,bottom) ( (This)->lpVtbl -> put_Bottom(This,bottom) ) #define Frame_get_Left(This,Left) ( (This)->lpVtbl -> get_Left(This,Left) ) #define Frame_put_Left(This,left) ( (This)->lpVtbl -> put_Left(This,left) ) #define Frame_get_Right(This,Right) ( (This)->lpVtbl -> get_Right(This,Right) ) #define Frame_put_Right(This,right) ( (This)->lpVtbl -> put_Right(This,right) ) #endif #endif #ifndef __Node_INTERFACE_DEFINED__ #define __Node_INTERFACE_DEFINED__ extern const IID IID_Node; typedef struct NodeVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Node * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Node * This); ULONG(STDMETHODCALLTYPE * Release) (Node * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Node * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Node * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Node * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Node * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get_Name) (Node * This, PBSTR Name); HRESULT(STDMETHODCALLTYPE * get_Property) (Node * This, BSTR PropertyName, PBSTR PropertyValue); HRESULT(STDMETHODCALLTYPE * get_Bookmark) (Node * This, PBSTR Bookmark); HRESULT(STDMETHODCALLTYPE * IsScopeNode) (Node * This, PBOOL IsScopeNode); HRESULT(STDMETHODCALLTYPE * get_Nodetype) (Node * This, PBSTR Nodetype); END_INTERFACE } NodeVtbl; interface Node { CONST_VTBL struct NodeVtbl *lpVtbl; }; #ifdef COBJMACROS #define Node_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Node_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Node_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Node_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Node_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Node_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Node_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Node_get_Name(This,Name) ( (This)->lpVtbl -> get_Name(This,Name) ) #define Node_get_Property(This,PropertyName,PropertyValue) ( (This)->lpVtbl -> get_Property(This,PropertyName,PropertyValue) ) #define Node_get_Bookmark(This,Bookmark) ( (This)->lpVtbl -> get_Bookmark(This,Bookmark) ) #define Node_IsScopeNode(This,IsScopeNode) ( (This)->lpVtbl -> IsScopeNode(This,IsScopeNode) ) #define Node_get_Nodetype(This,Nodetype) ( (This)->lpVtbl -> get_Nodetype(This,Nodetype) ) #endif #endif #ifndef __ScopeNamespace_INTERFACE_DEFINED__ #define __ScopeNamespace_INTERFACE_DEFINED__ extern const IID IID_ScopeNamespace; typedef struct ScopeNamespaceVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (ScopeNamespace * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (ScopeNamespace * This); ULONG(STDMETHODCALLTYPE * Release) (ScopeNamespace * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (ScopeNamespace * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (ScopeNamespace * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (ScopeNamespace * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (ScopeNamespace * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * GetParent) (ScopeNamespace * This, PNODE Node, PPNODE Parent); HRESULT(STDMETHODCALLTYPE * GetChild) (ScopeNamespace * This, PNODE Node, PPNODE Child); HRESULT(STDMETHODCALLTYPE * GetNext) (ScopeNamespace * This, PNODE Node, PPNODE Next); HRESULT(STDMETHODCALLTYPE * GetRoot) (ScopeNamespace * This, PPNODE Root); HRESULT(STDMETHODCALLTYPE * Expand) (ScopeNamespace * This, PNODE Node); END_INTERFACE } ScopeNamespaceVtbl; interface ScopeNamespace { CONST_VTBL struct ScopeNamespaceVtbl *lpVtbl; }; #ifdef COBJMACROS #define ScopeNamespace_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ScopeNamespace_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define ScopeNamespace_Release(This) ( (This)->lpVtbl -> Release(This) ) #define ScopeNamespace_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ScopeNamespace_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ScopeNamespace_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ScopeNamespace_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ScopeNamespace_GetParent(This,Node,Parent) ( (This)->lpVtbl -> GetParent(This,Node,Parent) ) #define ScopeNamespace_GetChild(This,Node,Child) ( (This)->lpVtbl -> GetChild(This,Node,Child) ) #define ScopeNamespace_GetNext(This,Node,Next) ( (This)->lpVtbl -> GetNext(This,Node,Next) ) #define ScopeNamespace_GetRoot(This,Root) ( (This)->lpVtbl -> GetRoot(This,Root) ) #define ScopeNamespace_Expand(This,Node) ( (This)->lpVtbl -> Expand(This,Node) ) #endif #endif #ifndef __Document_INTERFACE_DEFINED__ #define __Document_INTERFACE_DEFINED__ extern const IID IID_Document; typedef struct DocumentVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Document * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Document * This); ULONG(STDMETHODCALLTYPE * Release) (Document * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Document * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Document * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Document * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Document * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * Save) (Document * This); HRESULT(STDMETHODCALLTYPE * SaveAs) (Document * This, BSTR Filename); HRESULT(STDMETHODCALLTYPE * Close) (Document * This, BOOL SaveChanges); HRESULT(STDMETHODCALLTYPE * get_Views) (Document * This, PPVIEWS Views); HRESULT(STDMETHODCALLTYPE * get_SnapIns) (Document * This, PPSNAPINS SnapIns); HRESULT(STDMETHODCALLTYPE * get_ActiveView) (Document * This, PPVIEW View); HRESULT(STDMETHODCALLTYPE * get_Name) (Document * This, PBSTR Name); HRESULT(STDMETHODCALLTYPE * put_Name) (Document * This, BSTR Name); HRESULT(STDMETHODCALLTYPE * get_Location) (Document * This, PBSTR Location); HRESULT(STDMETHODCALLTYPE * get_IsSaved) (Document * This, PBOOL IsSaved); HRESULT(STDMETHODCALLTYPE * get_Mode) (Document * This, PDOCUMENTMODE Mode); HRESULT(STDMETHODCALLTYPE * put_Mode) (Document * This, DOCUMENTMODE Mode); HRESULT(STDMETHODCALLTYPE * get_RootNode) (Document * This, PPNODE Node); HRESULT(STDMETHODCALLTYPE * get_ScopeNamespace) (Document * This, PPSCOPENAMESPACE ScopeNamespace); HRESULT(STDMETHODCALLTYPE * CreateProperties) (Document * This, PPPROPERTIES Properties); HRESULT(STDMETHODCALLTYPE * get_Application) (Document * This, PPAPPLICATION Application); END_INTERFACE } DocumentVtbl; interface Document { CONST_VTBL struct DocumentVtbl *lpVtbl; }; #ifdef COBJMACROS #define Document_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Document_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Document_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Document_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Document_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Document_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Document_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Document_Save(This) ( (This)->lpVtbl -> Save(This) ) #define Document_SaveAs(This,Filename) ( (This)->lpVtbl -> SaveAs(This,Filename) ) #define Document_Close(This,SaveChanges) ( (This)->lpVtbl -> Close(This,SaveChanges) ) #define Document_get_Views(This,Views) ( (This)->lpVtbl -> get_Views(This,Views) ) #define Document_get_SnapIns(This,SnapIns) ( (This)->lpVtbl -> get_SnapIns(This,SnapIns) ) #define Document_get_ActiveView(This,View) ( (This)->lpVtbl -> get_ActiveView(This,View) ) #define Document_get_Name(This,Name) ( (This)->lpVtbl -> get_Name(This,Name) ) #define Document_put_Name(This,Name) ( (This)->lpVtbl -> put_Name(This,Name) ) #define Document_get_Location(This,Location) ( (This)->lpVtbl -> get_Location(This,Location) ) #define Document_get_IsSaved(This,IsSaved) ( (This)->lpVtbl -> get_IsSaved(This,IsSaved) ) #define Document_get_Mode(This,Mode) ( (This)->lpVtbl -> get_Mode(This,Mode) ) #define Document_put_Mode(This,Mode) ( (This)->lpVtbl -> put_Mode(This,Mode) ) #define Document_get_RootNode(This,Node) ( (This)->lpVtbl -> get_RootNode(This,Node) ) #define Document_get_ScopeNamespace(This,ScopeNamespace) ( (This)->lpVtbl -> get_ScopeNamespace(This,ScopeNamespace) ) #define Document_CreateProperties(This,Properties) ( (This)->lpVtbl -> CreateProperties(This,Properties) ) #define Document_get_Application(This,Application) ( (This)->lpVtbl -> get_Application(This,Application) ) #endif #endif #ifndef __SnapIn_INTERFACE_DEFINED__ #define __SnapIn_INTERFACE_DEFINED__ extern const IID IID_SnapIn; typedef struct SnapInVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (SnapIn * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (SnapIn * This); ULONG(STDMETHODCALLTYPE * Release) (SnapIn * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (SnapIn * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (SnapIn * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (SnapIn * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (SnapIn * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get_Name) (SnapIn * This, PBSTR Name); HRESULT(STDMETHODCALLTYPE * get_Vendor) (SnapIn * This, PBSTR Vendor); HRESULT(STDMETHODCALLTYPE * get_Version) (SnapIn * This, PBSTR Version); HRESULT(STDMETHODCALLTYPE * get_Extensions) (SnapIn * This, PPEXTENSIONS Extensions); HRESULT(STDMETHODCALLTYPE * get_SnapinCLSID) (SnapIn * This, PBSTR SnapinCLSID); HRESULT(STDMETHODCALLTYPE * get_Properties) (SnapIn * This, PPPROPERTIES Properties); HRESULT(STDMETHODCALLTYPE * EnableAllExtensions) (SnapIn * This, BOOL Enable); END_INTERFACE } SnapInVtbl; interface SnapIn { CONST_VTBL struct SnapInVtbl *lpVtbl; }; #ifdef COBJMACROS #define SnapIn_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define SnapIn_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define SnapIn_Release(This) ( (This)->lpVtbl -> Release(This) ) #define SnapIn_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define SnapIn_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define SnapIn_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define SnapIn_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define SnapIn_get_Name(This,Name) ( (This)->lpVtbl -> get_Name(This,Name) ) #define SnapIn_get_Vendor(This,Vendor) ( (This)->lpVtbl -> get_Vendor(This,Vendor) ) #define SnapIn_get_Version(This,Version) ( (This)->lpVtbl -> get_Version(This,Version) ) #define SnapIn_get_Extensions(This,Extensions) ( (This)->lpVtbl -> get_Extensions(This,Extensions) ) #define SnapIn_get_SnapinCLSID(This,SnapinCLSID) ( (This)->lpVtbl -> get_SnapinCLSID(This,SnapinCLSID) ) #define SnapIn_get_Properties(This,Properties) ( (This)->lpVtbl -> get_Properties(This,Properties) ) #define SnapIn_EnableAllExtensions(This,Enable) ( (This)->lpVtbl -> EnableAllExtensions(This,Enable) ) #endif #endif #ifndef __SnapIns_INTERFACE_DEFINED__ #define __SnapIns_INTERFACE_DEFINED__ extern const IID IID_SnapIns; typedef struct SnapInsVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (SnapIns * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (SnapIns * This); ULONG(STDMETHODCALLTYPE * Release) (SnapIns * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (SnapIns * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (SnapIns * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (SnapIns * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (SnapIns * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get__NewEnum) (SnapIns * This, IUnknown ** retval); HRESULT(STDMETHODCALLTYPE * Item) (SnapIns * This, long Index, PPSNAPIN SnapIn); HRESULT(STDMETHODCALLTYPE * get_Count) (SnapIns * This, PLONG Count); HRESULT(STDMETHODCALLTYPE * Add) (SnapIns * This, BSTR SnapinNameOrCLSID, VARIANT ParentSnapin, VARIANT Properties, PPSNAPIN SnapIn); HRESULT(STDMETHODCALLTYPE * Remove) (SnapIns * This, PSNAPIN SnapIn); END_INTERFACE } SnapInsVtbl; interface SnapIns { CONST_VTBL struct SnapInsVtbl *lpVtbl; }; #ifdef COBJMACROS #define SnapIns_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define SnapIns_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define SnapIns_Release(This) ( (This)->lpVtbl -> Release(This) ) #define SnapIns_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define SnapIns_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define SnapIns_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define SnapIns_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define SnapIns_get__NewEnum(This,retval) ( (This)->lpVtbl -> get__NewEnum(This,retval) ) #define SnapIns_Item(This,Index,SnapIn) ( (This)->lpVtbl -> Item(This,Index,SnapIn) ) #define SnapIns_get_Count(This,Count) ( (This)->lpVtbl -> get_Count(This,Count) ) #define SnapIns_Add(This,SnapinNameOrCLSID,ParentSnapin,Properties,SnapIn) ( (This)->lpVtbl -> Add(This,SnapinNameOrCLSID,ParentSnapin,Properties,SnapIn) ) #define SnapIns_Remove(This,SnapIn) ( (This)->lpVtbl -> Remove(This,SnapIn) ) #endif #endif #ifndef __Extension_INTERFACE_DEFINED__ #define __Extension_INTERFACE_DEFINED__ extern const IID IID_Extension; typedef struct ExtensionVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Extension * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Extension * This); ULONG(STDMETHODCALLTYPE * Release) (Extension * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Extension * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Extension * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Extension * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Extension * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get_Name) (Extension * This, PBSTR Name); HRESULT(STDMETHODCALLTYPE * get_Vendor) (Extension * This, PBSTR Vendor); HRESULT(STDMETHODCALLTYPE * get_Version) (Extension * This, PBSTR Version); HRESULT(STDMETHODCALLTYPE * get_Extensions) (Extension * This, PPEXTENSIONS Extensions); HRESULT(STDMETHODCALLTYPE * get_SnapinCLSID) (Extension * This, PBSTR SnapinCLSID); HRESULT(STDMETHODCALLTYPE * EnableAllExtensions) (Extension * This, BOOL Enable); HRESULT(STDMETHODCALLTYPE * Enable) (Extension * This, BOOL Enable); END_INTERFACE } ExtensionVtbl; interface Extension { CONST_VTBL struct ExtensionVtbl *lpVtbl; }; #ifdef COBJMACROS #define Extension_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Extension_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Extension_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Extension_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Extension_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Extension_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Extension_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Extension_get_Name(This,Name) ( (This)->lpVtbl -> get_Name(This,Name) ) #define Extension_get_Vendor(This,Vendor) ( (This)->lpVtbl -> get_Vendor(This,Vendor) ) #define Extension_get_Version(This,Version) ( (This)->lpVtbl -> get_Version(This,Version) ) #define Extension_get_Extensions(This,Extensions) ( (This)->lpVtbl -> get_Extensions(This,Extensions) ) #define Extension_get_SnapinCLSID(This,SnapinCLSID) ( (This)->lpVtbl -> get_SnapinCLSID(This,SnapinCLSID) ) #define Extension_EnableAllExtensions(This,Enable) ( (This)->lpVtbl -> EnableAllExtensions(This,Enable) ) #define Extension_Enable(This,Enable) ( (This)->lpVtbl -> Enable(This,Enable) ) #endif #endif #ifndef __Extensions_INTERFACE_DEFINED__ #define __Extensions_INTERFACE_DEFINED__ extern const IID IID_Extensions; typedef struct ExtensionsVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Extensions * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Extensions * This); ULONG(STDMETHODCALLTYPE * Release) (Extensions * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Extensions * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Extensions * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Extensions * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Extensions * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get__NewEnum) (Extensions * This, IUnknown ** retval); HRESULT(STDMETHODCALLTYPE * Item) (Extensions * This, long Index, PPEXTENSION Extension); HRESULT(STDMETHODCALLTYPE * get_Count) (Extensions * This, PLONG Count); END_INTERFACE } ExtensionsVtbl; interface Extensions { CONST_VTBL struct ExtensionsVtbl *lpVtbl; }; #ifdef COBJMACROS #define Extensions_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Extensions_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Extensions_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Extensions_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Extensions_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Extensions_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Extensions_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Extensions_get__NewEnum(This,retval) ( (This)->lpVtbl -> get__NewEnum(This,retval) ) #define Extensions_Item(This,Index,Extension) ( (This)->lpVtbl -> Item(This,Index,Extension) ) #define Extensions_get_Count(This,Count) ( (This)->lpVtbl -> get_Count(This,Count) ) #endif #endif #ifndef __Columns_INTERFACE_DEFINED__ #define __Columns_INTERFACE_DEFINED__ extern const IID IID_Columns; typedef struct ColumnsVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Columns * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Columns * This); ULONG(STDMETHODCALLTYPE * Release) (Columns * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Columns * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Columns * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Columns * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Columns * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * Item) (Columns * This, long Index, PPCOLUMN Column); HRESULT(STDMETHODCALLTYPE * get_Count) (Columns * This, PLONG Count); HRESULT(STDMETHODCALLTYPE * get__NewEnum) (Columns * This, IUnknown ** retval); END_INTERFACE } ColumnsVtbl; interface Columns { CONST_VTBL struct ColumnsVtbl *lpVtbl; }; #ifdef COBJMACROS #define Columns_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Columns_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Columns_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Columns_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Columns_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Columns_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Columns_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Columns_Item(This,Index,Column) ( (This)->lpVtbl -> Item(This,Index,Column) ) #define Columns_get_Count(This,Count) ( (This)->lpVtbl -> get_Count(This,Count) ) #define Columns_get__NewEnum(This,retval) ( (This)->lpVtbl -> get__NewEnum(This,retval) ) #endif #endif #ifndef __Column_INTERFACE_DEFINED__ #define __Column_INTERFACE_DEFINED__ typedef enum ColumnSortOrder { SortOrder_Ascending = 0, SortOrder_Descending = (SortOrder_Ascending + 1) } _ColumnSortOrder; typedef enum ColumnSortOrder COLUMNSORTORDER; extern const IID IID_Column; typedef struct ColumnVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Column * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Column * This); ULONG(STDMETHODCALLTYPE * Release) (Column * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Column * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Column * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Column * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Column * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * Name) (Column * This, BSTR * Name); HRESULT(STDMETHODCALLTYPE * get_Width) (Column * This, PLONG Width); HRESULT(STDMETHODCALLTYPE * put_Width) (Column * This, long Width); HRESULT(STDMETHODCALLTYPE * get_DisplayPosition) (Column * This, PLONG DisplayPosition); HRESULT(STDMETHODCALLTYPE * put_DisplayPosition) (Column * This, long Index); HRESULT(STDMETHODCALLTYPE * get_Hidden) (Column * This, PBOOL Hidden); HRESULT(STDMETHODCALLTYPE * put_Hidden) (Column * This, BOOL Hidden); HRESULT(STDMETHODCALLTYPE * SetAsSortColumn) (Column * This, COLUMNSORTORDER SortOrder); HRESULT(STDMETHODCALLTYPE * IsSortColumn) (Column * This, PBOOL IsSortColumn); END_INTERFACE } ColumnVtbl; interface Column { CONST_VTBL struct ColumnVtbl *lpVtbl; }; #ifdef COBJMACROS #define Column_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Column_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Column_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Column_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Column_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Column_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Column_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Column_Name(This,Name) ( (This)->lpVtbl -> Name(This,Name) ) #define Column_get_Width(This,Width) ( (This)->lpVtbl -> get_Width(This,Width) ) #define Column_put_Width(This,Width) ( (This)->lpVtbl -> put_Width(This,Width) ) #define Column_get_DisplayPosition(This,DisplayPosition) ( (This)->lpVtbl -> get_DisplayPosition(This,DisplayPosition) ) #define Column_put_DisplayPosition(This,Index) ( (This)->lpVtbl -> put_DisplayPosition(This,Index) ) #define Column_get_Hidden(This,Hidden) ( (This)->lpVtbl -> get_Hidden(This,Hidden) ) #define Column_put_Hidden(This,Hidden) ( (This)->lpVtbl -> put_Hidden(This,Hidden) ) #define Column_SetAsSortColumn(This,SortOrder) ( (This)->lpVtbl -> SetAsSortColumn(This,SortOrder) ) #define Column_IsSortColumn(This,IsSortColumn) ( (This)->lpVtbl -> IsSortColumn(This,IsSortColumn) ) #endif #endif #ifndef __Views_INTERFACE_DEFINED__ #define __Views_INTERFACE_DEFINED__ extern const IID IID_Views; typedef struct ViewsVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Views * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Views * This); ULONG(STDMETHODCALLTYPE * Release) (Views * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Views * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Views * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Views * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Views * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * Item) (Views * This, long Index, PPVIEW View); HRESULT(STDMETHODCALLTYPE * get_Count) (Views * This, PLONG Count); HRESULT(STDMETHODCALLTYPE * Add) (Views * This, PNODE Node, VIEWOPTIONS viewOptions); HRESULT(STDMETHODCALLTYPE * get__NewEnum) (Views * This, IUnknown ** retval); END_INTERFACE } ViewsVtbl; interface Views { CONST_VTBL struct ViewsVtbl *lpVtbl; }; #ifdef COBJMACROS #define Views_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Views_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Views_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Views_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Views_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Views_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Views_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Views_Item(This,Index,View) ( (This)->lpVtbl -> Item(This,Index,View) ) #define Views_get_Count(This,Count) ( (This)->lpVtbl -> get_Count(This,Count) ) #define Views_Add(This,Node,viewOptions) ( (This)->lpVtbl -> Add(This,Node,viewOptions) ) #define Views_get__NewEnum(This,retval) ( (This)->lpVtbl -> get__NewEnum(This,retval) ) #endif #endif #ifndef __View_INTERFACE_DEFINED__ #define __View_INTERFACE_DEFINED__ extern const IID IID_View; typedef struct ViewVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (View * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (View * This); ULONG(STDMETHODCALLTYPE * Release) (View * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (View * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (View * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (View * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (View * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get_ActiveScopeNode) (View * This, PPNODE Node); HRESULT(STDMETHODCALLTYPE * put_ActiveScopeNode) (View * This, PNODE Node); HRESULT(STDMETHODCALLTYPE * get_Selection) (View * This, PPNODES Nodes); HRESULT(STDMETHODCALLTYPE * get_ListItems) (View * This, PPNODES Nodes); HRESULT(STDMETHODCALLTYPE * SnapinScopeObject) (View * This, VARIANT ScopeNode, PPDISPATCH ScopeNodeObject); HRESULT(STDMETHODCALLTYPE * SnapinSelectionObject) (View * This, PPDISPATCH SelectionObject); HRESULT(STDMETHODCALLTYPE * Is) (View * This, PVIEW View, VARIANT_BOOL * TheSame); HRESULT(STDMETHODCALLTYPE * get_Document) (View * This, PPDOCUMENT Document); HRESULT(STDMETHODCALLTYPE * SelectAll) (View * This); HRESULT(STDMETHODCALLTYPE * Select) (View * This, PNODE Node); HRESULT(STDMETHODCALLTYPE * Deselect) (View * This, PNODE Node); HRESULT(STDMETHODCALLTYPE * IsSelected) (View * This, PNODE Node, PBOOL IsSelected); HRESULT(STDMETHODCALLTYPE * DisplayScopeNodePropertySheet) (View * This, VARIANT ScopeNode); HRESULT(STDMETHODCALLTYPE * DisplaySelectionPropertySheet) (View * This); HRESULT(STDMETHODCALLTYPE * CopyScopeNode) (View * This, VARIANT ScopeNode); HRESULT(STDMETHODCALLTYPE * CopySelection) (View * This); HRESULT(STDMETHODCALLTYPE * DeleteScopeNode) (View * This, VARIANT ScopeNode); HRESULT(STDMETHODCALLTYPE * DeleteSelection) (View * This); HRESULT(STDMETHODCALLTYPE * RenameScopeNode) (View * This, BSTR NewName, VARIANT ScopeNode); HRESULT(STDMETHODCALLTYPE * RenameSelectedItem) (View * This, BSTR NewName); HRESULT(STDMETHODCALLTYPE * get_ScopeNodeContextMenu) (View * This, VARIANT ScopeNode, PPCONTEXTMENU ContextMenu); HRESULT(STDMETHODCALLTYPE * get_SelectionContextMenu) (View * This, PPCONTEXTMENU ContextMenu); HRESULT(STDMETHODCALLTYPE * RefreshScopeNode) (View * This, VARIANT ScopeNode); HRESULT(STDMETHODCALLTYPE * RefreshSelection) (View * This); HRESULT(STDMETHODCALLTYPE * ExecuteSelectionMenuItem) (View * This, BSTR MenuItemPath); HRESULT(STDMETHODCALLTYPE * ExecuteScopeNodeMenuItem) (View * This, BSTR MenuItemPath, VARIANT ScopeNode); HRESULT(STDMETHODCALLTYPE * ExecuteShellCommand) (View * This, BSTR Command, BSTR Directory, BSTR Parameters, BSTR WindowState); HRESULT(STDMETHODCALLTYPE * get_Frame) (View * This, PPFRAME Frame); HRESULT(STDMETHODCALLTYPE * Close) (View * This); HRESULT(STDMETHODCALLTYPE * get_ScopeTreeVisible) (View * This, PBOOL Visible); HRESULT(STDMETHODCALLTYPE * put_ScopeTreeVisible) (View * This, BOOL Visible); HRESULT(STDMETHODCALLTYPE * Back) (View * This); HRESULT(STDMETHODCALLTYPE * Forward) (View * This); HRESULT(STDMETHODCALLTYPE * put_StatusBarText) (View * This, BSTR StatusBarText); HRESULT(STDMETHODCALLTYPE * get_Memento) (View * This, PBSTR Memento); HRESULT(STDMETHODCALLTYPE * ViewMemento) (View * This, BSTR Memento); HRESULT(STDMETHODCALLTYPE * get_Columns) (View * This, PPCOLUMNS Columns); HRESULT(STDMETHODCALLTYPE * get_CellContents) (View * This, PNODE Node, long Column, PBSTR CellContents); HRESULT(STDMETHODCALLTYPE * ExportList) (View * This, BSTR File, EXPORTLISTOPTIONS exportoptions); HRESULT(STDMETHODCALLTYPE * get_ListViewMode) (View * This, PLISTVIEWMODE Mode); HRESULT(STDMETHODCALLTYPE * put_ListViewMode) (View * This, LISTVIEWMODE mode); HRESULT(STDMETHODCALLTYPE * get_ControlObject) (View * This, PPDISPATCH Control); END_INTERFACE } ViewVtbl; interface View { CONST_VTBL struct ViewVtbl *lpVtbl; }; #ifdef COBJMACROS #define View_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define View_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define View_Release(This) ( (This)->lpVtbl -> Release(This) ) #define View_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define View_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define View_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define View_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define View_get_ActiveScopeNode(This,Node) ( (This)->lpVtbl -> get_ActiveScopeNode(This,Node) ) #define View_put_ActiveScopeNode(This,Node) ( (This)->lpVtbl -> put_ActiveScopeNode(This,Node) ) #define View_get_Selection(This,Nodes) ( (This)->lpVtbl -> get_Selection(This,Nodes) ) #define View_get_ListItems(This,Nodes) ( (This)->lpVtbl -> get_ListItems(This,Nodes) ) #define View_SnapinScopeObject(This,ScopeNode,ScopeNodeObject) ( (This)->lpVtbl -> SnapinScopeObject(This,ScopeNode,ScopeNodeObject) ) #define View_SnapinSelectionObject(This,SelectionObject) ( (This)->lpVtbl -> SnapinSelectionObject(This,SelectionObject) ) #define View_Is(This,View,TheSame) ( (This)->lpVtbl -> Is(This,View,TheSame) ) #define View_get_Document(This,Document) ( (This)->lpVtbl -> get_Document(This,Document) ) #define View_SelectAll(This) ( (This)->lpVtbl -> SelectAll(This) ) #define View_Select(This,Node) ( (This)->lpVtbl -> Select(This,Node) ) #define View_Deselect(This,Node) ( (This)->lpVtbl -> Deselect(This,Node) ) #define View_IsSelected(This,Node,IsSelected) ( (This)->lpVtbl -> IsSelected(This,Node,IsSelected) ) #define View_DisplayScopeNodePropertySheet(This,ScopeNode) ( (This)->lpVtbl -> DisplayScopeNodePropertySheet(This,ScopeNode) ) #define View_DisplaySelectionPropertySheet(This) ( (This)->lpVtbl -> DisplaySelectionPropertySheet(This) ) #define View_CopyScopeNode(This,ScopeNode) ( (This)->lpVtbl -> CopyScopeNode(This,ScopeNode) ) #define View_CopySelection(This) ( (This)->lpVtbl -> CopySelection(This) ) #define View_DeleteScopeNode(This,ScopeNode) ( (This)->lpVtbl -> DeleteScopeNode(This,ScopeNode) ) #define View_DeleteSelection(This) ( (This)->lpVtbl -> DeleteSelection(This) ) #define View_RenameScopeNode(This,NewName,ScopeNode) ( (This)->lpVtbl -> RenameScopeNode(This,NewName,ScopeNode) ) #define View_RenameSelectedItem(This,NewName) ( (This)->lpVtbl -> RenameSelectedItem(This,NewName) ) #define View_get_ScopeNodeContextMenu(This,ScopeNode,ContextMenu) ( (This)->lpVtbl -> get_ScopeNodeContextMenu(This,ScopeNode,ContextMenu) ) #define View_get_SelectionContextMenu(This,ContextMenu) ( (This)->lpVtbl -> get_SelectionContextMenu(This,ContextMenu) ) #define View_RefreshScopeNode(This,ScopeNode) ( (This)->lpVtbl -> RefreshScopeNode(This,ScopeNode) ) #define View_RefreshSelection(This) ( (This)->lpVtbl -> RefreshSelection(This) ) #define View_ExecuteSelectionMenuItem(This,MenuItemPath) ( (This)->lpVtbl -> ExecuteSelectionMenuItem(This,MenuItemPath) ) #define View_ExecuteScopeNodeMenuItem(This,MenuItemPath,ScopeNode) ( (This)->lpVtbl -> ExecuteScopeNodeMenuItem(This,MenuItemPath,ScopeNode) ) #define View_ExecuteShellCommand(This,Command,Directory,Parameters,WindowState) ( (This)->lpVtbl -> ExecuteShellCommand(This,Command,Directory,Parameters,WindowState) ) #define View_get_Frame(This,Frame) ( (This)->lpVtbl -> get_Frame(This,Frame) ) #define View_Close(This) ( (This)->lpVtbl -> Close(This) ) #define View_get_ScopeTreeVisible(This,Visible) ( (This)->lpVtbl -> get_ScopeTreeVisible(This,Visible) ) #define View_put_ScopeTreeVisible(This,Visible) ( (This)->lpVtbl -> put_ScopeTreeVisible(This,Visible) ) #define View_Back(This) ( (This)->lpVtbl -> Back(This) ) #define View_Forward(This) ( (This)->lpVtbl -> Forward(This) ) #define View_put_StatusBarText(This,StatusBarText) ( (This)->lpVtbl -> put_StatusBarText(This,StatusBarText) ) #define View_get_Memento(This,Memento) ( (This)->lpVtbl -> get_Memento(This,Memento) ) #define View_ViewMemento(This,Memento) ( (This)->lpVtbl -> ViewMemento(This,Memento) ) #define View_get_Columns(This,Columns) ( (This)->lpVtbl -> get_Columns(This,Columns) ) #define View_get_CellContents(This,Node,Column,CellContents) ( (This)->lpVtbl -> get_CellContents(This,Node,Column,CellContents) ) #define View_ExportList(This,File,exportoptions) ( (This)->lpVtbl -> ExportList(This,File,exportoptions) ) #define View_get_ListViewMode(This,Mode) ( (This)->lpVtbl -> get_ListViewMode(This,Mode) ) #define View_put_ListViewMode(This,mode) ( (This)->lpVtbl -> put_ListViewMode(This,mode) ) #define View_get_ControlObject(This,Control) ( (This)->lpVtbl -> get_ControlObject(This,Control) ) #endif #endif #ifndef __Nodes_INTERFACE_DEFINED__ #define __Nodes_INTERFACE_DEFINED__ extern const IID IID_Nodes; typedef struct NodesVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Nodes * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Nodes * This); ULONG(STDMETHODCALLTYPE * Release) (Nodes * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Nodes * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Nodes * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Nodes * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Nodes * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get__NewEnum) (Nodes * This, IUnknown ** retval); HRESULT(STDMETHODCALLTYPE * Item) (Nodes * This, long Index, PPNODE Node); HRESULT(STDMETHODCALLTYPE * get_Count) (Nodes * This, PLONG Count); END_INTERFACE } NodesVtbl; interface Nodes { CONST_VTBL struct NodesVtbl *lpVtbl; }; #ifdef COBJMACROS #define Nodes_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Nodes_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Nodes_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Nodes_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Nodes_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Nodes_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Nodes_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Nodes_get__NewEnum(This,retval) ( (This)->lpVtbl -> get__NewEnum(This,retval) ) #define Nodes_Item(This,Index,Node) ( (This)->lpVtbl -> Item(This,Index,Node) ) #define Nodes_get_Count(This,Count) ( (This)->lpVtbl -> get_Count(This,Count) ) #endif #endif #ifndef __ContextMenu_INTERFACE_DEFINED__ #define __ContextMenu_INTERFACE_DEFINED__ extern const IID IID_ContextMenu; typedef struct ContextMenuVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (ContextMenu * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (ContextMenu * This); ULONG(STDMETHODCALLTYPE * Release) (ContextMenu * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (ContextMenu * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (ContextMenu * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (ContextMenu * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (ContextMenu * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get__NewEnum) (ContextMenu * This, IUnknown ** retval); HRESULT(STDMETHODCALLTYPE * get_Item) (ContextMenu * This, VARIANT IndexOrPath, PPMENUITEM MenuItem); HRESULT(STDMETHODCALLTYPE * get_Count) (ContextMenu * This, PLONG Count); END_INTERFACE } ContextMenuVtbl; interface ContextMenu { CONST_VTBL struct ContextMenuVtbl *lpVtbl; }; #ifdef COBJMACROS #define ContextMenu_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ContextMenu_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define ContextMenu_Release(This) ( (This)->lpVtbl -> Release(This) ) #define ContextMenu_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ContextMenu_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ContextMenu_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ContextMenu_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ContextMenu_get__NewEnum(This,retval) ( (This)->lpVtbl -> get__NewEnum(This,retval) ) #define ContextMenu_get_Item(This,IndexOrPath,MenuItem) ( (This)->lpVtbl -> get_Item(This,IndexOrPath,MenuItem) ) #define ContextMenu_get_Count(This,Count) ( (This)->lpVtbl -> get_Count(This,Count) ) #endif #endif #ifndef __MenuItem_INTERFACE_DEFINED__ #define __MenuItem_INTERFACE_DEFINED__ extern const IID IID_MenuItem; typedef struct MenuItemVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (MenuItem * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (MenuItem * This); ULONG(STDMETHODCALLTYPE * Release) (MenuItem * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (MenuItem * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (MenuItem * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (MenuItem * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (MenuItem * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get_DisplayName) (MenuItem * This, PBSTR DisplayName); HRESULT(STDMETHODCALLTYPE * get_LanguageIndependentName) (MenuItem * This, PBSTR LanguageIndependentName); HRESULT(STDMETHODCALLTYPE * get_Path) (MenuItem * This, PBSTR Path); HRESULT(STDMETHODCALLTYPE * get_LanguageIndependentPath) (MenuItem * This, PBSTR LanguageIndependentPath); HRESULT(STDMETHODCALLTYPE * Execute) (MenuItem * This); HRESULT(STDMETHODCALLTYPE * get_Enabled) (MenuItem * This, PBOOL Enabled); END_INTERFACE } MenuItemVtbl; interface MenuItem { CONST_VTBL struct MenuItemVtbl *lpVtbl; }; #ifdef COBJMACROS #define MenuItem_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define MenuItem_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define MenuItem_Release(This) ( (This)->lpVtbl -> Release(This) ) #define MenuItem_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define MenuItem_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define MenuItem_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define MenuItem_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define MenuItem_get_DisplayName(This,DisplayName) ( (This)->lpVtbl -> get_DisplayName(This,DisplayName) ) #define MenuItem_get_LanguageIndependentName(This,LanguageIndependentName) ( (This)->lpVtbl -> get_LanguageIndependentName(This,LanguageIndependentName) ) #define MenuItem_get_Path(This,Path) ( (This)->lpVtbl -> get_Path(This,Path) ) #define MenuItem_get_LanguageIndependentPath(This,LanguageIndependentPath) ( (This)->lpVtbl -> get_LanguageIndependentPath(This,LanguageIndependentPath) ) #define MenuItem_Execute(This) ( (This)->lpVtbl -> Execute(This) ) #define MenuItem_get_Enabled(This,Enabled) ( (This)->lpVtbl -> get_Enabled(This,Enabled) ) #endif #endif #ifndef __Properties_INTERFACE_DEFINED__ #define __Properties_INTERFACE_DEFINED__ extern const IID IID_Properties; typedef struct PropertiesVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Properties * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Properties * This); ULONG(STDMETHODCALLTYPE * Release) (Properties * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Properties * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Properties * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Properties * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Properties * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get__NewEnum) (Properties * This, IUnknown ** retval); HRESULT(STDMETHODCALLTYPE * Item) (Properties * This, BSTR Name, PPPROPERTY Property); HRESULT(STDMETHODCALLTYPE * get_Count) (Properties * This, PLONG Count); HRESULT(STDMETHODCALLTYPE * Remove) (Properties * This, BSTR Name); END_INTERFACE } PropertiesVtbl; interface Properties { CONST_VTBL struct PropertiesVtbl *lpVtbl; }; #ifdef COBJMACROS #define Properties_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Properties_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Properties_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Properties_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Properties_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Properties_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Properties_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Properties_get__NewEnum(This,retval) ( (This)->lpVtbl -> get__NewEnum(This,retval) ) #define Properties_Item(This,Name,Property) ( (This)->lpVtbl -> Item(This,Name,Property) ) #define Properties_get_Count(This,Count) ( (This)->lpVtbl -> get_Count(This,Count) ) #define Properties_Remove(This,Name) ( (This)->lpVtbl -> Remove(This,Name) ) #endif #endif #ifndef __Property_INTERFACE_DEFINED__ #define __Property_INTERFACE_DEFINED__ extern const IID IID_Property; typedef struct PropertyVtbl { BEGIN_INTERFACE HRESULT(STDMETHODCALLTYPE * QueryInterface) (Property * This, REFIID riid, void **ppvObject); ULONG(STDMETHODCALLTYPE * AddRef) (Property * This); ULONG(STDMETHODCALLTYPE * Release) (Property * This); HRESULT(STDMETHODCALLTYPE * GetTypeInfoCount) (Property * This, UINT * pctinfo); HRESULT(STDMETHODCALLTYPE * GetTypeInfo) (Property * This, UINT iTInfo, LCID lcid, ITypeInfo ** ppTInfo); HRESULT(STDMETHODCALLTYPE * GetIDsOfNames) (Property * This, REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID lcid, DISPID * rgDispId); HRESULT(STDMETHODCALLTYPE * Invoke) (Property * This, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr); HRESULT(STDMETHODCALLTYPE * get_Value) (Property * This, PVARIANT Value); HRESULT(STDMETHODCALLTYPE * put_Value) (Property * This, VARIANT Value); HRESULT(STDMETHODCALLTYPE * get_Name) (Property * This, PBSTR Name); END_INTERFACE } PropertyVtbl; interface Property { CONST_VTBL struct PropertyVtbl *lpVtbl; }; #ifdef COBJMACROS #define Property_QueryInterface(This,riid,ppvObject) ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define Property_AddRef(This) ( (This)->lpVtbl -> AddRef(This) ) #define Property_Release(This) ( (This)->lpVtbl -> Release(This) ) #define Property_GetTypeInfoCount(This,pctinfo) ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define Property_GetTypeInfo(This,iTInfo,lcid,ppTInfo) ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define Property_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define Property_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define Property_get_Value(This,Value) ( (This)->lpVtbl -> get_Value(This,Value) ) #define Property_put_Value(This,Value) ( (This)->lpVtbl -> put_Value(This,Value) ) #define Property_get_Name(This,Name) ( (This)->lpVtbl -> get_Name(This,Name) ) #endif #endif #endif #endif extern RPC_IF_HANDLE __MIDL_itf_mmcobj_0001_0042_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_mmcobj_0001_0042_v0_0_s_ifspec; unsigned long __RPC_USER VARIANT_UserSize(unsigned long *, unsigned long, VARIANT *); unsigned char *__RPC_USER VARIANT_UserMarshal(unsigned long *, unsigned char *, VARIANT *); unsigned char *__RPC_USER VARIANT_UserUnmarshal(unsigned long *, unsigned char *, VARIANT *); void __RPC_USER VARIANT_UserFree(unsigned long *, VARIANT *); unsigned long __RPC_USER VARIANT_UserSize64(unsigned long *, unsigned long, VARIANT *); unsigned char *__RPC_USER VARIANT_UserMarshal64(unsigned long *, unsigned char *, VARIANT *); unsigned char *__RPC_USER VARIANT_UserUnmarshal64(unsigned long *, unsigned char *, VARIANT *); void __RPC_USER VARIANT_UserFree64(unsigned long *, VARIANT *); #endif
Frankie-PellesC/fSDK
Include/MMCObj.h
C
lgpl-3.0
77,824
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */ /* * Copyright (C) 2008 Sven Herzberg * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ #ifndef __DH_ASSISTANT_VIEW_H__ #define __DH_ASSISTANT_VIEW_H__ #include <webkit/webkit.h> #include "dh-base.h" #include "dh-link.h" G_BEGIN_DECLS #define DH_TYPE_ASSISTANT_VIEW (dh_assistant_view_get_type ()) #define DH_ASSISTANT_VIEW(i) (G_TYPE_CHECK_INSTANCE_CAST ((i), DH_TYPE_ASSISTANT_VIEW, DhAssistantView)) #define DH_ASSISTANT_VIEW_CLASS(c) (G_TYPE_CHECK_CLASS_CAST ((c), DH_TYPE_ASSISTANT_VIEW, DhAssistantViewClass)) #define DH_IS_ASSISTANT_VIEW(i) (G_TYPE_CHECK_INSTANCE_TYPE ((i), DH_TYPE_ASSISTANT_VIEW)) #define DH_IS_ASSISTANT_VIEW_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE ((c), DH_ASSISTANT_VIEW)) #define DH_ASSISTANT_VIEW_GET_CLASS(i) (G_TYPE_INSTANCE_GET_CLASS ((i), DH_TYPE_ASSISTANT_VIEW, DhAssistantView)) typedef struct _DhAssistantView DhAssistantView; typedef struct _DhAssistantViewClass DhAssistantViewClass; struct _DhAssistantView { WebKitWebView parent_instance; }; struct _DhAssistantViewClass { WebKitWebViewClass parent_class; }; GType dh_assistant_view_get_type (void) G_GNUC_CONST; GtkWidget* dh_assistant_view_new (void); gboolean dh_assistant_view_search (DhAssistantView *view, const gchar *str); DhBase* dh_assistant_view_get_base (DhAssistantView *view); void dh_assistant_view_set_base (DhAssistantView *view, DhBase *base); gboolean dh_assistant_view_set_link (DhAssistantView *view, DhLink *link); G_END_DECLS #endif /* __DH_ASSISTANT_VIEW_H__ */
gandalfn/geany-vala-toys
plugins/help/devhelp/dh-assistant-view.h
C
lgpl-3.0
2,446
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * 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. */ /* ------------------------- * GraphEdgeChangeEvent.java * ------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: GraphEdgeChangeEvent.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 10-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package edu.nd.nina.event; /** * An event which indicates that a graph edge has changed, or is about to * change. The event can be used either as an indication <i>after</i> the edge * has been added or removed, or <i>before</i> it is added. The type of the * event can be tested using the {@link * edu.nd.nina.event.GraphChangeEvent#getType()} method. * * @author Barak Naveh * @since Aug 10, 2003 */ public class GraphEdgeChangeEvent<V, E> extends GraphChangeEvent { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3618134563335844662L; /** * Before edge added event. This event is fired before an edge is added to a * graph. */ public static final int BEFORE_EDGE_ADDED = 21; /** * Before edge removed event. This event is fired before an edge is removed * from a graph. */ public static final int BEFORE_EDGE_REMOVED = 22; /** * Edge added event. This event is fired after an edge is added to a graph. */ public static final int EDGE_ADDED = 23; /** * Edge removed event. This event is fired after an edge is removed from a * graph. */ public static final int EDGE_REMOVED = 24; //~ Instance fields -------------------------------------------------------- /** * The edge that this event is related to. */ protected E edge; //~ Constructors ----------------------------------------------------------- /** * Constructor for GraphEdgeChangeEvent. * * @param eventSource the source of this event. * @param type the event type of this event. * @param e the edge that this event is related to. */ public GraphEdgeChangeEvent(Object eventSource, int type, E e) { super(eventSource, type); edge = e; } //~ Methods ---------------------------------------------------------------- /** * Returns the edge that this event is related to. * * @return the edge that this event is related to. */ public E getEdge() { return edge; } } // End GraphEdgeChangeEvent.java
tweninger/nina
src/edu/nd/nina/event/GraphEdgeChangeEvent.java
Java
lgpl-3.0
3,785
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * 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 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ namespace pocketmine\level\format\mcregion; use pocketmine\level\format\FullChunk; use pocketmine\level\format\LevelProvider; use pocketmine\nbt\NBT; use pocketmine\nbt\tag\Byte; use pocketmine\nbt\tag\ByteArray; use pocketmine\nbt\tag\Compound; use pocketmine\nbt\tag\Enum; use pocketmine\nbt\tag\Int; use pocketmine\nbt\tag\IntArray; use pocketmine\nbt\tag\Long; use pocketmine\utils\Binary; use pocketmine\utils\ChunkException; use pocketmine\utils\MainLogger; class RegionLoader{ const VERSION = 1; const COMPRESSION_GZIP = 1; const COMPRESSION_ZLIB = 2; const MAX_SECTOR_LENGTH = 256 << 12; //256 sectors, (1 MiB) public static $COMPRESSION_LEVEL = 7; protected $x; protected $z; protected $filePath; protected $filePointer; protected $lastSector; /** @var LevelProvider */ protected $levelProvider; protected $locationTable = []; public $lastUsed; public function __construct(LevelProvider $level, $regionX, $regionZ){ $this->x = $regionX; $this->z = $regionZ; $this->levelProvider = $level; $this->filePath = $this->levelProvider->getPath() . "region/r.$regionX.$regionZ.mcr"; $exists = file_exists($this->filePath); touch($this->filePath); $this->filePointer = fopen($this->filePath, "r+b"); stream_set_read_buffer($this->filePointer, 1024 * 16); //16KB stream_set_write_buffer($this->filePointer, 1024 * 16); //16KB if(!$exists){ $this->createBlank(); }else{ $this->loadLocationTable(); } $this->lastUsed = time(); } public function __destruct(){ if(is_resource($this->filePointer)){ $this->writeLocationTable(); fclose($this->filePointer); } } protected function isChunkGenerated($index){ return !($this->locationTable[$index][0] === 0 or $this->locationTable[$index][1] === 0); } public function readChunk($x, $z, $generate = true, $forward = false){ $index = self::getChunkOffset($x, $z); if($index < 0 or $index >= 4096){ return null; } $this->lastUsed = time(); if(!$this->isChunkGenerated($index)){ if($generate === true){ //Allocate space $this->locationTable[$index][0] = ++$this->lastSector; $this->locationTable[$index][1] = 1; fseek($this->filePointer, $this->locationTable[$index][0] << 12); fwrite($this->filePointer, str_pad(Binary::writeInt(0) . chr(self::COMPRESSION_ZLIB), 4096, "\x00", STR_PAD_RIGHT)); $this->writeLocationIndex($index); }else{ return null; } } fseek($this->filePointer, $this->locationTable[$index][0] << 12); $length = Binary::readInt(fread($this->filePointer, 4)); $compression = ord(fgetc($this->filePointer)); if($length <= 0 or $length > self::MAX_SECTOR_LENGTH){ //Not yet generated / corrupted if($length >= self::MAX_SECTOR_LENGTH){ $this->locationTable[$index][0] = ++$this->lastSector; $this->locationTable[$index][1] = 1; MainLogger::getLogger()->error("Corrupted chunk header detected"); } $this->generateChunk($x, $z); fseek($this->filePointer, $this->locationTable[$index][0] << 12); $length = Binary::readInt(fread($this->filePointer, 4)); $compression = ord(fgetc($this->filePointer)); } if($length > ($this->locationTable[$index][1] << 12)){ //Invalid chunk, bigger than defined number of sectors MainLogger::getLogger()->error("Corrupted bigger chunk detected"); $this->locationTable[$index][1] = $length >> 12; $this->writeLocationIndex($index); }elseif($compression !== self::COMPRESSION_ZLIB and $compression !== self::COMPRESSION_GZIP){ MainLogger::getLogger()->error("Invalid compression type"); return null; } $chunk = Chunk::fromBinary(fread($this->filePointer, $length - 1), $this->levelProvider); if($chunk instanceof Chunk){ return $chunk; }elseif($forward === false){ MainLogger::getLogger()->error("Corrupted chunk detected"); $this->generateChunk($x, $z); return $this->readChunk($x, $z, $generate, true); }else{ return null; } } public function chunkExists($x, $z){ return $this->isChunkGenerated(self::getChunkOffset($x, $z)); } public function generateChunk($x, $z){ $nbt = new Compound("Level", []); $nbt->xPos = new Int("xPos", ($this->getX() * 32) + $x); $nbt->zPos = new Int("zPos", ($this->getZ() * 32) + $z); $nbt->LastUpdate = new Long("LastUpdate", 0); $nbt->LightPopulated = new Byte("LightPopulated", 0); $nbt->TerrainPopulated = new Byte("TerrainPopulated", 0); $nbt->V = new Byte("V", self::VERSION); $nbt->InhabitedTime = new Long("InhabitedTime", 0); $nbt->Biomes = new ByteArray("Biomes", str_repeat(Binary::writeByte(-1), 256)); $nbt->HeightMap = new IntArray("HeightMap", array_fill(0, 256, 127)); $nbt->BiomeColors = new IntArray("BiomeColors", array_fill(0, 256, Binary::readInt("\x00\x85\xb2\x4a"))); $nbt->Blocks = new ByteArray("Blocks", str_repeat("\x00", 32768)); $nbt->Data = new ByteArray("Data", $half = str_repeat("\x00", 16384)); $nbt->SkyLight = new ByteArray("SkyLight", $half); $nbt->BlockLight = new ByteArray("BlockLight", $half); $nbt->Entities = new Enum("Entities", []); $nbt->Entities->setTagType(NBT::TAG_Compound); $nbt->TileEntities = new Enum("TileEntities", []); $nbt->TileEntities->setTagType(NBT::TAG_Compound); $nbt->TileTicks = new Enum("TileTicks", []); $nbt->TileTicks->setTagType(NBT::TAG_Compound); $writer = new NBT(NBT::BIG_ENDIAN); $nbt->setName("Level"); $writer->setData(new Compound("", ["Level" => $nbt])); $chunkData = $writer->writeCompressed(ZLIB_ENCODING_DEFLATE, self::$COMPRESSION_LEVEL); if($chunkData !== false){ $this->saveChunk($x, $z, $chunkData); } } protected function saveChunk($x, $z, $chunkData){ $length = strlen($chunkData) + 1; if($length + 4 > self::MAX_SECTOR_LENGTH){ throw new ChunkException("Chunk is too big! ".($length + 4)." > ".self::MAX_SECTOR_LENGTH); } $sectors = (int) ceil(($length + 4) / 4096); $index = self::getChunkOffset($x, $z); if($this->locationTable[$index][1] < $sectors){ $this->locationTable[$index][0] = $this->lastSector + 1; $this->lastSector += $sectors; //The GC will clean this shift "later" } $this->locationTable[$index][1] = $sectors; $this->locationTable[$index][2] = time(); fseek($this->filePointer, $this->locationTable[$index][0] << 12); fwrite($this->filePointer, str_pad(Binary::writeInt($length) . chr(self::COMPRESSION_ZLIB) . $chunkData, $sectors << 12, "\x00", STR_PAD_RIGHT)); $this->writeLocationIndex($index); } public function removeChunk($x, $z){ $index = self::getChunkOffset($x, $z); $this->locationTable[$index][0] = 0; $this->locationTable[$index][1] = 0; } public function writeChunk(FullChunk $chunk){ $this->lastUsed = time(); $chunkData = $chunk->toBinary(); if($chunkData !== false){ $this->saveChunk($chunk->getX() - ($this->getX() * 32), $chunk->getZ() - ($this->getZ() * 32), $chunkData); } } protected static function getChunkOffset($x, $z){ return $x + ($z << 5); } public function close(){ $this->writeLocationTable(); fclose($this->filePointer); $this->levelProvider = null; } public function doSlowCleanUp(){ for($i = 0; $i < 1024; ++$i){ if($this->locationTable[$i][0] === 0 or $this->locationTable[$i][1] === 0){ continue; } fseek($this->filePointer, $this->locationTable[$i][0] << 12); $chunk = fread($this->filePointer, $this->locationTable[$i][1] << 12); $length = Binary::readInt(substr($chunk, 0, 4)); if($length <= 1){ $this->locationTable[$i] = [0, 0, 0]; //Non-generated chunk, remove it from index } try{ $chunk = zlib_decode(substr($chunk, 5)); }catch(\Exception $e){ $this->locationTable[$i] = [0, 0, 0]; //Corrupted chunk, remove it continue; } $chunk = chr(self::COMPRESSION_ZLIB) . zlib_encode($chunk, ZLIB_ENCODING_DEFLATE, 9); $chunk = Binary::writeInt(strlen($chunk)) . $chunk; $sectors = (int) ceil(strlen($chunk) / 4096); if($sectors > $this->locationTable[$i][1]){ $this->locationTable[$i][0] = $this->lastSector + 1; $this->lastSector += $sectors; } fseek($this->filePointer, $this->locationTable[$i][0] << 12); fwrite($this->filePointer, str_pad($chunk, $sectors << 12, "\x00", STR_PAD_RIGHT)); } $this->writeLocationTable(); $n = $this->cleanGarbage(); $this->writeLocationTable(); return $n; } private function cleanGarbage(){ $sectors = []; foreach($this->locationTable as $index => $data){ //Calculate file usage if($data[0] === 0 or $data[1] === 0){ $this->locationTable[$index] = [0, 0, 0]; continue; } for($i = 0; $i < $data[1]; ++$i){ $sectors[$data[0]] = $index; } } if(count($sectors) === ($this->lastSector - 2)){ //No collection needed return 0; } ksort($sectors); $shift = 0; $lastSector = 1; //First chunk - 1 fseek($this->filePointer, 8192); $sector = 2; foreach($sectors as $sector => $index){ if(($sector - $lastSector) > 1){ $shift += $sector - $lastSector - 1; } if($shift > 0){ fseek($this->filePointer, $sector << 12); $old = fread($this->filePointer, 4096); fseek($this->filePointer, ($sector - $shift) << 12); fwrite($this->filePointer, $old, 4096); } $this->locationTable[$index][0] -= $shift; $lastSector = $sector; } ftruncate($this->filePointer, ($sector + 1) << 12); //Truncate to the end of file written return $shift; } protected function loadLocationTable(){ fseek($this->filePointer, 0); $this->lastSector = 1; $table = fread($this->filePointer, 4 * 1024 * 2); //1024 records * 4 bytes * 2 times for($i = 0; $i < 1024; ++$i){ $index = unpack("N", substr($table, $i << 2, 4))[1]; $this->locationTable[$i] = [$index >> 8, $index & 0xff, unpack("N", substr($table, 4096 + ($i << 2), 4))[1]]; if(($this->locationTable[$i][0] + $this->locationTable[$i][1] - 1) > $this->lastSector){ $this->lastSector = $this->locationTable[$i][0] + $this->locationTable[$i][1] - 1; } } } private function writeLocationTable(){ $write = []; for($i = 0; $i < 1024; ++$i){ $write[] = (($this->locationTable[$i][0] << 8) | $this->locationTable[$i][1]); } for($i = 0; $i < 1024; ++$i){ $write[] = $this->locationTable[$i][2]; } fseek($this->filePointer, 0); fwrite($this->filePointer, pack("N*", ...$write), 4096 * 2); } protected function writeLocationIndex($index){ fseek($this->filePointer, $index << 2); fwrite($this->filePointer, Binary::writeInt(($this->locationTable[$index][0] << 8) | $this->locationTable[$index][1]), 4); fseek($this->filePointer, 4096 + ($index << 2)); fwrite($this->filePointer, Binary::writeInt($this->locationTable[$index][2]), 4); } protected function createBlank(){ fseek($this->filePointer, 0); ftruncate($this->filePointer, 0); $this->lastSector = 1; $table = ""; for($i = 0; $i < 1024; ++$i){ $this->locationTable[$i] = [0, 0]; $table .= Binary::writeInt(0); } $time = time(); for($i = 0; $i < 1024; ++$i){ $this->locationTable[$i][2] = $time; $table .= Binary::writeInt($time); } fwrite($this->filePointer, $table, 4096 * 2); } public function getX(){ return $this->x; } public function getZ(){ return $this->z; } }
NickY5/mitko_e_prostak
src/pocketmine/level/format/mcregion/RegionLoader.php
PHP
lgpl-3.0
11,885
#PBS -S /bin/bash #PBS -N mnakao_job #PBS -A XMPTCA #PBS -q tcaq-q1 #PBS -l select=1:ncpus=1:host=tcag-0001-eth0+1:ncpus=1:host=tcag-0002-eth0+1:ncpus=1:host=tcag-0003-eth0+1:ncpus=1:host=tcag-0004-eth0+1:ncpus=1:host=tcag-0005-eth0+1:ncpus=1:host=tcag-0006-eth0+1:ncpus=1:host=tcag-0007-eth0+1:ncpus=1:host=tcag-0008-eth0 #PBS -l walltime=00:01:00 . /opt/Modules/default/init/bash #--------------- # select=NODES:ncpus=CORES:mpiprocs=PROCS:ompthreads=THREADS:mem=MEMORY # NODES : num of nodes # CORES : num of cores per node # PROCS : num of procs per node # THREADS : num of threads per process #---------------- NP=8 module purge module load cuda/6.5.14 mvapich2-gdr/2.0_gnu_cuda-6.5 export LD_LIBRARY_PATH=/work/XMPTCA/mnakao/omni-compiler/PEACH2:$LD_LIBRARY_PATH cd $PBS_O_WORKDIR OPT="MV2_GPUDIRECT_LIMIT=4194304 MV2_ENABLE_AFFINITY=0 MV2_SHOW_CPU_BINDING=1 numactl --cpunodebind=0 --localalloc" for i in $(seq 1 10) do mpirun_rsh -np $NP -hostfile $PBS_NODEFILE $OPT ./L done
omni-compiler/omni-compiler
samples/XACC/HIMENO-C/Global-view/job_scripts/HA-PACS/TCA/tcaq-q1-4x2nodes.sh
Shell
lgpl-3.0
989
<?php namespace Pardisan\Support\Facades; use Illuminate\Support\Facades\Facade; class Menu extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'menu'; } }
lucknerjb/hammihan-online
app/Pardisan/Support/Facades/Menu.php
PHP
lgpl-3.0
294
package edu.mit.blocks.codeblockutil; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JToolTip; import javax.swing.KeyStroke; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import edu.mit.blocks.renderable.BlockLabel; public class LabelWidget extends JComponent { public static final int DROP_DOWN_MENU_WIDTH = 7; private static final long serialVersionUID = 837647234895L; /** Border of textfield*/ private static final Border textFieldBorder = new CompoundBorder(BorderFactory.createLoweredBevelBorder(), new EmptyBorder(1, 2, 1, 2)); /** Number formatter for this label */ private static final NumberFormatter nf = new NumberFormatter(NumberFormatter.MEDIUM_PRECISION); /** Label that is visable iff editingText is false */ private final ShadowLabel textLabel = new ShadowLabel(); /** TextField that is visable iff editingText is true */ private final BlockLabelTextField textField = new BlockLabelTextField(); /** drop down menu icon */ private final LabelMenu menu = new LabelMenu(); ; /** The label text before user begins edit (applies only to editable labels)*/ private String labelBeforeEdit = ""; /** If this is a number, then only allow nagatvie signs and periods at certain spots */ private boolean isNumber = false; /** Is labelText editable by the user -- default true */ private boolean isEditable = false; /** If focus is true, then show the combo pop up menu */ private boolean isFocused = false; /** Has ComboPopup accessable selections */ private boolean hasSiblings = false; /** True if TEXTFIELD is being edited by user. */ private boolean editingText; /** the background color of the tooltip */ private Color tooltipBackground = new Color(255, 255, 225); private double zoom = 1.0; private BlockLabel blockLabel; /** * BlockLabel Constructor that takes in BlockID as well. * Unfortunately BlockID is needed, so the label can redirect mouse actions. * */ public LabelWidget(String initLabelText, Color fieldColor, Color tooltipBackground) { if (initLabelText == null) { initLabelText = ""; } this.setFocusTraversalKeysEnabled(false);//MOVE DEFAULT FOCUS TRAVERSAL KEYS SUCH AS TABS this.setLayout(new BorderLayout()); this.tooltipBackground = tooltipBackground; this.labelBeforeEdit = initLabelText; //set up textfield colors textField.setForeground(Color.WHITE);//white text textField.setBackground(fieldColor);//background matching block color textField.setCaretColor(Color.WHITE);//white caret textField.setSelectionColor(Color.BLACK);//black highlight textField.setSelectedTextColor(Color.WHITE);//white text when highlighted textField.setBorder(textFieldBorder); textField.setMargin(textFieldBorder.getBorderInsets(textField)); } public void setBlockLabel(BlockLabel blockLabel) { this.blockLabel = blockLabel; } protected void fireTextChanged(String text) { blockLabel.textChanged(text); } protected void fireGenusChanged(String genus) { blockLabel.genusChanged(genus); } protected void fireDimensionsChanged(Dimension value) { blockLabel.dimensionsChanged(value); } protected boolean isTextValid(String text) { return blockLabel.textValid(text); } public void addKeyListenerToTextField(KeyListener l) { textField.addKeyListener(l); } public void addMouseListenerToLabel(MouseListener l) { textLabel.addMouseListener(l); } public void addMouseMotionListenerToLabel(MouseMotionListener l) { textLabel.addMouseMotionListener(l); } ////////////////////////////// //// LABEL CONFIGURATION ///// ///////////////////////////// public void showMenuIcon(boolean show) { if (this.hasSiblings) { isFocused = show; // repaints the menu and items with the new zoom level menu.popupmenu.setZoomLevel(zoom); menu.repaint(); } } /** * setEditingState sets the current editing state of the BlockLabel. * Repaints BlockLabel to reflect the change. */ public void setEditingState(boolean editing) { if (editing) { editingText = true; textField.setText(textLabel.getText().trim()); labelBeforeEdit = textLabel.getText(); this.removeAll(); this.add(textField); textField.grabFocus(); } else { //update to current textfield.text //if text entered was not empty and if it was editing before if (editingText) { //make sure to remove leading and trailing spaces before testing if text is valid //TODO if allow labels to have leading and trailing spaces, will need to modify this if statement if (isTextValid(textField.getText().trim())) { setText(textField.getText()); } else { setText(labelBeforeEdit); } } editingText = false; } } /** * editingText returns if BlockLable is being edited * @return editingText */ public boolean editingText() { return editingText; } /** * setEditable state of BlockLabel * @param isEditable specifying editable state of BlockLabel */ public void setEditable(boolean isEditable) { this.isEditable = isEditable; } /** * isEditable returns if BlockLable is editable * @return isEditable */ public boolean isEditable() { return isEditable; } public void setNumeric(boolean isNumber) { this.isNumber = isNumber; } /** * isEditable returns if BlockLable is editable * @return isEditable */ public boolean isNumeric() { return isNumber; } public void setSiblings(boolean hasSiblings, String[][] siblings) { this.hasSiblings = hasSiblings; this.menu.setSiblings(siblings); } public boolean hasSiblings() { return this.hasSiblings; } /** * set up fonts * @param font */ public void setFont(Font font) { super.setFont(font); textLabel.setFont(font); textField.setFont(font); menu.setFont(font); } /** * sets the tool tip of the label */ public void assignToolTipToLabel(String text) { this.textLabel.setToolTipText(text); } /** * getText * @return String of the current BlockLabel */ public String getText() { return textLabel.getText().trim(); } /** * setText to a NumberFormatted double * @param value */ public void setText(double value) { //check for +/- Infinity if (Math.abs(value - Double.MAX_VALUE) < 1) { updateLabelText("Infinity"); } else if (Math.abs(value + Double.MAX_VALUE) < 1) { updateLabelText("-Infinity"); } else { updateLabelText(nf.format(value)); } } /** * setText to a String (trimmed to remove excess spaces) * @param string */ public void setText(String string) { if (string != null) { updateLabelText(string.trim()); } } /** * setText to a boolean * @param bool */ public void setText(boolean bool) { updateLabelText(bool ? "True" : "False"); } /** * updateLabelText updates labelText and sychronizes textField and textLabel to it * @param text */ public void updateLabelText(String text) { //leave some space to click on if (text.equals("")) { text = " "; } //update the text everywhere textLabel.setText(text); textField.setText(text); //resize to new text updateDimensions(); //the blockLabel needs to update the data in Block this.fireTextChanged(text); //show text label and additional ComboPopup if one exists this.removeAll(); this.add(textLabel, BorderLayout.CENTER); if (hasSiblings) { this.add(menu, BorderLayout.EAST); } } //////////////////// //// RENDERING ///// //////////////////// /** * Updates the dimensions of the textRect, textLabel, and textField to the minimum size needed * to contain all of the text in the current font. */ private void updateDimensions() { Dimension updatedDimension = new Dimension( textField.getPreferredSize().width, textField.getPreferredSize().height); if (this.hasSiblings) { updatedDimension.width += LabelWidget.DROP_DOWN_MENU_WIDTH; } textField.setSize(updatedDimension); textLabel.setSize(updatedDimension); this.setSize(updatedDimension); this.fireDimensionsChanged(this.getSize()); } /** * high lights the text of the editing text field from * 0 to the end of textfield */ public void highlightText() { this.textField.setSelectionStart(0); } /** * Toggles the visual suggestion that this label may be editable depending on the specified * suggest flag and properties of the block and label. If suggest is true, the visual suggestion will display. Otherwise, nothing * is shown. For now, the visual suggestion is a simple white line boder. * Other requirements for indicator to show: * - label type must be NAME * - label must be editable * - block can not be a factory block * @param suggest */ protected void suggestEditable(boolean suggest) { if (isEditable) { if (suggest) { setBorder(BorderFactory.createLineBorder(Color.white));//show white border } else { setBorder(null);//hide white border } } } public void setZoomLevel(double newZoom) { this.zoom = newZoom; Font renderingFont;// = new Font(font.getFontName(), font.getStyle(), (int)(font.getSize()*newZoom)); AffineTransform at = new AffineTransform(); at.setToScale(newZoom, newZoom); renderingFont = this.getFont().deriveFont(at); this.setFont(renderingFont); this.repaint(); this.updateDimensions(); } public String toString() { return "Label at " + this.getLocation() + " with text: \"" + textLabel.getText() + "\""; } /** * returns true if this block should can accept a negative sign */ public boolean canProcessNegativeSign() { if (this.getText() != null && this.getText().contains("-")) { //if it already has a negative sign, //make sure we're highlighting it if (textField.getSelectedText() != null && textField.getSelectedText().contains("-")) { return true; } else { return false; } } else { //if it does not have negative sign, //make sure our highlight covers index 0 if (textField.getCaretPosition() == 0) { return true; } else { if (textField.getSelectionStart() == 0) { return true; } } } return false; } /** * BlockLabelTextField is a java JtextField that internally handles various events * and provides the semantic to interface with the user. Unliek typical JTextFields, * the blockLabelTextField allows clients to only enter certain keys board input. * It also reacts to enters and escapse by delegating the KeyEvent to the parent * RenderableBlock. */ private class BlockLabelTextField extends JTextField implements MouseListener, DocumentListener, FocusListener, ActionListener { private static final long serialVersionUID = 873847239234L; /** These Key inputs are processed by this text field */ private final char[] validNumbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'}; /** These Key inputs are processed by this text field if NOT a number block*/ private final char[] validChar = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '\'', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '{', '}', '|', '[', ']', '\\', ' ', ':', '"', ';', '\'', '<', '>', '?', ',', '.', '/', '`', '~'}; /** These Key inputs are processed by all this text field */ private final int[] validMasks = {KeyEvent.VK_BACK_SPACE, KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_END, KeyEvent.VK_HOME, '-', KeyEvent.VK_DELETE, KeyEvent.VK_SHIFT, KeyEvent.VK_CONTROL, InputEvent.SHIFT_MASK, InputEvent.SHIFT_DOWN_MASK}; /** * Contructs new block label text field */ private BlockLabelTextField() { this.addActionListener(this); this.getDocument().addDocumentListener(this); this.addFocusListener(this); this.addMouseListener(this); /* * Sets whether focus traversal keys are enabled * for this Component. Components for which focus * traversal keys are disabled receive key events * for focus traversal keys. */ this.setFocusTraversalKeysEnabled(false); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseExited(MouseEvent arg0) { //remove the white line border //note: make call here since text fields consume mouse events //preventing parent from responding to mouse exited events suggestEditable(false); } public void actionPerformed(ActionEvent e) { setEditingState(false); } public void changedUpdate(DocumentEvent e) { //listens for change in attributes } public void insertUpdate(DocumentEvent e) { updateDimensions(); } public void removeUpdate(DocumentEvent e) { updateDimensions(); } public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { setEditingState(false); } /** * for all user-generated AND/OR system generated key inputs, * either perform some action that should be triggered by * that key or */ protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { if (isNumber) { if (e.getKeyChar() == '-' && canProcessNegativeSign()) { return super.processKeyBinding(ks, e, condition, pressed); } if (this.getText().contains(".") && e.getKeyChar() == '.') { return false; } for (char c : validNumbers) { if (e.getKeyChar() == c) { return super.processKeyBinding(ks, e, condition, pressed); } } } else { for (char c : validChar) { if (e.getKeyChar() == c) { return super.processKeyBinding(ks, e, condition, pressed); } } } for (int i : validMasks) { if (e.getKeyCode() == i) { return super.processKeyBinding(ks, e, condition, pressed); } } if ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) { return super.processKeyBinding(ks, e, condition, pressed); } return false; } } private class LabelMenu extends JPanel implements MouseListener, MouseMotionListener { private static final long serialVersionUID = 328149080240L; private CPopupMenu popupmenu; private GeneralPath triangle; private LabelMenu() { this.setOpaque(false); this.addMouseListener(this); this.addMouseMotionListener(this); this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); this.popupmenu = new CPopupMenu(); } /** * @param siblings = array of siblin's genus and initial label * { {genus, label}, {genus, label}, {genus, label} ....} */ private void setSiblings(String[][] siblings) { popupmenu = new CPopupMenu(); //if connected to a block, add self and add siblings for (int i = 0; i < siblings.length; i++) { final String selfGenus = siblings[i][0]; CMenuItem selfItem = new CMenuItem(siblings[i][1]); selfItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fireGenusChanged(selfGenus); showMenuIcon(false); } }); popupmenu.add(selfItem); } } public boolean contains(Point p) { return triangle != null && triangle.contains(p); } public boolean contains(int x, int y) { return triangle != null && triangle.contains(x, y); } public void paint(Graphics g) { super.paint(g); if (isFocused) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); triangle = new GeneralPath(); triangle.moveTo(0, this.getHeight() / 4); triangle.lineTo(this.getWidth() - 1, this.getHeight() / 4); triangle.lineTo(this.getWidth() / 2 - 1, this.getHeight() / 4 + LabelWidget.DROP_DOWN_MENU_WIDTH); triangle.lineTo(0, this.getHeight() / 4); triangle.closePath(); g2.setColor(new Color(255, 255, 255, 100)); g2.fill(triangle); g2.setColor(Color.BLACK); g2.draw(triangle); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { if (hasSiblings) { popupmenu.show(this, 0, 0); } } public void mouseReleased(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } } /** * Much like a JLabel, only the text is displayed with a shadow like outline */ private class ShadowLabel extends JLabel implements MouseListener, MouseMotionListener { private static final long serialVersionUID = 90123787382L; //To get the shadow effect the text must be displayed multiple times at //multiple locations. x represents the center, white label. // o is color values (0,0,0,0.5f) and b is black. // o o // o x b o // o b o // o //offsetArrays representing the translation movement needed to get from // the center location to a specific offset location given in {{x,y},{x,y}....} //..........................................grey points.............................................black points private final int[][] shadowPositionArray = {{0, -1}, {1, -1}, {-1, 0}, {2, 0}, {-1, 1}, {1, 1}, {0, 2}, {1, 0}, {0, 1}}; private final float[] shadowColorArray = {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0, 0}; private double offsetSize = 1; private ShadowLabel() { this.addMouseListener(this); this.addMouseMotionListener(this); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); //DO NOT DRAW SUPER's to prevent drawing of label's string. //Implecations: background not automatically drawn //super.paint(g); //draw shadows for (int i = 0; i < shadowPositionArray.length; i++) { int dx = shadowPositionArray[i][0]; int dy = shadowPositionArray[i][1]; g2.setColor(new Color(0, 0, 0, shadowColorArray[i])); g2.drawString(this.getText(), (int) ((4 + dx) * offsetSize), this.getHeight() + (int) ((dy - 6) * offsetSize)); } //draw main Text g2.setColor(Color.white); g2.drawString(this.getText(), (int) ((4) * offsetSize), this.getHeight() + (int) ((-6) * offsetSize)); } public JToolTip createToolTip() { return new CToolTip(tooltipBackground); } /** * Set to editing state upon mouse click if this block label is editable */ public void mouseClicked(MouseEvent e) { //if clicked and if the label is editable, if ((e.getClickCount() == 1) && isEditable) { //if clicked and if the label is editable, //then set it to the editing state when the label is clicked on setEditingState(true); textField.setSelectionStart(0); } } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { suggestEditable(true); } public void mouseExited(MouseEvent e) { suggestEditable(false); } public void mouseDragged(MouseEvent e) { suggestEditable(false); } public void mouseMoved(MouseEvent e) { suggestEditable(true); } } }
laurentschall/openblocks
src/main/java/edu/mit/blocks/codeblockutil/LabelWidget.java
Java
lgpl-3.0
24,554
/* * This class was automatically generated with * <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML * Schema. * $Id: CreditCardCreditModRqTypeDescriptor.java,v 1.1.1.1 2010-05-04 22:06:01 ryan Exp $ */ package org.chocolate_milk.model.descriptors; //---------------------------------/ //- Imported classes and packages -/ //---------------------------------/ import org.chocolate_milk.model.CreditCardCreditModRqType; /** * Class CreditCardCreditModRqTypeDescriptor. * * @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:01 $ */ public class CreditCardCreditModRqTypeDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl { //--------------------------/ //- Class/Member Variables -/ //--------------------------/ /** * Field _elementDefinition. */ private boolean _elementDefinition; /** * Field _nsPrefix. */ private java.lang.String _nsPrefix; /** * Field _nsURI. */ private java.lang.String _nsURI; /** * Field _xmlName. */ private java.lang.String _xmlName; /** * Field _identity. */ private org.exolab.castor.xml.XMLFieldDescriptor _identity; //----------------/ //- Constructors -/ //----------------/ public CreditCardCreditModRqTypeDescriptor() { super(); _xmlName = "CreditCardCreditModRqType"; _elementDefinition = false; //-- set grouping compositor setCompositorAsSequence(); org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null; org.exolab.castor.mapping.FieldHandler handler = null; org.exolab.castor.xml.FieldValidator fieldValidator = null; //-- initialize attribute descriptors //-- _requestID desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_requestID", "requestID", org.exolab.castor.xml.NodeType.Attribute); desc.setImmutable(true); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; return target.getRequestID(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; target.setRequestID( (java.lang.String) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("string"); desc.setHandler(handler); desc.setMultivalued(false); addFieldDescriptor(desc); //-- validation code for: _requestID fieldValidator = new org.exolab.castor.xml.FieldValidator(); { //-- local scope org.exolab.castor.xml.validators.StringValidator typeValidator; typeValidator = new org.exolab.castor.xml.validators.StringValidator(); fieldValidator.setValidator(typeValidator); typeValidator.setWhiteSpace("preserve"); } desc.setValidator(fieldValidator); //-- initialize element descriptors //-- _creditCardCreditMod desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.CreditCardCreditMod.class, "_creditCardCreditMod", "CreditCardCreditMod", org.exolab.castor.xml.NodeType.Element); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; return target.getCreditCardCreditMod(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; target.setCreditCardCreditMod( (org.chocolate_milk.model.CreditCardCreditMod) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("org.chocolate_milk.model.CreditCardCreditMod"); desc.setHandler(handler); desc.setRequired(true); desc.setMultivalued(false); addFieldDescriptor(desc); addSequenceElement(desc); //-- validation code for: _creditCardCreditMod fieldValidator = new org.exolab.castor.xml.FieldValidator(); fieldValidator.setMinOccurs(1); { //-- local scope } desc.setValidator(fieldValidator); //-- _includeRetElementList desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_includeRetElementList", "IncludeRetElement", org.exolab.castor.xml.NodeType.Element); desc.setImmutable(true); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; return target.getIncludeRetElement(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; target.addIncludeRetElement( (java.lang.String) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException { try { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; target.removeAllIncludeRetElement(); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("list"); desc.setComponentType("string"); desc.setHandler(handler); desc.setMultivalued(true); addFieldDescriptor(desc); addSequenceElement(desc); //-- validation code for: _includeRetElementList fieldValidator = new org.exolab.castor.xml.FieldValidator(); fieldValidator.setMinOccurs(0); { //-- local scope org.exolab.castor.xml.validators.StringValidator typeValidator; typeValidator = new org.exolab.castor.xml.validators.StringValidator(); fieldValidator.setValidator(typeValidator); typeValidator.setWhiteSpace("preserve"); typeValidator.setMaxLength(50); } desc.setValidator(fieldValidator); } //-----------/ //- Methods -/ //-----------/ /** * Method getAccessMode. * * @return the access mode specified for this class. */ @Override() public org.exolab.castor.mapping.AccessMode getAccessMode( ) { return null; } /** * Method getIdentity. * * @return the identity field, null if this class has no * identity. */ @Override() public org.exolab.castor.mapping.FieldDescriptor getIdentity( ) { return _identity; } /** * Method getJavaClass. * * @return the Java class represented by this descriptor. */ @Override() public java.lang.Class getJavaClass( ) { return org.chocolate_milk.model.CreditCardCreditModRqType.class; } /** * Method getNameSpacePrefix. * * @return the namespace prefix to use when marshaling as XML. */ @Override() public java.lang.String getNameSpacePrefix( ) { return _nsPrefix; } /** * Method getNameSpaceURI. * * @return the namespace URI used when marshaling and * unmarshaling as XML. */ @Override() public java.lang.String getNameSpaceURI( ) { return _nsURI; } /** * Method getValidator. * * @return a specific validator for the class described by this * ClassDescriptor. */ @Override() public org.exolab.castor.xml.TypeValidator getValidator( ) { return this; } /** * Method getXMLName. * * @return the XML Name for the Class being described. */ @Override() public java.lang.String getXMLName( ) { return _xmlName; } /** * Method isElementDefinition. * * @return true if XML schema definition of this Class is that * of a global * element or element with anonymous type definition. */ public boolean isElementDefinition( ) { return _elementDefinition; } }
galleon1/chocolate-milk
src/org/chocolate_milk/model/descriptors/CreditCardCreditModRqTypeDescriptor.java
Java
lgpl-3.0
10,197
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.technicaldebt.server.internal; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.WorkUnit; import org.sonar.api.utils.internal.WorkDuration; import static org.fest.assertions.Assertions.assertThat; public class DefaultCharacteristicTest { @Test public void test_setters_and_getters_for_characteristic() throws Exception { DefaultCharacteristic characteristic = new DefaultCharacteristic() .setId(1) .setKey("NETWORK_USE") .setName("Network use") .setOrder(5) .setParentId(2) .setRootId(2); assertThat(characteristic.id()).isEqualTo(1); assertThat(characteristic.key()).isEqualTo("NETWORK_USE"); assertThat(characteristic.name()).isEqualTo("Network use"); assertThat(characteristic.order()).isEqualTo(5); assertThat(characteristic.ruleKey()).isNull(); assertThat(characteristic.function()).isNull(); assertThat(characteristic.factorValue()).isNull(); assertThat(characteristic.factorUnit()).isNull(); assertThat(characteristic.offsetValue()).isNull(); assertThat(characteristic.offsetUnit()).isNull(); assertThat(characteristic.parentId()).isEqualTo(2); assertThat(characteristic.rootId()).isEqualTo(2); } @Test public void test_setters_and_getters_for_requirement() throws Exception { DefaultCharacteristic requirement = new DefaultCharacteristic() .setId(1) .setRuleKey(RuleKey.of("repo", "rule")) .setFunction("linear_offset") .setFactorValue(2) .setFactorUnit(WorkDuration.UNIT.MINUTES) .setOffsetValue(1) .setOffsetUnit(WorkDuration.UNIT.HOURS) .setRootId(3) .setParentId(2); assertThat(requirement.id()).isEqualTo(1); assertThat(requirement.key()).isNull(); assertThat(requirement.name()).isNull(); assertThat(requirement.order()).isNull(); assertThat(requirement.ruleKey()).isEqualTo(RuleKey.of("repo", "rule")); assertThat(requirement.function()).isEqualTo("linear_offset"); assertThat(requirement.factorValue()).isEqualTo(2); assertThat(requirement.factorUnit()).isEqualTo(WorkDuration.UNIT.MINUTES); assertThat(requirement.offsetValue()).isEqualTo(1); assertThat(requirement.offsetUnit()).isEqualTo(WorkDuration.UNIT.HOURS); assertThat(requirement.parentId()).isEqualTo(2); assertThat(requirement.rootId()).isEqualTo(3); } @Test public void is_root() throws Exception { DefaultCharacteristic characteristic = new DefaultCharacteristic() .setId(1) .setKey("NETWORK_USE") .setName("Network use") .setOrder(5) .setParentId(null) .setRootId(null); assertThat(characteristic.isRoot()).isTrue(); } @Test public void is_requirement() throws Exception { DefaultCharacteristic requirement = new DefaultCharacteristic() .setId(1) .setRuleKey(RuleKey.of("repo", "rule")) .setFunction("linear_offset") .setFactorValue(2) .setFactorUnit(WorkDuration.UNIT.MINUTES) .setOffsetValue(1) .setOffsetUnit(WorkDuration.UNIT.HOURS) .setRootId(3) .setParentId(2); assertThat(requirement.isRequirement()).isTrue(); } @Test public void test_equals() throws Exception { assertThat(new DefaultCharacteristic().setKey("NETWORK_USE")).isEqualTo(new DefaultCharacteristic().setKey("NETWORK_USE")); assertThat(new DefaultCharacteristic().setKey("NETWORK_USE")).isNotEqualTo(new DefaultCharacteristic().setKey("MAINTABILITY")); assertThat(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule"))).isEqualTo(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule"))); assertThat(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule"))).isNotEqualTo(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo2", "rule2"))); } @Test public void test_hascode() throws Exception { assertThat(new DefaultCharacteristic().setKey("NETWORK_USE").hashCode()).isEqualTo(new DefaultCharacteristic().setKey("NETWORK_USE").hashCode()); assertThat(new DefaultCharacteristic().setKey("NETWORK_USE").hashCode()).isNotEqualTo(new DefaultCharacteristic().setKey("MAINTABILITY").hashCode()); assertThat(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule")).hashCode()).isEqualTo(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule")).hashCode()); assertThat(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule")).hashCode()).isNotEqualTo(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo2", "rule2")).hashCode()); } @Test public void test_deprecated_setters_and_getters_for_characteristic() throws Exception { DefaultCharacteristic requirement = new DefaultCharacteristic() .setId(1) .setRuleKey(RuleKey.of("repo", "rule")) .setFunction("linear_offset") .setFactor(WorkUnit.create(2d, WorkUnit.MINUTES)) .setOffset(WorkUnit.create(1d, WorkUnit.HOURS)); assertThat(requirement.factor()).isEqualTo(WorkUnit.create(2d, WorkUnit.MINUTES)); assertThat(requirement.offset()).isEqualTo(WorkUnit.create(1d, WorkUnit.HOURS)); assertThat(new DefaultCharacteristic() .setId(1) .setRuleKey(RuleKey.of("repo", "rule")) .setFunction("linear") .setFactor(WorkUnit.create(2d, WorkUnit.DAYS)) .factor()).isEqualTo(WorkUnit.create(2d, WorkUnit.DAYS)); } }
teryk/sonarqube
sonar-plugin-api/src/test/java/org/sonar/api/technicaldebt/server/internal/DefaultCharacteristicTest.java
Java
lgpl-3.0
6,276
/* * @BEGIN LICENSE * * Psi4: an open-source quantum chemistry software package * * Copyright (c) 2007-2018 The Psi4 Developers. * * The copyrights for code used from other parties are included in * the corresponding files. * * This file is part of Psi4. * * Psi4 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, version 3. * * Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @END LICENSE */ #ifndef __math_test_uhf_h__ #define __math_test_uhf_h__ #include "psi4/libpsio/psio.hpp" #include "hf.h" namespace psi { namespace scf { class UHF : public HF { protected: SharedMatrix Dt_, Dt_old_; SharedMatrix Da_old_, Db_old_; SharedMatrix Ga_, Gb_, J_, Ka_, Kb_, wKa_, wKb_; void form_initialF(); void form_C(); void form_V(); void form_D(); double compute_initial_E(); virtual double compute_E(); virtual bool stability_analysis(); bool stability_analysis_pk(); virtual void form_G(); virtual void form_F(); virtual void compute_orbital_gradient(bool save_diis); bool diis(); bool test_convergency(); void save_information(); void common_init(); void save_density_and_energy(); // Finalize memory/files virtual void finalize(); // Scaling factor for orbital rotation double step_scale_; // Increment to explore different scaling factors double step_increment_; // Stability eigenvalue, for doing smart eigenvector following double stab_val; // Compute UHF NOs void compute_nos(); // Damp down the density update virtual void damp_update(); // Second-order convergence code void Hx(SharedMatrix x_a, SharedMatrix IFock_a, SharedMatrix Cocc_a, SharedMatrix Cvir_a, SharedMatrix ret_a, SharedMatrix x_b, SharedMatrix IFock_b, SharedMatrix Cocc_b, SharedMatrix Cvir_b, SharedMatrix ret_b); virtual int soscf_update(void); public: UHF(SharedWavefunction ref_wfn, std::shared_ptr<SuperFunctional> functional); UHF(SharedWavefunction ref_wfn, std::shared_ptr<SuperFunctional> functional, Options& options, std::shared_ptr<PSIO> psio); virtual ~UHF(); virtual bool same_a_b_orbs() const { return false; } virtual bool same_a_b_dens() const { return false; } /// Hessian-vector computers and solvers virtual std::vector<SharedMatrix> onel_Hx(std::vector<SharedMatrix> x); virtual std::vector<SharedMatrix> twoel_Hx(std::vector<SharedMatrix> x, bool combine = true, std::string return_basis = "MO"); virtual std::vector<SharedMatrix> cphf_Hx(std::vector<SharedMatrix> x); virtual std::vector<SharedMatrix> cphf_solve(std::vector<SharedMatrix> x_vec, double conv_tol = 1.e-4, int max_iter = 10, int print_lvl = 1); std::shared_ptr<UHF> c1_deep_copy(std::shared_ptr<BasisSet> basis); }; }} #endif
amjames/psi4
psi4/src/psi4/libscf_solver/uhf.h
C
lgpl-3.0
3,521
// Created file "Lib\src\ksuser\X64\guids" typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } DEFINE_GUID(IID_IKsAggregateControl, 0x7f40eac0, 0x3947, 0x11d2, 0x87, 0x4e, 0x00, 0xa0, 0xc9, 0x22, 0x31, 0x96);
Frankie-PellesC/fSDK
Lib/src/ksuser/X64/guids000001B3.c
C
lgpl-3.0
459
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QDECLARATIVECOMPONENT_P_H #define QDECLARATIVECOMPONENT_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include "qdeclarativecomponent.h" #include "private/qdeclarativeengine_p.h" #include "private/qdeclarativetypeloader_p.h" #include "private/qbitfield_p.h" #include "qdeclarativeerror.h" #include "qdeclarative.h" #include <QtCore/QString> #include <QtCore/QStringList> #include <QtCore/QList> #include <private/qobject_p.h> QT_BEGIN_NAMESPACE class QDeclarativeComponent; class QDeclarativeEngine; class QDeclarativeCompiledData; class QDeclarativeComponentAttached; class Q_AUTOTEST_EXPORT QDeclarativeComponentPrivate : public QObjectPrivate, public QDeclarativeTypeData::TypeDataCallback { Q_DECLARE_PUBLIC(QDeclarativeComponent) public: QDeclarativeComponentPrivate() : typeData(0), progress(0.), start(-1), count(-1), cc(0), engine(0), creationContext(0) {} QObject *beginCreate(QDeclarativeContextData *, const QBitField &); void completeCreate(); QDeclarativeTypeData *typeData; virtual void typeDataReady(QDeclarativeTypeData *) {}; virtual void typeDataProgress(QDeclarativeTypeData *, qreal) {}; void fromTypeData(QDeclarativeTypeData *data); QUrl url; qreal progress; int start; int count; QDeclarativeCompiledData *cc; struct ConstructionState { ConstructionState() : componentAttached(0), completePending(false) {} QList<QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding> > bindValues; QList<QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus> > parserStatus; QList<QPair<QDeclarativeGuard<QObject>, int> > finalizedParserStatus; QDeclarativeComponentAttached *componentAttached; QList<QDeclarativeError> errors; bool completePending; }; ConstructionState state; static QObject *begin(QDeclarativeContextData *parentContext, QDeclarativeContextData *componentCreationContext, QDeclarativeCompiledData *component, int start, int count, ConstructionState *state, QList<QDeclarativeError> *errors, const QBitField &bindings = QBitField()); static void beginDeferred(QDeclarativeEnginePrivate *enginePriv, QObject *object, ConstructionState *state); static void complete(QDeclarativeEnginePrivate *enginePriv, ConstructionState *state); QScriptValue createObject(QObject *publicParent, const QScriptValue valuemap); QDeclarativeEngine *engine; QDeclarativeGuardedContextData creationContext; void clear(); static QDeclarativeComponentPrivate *get(QDeclarativeComponent *c) { return static_cast<QDeclarativeComponentPrivate *>(QObjectPrivate::get(c)); } }; class QDeclarativeComponentAttached : public QObject { Q_OBJECT public: QDeclarativeComponentAttached(QObject *parent = 0); virtual ~QDeclarativeComponentAttached() {}; void add(QDeclarativeComponentAttached **a) { prev = a; next = *a; *a = this; if (next) next->prev = &next; } void rem() { if (next) next->prev = prev; *prev = next; next = 0; prev = 0; } QDeclarativeComponentAttached **prev; QDeclarativeComponentAttached *next; Q_SIGNALS: void completed(); void destruction(); private: friend class QDeclarativeContextData; friend class QDeclarativeComponentPrivate; }; QT_END_NAMESPACE #endif // QDECLARATIVECOMPONENT_P_H
vakkov/qt-components-hildon
src/components/private/qdeclarativecomponent_p.h
C
lgpl-3.0
5,239
'use strict'; const chai = require('chai'); const assert = chai.assert; const sinon = require('sinon'); const responseError = require('../../../server/utils/errors/responseError'); describe('responseError', () => { let spyCall; const res = {}; let error = 'An error message'; beforeEach(() => { res.status = sinon.stub().returns(res); res.json = sinon.stub(); responseError(error, res); }); it('Calls response method with default(500) error code', () => { spyCall = res.status.getCall(0); assert.isTrue(res.status.calledOnce); assert.isTrue(spyCall.calledWithExactly(500)); }); it('Returns error wrapped in json response', () => { spyCall = res.json.getCall(0); assert.isTrue(res.json.calledOnce); assert.isObject(spyCall.args[0]); assert.property(spyCall.args[0], 'response', 'status'); }); it('Calls response method with custom error code', () => { error = { description: 'Bad request', status_code: 400, }; responseError(error, res); spyCall = res.status.getCall(0); assert.isTrue(res.status.called); assert.isTrue(res.status.calledWithExactly(400)); }); });
kn9ts/project-mulla
test/utils/errors/reponseError.js
JavaScript
lgpl-3.0
1,168
/* * Copyright (c) 2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef B2_DYNAMIC_TREE_H #define B2_DYNAMIC_TREE_H #include <Box2D/Collision/b2Collision.h> #include <Box2D/Common/b2GrowableStack.h> #define b2_nullNode (-1) /// A node in the dynamic tree. The client does not interact with this directly. struct b2TreeNode { bool IsLeaf() const { return child1 == b2_nullNode; } /// Enlarged AABB b2AABB aabb; void* userData; union { int32 parent; int32 next; }; int32 child1; int32 child2; // leaf = 0, free node = -1 int32 height; }; /// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. /// A dynamic tree arranges data in a binary tree to accelerate /// queries such as volume queries and ray casts. Leafs are proxies /// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor /// so that the proxy AABB is bigger than the client object. This allows the client /// object to move by small amounts without triggering a tree update. /// /// Nodes are pooled and relocatable, so we use node indices rather than pointers. class b2DynamicTree { public: /// Constructing the tree initializes the node pool. b2DynamicTree(); /// Destroy the tree, freeing the node pool. ~b2DynamicTree(); /// create a proxy. Provide a tight fitting AABB and a userData pointer. int32 CreateProxy(const b2AABB& aabb, void* userData); /// Destroy a proxy. This asserts if the id is invalid. void DestroyProxy(int32 proxyId); /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, /// then the proxy is removed from the tree and re-inserted. Otherwise /// the function returns immediately. /// @return true if the proxy was re-inserted. bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); /// Get proxy user data. /// @return the proxy user data or 0 if the id is invalid. void* GetUserData(int32 proxyId) const; /// Get the fat AABB for a proxy. const b2AABB& GetFatAABB(int32 proxyId) const; /// Query an AABB for overlapping proxies. The callback class /// is called for each proxy that overlaps the supplied AABB. template <typename T> void Query(T* callback, const b2AABB& aabb) const; /// Ray-cast against the proxies in the tree. This relies on the callback /// to perform a exact ray-cast in the case were the proxy contains a shape. /// The callback also performs the any collision filtering. This has performance /// roughly equal to k * log(n), where k is the number of collisions and n is the /// number of proxies in the tree. /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). /// @param callback a callback class that is called for each proxy that is hit by the ray. template <typename T> void RayCast(T* callback, const b2RayCastInput& input) const; /// Validate this tree. For testing. void Validate() const; /// Compute the height of the binary tree in O(N) time. Should not be /// called often. int32 GetHeight() const; /// Get the maximum balance of an node in the tree. The balance is the difference /// in height of the two children of a node. int32 GetMaxBalance() const; /// Get the ratio of the sum of the node areas to the root area. float32 GetAreaRatio() const; /// Build an optimal tree. Very expensive. For testing. void RebuildBottomUp(); private: int32 AllocateNode(); void FreeNode(int32 node); void InsertLeaf(int32 node); void RemoveLeaf(int32 node); int32 Balance(int32 index); int32 ComputeHeight() const; int32 ComputeHeight(int32 nodeId) const; void ValidateStructure(int32 index) const; void ValidateMetrics(int32 index) const; int32 m_root; b2TreeNode* m_nodes; int32 m_nodeCount; int32 m_nodeCapacity; int32 m_freeList; /// This is used to incrementally traverse the tree for re-balancing. uint32 m_path; int32 m_insertionCount; }; inline void* b2DynamicTree::GetUserData(int32 proxyId) const { b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); return m_nodes[proxyId].userData; } inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const { b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); return m_nodes[proxyId].aabb; } template <typename T> inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const { b2GrowableStack<int32, 256> stack; stack.Push(m_root); while (stack.GetCount() > 0) { int32 nodeId = stack.Pop(); if (nodeId == b2_nullNode) { continue; } const b2TreeNode* node = m_nodes + nodeId; if (b2TestOverlap(node->aabb, aabb)) { if (node->IsLeaf()) { bool proceed = callback->QueryCallback(nodeId); if (proceed == false) { return; } } else { stack.Push(node->child1); stack.Push(node->child2); } } } } template <typename T> inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const { b2Vec2 p1 = input.p1; b2Vec2 p2 = input.p2; b2Vec2 r = p2 - p1; b2Assert(r.LengthSquared() > 0.0f); r.Normalize(); // v is perpendicular to the segment. b2Vec2 v = b2Cross(1.0f, r); b2Vec2 abs_v = b2Abs(v); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) float32 maxFraction = input.maxFraction; // Build a bounding box for the segment. b2AABB segmentAABB; { b2Vec2 t = p1 + maxFraction * (p2 - p1); segmentAABB.lowerBound = b2Min(p1, t); segmentAABB.upperBound = b2Max(p1, t); } b2GrowableStack<int32, 256> stack; stack.Push(m_root); while (stack.GetCount() > 0) { int32 nodeId = stack.Pop(); if (nodeId == b2_nullNode) { continue; } const b2TreeNode* node = m_nodes + nodeId; if (b2TestOverlap(node->aabb, segmentAABB) == false) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) b2Vec2 c = node->aabb.GetCenter(); b2Vec2 h = node->aabb.GetExtents(); float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); if (separation > 0.0f) { continue; } if (node->IsLeaf()) { b2RayCastInput subInput; subInput.p1 = input.p1; subInput.p2 = input.p2; subInput.maxFraction = maxFraction; float32 value = callback->RayCastCallback(subInput, nodeId); if (value == 0.0f) { // The client has terminated the ray cast. return; } if (value > 0.0f) { // Update segment bounding box. maxFraction = value; b2Vec2 t = p1 + maxFraction * (p2 - p1); segmentAABB.lowerBound = b2Min(p1, t); segmentAABB.upperBound = b2Max(p1, t); } } else { stack.Push(node->child1); stack.Push(node->child2); } } } #endif
gameview/WareCocos2dx
external/Box2D/Collision/b2DynamicTree.h
C
lgpl-3.0
8,362
package GT::Signals::Graphical::CandleSticks::BullishHarami; # Copyright (C) 2007 M.K.Pai # # 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., 675 Mass Ave, Cambridge, MA 02139, USA. use strict; use vars qw(@ISA @NAMES); use GT::Signals; use GT::Prices; use GT::Indicators::CNDL; @ISA = qw(GT::Signals); @NAMES = ("BullishHarami"); =head1 GT::Signals::Graphical::CandleSticks::BullishHarami =head2 Overview The Bullish Harami signifies a decrease of momentum. It occurs when a small bullish (empty) line occurs after a large bearish (filled) line in such a way that close of the bullish line is above the open of the bearish line and the open of the bullish line is lower than the close of the bearish line. The Bullish Harami is a mirror image of the Bearish Engulfing Line. =head2 Construction If yesterday closed higher, a Bullish Harami will form when today's open is above yesterday's close and today's close is above yesterday's open. =head2 Representation | ### ### _|_ ### | | ### |___| ### | ### | Bullish Harami =head2 Links 1. More information about the bullish harami on Page 33 of the book "Candlestick Charting Explained" by Gregory L. Morris. Morris says that this pattern suggests a trend change. 2. Steve Nison also says that the Harami Patterns suggest a trend change. This is on page 80 of his book "Japanese Candlesticks Charting Techniques". 3. http://www.equis.com/Customer/Resources/TAAZ/. =cut sub new { my $type = shift; my $class = ref($type) || $type; my $args = shift; my $self = { "args" => defined($args) ? $args : [] }; return manage_object(\@NAMES, $self, $class, $self->{'args'}, ""); } sub initialize { my ($self) = @_; $self->{'cndl'} = GT::Indicators::CNDL->new($self->{'args'}); $self->add_indicator_dependency($self->{'cndl'}, 2); } sub detect { my ($self, $calc, $i) = @_; my $prices = $calc->prices; my $cndl_name = $self->{'cndl'}->get_name(0); my $bullish_harami_name = $self->get_name(0);; return if ($calc->signals->is_available($self->get_name(0), $i)); return if (! $self->check_dependencies($calc, $i)); my $previous_cndl_code = $calc->indicators->get($cndl_name, $i - 1); my $cndl_code = $calc->indicators->get($cndl_name, $i); # Previous CandleCode from 0 to 15 # CandleCode from 80 to 111 if (($previous_cndl_code >= 0) and ($previous_cndl_code <= 15) and ($cndl_code >= 80) and ($cndl_code <= 111) and ($prices->at($i)->[$OPEN] > $prices->at($i - 1)->[$CLOSE]) and ($prices->at($i)->[$CLOSE] < $prices->at($i - 1)->[$OPEN]) ) { $calc->signals->set($bullish_harami_name, $i, 1); } else { $calc->signals->set($bullish_harami_name, $i, 0); } } 1;
hunterfu/it-manager
stock_tech/GeniusTrader/GT/Signals/Graphical/CandleSticks/BullishHarami.pm
Perl
lgpl-3.0
3,550
worldstate-analysis-widgets [![Build Status](http://ci.cismet.de/buildStatus/icon?job=worldstate-analysis-widgets)](https://ci.cismet.de/view/html5%20javascript/job/worldstate-analysis-widgets/) =========================== The AngularJS implementation of the Scenario Comparison and Analysis and the Multi-Criteria-Analysis and Decision Support Functional Building Block. ![worldstate_analysis_widgets_example](https://cloud.githubusercontent.com/assets/973421/4491054/3979b86c-4a34-11e4-800f-034f4612860d.png) ## Get started Simply pull in the libraries and all the dependencies via [bower](http://bower.io/) ```sh bower install --save worldstate-analysis-widgets ``` There is a number of directives that are useful for the different parts of the worldstate analysis. Currently the best way to get a grip on the usage, see the <code>index.html</code> of this repo. Pull in and wire toghether the directives that you want to use in your application accordingly. However, this will only work correctly if you provide info where to find the ICMM instance to use: ```javascript angular.module( 'myCoolModule' ).config( [ '$provide', function ($provide) { 'use strict'; $provide.constant('CRISMA_DOMAIN', 'CRISMA'); // the name of the CRISMA domain to use $provide.constant('CRISMA_ICMM_API', 'http://url/to/the/icmm/api'); // the url to the API of the ICMM instance to use } } ] ); ``` ## Demo Simply checkout the project and put the app folder in your favourite web server, or even more simple, use grunt to fire up a web server for you ```sh grunt serve ```
crismaproject/worldstate-analysis-widgets
README.md
Markdown
lgpl-3.0
1,644
#include "sensorcontrol.h" using namespace oi; /*! * \brief SensorControl::SensorControl * \param station * \param parent */ SensorControl::SensorControl(QPointer<Station> &station, QObject *parent) : QObject(parent), station(station), sensorValid(false){ this->worker = new SensorWorker(); this->connectSensorWorker(); } /*! * \brief SensorControl::~SensorControl */ SensorControl::~SensorControl(){ this->disconnectSensorWorker(); } /*! * \brief SensorControl::getSensor * Returns a copy of the current sensor * \return */ Sensor SensorControl::getSensor(){ //get sensor Sensor sensor; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSensor", Qt::DirectConnection, Q_RETURN_ARG(Sensor, sensor)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return sensor; } /*! * \brief SensorControl::setSensor * Sets the current sensor to the given one * \param sensor */ void SensorControl::setSensor(const QPointer<Sensor> &sensor){ //check sensor if(sensor.isNull()){ return; } //check old sensor and add it to the list of used sensors if(sensorValid){ this->usedSensors.append(this->getSensor()); } //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "setSensor", Qt::DirectConnection, Q_ARG(QPointer<Sensor>, sensor)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } //set sensor valid this->sensorValid = true; } /*! * \brief SensorControl::takeSensor * Returns the current sensor instance. That sensor will no longer be used by the sensor worker * \return */ QPointer<Sensor> SensorControl::takeSensor(){ //check old sensor and add it to the list of used sensors if(sensorValid){ this->usedSensors.append(this->getSensor()); } //call method of sensor worker QPointer<Sensor> sensor(NULL); bool hasInvoked = QMetaObject::invokeMethod(this->worker, "takeSensor", Qt::DirectConnection, Q_RETURN_ARG(QPointer<Sensor>, sensor)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } //set sensor invalid this->sensorValid = false; return sensor; } /*! * \brief SensorControl::resetSensor * Disconnects and deletes the current sensor */ void SensorControl::resetSensor(){ //check old sensor and add it to the list of used sensors if(sensorValid){ this->usedSensors.append(this->getSensor()); } //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "resetSensor", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } //set sensor invalid this->sensorValid = false; } /*! * \brief SensorControl::getUsedSensors * \return */ const QList<Sensor> &SensorControl::getUsedSensors(){ return this->usedSensors; } /*! * \brief SensorControl::setUsedSensors * \param sensors */ void SensorControl::setUsedSensors(const QList<Sensor> &sensors){ this->usedSensors = sensors; } /*! * \brief SensorControl::getStreamFormat * \return */ ReadingTypes SensorControl::getStreamFormat(){ //call method of sensor worker ReadingTypes type = eUndefinedReading; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getStreamFormat", Qt::DirectConnection, Q_RETURN_ARG(ReadingTypes, type)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return type; } /*! * \brief SensorControl::setStreamFormat * \param streamFormat */ void SensorControl::setStreamFormat(ReadingTypes streamFormat){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "setStreamFormat", Qt::QueuedConnection, Q_ARG(ReadingTypes, streamFormat)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::getIsSensorSet * \return */ bool SensorControl::getIsSensorSet(){ return this->sensorValid; } /*! * \brief SensorControl::getIsSensorConnected * \return */ bool SensorControl::getIsSensorConnected(){ //call method of sensor worker bool isConnected = false; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getIsSensorConnected", Qt::DirectConnection, Q_RETURN_ARG(bool, isConnected)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return isConnected; } /*! * \brief SensorControl::getIsReadyForMeasurement * \return */ bool SensorControl::getIsReadyForMeasurement(){ //call method of sensor worker bool isReady = false; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getIsReadyForMeasurement", Qt::DirectConnection, Q_RETURN_ARG(bool, isReady)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return isReady; } /*! * \brief SensorControl::getIsBusy * \return */ bool SensorControl::getIsBusy(){ //call method of sensor worker bool isBusy = false; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getIsBusy", Qt::DirectConnection, Q_RETURN_ARG(bool, isBusy)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return isBusy; } /*! * \brief SensorControl::getSensorStatus * \return */ QMap<QString, QString> SensorControl::getSensorStatus(){ //call method of sensor worker QMap<QString, QString> status; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSensorStatus", Qt::DirectConnection, Q_RETURN_ARG(StringStringMap, status)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return status; } /*! * \brief SensorControl::getActiveSensorType * \return */ SensorTypes SensorControl::getActiveSensorType(){ //call method of sensor worker SensorTypes type; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getActiveSensorType", Qt::DirectConnection, Q_RETURN_ARG(SensorTypes, type)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return type; } /*! * \brief SensorControl::getSupportedReadingTypes * \return */ QList<ReadingTypes> SensorControl::getSupportedReadingTypes(){ //call method of sensor worker QList<ReadingTypes> types; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSupportedReadingTypes", Qt::DirectConnection, Q_RETURN_ARG(QList<ReadingTypes>, types)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return types; } /*! * \brief SensorControl::getSupportedConnectionTypes * \return */ QList<ConnectionTypes> SensorControl::getSupportedConnectionTypes(){ //call method of sensor worker QList<ConnectionTypes> types; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSupportedConnectionTypes", Qt::DirectConnection, Q_RETURN_ARG(QList<ConnectionTypes>, types)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return types; } /*! * \brief SensorControl::getSupportedSensorActions * \return */ QList<SensorFunctions> SensorControl::getSupportedSensorActions(){ //call method of sensor worker QList<SensorFunctions> actions; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSupportedSensorActions", Qt::DirectConnection, Q_RETURN_ARG(QList<SensorFunctions>, actions)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return actions; } /*! * \brief SensorControl::getSelfDefinedActions * \return */ QStringList SensorControl::getSelfDefinedActions(){ //call method of sensor worker QStringList actions; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSelfDefinedActions", Qt::DirectConnection, Q_RETURN_ARG(QStringList, actions)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return actions; } /*! * \brief SensorControl::getSensorConfiguration * \return */ SensorConfiguration SensorControl::getSensorConfiguration(){ //call method of sensor worker SensorConfiguration sConfig; bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSensorConfiguration", Qt::DirectConnection, Q_RETURN_ARG(SensorConfiguration, sConfig)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } return sConfig; } /*! * \brief SensorControl::setSensorConfiguration * \param sConfig */ void SensorControl::setSensorConfiguration(const SensorConfiguration &sConfig){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "setSensorConfiguration", Qt::QueuedConnection, Q_ARG(SensorConfiguration, sConfig)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::connectSensor */ void SensorControl::connectSensor(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "connectSensor", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::disconnectSensor */ void SensorControl::disconnectSensor(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "disconnectSensor", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::measure * \param geomId * \param mConfig */ void SensorControl::measure(const int &geomId, const MeasurementConfig &mConfig){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "measure", Qt::QueuedConnection, Q_ARG(int, geomId), Q_ARG(MeasurementConfig, mConfig)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::move * \param azimuth * \param zenith * \param distance * \param isRelative * \param measure * \param geomId * \param mConfig */ void SensorControl::move(const double &azimuth, const double &zenith, const double &distance, const bool &isRelative, const bool &measure, const int &geomId, const MeasurementConfig &mConfig){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "move", Qt::QueuedConnection, Q_ARG(double, azimuth), Q_ARG(double, zenith), Q_ARG(double, distance), Q_ARG(bool, isRelative), Q_ARG(bool, measure), Q_ARG(int, geomId), Q_ARG(MeasurementConfig, mConfig)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::move * \param x * \param y * \param z * \param measure * \param geomId * \param mConfig */ void SensorControl::move(const double &x, const double &y, const double &z, const bool &measure, const int &geomId, const MeasurementConfig &mConfig){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "move", Qt::QueuedConnection, Q_ARG(double, x), Q_ARG(double, y), Q_ARG(double, z), Q_ARG(bool, measure), Q_ARG(int, geomId), Q_ARG(MeasurementConfig, mConfig)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::initialize */ void SensorControl::initialize(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "initialize", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::motorState */ void SensorControl::motorState(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "motorState", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::home */ void SensorControl::home(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "home", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::toggleSight */ void SensorControl::toggleSight(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "toggleSight", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::compensation */ void SensorControl::compensation(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "compensation", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::selfDefinedAction * \param action */ void SensorControl::selfDefinedAction(const QString &action){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "selfDefinedAction", Qt::QueuedConnection, Q_ARG(QString, action)); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } void SensorControl::search(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "search", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::startReadingStream */ void SensorControl::startReadingStream(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "startReadingStream", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::stopReadingStream */ void SensorControl::stopReadingStream(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "stopReadingStream", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::startConnectionMonitoringStream */ void SensorControl::startConnectionMonitoringStream(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "startConnectionMonitoringStream", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::stopConnectionMonitoringStream */ void SensorControl::stopConnectionMonitoringStream(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "stopConnectionMonitoringStream", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::startStatusMonitoringStream */ void SensorControl::startStatusMonitoringStream(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "startStatusMonitoringStream", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::stopStatusMonitoringStream */ void SensorControl::stopStatusMonitoringStream(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "stopStatusMonitoringStream", Qt::QueuedConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } void SensorControl::finishMeasurement(){ //call method of sensor worker bool hasInvoked = QMetaObject::invokeMethod(this->worker, "finishMeasurement", Qt::DirectConnection); if(!hasInvoked){ emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage); } } /*! * \brief SensorControl::connectSensorWorker */ void SensorControl::connectSensorWorker(){ //connect sensor action results QObject::connect(this->worker, &SensorWorker::commandFinished, this, &SensorControl::commandFinished, Qt::QueuedConnection); QObject::connect(this->worker, &SensorWorker::measurementFinished, this, &SensorControl::measurementFinished, Qt::QueuedConnection); QObject::connect(this->worker, &SensorWorker::measurementDone, this, &SensorControl::measurementDone, Qt::QueuedConnection); //connect streaming results QObject::connect(this->worker, &SensorWorker::realTimeReading, this, &SensorControl::realTimeReading, Qt::QueuedConnection); QObject::connect(this->worker, &SensorWorker::realTimeStatus, this, &SensorControl::realTimeStatus, Qt::QueuedConnection); QObject::connect(this->worker, &SensorWorker::connectionLost, this, &SensorControl::connectionLost, Qt::QueuedConnection); QObject::connect(this->worker, &SensorWorker::connectionReceived, this, &SensorControl::connectionReceived, Qt::QueuedConnection); QObject::connect(this->worker, &SensorWorker::isReadyForMeasurement, this, &SensorControl::isReadyForMeasurement, Qt::QueuedConnection); //connect sensor messages QObject::connect(this->worker, &SensorWorker::sensorMessage, this, &SensorControl::sensorMessage, Qt::QueuedConnection); } /*! * \brief SensorControl::disconnectSensorWorker */ void SensorControl::disconnectSensorWorker(){ } void SensorControl::setSensorWorkerThread(QPointer<QThread> t) { this->worker->moveToThread(t); }
OpenIndy/OpenIndy-Core
src/sensorcontrol.cpp
C++
lgpl-3.0
20,686
#bo general settings #set default start location Set-Location C:\ #change how powershell does tab completion #@see: http://stackoverflow.com/questions/39221953/can-i-make-powershell-tab-complete-show-me-all-options-rather-than-picking-a-sp Set-PSReadlineKeyHandler -Chord Tab -Function MenuComplete #eo general settings #bo variables $isElevated = [System.Security.Principal.WindowsPrincipal]::New( [System.Security.Principal.WindowsIdentity]::GetCurrent() ).IsInRole( [System.Security.Principal.WindowsBuiltInRole]::Administrator ) $configurationSourcePath = (Split-Path $profile -Parent) $localConfigurationFilePath = $($configurationSourcePath + "\local.profile.ps1") #eo variables #bo functions #@see: https://github.com/gummesson/kapow/blob/master/themes/bashlet.ps1 #a Function Add-StarsToTheBeginningAndTheEndOfAStringIfNeeded () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $String ) If ($String.StartsWith("*") -eq $false) { $String = $("*" + $String) } If ($String.EndsWith("*") -eq $false) { $String = $($String + "*") } Return $String } #e Function Execute-7zipAllDirectories () { [CmdletBinding()] Param( [Parameter(Mandatory=$false)] [String] $SourcePath = $PWD.Path ) $PreviousCurrentWorkingDirectory = $PWD.Path Set-Location -Path $SourcePath ForEach ($CurrentDirectory In Get-ChildItem -Path . -Depth 0 -Directory) { If (Test-Path -Path "${CurrentDirectory}.7z") { Write-Host ":: Skipping directory >>${CurrentDirectory}<<, >>${CurrentDirectory}.7z<< already exists." } Else { $ListOfArgument = @( 'a' '-t7z' '-mx9' "${CurrentDirectory}.7z" "${CurrentDirectory}" ) Write-Verbose ":: Processing directory >>${CurrentDirectory}<<." Start-Process 7z.exe -ArgumentList $ListOfArgument -NoNewWindow -Wait Write-Host ":: Archiving done, please delete directory >>${CurrentDirectory}<<." } } Set-Location -Path $PreviousCurrentWorkingDirectory } #f Function Find-Directory () { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string] $KeyWord, [Parameter(Mandatory = $false)] [string] $RootPath = $PWD.Path, [Parameter(Mandatory = $false)] [switch] $BeVerbose ) If ($BeVerbose.IsPresent) { Get-ChildItem $RootPath -Recurse -Directory | Where-Object {$_.Name -match "${KeyWord}"} } Else { Get-ChildItem $RootPath -Recurse -Directory -ErrorAction SilentlyContinue | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "${KeyWord}"} } } Function Find-File () { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string] $KeyWord, [Parameter(Mandatory = $false)] [string] $RootPath = $PWD.Path, [Parameter(Mandatory = $false)] [switch] $BeVerbose ) If ($BeVerbose.IsPresent) { Get-ChildItem $RootPath -Recurse -File | Where-Object {$_.Name -match "${KeyWord}"} } Else { Get-ChildItem $RootPath -Recurse -File -ErrorAction SilentlyContinue | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "${KeyWord}"} } } #g #@see https://sid-500.com/2019/07/30/powershell-retrieve-list-of-domain-computers-by-operating-system/ Function Get-ADComputerClientList () { Get-ADComputer -Filter { (OperatingSystem -notlike "*server*") -and (Enabled -eq $true) } ` -Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address | Sort-Object -Property Name | Select-Object -Property Name,Operatingsystem,OperatingSystemVersion,IPv4Address } #@see: https://sid-500.com/2019/07/30/powershell-retrieve-list-of-domain-computers-by-operating-system/ #@see: https://adsecurity.org/?p=873 Function Get-ADComputerDCList () { #primary group id: # 515 -> domain computer # 516 -> domain controller writeable (server) # 521 -> domain controller readable (client) Get-ADComputer -Filter { (PrimaryGroupId -eq 516) -or (PrimaryGroupId -eq 521) } ` -Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address,primarygroupid | Sort-Object -Property Name | Select-Object -Property Name,Operatingsystem,OperatingSystemVersion,IPv4Address,PrimaryGroupId | Format-Table } #@see: https://sid-500.com/2019/07/30/powershell-retrieve-list-of-domain-computers-by-operating-system/ Function Get-ADComputerList () { Get-ADComputer -Filter { (Enabled -eq $true) } ` -Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address,primarygroupid | Sort-Object -Property Name | Select-Object -Property Name,Operatingsystem,OperatingSystemVersion,IPv4Address,PrimaryGroupId | Format-Table } #@see https://sid-500.com/2019/07/30/powershell-retrieve-list-of-domain-computers-by-operating-system/ Function Get-ADComputerServerList () { Get-ADComputer -Filter { (OperatingSystem -like "*server*") -and (Enabled -eq $true) } ` -Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address,primarygroupid | Sort-Object -Property Name | Select-Object -Property Name,Operatingsystem,OperatingSystemVersion,IPv4Address,PrimaryGroupId | Format-Table } Function Get-ADGroupBySid () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $SID ) Get-ADGroup -Identity $SID } #@see: http://woshub.com/convert-sid-to-username-and-vice-versa/ Function Get-ADObjectBySid () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $SID ) Get-ADObject IncludeDeletedObjects -Filter "objectSid -eq '$SID'" | Select-Object name, objectClass } Function Get-ADUserBySid () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $SID ) Get-ADUser -Identity $SID } Function Get-IsSoftwareInstalled () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $SoftwareName ) #regular way to check $isInstalled = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where { $_.DisplayName -like "*$SoftwareName*" }) -ne $null #if we are running a 64bit windows, there is a place for 32bit software if (-Not $isInstalled) { #check if we are running 64 bit windows if (Test-Path HKLM:SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall) { $isInstalled = (Get-ItemProperty HKLM:SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where { $_.DisplayName -like "*$SoftwareName*" }) -ne $null } } #there is one legacy place left if (-Not $isInstalled) { $isInstalled = (Get-WmiObject -Class Win32_Product | WHERE { $_.Name -like "*$ProcessName*" }) } if (-Not $isInstalled) { Write-Host $("Software >>" + $SoftwareName + "<< is not installed.") } Else { Write-Host $("Software >>" + $SoftwareName + "<< is installed.") } } #@see: https://sid-500.com/2020/05/23/video-powershell-cmdlets-as-a-replacement-for-ping-arp-traceroute-and-nmap/ Function Get-ListOfLocalOpenPorts () { Get-NetTCPConnection -State Established,Listen | Sort-Object LocalPort } Function Get-UpTime () { [CmdletBinding()] Param ( [Parameter(Mandatory=$false,Position=0)] [String[]] $ListOfComputerName=$null ) $DataTable = @() $RequestForLocalHost = ($ListOfComputerName -eq $null) If ($RequestForLocalHost -eq $true) { $DateObject = (get-date) - (gcim Win32_OperatingSystem).LastBootUpTime $DataTable += [Pscustomobject]@{ComputerName = "LocalHost";Days = $DateObject.Days; Hours = $DateObject.Hours; Minutes = $DateObject.Minutes; Seconds= $DateObject.Seconds} } Else { Write-Host ":: Fetching uptime for remote computers." ForEach ($CurrentComputerName in $ListOfComputerName) { Write-Host -NoNewLine "." $DateObject = Invoke-Command -ComputerName $CurrentComputerName -ScriptBlock {(get-date) - (gcim Win32_OperatingSystem).LastBootUpTime} $DataTable += [Pscustomobject]@{ComputerName = $CurrentComputerName;Days = $DateObject.Days; Hours = $DateObject.Hours; Minutes = $DateObject.Minutes; Seconds= $DateObject.Seconds} } Write-Host "" } $DataTable | Format-Table } Function Get-UserLogon () { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [String] $ComputerName, [Parameter(Mandatory=$false)] [Int] $Days = 10 ) $ListOfEventSearches = @( <# @see: https://social.technet.microsoft.com/wiki/contents/articles/51413.active-directory-how-to-get-user-login-history-using-powershell.aspx Either this is not working on my environment or not working in general. I can't find any log entry with a UserName or something user related when searching for this id's in that log name. I've decided to keep it in and have a look on it again by figuring out how to use the existing code with the logic of the following post: https://adamtheautomator.com/user-logon-event-id/ @{ 'ID' = 4624 'LogName' = 'Security' 'EventType' = 'SessionStart' } @{ 'ID' = 4778 'LogName' = 'Security' 'EventType' = 'RdpSessionReconnect' } #> @{ 'ID' = 7001 'LogName' = 'System' 'EventType' = 'Logon' } ) $ListOfResultObjects = @{} $StartDate = (Get-Date).AddDays(-$Days) Write-Host $(":: Fetching event logs for the last >>" + $Days + "<< days. This will take a while.") ForEach ($EventSearch in $ListOfEventSearches) { Write-Host $(" Fetching events for id >>" + $EventSearch.ID + "<<, log name >>" + $EventSearch.LogName + "<<.") $ListOfEventLogs = Get-EventLog -ComputerName $ComputerName -InstanceId $EventSearch.ID -LogName $EventSearch.LogName -After $StartDate Write-Host $(" Processing >>" + $ListOfEventLogs.Count + "<< entries.") If ($ListOfEventLogs -ne $null) { ForEach ($EventLog in $ListOfEventLogs) { $StoreEventInTheResultList = $true If ($EventLog.InstanceId -eq 7001) { $EventType = "Logon" $User = (New-Object System.Security.Principal.SecurityIdentifier $EventLog.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount]) <# Same reason as mentioned in the $ListOfEventSearches } ElseIf ($EventLog.InstanceId -eq 4624) { If ($EventLog.ReplacementStrings[8] -eq 2) { $EventType = "Local Session Start" $User = (New-Object System.Security.Principal.SecurityIdentifier $EventLog.ReplacementStrings[5]).Translate([System.Security.Principal.NTAccount]) } ElseIf ($EventLog.ReplacementStrings[8] -eq 10) { $EventType = "Remote Session Start" $User = (New-Object System.Security.Principal.SecurityIdentifier $EventLog.ReplacementStrings[5]).Translate([System.Security.Principal.NTAccount]) } Else { $StoreEventInTheResultList = $false } } ElseIf ($EventLog.InstanceId -eq 4778) { $EventType = "RDPSession Reconnect" $User = (New-Object System.Security.Principal.SecurityIdentifier $EventLog.ReplacementStrings[5]).Translate([System.Security.Principal.NTAccount]) #> } Else { $StoreEventInTheResultList = $false } If ($StoreEventInTheResultList -eq $true) { $ResultListKey = $User.Value If ($ListOfResultObjects.ContainsKey($ResultListKey)) { $ResultObject = $ListOfResultObjects[$ResultListKey] If ($ResultObject.Time -lt $EventLog.TimeWritten ) { $ResultObject.Time = $EventLog.TimeWritten $ListOfResultObjects[$ResultListKey] = $ResultObject } } Else { $ResultObject = New-Object PSObject -Property @{ Time = $EventLog.TimeWritten 'Event Type' = $EventType User = $User } $ListOfResultObjects.Add($ResultListKey, $ResultObject) } } } } } If ($ListOfResultObjects -ne $null) { <# We are doing evil things. I have no idea how to output and sort the existing list. That is the reason why we create an array we can output and sort easily. #> $ArrayOfResultObjects = @() ForEach ($key in $ListOfResultObjects.Keys) { $ArrayOfResultObjects += $ListOfResultObjects[$key] } Write-Host $(":: Dumping >>" + $ListOfResultObjects.Count + "<< event logs.") $ArrayOfResultObjects | Select Time,"Event Type",User | Sort Time -Descending } Else { Write-Host ":: Could not find any matching event logs." } } #i #@see: https://matthewjdegarmo.com/powershell/2021/03/31/how-to-import-a-locally-defined-function-into-a-remote-powershell-session.html Function Invoke-LocalCommandRemotely () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [System.String[]] $FunctionName, [Parameter(Mandatory=$true,HelpMessage='Run >>$Session = New-PSSession -ComputerName <host name>')] $Session ) Process { $FunctionName | ForEach-Object { Try { #check if we can find a function for the current function name $CurrentFunction = Get-Command -Name $_ If ($CurrentFunction) { #if there is a function available # we create a script block with the name of the # function and the body of the found function #at the end, we copy the whole function into a # script block and this script block is # executed on the (remote) session $CurrentFunctionDefinition = @" $($CurrentFunction.CommandType) $_() { $($CurrentFunction.Definition) } "@ Invoke-Command -Session $Session -ScriptBlock { Param($CodeToLoadAsString) . ([ScriptBlock]::Create($CodeToLoadAsString)) } -ArgumentList $CurrentFunctionDefinition Write-Host $(':: You can now run >>Invoke-Command -Session $Session -ScriptBlock {' + $_ + '}<<.') } } Catch { Throw $_ } } } } #k #@see: https://github.com/mikemaccana/powershell-profile/blob/master/unix.ps1 Function Kill-Process () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $ProcessName ) Get-Process $ProcessName-ErrorAction SilentlyContinue | Stop-Process } #l Function List-UserOnHost () { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [String] $HostName, [Parameter(Mandatory=$false)] [String] $UserNameToFilterAgainstOrNull = $null ) #contains array of objects like: #>>USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME #>>randomnote1 console 1 Active none 8/14/2019 6:52 AM $arrayOfResultObjects = Invoke-Expression ("quser /server:$HostName"); #contains array of lines like: #>>USERNAME,SESSIONNAME,ID,STATE,IDLE TIME,LOGON TIME #>>randomnote1,console,1,Active,none,8/14/2019 6:52 AM $ArrayOfCommaSeparatedValues = $ArrayOfResultObjects | ForEach-Object -Process { $_ -replace '\s{2,}',',' } $ArrayOfUserObjects = $ArrayOfCommaSeparatedValues| ConvertFrom-Csv Write-Host $(":: Aktueller Host: " + $HostName) #@see: https://devblogs.microsoft.com/scripting/automating-quser-through-powershell/ #@see: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/query-user If ($UserNameToFilterAgainstOrNull -eq $null) { $ArrayOfUserObjects | Format-Table } Else { $ArrayOfUserObjects | Where-Object { ($_.USERNAME -like "*$UserNameToFilterAgainstOrNull*") -or ($_.BENUTZERNAME -like "*$UserNameToFilterAgainstOrNull*") } | Format-Table } } #m Function Mirror-UserSession () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $HostName, [Parameter(Mandatory=$false)] [String] $SessionId ) If (-not($SessionId)) { #no session id is used if there is no user logged in our you want # to login on a running pc mstsc.exe /v:$HostName } Else { #session id is used, ask if you can mirror the existing user session mstsc.exe /v:$HostName /shadow:$SessionId /control } } #p Function Prompt () { $promptColor = If ($isElevated) { "Red" } Else { "DarkGreen"} Write-Host "$env:username" -NoNewline -ForegroundColor $promptColor Write-Host "@" -NoNewline -ForegroundColor $promptColor Write-Host "$env:computername" -NoNewline -ForegroundColor $promptColor Write-Host " " -NoNewline #Write-Host $(Set-HomeDirectory("$pwd")) -ForegroundColor Yellow Write-Host $(Get-Location) -NoNewLine Write-Host ">" -NoNewline Return " " } #r Function Reload-Profile () { . $profile } Function Replace-GermanUmlauts () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $String ) Return ($String.Replace('ä','ae').Replace('Ä','Ae').Replace('ö','oe').Replace('Ö','Oe').Replace('ü','ue').Replace('Ü','Ue')) } #@see: https://4sysops.com/archives/how-to-reset-an-active-directory-password-with-powershell/ Function Reset-ADUserPassword () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $UserName, [Parameter(Mandatory=$true)] [String] $Password, [Parameter(Mandatory=$false)] [Bool] $ChangeAfterLogin = $false ) $SecuredPassword = ConvertTo-SecureString $Password -AsPlanText -Force Set-ADAccountPassword -Identity $UserName -NewPassword $SecuredPassword -Reset If ($ChangeAfterLogin -eq $true) { Set-ADUser -Identity $UserName -ChangePasswordAtLogon $true } } #s Function Search-ADComputerList () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $Name ) $Name = Add-StarsToTheBeginningAndTheEndOfAStringIfNeeded ($Name) Get-ADComputer -Filter { (Enabled -eq $true) -and (Name -like $Name) } ` -Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address,primarygroupid | Sort-Object -Property Name | Select-Object -Property Name,Operatingsystem,OperatingSystemVersion,IPv4Address,PrimaryGroupId | Format-Table } Function Search-ADUserByName () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $Name ) $Name = Add-StarsToTheBeginningAndTheEndOfAStringIfNeeded ($Name) Get-ADUser -Filter {(Name -like $Name) -or (SamAccountName -like $Name)} -Properties SamAccountName,Name,EmailAddress,Enabled,ObjectGUID,SID | SELECT SamAccountName,Name,EmailAddress,Enabled,ObjectGUID,SID } Function Search-ADUserPathOnComputerNameList () { [CmdletBinding()] Param ( [Parameter(Mandatory=$true,Position=0)] [String[]] $ListOfComputerName, [Parameter(Mandatory=$false,Position=1)] [String[]] $UserNameToFilterAgainst=$null ) ForEach ($CurrentComputerName in $ListOfComputerName) { If ((Test-NetConnection $CurrentComputerName -WarningAction SilentlyContinue).PingSucceeded -eq $true) { #contains array of objects like: #>>USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME #>>randomnote1 console 1 Active none 8/14/2019 6:52 AM $ArrayOfResultObjects = Get-ChildItem -Path ("\\" + $CurrentComputerName + "\c$\Users") #contains array of lines like: #>>Mode,LastWriteTime,Length,Name #>>d----- 15.06.2020 09:21 mustermann If ($UserNameToFilterAgainstOrNull -eq $null) { Write-Host $(":: Computer name: " + $CurrentComputerName) $ArrayOfResultObjects | Format-Table } Else { #check if the name is inside this array to only print the current terminal server when needed, else be silent. If ($ArrayOfResultObjects -like "*$UserNameToFilterAgainstOrNull*") { Write-Host $(":: Computer name: " + $CurrentComputerName) #@see: https://devblogs.microsoft.com/scripting/automating-quser-through-powershell/ #@see: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/query-user $ArrayOfResultObjects | Where-Object { ($_.NAME -like "*$UserNameToFilterAgainstOrNull*")} | Format-Table } } } Else { Write-Host $(":: Hostname >>" + $CurrentComputerName + "<< is offline. Skipping it.") } } } Function Search-ADUserSessionOnComputerNameList () { [CmdletBinding()] Param ( [Parameter(Mandatory=$true,Position=0)] [String[]] $ListOfComputerName, [Parameter(Mandatory=$false,Position=1)] [String[]] $UserNameToFilterAgainst=$null ) ForEach ($CurrentComputerName in $ListOfComputerName) { #only work on online systems #if you prefere having a visual feedback, is this line If ((Test-NetConnection $CurrentComputerName -WarningAction SilentlyContinue).PingSucceeded -eq $true) { #contains array of objects like: #>>USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME #>>randomnote1 console 1 Active none 8/14/2019 6:52 AM $ArrayOfResultObjects = Invoke-Expression ("quser /server:$CurrentComputerName"); #contains array of lines like: #>>USERNAME,SESSIONNAME,ID,STATE,IDLE TIME,LOGON TIME #>>randomnote1,console,1,Active,none,8/14/2019 6:52 AM $ArrayOfCommaSeparatedValues = $ArrayOfResultObjects | ForEach-Object -Process { $_ -replace '\s{2,}',',' } $ArrayOfUserObjects = $ArrayOfCommaSeparatedValues| ConvertFrom-Csv If ($UserNameToFilterAgainstOrNull -eq $null) { Write-Host $(":: Computer name: " + $CurrentComputerName) $ArrayOfUserObjects | Format-Table } Else { #check if the name is inside this array to only print the current terminal server when needed, else be silent. If ($ArrayOfResultObjects -like "*$UserNameToFilterAgainstOrNull*") { Write-Host $(":: Computer name: " + $CurrentComputerName) #@see: https://devblogs.microsoft.com/scripting/automating-quser-through-powershell/ #@see: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/query-user $ArrayOfUserObjects | Where-Object { ($_.USERNAME -like "*$userNameToFilterAgainstOrNull*") -or ($_.BENUTZERNAME -like "*$userNameToFilterAgainstOrNull*") } | Format-Table } } } Else { Write-Host $(":: Hostname >>" + $CurrentComputerName + "<< is offline. Skipping it.") } } } Function Search-CommandByName () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $CommandName ) $CommandName = Add-StarsToTheBeginningAndTheEndOfAStringIfNeeded ($CommandName) Get-Command -Verb Get -Noun $CommandName } Function Search-ProcessByName () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $ProcessName ) $ProcessName = Add-StarsToTheBeginningAndTheEndOfAStringIfNeeded ($ProcessName) Get-Process | Where-Object { $_.ProcessName -like $ProcessName } } Function Show-DiskStatus () { #@see: http://woshub.com/check-hard-drive-health-smart-windows/ Get-PhysicalDisk | Get-StorageReliabilityCounter | Select-Object -Property DeviceID, Wear, ReadErrorsTotal, ReadErrorsCorrected, WriteErrorsTotal, WriteErrorsUncorrected, Temperature, TemperatureMax | Format-Table } Function Show-IpAndMacAddressFromComputer () { [CmdletBinding()] #@see: https://gallery.technet.microsoft.com/scriptcenter/How-do-I-get-MAC-and-IP-46382777 Param ( [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)] [string[]]$ListOfComputerName ) ForEach ($ComputerName in $ListOfComputerName) { If ((Test-NetConnection $ComputerName -WarningAction SilentlyContinue).PingSucceeded -eq $true) { $IpAddressToString = ([System.Net.Dns]::GetHostByName($ComputerName).AddressList[0]).IpAddressToString $IPMAC = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $ComputerName $MacAddress = ($IPMAC | where { $_.IpAddress -eq $IpAddressToString }).MACAddress Write-Host ($ComputerName + ": IP Address >>" + $IpAddressToString + "<<, MAC Address >>" + $MacAddress + "<<.") } Else { Write-Host ("Maschine is offline >>" + $ComputerName + "<<.") -BackgroundColor Red } } } Function Show-Links () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $directoryPath ) Get-Childitem $directoryPath | Where-Object {$_.LinkType} | Select-Object FullName,LinkType,Target } #t Function Tail-Logs () { [CmdletBinding()] Param( [Parameter(Mandatory=$false)] [String] $pathToTheLogs = "C:\Windows\logs\*\" ) if (-Not $pathToTheLogs.endsWith(".log")) { $pathToTheLogs += "*.log" } Get-Content $pathToTheLogs -tail 10 -wait } #@see: https://www.powershellbros.com/test-credentials-using-powershell-function/ Function Test-ADCredential () { $DirectoryRoot = $null $Domain = $null $Password = $null $UserName = $null Try { $Credential = Get-Credential -ErrorAction Stop } Catch { $ErrorMessage = $_.Exception.Message Write-Warning "Failed to validate credentials with error message >>$ErrorMessage<<." Pause Break } Try { $DirectoryRoot = "LDAP://" + ([ADSI]'').distinguishedName $Password = $Credential.GetNetworkCredential().password $UserName = $Credential.username $Domain = New-Object System.DirectoryServices.DirectoryEntry($DirectoryRoot,$UserName,$Password) } Catch { $ErrorMessage = $_.Exception.Message Write-Warning "Faild to fetch the domain object from directory service with error message >>$ErrorMessage<<." Continue } If (!$Domain) { Write-Warning "An unexpected error has happend. Could not fetch the domain object from directory service." } Else { If ($Domain.name -ne $null) { return "User is authenticated" } Else { return "User is not authenticated" } } } #@see: https://devblogs.microsoft.com/scripting/use-a-powershell-function-to-see-if-a-command-exists/ Function Test-CommandExists () { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String] $CommandName ) $OldErrorActionPreference = $ErrorActionPreference $ErrorActionPreference = "stop" Try { If (Get-Command $CommandName) { $CommandExists = $true } } Catch { $CommandExists = $false } Finally { $ErrorActionPreference = $OldErrorActionPreference } return $CommandExists } #eo functions #bo alias #### #PowerShell does not support creating alias command calls with arguments #@see: https://seankilleen.com/2020/04/how-to-create-a-powershell-alias-with-parameters/ #If (Test-CommandExists chocolatey) { #eo alias #bo load local/confidential code If (Test-Path $localConfigurationFilePath) { . $localConfigurationFilePath } #eo load local/confidential code # Chocolatey profile $ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1" if (Test-Path($ChocolateyProfile)) { Import-Module "$ChocolateyProfile" }
stevleibelt/settings
powershell/Microsoft.PowerShell_profile.ps1
PowerShell
lgpl-3.0
28,712
# Copyright (C) 2014 Optiv, Inc. ([email protected]) # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from lib.cuckoo.common.abstracts import Signature class InjectionRWX(Signature): name = "injection_rwx" description = "Creates RWX memory" severity = 2 confidence = 50 categories = ["injection"] authors = ["Optiv"] minimum = "1.2" evented = True def __init__(self, *args, **kwargs): Signature.__init__(self, *args, **kwargs) filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"]) filter_analysistypes = set(["file"]) def on_call(self, call, process): if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx": protection = self.get_argument(call, "Protection") # PAGE_EXECUTE_READWRITE if protection == "0x00000040": return True elif call["api"] == "NtProtectVirtualMemory": protection = self.get_argument(call, "NewAccessProtection") # PAGE_EXECUTE_READWRITE if protection == "0x00000040": return True
lixiangning888/whole_project
modules/signatures_orginal_20151110/injection_rwx.py
Python
lgpl-3.0
1,229
using System; namespace MakingSense.AspNetCore.HypermediaApi.Linking.StandardRelations { public class RelatedRelation : IRelation { public Type InputModel => null; public bool IsVirtual => false; public HttpMethod? Method => null; public Type OutputModel => null; public string RelationName => "related"; } }
MakingSense/aspnet-hypermedia-api
src/MakingSense.AspNetCore.HypermediaApi/Linking/StandardRelations/RelatedRelation.cs
C#
lgpl-3.0
330
/* * Copyright (c) 2005–2012 Goethe Center for Scientific Computing - Simulation and Modelling (G-CSC Frankfurt) * Copyright (c) 2012-2015 Goethe Center for Scientific Computing - Computational Neuroscience (G-CSC Frankfurt) * * This file is part of NeuGen. * * NeuGen is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * see: http://opensource.org/licenses/LGPL-3.0 * file://path/to/NeuGen/LICENSE * * NeuGen 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. * * This version of NeuGen includes copyright notice and attribution requirements. * According to the LGPL this information must be displayed even if you modify * the source code of NeuGen. The copyright statement/attribution may not be removed. * * Attribution Requirements: * * If you create derived work you must do the following regarding copyright * notice and author attribution. * * Add an additional notice, stating that you modified NeuGen. In addition * you must cite the publications listed below. A suitable notice might read * "NeuGen source code modified by YourName 2012". * * Note, that these requirements are in full accordance with the LGPL v3 * (see 7. Additional Terms, b). * * Publications: * * S. Wolf, S. Grein, G. Queisser. NeuGen 2.0 - * Employing NeuGen 2.0 to automatically generate realistic * morphologies of hippocapal neurons and neural networks in 3D. * Neuroinformatics, 2013, 11(2), pp. 137-148, doi: 10.1007/s12021-012-9170-1 * * * J. P. Eberhard, A. Wanner, G. Wittum. NeuGen - * A tool for the generation of realistic morphology * of cortical neurons and neural networks in 3D. * Neurocomputing, 70(1-3), pp. 327-343, doi: 10.1016/j.neucom.2006.01.028 * */ package org.neugen.gui; import org.jdesktop.application.Action; /** * @author Sergei Wolf */ public final class NGAboutBox extends javax.swing.JDialog { private static final long serialVersionUID = 1L; public NGAboutBox(java.awt.Frame parent) { super(parent); initComponents(); getRootPane().setDefaultButton(closeButton); } @Action public void closeAboutBox() { dispose(); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { closeButton = new javax.swing.JButton(); javax.swing.JLabel appTitleLabel = new javax.swing.JLabel(); javax.swing.JLabel versionLabel = new javax.swing.JLabel(); javax.swing.JLabel appVersionLabel = new javax.swing.JLabel(); javax.swing.JLabel vendorLabel = new javax.swing.JLabel(); javax.swing.JLabel appVendorLabel = new javax.swing.JLabel(); javax.swing.JLabel homepageLabel = new javax.swing.JLabel(); javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel(); javax.swing.JLabel appDescLabel = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.neugen.gui.NeuGenApp.class).getContext().getResourceMap(NGAboutBox.class); setTitle(resourceMap.getString("title")); // NOI18N setModal(true); setName("aboutBox"); // NOI18N setResizable(false); javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.neugen.gui.NeuGenApp.class).getContext().getActionMap(NGAboutBox.class, this); closeButton.setAction(actionMap.get("closeAboutBox")); // NOI18N closeButton.setName("closeButton"); // NOI18N appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4)); appTitleLabel.setText(resourceMap.getString("Application.title")); // NOI18N appTitleLabel.setName("appTitleLabel"); // NOI18N versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD)); versionLabel.setText(resourceMap.getString("versionLabel.text")); // NOI18N versionLabel.setName("versionLabel"); // NOI18N appVersionLabel.setText(resourceMap.getString("Application.version")); // NOI18N appVersionLabel.setName("appVersionLabel"); // NOI18N vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD)); vendorLabel.setText(resourceMap.getString("vendorLabel.text")); // NOI18N vendorLabel.setName("vendorLabel"); // NOI18N appVendorLabel.setText(resourceMap.getString("Application.vendor")); // NOI18N appVendorLabel.setName("appVendorLabel"); // NOI18N homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD)); homepageLabel.setText(resourceMap.getString("homepageLabel.text")); // NOI18N homepageLabel.setName("homepageLabel"); // NOI18N appHomepageLabel.setText(resourceMap.getString("Application.homepage")); // NOI18N appHomepageLabel.setName("appHomepageLabel"); // NOI18N appDescLabel.setText(resourceMap.getString("appDescLabel.text")); // NOI18N appDescLabel.setName("appDescLabel"); // NOI18N org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(vendorLabel) .add(appTitleLabel) .add(appDescLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(versionLabel) .add(homepageLabel)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(appVendorLabel) .add(appVersionLabel) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(closeButton) .add(appHomepageLabel))))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap() .add(appTitleLabel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(appDescLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(versionLabel) .add(appVersionLabel)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(layout.createSequentialGroup() .add(appVendorLabel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(appHomepageLabel)) .add(homepageLabel)) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(vendorLabel) .add(49, 49, 49)) .add(layout.createSequentialGroup() .add(18, 18, 18) .add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton closeButton; // End of variables declaration//GEN-END:variables }
NeuroBox3D/NeuGen
NeuGen/src/org/neugen/gui/NGAboutBox.java
Java
lgpl-3.0
9,348
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_DELETEAPPREQUEST_H #define QTAWS_DELETEAPPREQUEST_H #include "sagemakerrequest.h" namespace QtAws { namespace SageMaker { class DeleteAppRequestPrivate; class QTAWSSAGEMAKER_EXPORT DeleteAppRequest : public SageMakerRequest { public: DeleteAppRequest(const DeleteAppRequest &other); DeleteAppRequest(); virtual bool isValid() const Q_DECL_OVERRIDE; protected: virtual QtAws::Core::AwsAbstractResponse * response(QNetworkReply * const reply) const Q_DECL_OVERRIDE; private: Q_DECLARE_PRIVATE(DeleteAppRequest) }; } // namespace SageMaker } // namespace QtAws #endif
pcolby/libqtaws
src/sagemaker/deleteapprequest.h
C
lgpl-3.0
1,343
// // This file is auto-generated. Please don't modify it! // package org.opencv.video; import java.util.List; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.MatOfFloat; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Rect; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.core.TermCriteria; import org.opencv.utils.Converters; public class Video { public static final int OPTFLOW_USE_INITIAL_FLOW = 4, OPTFLOW_LK_GET_MIN_EIGENVALS = 8, OPTFLOW_FARNEBACK_GAUSSIAN = 256, MOTION_TRANSLATION = 0, MOTION_EUCLIDEAN = 1, MOTION_AFFINE = 2, MOTION_HOMOGRAPHY = 3; private static final int CV_LKFLOW_INITIAL_GUESSES = 4, CV_LKFLOW_GET_MIN_EIGENVALS = 8; // // C++: Mat estimateRigidTransform(Mat src, Mat dst, bool fullAffine) // //javadoc: estimateRigidTransform(src, dst, fullAffine) public static Mat estimateRigidTransform(Mat src, Mat dst, boolean fullAffine) { Mat retVal = new Mat(estimateRigidTransform_0(src.nativeObj, dst.nativeObj, fullAffine)); return retVal; } // // C++: Ptr_BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history = 500, double dist2Threshold = 400.0, bool detectShadows = true) // //javadoc: createBackgroundSubtractorKNN(history, dist2Threshold, detectShadows) public static BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history, double dist2Threshold, boolean detectShadows) { BackgroundSubtractorKNN retVal = new BackgroundSubtractorKNN(createBackgroundSubtractorKNN_0(history, dist2Threshold, detectShadows)); return retVal; } //javadoc: createBackgroundSubtractorKNN() public static BackgroundSubtractorKNN createBackgroundSubtractorKNN() { BackgroundSubtractorKNN retVal = new BackgroundSubtractorKNN(createBackgroundSubtractorKNN_1()); return retVal; } // // C++: Ptr_BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history = 500, double varThreshold = 16, bool detectShadows = true) // //javadoc: createBackgroundSubtractorMOG2(history, varThreshold, detectShadows) public static BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history, double varThreshold, boolean detectShadows) { BackgroundSubtractorMOG2 retVal = new BackgroundSubtractorMOG2(createBackgroundSubtractorMOG2_0(history, varThreshold, detectShadows)); return retVal; } //javadoc: createBackgroundSubtractorMOG2() public static BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2() { BackgroundSubtractorMOG2 retVal = new BackgroundSubtractorMOG2(createBackgroundSubtractorMOG2_1()); return retVal; } // // C++: Ptr_DualTVL1OpticalFlow createOptFlow_DualTVL1() // //javadoc: createOptFlow_DualTVL1() public static DualTVL1OpticalFlow createOptFlow_DualTVL1() { DualTVL1OpticalFlow retVal = new DualTVL1OpticalFlow(createOptFlow_DualTVL1_0()); return retVal; } // // C++: RotatedRect CamShift(Mat probImage, Rect& window, TermCriteria criteria) // //javadoc: CamShift(probImage, window, criteria) public static RotatedRect CamShift(Mat probImage, Rect window, TermCriteria criteria) { double[] window_out = new double[4]; RotatedRect retVal = new RotatedRect(CamShift_0(probImage.nativeObj, window.x, window.y, window.width, window.height, window_out, criteria.type, criteria.maxCount, criteria.epsilon)); if (window != null) { window.x = (int) window_out[0]; window.y = (int) window_out[1]; window.width = (int) window_out[2]; window.height = (int) window_out[3]; } return retVal; } // // C++: double findTransformECC(Mat templateImage, Mat inputImage, Mat& warpMatrix, int motionType = MOTION_AFFINE, TermCriteria criteria = TermCriteria // (TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), Mat inputMask = Mat()) // //javadoc: findTransformECC(templateImage, inputImage, warpMatrix, motionType, criteria, inputMask) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix, int motionType, TermCriteria criteria, Mat inputMask) { double retVal = findTransformECC_0(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj, motionType, criteria.type, criteria.maxCount, criteria.epsilon, inputMask.nativeObj); return retVal; } //javadoc: findTransformECC(templateImage, inputImage, warpMatrix, motionType) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix, int motionType) { double retVal = findTransformECC_1(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj, motionType); return retVal; } //javadoc: findTransformECC(templateImage, inputImage, warpMatrix) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix) { double retVal = findTransformECC_2(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj); return retVal; } // // C++: int buildOpticalFlowPyramid(Mat img, vector_Mat& pyramid, Size winSize, int maxLevel, bool withDerivatives = true, int pyrBorder = BORDER_REFLECT_101, int // derivBorder = BORDER_CONSTANT, bool tryReuseInputImage = true) // //javadoc: buildOpticalFlowPyramid(img, pyramid, winSize, maxLevel, withDerivatives, pyrBorder, derivBorder, tryReuseInputImage) public static int buildOpticalFlowPyramid(Mat img, List<Mat> pyramid, Size winSize, int maxLevel, boolean withDerivatives, int pyrBorder, int derivBorder, boolean tryReuseInputImage) { Mat pyramid_mat = new Mat(); int retVal = buildOpticalFlowPyramid_0(img.nativeObj, pyramid_mat.nativeObj, winSize.width, winSize.height, maxLevel, withDerivatives, pyrBorder, derivBorder, tryReuseInputImage); Converters.Mat_to_vector_Mat(pyramid_mat, pyramid); pyramid_mat.release(); return retVal; } //javadoc: buildOpticalFlowPyramid(img, pyramid, winSize, maxLevel) public static int buildOpticalFlowPyramid(Mat img, List<Mat> pyramid, Size winSize, int maxLevel) { Mat pyramid_mat = new Mat(); int retVal = buildOpticalFlowPyramid_1(img.nativeObj, pyramid_mat.nativeObj, winSize.width, winSize.height, maxLevel); Converters.Mat_to_vector_Mat(pyramid_mat, pyramid); pyramid_mat.release(); return retVal; } // // C++: int meanShift(Mat probImage, Rect& window, TermCriteria criteria) // //javadoc: meanShift(probImage, window, criteria) public static int meanShift(Mat probImage, Rect window, TermCriteria criteria) { double[] window_out = new double[4]; int retVal = meanShift_0(probImage.nativeObj, window.x, window.y, window.width, window.height, window_out, criteria.type, criteria.maxCount, criteria.epsilon); if (window != null) { window.x = (int) window_out[0]; window.y = (int) window_out[1]; window.width = (int) window_out[2]; window.height = (int) window_out[3]; } return retVal; } // // C++: void calcOpticalFlowFarneback(Mat prev, Mat next, Mat& flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) // //javadoc: calcOpticalFlowFarneback(prev, next, flow, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags) public static void calcOpticalFlowFarneback(Mat prev, Mat next, Mat flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) { calcOpticalFlowFarneback_0(prev.nativeObj, next.nativeObj, flow.nativeObj, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags); return; } // // C++: void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, vector_Point2f prevPts, vector_Point2f& nextPts, vector_uchar& status, vector_float& err, Size winSize = Size // (21,21), int maxLevel = 3, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), int flags = 0, double minEigThreshold = 1e-4) // //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err, winSize, maxLevel, criteria, flags, minEigThreshold) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err, Size winSize, int maxLevel, TermCriteria criteria, int flags, double minEigThreshold) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_0(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj, winSize.width, winSize.height, maxLevel, criteria.type, criteria.maxCount, criteria.epsilon, flags, minEigThreshold); return; } //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err, winSize, maxLevel) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err, Size winSize, int maxLevel) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_1(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj, winSize.width, winSize.height, maxLevel); return; } //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_2(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj); return; } // C++: Mat estimateRigidTransform(Mat src, Mat dst, bool fullAffine) private static native long estimateRigidTransform_0(long src_nativeObj, long dst_nativeObj, boolean fullAffine); // C++: Ptr_BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history = 500, double dist2Threshold = 400.0, bool detectShadows = true) private static native long createBackgroundSubtractorKNN_0(int history, double dist2Threshold, boolean detectShadows); private static native long createBackgroundSubtractorKNN_1(); // C++: Ptr_BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history = 500, double varThreshold = 16, bool detectShadows = true) private static native long createBackgroundSubtractorMOG2_0(int history, double varThreshold, boolean detectShadows); private static native long createBackgroundSubtractorMOG2_1(); // C++: Ptr_DualTVL1OpticalFlow createOptFlow_DualTVL1() private static native long createOptFlow_DualTVL1_0(); // C++: RotatedRect CamShift(Mat probImage, Rect& window, TermCriteria criteria) private static native double[] CamShift_0(long probImage_nativeObj, int window_x, int window_y, int window_width, int window_height, double[] window_out, int criteria_type, int criteria_maxCount, double criteria_epsilon); // C++: double findTransformECC(Mat templateImage, Mat inputImage, Mat& warpMatrix, int motionType = MOTION_AFFINE, TermCriteria criteria = TermCriteria // (TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), Mat inputMask = Mat()) private static native double findTransformECC_0(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj, int motionType, int criteria_type, int criteria_maxCount, double criteria_epsilon, long inputMask_nativeObj); private static native double findTransformECC_1(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj, int motionType); private static native double findTransformECC_2(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj); // C++: int buildOpticalFlowPyramid(Mat img, vector_Mat& pyramid, Size winSize, int maxLevel, bool withDerivatives = true, int pyrBorder = BORDER_REFLECT_101, int // derivBorder = BORDER_CONSTANT, bool tryReuseInputImage = true) private static native int buildOpticalFlowPyramid_0(long img_nativeObj, long pyramid_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel, boolean withDerivatives, int pyrBorder, int derivBorder, boolean tryReuseInputImage); private static native int buildOpticalFlowPyramid_1(long img_nativeObj, long pyramid_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel); // C++: int meanShift(Mat probImage, Rect& window, TermCriteria criteria) private static native int meanShift_0(long probImage_nativeObj, int window_x, int window_y, int window_width, int window_height, double[] window_out, int criteria_type, int criteria_maxCount, double criteria_epsilon); // C++: void calcOpticalFlowFarneback(Mat prev, Mat next, Mat& flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) private static native void calcOpticalFlowFarneback_0(long prev_nativeObj, long next_nativeObj, long flow_nativeObj, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags); // C++: void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, vector_Point2f prevPts, vector_Point2f& nextPts, vector_uchar& status, vector_float& err, Size winSize = Size // (21,21), int maxLevel = 3, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), int flags = 0, double minEigThreshold = 1e-4) private static native void calcOpticalFlowPyrLK_0(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel, int criteria_type, int criteria_maxCount, double criteria_epsilon, int flags, double minEigThreshold); private static native void calcOpticalFlowPyrLK_1(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel); private static native void calcOpticalFlowPyrLK_2(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj); }
openstreetview/android
sensorlib/src/main/java/org/opencv/video/Video.java
Java
lgpl-3.0
15,311
FILE(REMOVE_RECURSE "CommonBehavior.cpp" "CommonBehavior.h" "RGBD.cpp" "RGBD.h" "JointMotor.cpp" "JointMotor.h" "DifferentialRobot.cpp" "DifferentialRobot.h" "moc_specificworker.cxx" "moc_specificmonitor.cxx" "moc_genericmonitor.cxx" "moc_commonbehaviorI.cxx" "moc_genericworker.cxx" "ui_mainUI.h" "CMakeFiles/trainCNN.dir/specificworker.cpp.o" "CMakeFiles/trainCNN.dir/specificmonitor.cpp.o" "CMakeFiles/trainCNN.dir/opt/robocomp/classes/rapplication/rapplication.cpp.o" "CMakeFiles/trainCNN.dir/opt/robocomp/classes/qlog/qlog.cpp.o" "CMakeFiles/trainCNN.dir/main.cpp.o" "CMakeFiles/trainCNN.dir/genericmonitor.cpp.o" "CMakeFiles/trainCNN.dir/commonbehaviorI.cpp.o" "CMakeFiles/trainCNN.dir/genericworker.cpp.o" "CMakeFiles/trainCNN.dir/CommonBehavior.cpp.o" "CMakeFiles/trainCNN.dir/RGBD.cpp.o" "CMakeFiles/trainCNN.dir/JointMotor.cpp.o" "CMakeFiles/trainCNN.dir/DifferentialRobot.cpp.o" "CMakeFiles/trainCNN.dir/moc_specificworker.cxx.o" "CMakeFiles/trainCNN.dir/moc_specificmonitor.cxx.o" "CMakeFiles/trainCNN.dir/moc_genericmonitor.cxx.o" "CMakeFiles/trainCNN.dir/moc_commonbehaviorI.cxx.o" "CMakeFiles/trainCNN.dir/moc_genericworker.cxx.o" "../bin/trainCNN.pdb" "../bin/trainCNN" ) # Per-language clean rules from dependency scanning. FOREACH(lang CXX) INCLUDE(CMakeFiles/trainCNN.dir/cmake_clean_${lang}.cmake OPTIONAL) ENDFOREACH(lang)
ljmanso/prp
components/trainCNN/src/CMakeFiles/trainCNN.dir/cmake_clean.cmake
CMake
lgpl-3.0
1,413