text:
using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Tmds.DBus.CodeGen;
using Tmds.DBus.Protocol;

namespace Tmds.DBus
{
    /// <summary>
    /// Connection with a D-Bus peer.
    /// </summary>
    public class Connection : IConnection
    {
        [Flags]
        private enum ConnectionType
        {
            None              = 0,
            ClientManual      = 1,
            ClientAutoConnect = 2,
            Server            = 4
        }

        /// <summary>
        /// Assembly name where the dynamically generated code resides.
        /// </summary>
        public const string DynamicAssemblyName = "Tmds.DBus.Emit, PublicKey=002400000480000094000000060200000024000052534131000400000100010071a8770f460cce31df0feb6f94b328aebd55bffeb5c69504593df097fdd9b29586dbd155419031834411c8919516cc565dee6b813c033676218496edcbe7939c0dd1f919f3d1a228ebe83b05a3bbdbae53ce11bcf4c04a42d8df1a83c2d06cb4ebb0b447e3963f48a1ca968996f3f0db8ab0e840a89d0a5d5a237e2f09189ed3";

        private static Connection s_systemConnection;
        private static Connection s_sessionConnection;
        private static readonly object NoDispose = new object();

        /// <summary>
        /// An AutoConnect Connection to the system bus.
        /// </summary>
        public static Connection System => s_systemConnection ?? CreateSystemConnection();

        /// <summary>
        /// An AutoConnect Connection to the session bus.
        /// </summary>
        public static Connection Session => s_sessionConnection ?? CreateSessionConnection();

        private class ProxyFactory : IProxyFactory
        {
            public Connection Connection { get; }
            public ProxyFactory(Connection connection)
            {
                Connection = connection;
            }
            public T CreateProxy<T>(string serviceName, ObjectPath path)
            {
                return Connection.CreateProxy<T>(serviceName, path);
            }
        }

        private readonly object _gate = new object();
        private readonly Dictionary<ObjectPath, DBusAdapter> _registeredObjects = new Dictionary<ObjectPath, DBusAdapter>();
        private readonly Func<Task<ClientSetupResult>> _connectFunction;
        private readonly Action<object> _disposeAction;
        private readonly SynchronizationContext _synchronizationContext;
        private readonly bool _runContinuationsAsynchronously;
        private readonly ConnectionType _connectionType;

        private ConnectionState _state = ConnectionState.Created;
        private bool _disposed = false;
        private IProxyFactory _factory;
        private DBusConnection _dbusConnection;
        private Task<DBusConnection> _dbusConnectionTask;
        private TaskCompletionSource<DBusConnection> _dbusConnectionTcs;
        private CancellationTokenSource _connectCts;
        private Exception _disconnectReason;
        private IDBus _bus;
        private EventHandler<ConnectionStateChangedEventArgs> _stateChangedEvent;
        private object _disposeUserToken = NoDispose;

        private IDBus DBus
        {
            get
            {
                if (_bus != null)
                {
                    return _bus;
                }
                lock (_gate)
                {
                    _bus = _bus ?? CreateProxy<IDBus>(DBusConnection.DBusServiceName, DBusConnection.DBusObjectPath);
                    return _bus;
                }
            }
        }

        /// <summary>
        /// Occurs when the state changes.
        /// </summary>
        /// <remarks>
        /// The event handler will be called when it is added to the event.
        /// The event handler is invoked on the ConnectionOptions.SynchronizationContext.
        /// </remarks>
        public event EventHandler<ConnectionStateChangedEventArgs> StateChanged
        {
            add
            {
                lock (_gate)
                {
                    _stateChangedEvent += value;
                    if (_state != ConnectionState.Created)
                    {
                        EmitConnectionStateChanged(value);
                    }
                }
            }
            remove
            {
                lock (_gate)
                {
                    _stateChangedEvent -= value;
                }
            }
        }

        /// <summary>
        /// Creates a new Connection with a specific address.
        /// </summary>
        /// <param name="address">Address of the D-Bus peer.</param>
        public Connection(string address) :
            this(new ClientConnectionOptions(address))
        { }

        /// <summary>
        /// Creates a new Connection with specific ConnectionOptions.
        /// </summary>
        /// <param name="connectionOptions"></param>
        public Connection(ConnectionOptions connectionOptions)
        {
            if (connectionOptions == null)
                throw new ArgumentNullException(nameof(connectionOptions));

            _factory = new ProxyFactory(this);
            _synchronizationContext = connectionOptions.SynchronizationContext;
            if (connectionOptions is ClientConnectionOptions clientConnectionOptions)
            {
                _connectionType = clientConnectionOptions.AutoConnect ? ConnectionType.ClientAutoConnect : ConnectionType.ClientManual ;
                _connectFunction = clientConnectionOptions.SetupAsync;
                _disposeAction = clientConnectionOptions.Teardown;
                _runContinuationsAsynchronously = clientConnectionOptions.RunContinuationsAsynchronously;
            }
            else if (connectionOptions is ServerConnectionOptions serverConnectionOptions)
            {
                _connectionType = ConnectionType.Server;
                _state = ConnectionState.Connected;
                _dbusConnection = new DBusConnection(localServer: true, runContinuationsAsynchronously: false);
                _dbusConnectionTask = Task.FromResult(_dbusConnection);
                serverConnectionOptions.Connection = this;
            }
            else
            {
                throw new NotSupportedException($"Unknown ConnectionOptions type: '{typeof(ConnectionOptions).FullName}'");
            }
        }

        /// <summary>
        /// Connect with the remote peer.
        /// </summary>
        /// <returns>
        /// Information about the established connection.
        /// </returns>
        /// <exception cref="ConnectException">There was an error establishing the connection.</exception>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
        public async Task<ConnectionInfo> ConnectAsync()
            => (await DoConnectAsync().ConfigureAwait(false)).ConnectionInfo;

        private async Task<DBusConnection> DoConnectAsync()
        {
            Task<DBusConnection> connectionTask = null;
            bool alreadyConnecting = false;
            lock (_gate)
            {
                if (_disposed)
                {
                    ThrowDisposed();
                }

                if (_connectionType == ConnectionType.ClientManual)
                {
                    if (_state != ConnectionState.Created)
                    {
                        throw new InvalidOperationException("Can only connect once");
                    }
                }
                else
                {
                    if (_state == ConnectionState.Connecting || _state == ConnectionState.Connected)
                    {
                        connectionTask = _dbusConnectionTask;
                        alreadyConnecting = true;
                    }
                }
                if (!alreadyConnecting)
                {
                    _connectCts = new CancellationTokenSource();
                    _dbusConnectionTcs = new TaskCompletionSource<DBusConnection>();
                    _dbusConnectionTask = _dbusConnectionTcs.Task;
                    connectionTask = _dbusConnectionTask;
                    _state = ConnectionState.Connecting;

                    EmitConnectionStateChanged();
                }
            }

            if (alreadyConnecting)
            {
                return await connectionTask.ConfigureAwait(false);
            }

            DBusConnection connection;
            object disposeUserToken = NoDispose;
            try
            {
                ClientSetupResult connectionContext = await _connectFunction().ConfigureAwait(false);
                disposeUserToken = connectionContext.TeardownToken;
                connection = await DBusConnection.ConnectAsync(connectionContext, _runContinuationsAsynchronously, OnDisconnect, _connectCts.Token).ConfigureAwait(false);
            }
            catch (ConnectException ce)
            {
                if (disposeUserToken != NoDispose)
                {
                    _disposeAction?.Invoke(disposeUserToken);
                }
                Disconnect(dispose: false, exception: ce);
                throw;
            }
            catch (Exception e)
            {
                if (disposeUserToken != NoDispose)
                {
                    _disposeAction?.Invoke(disposeUserToken);
                }
                var ce = new ConnectException(e.Message, e);
                Disconnect(dispose: false, exception: ce);
                throw ce;
            }
            lock (_gate)
            {
                if (_state == ConnectionState.Connecting)
                {
                    _disposeUserToken = disposeUserToken;
                    _dbusConnection = connection;
                    _connectCts.Dispose();
                    _connectCts = null;
                    _state = ConnectionState.Connected;
                    _dbusConnectionTcs.SetResult(connection);
                    _dbusConnectionTcs = null;

                    EmitConnectionStateChanged();
                }
                else
                {
                    connection.Dispose();
                    if (disposeUserToken != NoDispose)
                    {
                        _disposeAction?.Invoke(disposeUserToken);
                    }
                }
                ThrowIfNotConnected();
            }
            return connection;
        }

        /// <summary>
        /// Disposes the connection.
        /// </summary>
        public void Dispose()
        {
            Disconnect(dispose: true, exception: CreateDisposedException());
        }

        /// <summary>
        /// Creates a proxy object that represents a remote D-Bus object.
        /// </summary>
        /// <typeparam name="T">Interface of the D-Bus object.</typeparam>
        /// <param name="serviceName">Name of the service that exposes the object.</param>
        /// <param name="path">Object path of the object.</param>
        /// <returns>
        /// Proxy object.
        /// </returns>
        public T CreateProxy<T>(string serviceName, ObjectPath path)
        {
            CheckNotConnectionType(ConnectionType.Server);
            return (T)CreateProxy(typeof(T), serviceName, path);
        }

        /// <summary>
        /// Releases a service name assigned to the connection.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <returns>
        /// <c>true</c> when the name was assigned to this connection; <c>false</c> when the name was not assigned to this connection.
        /// </returns>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
        /// <exception cref="DBusException">Error returned by remote peer.</exception>
        /// <remarks>
        /// This operation is not supported for AutoConnection connections.
        /// </remarks>
        public async Task<bool> UnregisterServiceAsync(string serviceName)
        {
            CheckNotConnectionType(ConnectionType.ClientAutoConnect);
            var connection = GetConnectedConnection();
            var reply = await connection.ReleaseNameAsync(serviceName).ConfigureAwait(false);
            return reply == ReleaseNameReply.ReplyReleased;
        }

        /// <summary>
        /// Queues a service name registration for the connection.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="onAquired">Action invoked when the service name is assigned to the connection.</param>
        /// <param name="onLost">Action invoked when the service name is no longer assigned to the connection.</param>
        /// <param name="options">Options for the registration.</param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
        /// <exception cref="DBusException">Error returned by remote peer.</exception>
        /// <exception cref="ProtocolException">Unexpected reply.</exception>
        /// <remarks>
        /// This operation is not supported for AutoConnection connections.
        /// </remarks>
        public async Task QueueServiceRegistrationAsync(string serviceName, Action onAquired = null, Action onLost = null, ServiceRegistrationOptions options = ServiceRegistrationOptions.Default)
        {
            CheckNotConnectionType(ConnectionType.ClientAutoConnect);
            var connection = GetConnectedConnection();
            if (!options.HasFlag(ServiceRegistrationOptions.AllowReplacement) && (onLost != null))
            {
                throw new ArgumentException($"{nameof(onLost)} can only be set when {nameof(ServiceRegistrationOptions.AllowReplacement)} is also set", nameof(onLost));
            }

            RequestNameOptions requestOptions = RequestNameOptions.None;
            if (options.HasFlag(ServiceRegistrationOptions.ReplaceExisting))
            {
                requestOptions |= RequestNameOptions.ReplaceExisting;
            }
            if (options.HasFlag(ServiceRegistrationOptions.AllowReplacement))
            {
                requestOptions |= RequestNameOptions.AllowReplacement;
            }
            var reply = await connection.RequestNameAsync(serviceName, requestOptions, onAquired, onLost, CaptureSynchronizationContext()).ConfigureAwait(false);
            switch (reply)
            {
                case RequestNameReply.PrimaryOwner:
                case RequestNameReply.InQueue:
                    return;
                case RequestNameReply.Exists:
                case RequestNameReply.AlreadyOwner:
                default:
                    throw new ProtocolException("Unexpected reply");
            }
        }

        /// <summary>
        /// Queues a service name registration for the connection.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="options">Options for the registration.</param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
        /// <exception cref="DBusException">Error returned by remote peer.</exception>
        /// <exception cref="ProtocolException">Unexpected reply.</exception>
        /// <remarks>
        /// This operation is not supported for AutoConnection connections.
        /// </remarks>
        public Task QueueServiceRegistrationAsync(string serviceName, ServiceRegistrationOptions options)
            => QueueServiceRegistrationAsync(serviceName, null, null, options);

        /// <summary>
        /// Requests a service name to be assigned to the connection.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="onLost">Action invoked when the service name is no longer assigned to the connection.</param>
        /// <param name="options"></param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
        /// <exception cref="DBusException">Error returned by remote peer.</exception>
        /// <remarks>
        /// This operation is not supported for AutoConnection connections.
        /// </remarks>
        public async Task RegisterServiceAsync(string serviceName, Action onLost = null, ServiceRegistrationOptions options = ServiceRegistrationOptions.Default)
        {
            CheckNotConnectionType(ConnectionType.ClientAutoConnect);
            var connection = GetConnectedConnection();
            if (!options.HasFlag(ServiceRegistrationOptions.AllowReplacement) && (onLost != null))
            {
                throw new ArgumentException($"{nameof(onLost)} can only be set when {nameof(ServiceRegistrationOptions.AllowReplacement)} is also set", nameof(onLost));
            }

            RequestNameOptions requestOptions = RequestNameOptions.DoNotQueue;
            if (options.HasFlag(ServiceRegistrationOptions.ReplaceExisting))
            {
                requestOptions |= RequestNameOptions.ReplaceExisting;
            }
            if (options.HasFlag(ServiceRegistrationOptions.AllowReplacement))
            {
                requestOptions |= RequestNameOptions.AllowReplacement;
            }
            var reply = await connection.RequestNameAsync(serviceName, requestOptions, null, onLost, CaptureSynchronizationContext()).ConfigureAwait(false);
            switch (reply)
            {
                case RequestNameReply.PrimaryOwner:
                    return;
                case RequestNameReply.Exists:
                    throw new InvalidOperationException("Service is registered by another connection");
                case RequestNameReply.AlreadyOwner:
                    throw new InvalidOperationException("Service is already registered by this connection");
                case RequestNameReply.InQueue:
                default:
                    throw new ProtocolException("Unexpected reply");
            }
        }

        /// <summary>
        /// Requests a service name to be assigned to the connection.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="options"></param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection was closed after it was established.</exception>
        /// <exception cref="DBusException">Error returned by remote peer.</exception>
        /// <remarks>
        /// This operation is not supported for AutoConnection connections.
        /// </remarks>
        public Task RegisterServiceAsync(string serviceName, ServiceRegistrationOptions options)
            => RegisterServiceAsync(serviceName, null, options);

        /// <summary>
        /// Publishes an object.
        /// </summary>
        /// <param name="o">Object to publish.</param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection was closed.</exception>
        public Task RegisterObjectAsync(IDBusObject o)
        {
            return RegisterObjectsAsync(new[] { o });
        }

        /// <summary>
        /// Publishes objects.
        /// </summary>
        /// <param name="objects">Objects to publish.</param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection was closed.</exception>
        /// <remarks>
        /// This operation is not supported for AutoConnection connections.
        /// </remarks>
        public async Task RegisterObjectsAsync(IEnumerable<IDBusObject> objects)
        {
            CheckNotConnectionType(ConnectionType.ClientAutoConnect);
            var connection = GetConnectedConnection();
            var assembly = DynamicAssembly.Instance;
            var registrations = new List<DBusAdapter>();
            foreach (var o in objects)
            {
                var implementationType = assembly.GetExportTypeInfo(o.GetType());
                var objectPath = o.ObjectPath;
                var registration = (DBusAdapter)Activator.CreateInstance(implementationType.AsType(), _dbusConnection, objectPath, o, _factory, CaptureSynchronizationContext());
                registrations.Add(registration);
            }

            lock (_gate)
            {
                connection.AddMethodHandlers(registrations.Select(r => new KeyValuePair<ObjectPath, MethodHandler>(r.Path, r.HandleMethodCall)));

                foreach (var registration in registrations)
                {
                    _registeredObjects.Add(registration.Path, registration);
                }
            }
            try
            {
                foreach (var registration in registrations)
                {
                    await registration.WatchSignalsAsync().ConfigureAwait(false);
                }
                lock (_gate)
                {
                    foreach (var registration in registrations)
                    {
                        registration.CompleteRegistration();
                    }
                }
            }
            catch
            {
                lock (_gate)
                {
                    foreach (var registration in registrations)
                    {
                        registration.Unregister();
                        _registeredObjects.Remove(registration.Path);
                    }
                    connection.RemoveMethodHandlers(registrations.Select(r => r.Path));
                }
                throw;
            }
        }

        /// <summary>
        /// Unpublishes an object.
        /// </summary>
        /// <param name="path">Path of object to unpublish.</param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        public void UnregisterObject(ObjectPath path)
            => UnregisterObjects(new[] { path });

        /// <summary>
        /// Unpublishes an object.
        /// </summary>
        /// <param name="o">object to unpublish.</param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        public void UnregisterObject(IDBusObject o)
            => UnregisterObject(o.ObjectPath);

        /// <summary>
        /// Unpublishes objects.
        /// </summary>
        /// <param name="paths">Paths of objects to unpublish.</param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        /// <remarks>
        /// This operation is not supported for AutoConnection connections.
        /// </remarks>
        public void UnregisterObjects(IEnumerable<ObjectPath> paths)
        {
            CheckNotConnectionType(ConnectionType.ClientAutoConnect);
            lock (_gate)
            {
                var connection = GetConnectedConnection();

                foreach(var objectPath in paths)
                {
                    DBusAdapter registration;
                    if (_registeredObjects.TryGetValue(objectPath, out registration))
                    {
                        registration.Unregister();
                        _registeredObjects.Remove(objectPath);
                    }
                }

                connection.RemoveMethodHandlers(paths);
            }
        }

        /// <summary>
        /// Unpublishes objects.
        /// </summary>
        /// <param name="objects">Objects to unpublish.</param>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        /// <remarks>
        /// This operation is not supported for AutoConnection connections.
        /// </remarks>
        public void UnregisterObjects(IEnumerable<IDBusObject> objects)
            => UnregisterObjects(objects.Select(o => o.ObjectPath));

        /// <summary>
        /// List services that can be activated.
        /// </summary>
        /// <returns>
        /// List of activatable services.
        /// </returns>
        /// <exception cref="ConnectException">There was an error establishing the connection.</exception>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        public Task<string[]> ListActivatableServicesAsync()
            => DBus.ListActivatableNamesAsync();

        /// <summary>
        /// Resolves the local address for a service.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <returns>
        /// Local address of service. <c>null</c> is returned when the service name is not available.
        /// </returns>
        /// <exception cref="ConnectException">There was an error establishing the connection.</exception>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        public async Task<string> ResolveServiceOwnerAsync(string serviceName)
        {
            try
            {
                return await DBus.GetNameOwnerAsync(serviceName).ConfigureAwait(false);
            }
            catch (DBusException e) when (e.ErrorName == "org.freedesktop.DBus.Error.NameHasNoOwner")
            {
                return null;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Activates a service.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <returns>
        /// The result of the activation.
        /// </returns>
        /// <exception cref="ConnectException">There was an error establishing the connection.</exception>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        public Task<ServiceStartResult> ActivateServiceAsync(string serviceName)
            => DBus.StartServiceByNameAsync(serviceName, 0);

        /// <summary>
        /// Checks if a service is available.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <returns>
        /// <c>true</c> when the service is available, <c>false</c> otherwise.
        /// </returns>
        /// <exception cref="ConnectException">There was an error establishing the connection.</exception>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        public Task<bool> IsServiceActiveAsync(string serviceName)
            => DBus.NameHasOwnerAsync(serviceName);

        /// <summary>
        /// Resolves the local address for a service.
        /// </summary>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="handler">Action invoked when the local name of the service changes.</param>
        /// <param name="onError">Action invoked when the connection closes.</param>
        /// <returns>
        /// Disposable that allows to stop receiving notifications.
        /// </returns>
        /// <exception cref="ConnectException">There was an error establishing the connection.</exception>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        /// <remarks>
        /// The event handler will be called when the service name is already registered.
        /// </remarks>
        public async Task<IDisposable> ResolveServiceOwnerAsync(string serviceName, Action<ServiceOwnerChangedEventArgs> handler, Action<Exception> onError = null)
        {
            if (serviceName == "*")
            {
                serviceName = ".*";
            }

            var synchronizationContext = CaptureSynchronizationContext();
            var wrappedDisposable = new WrappedDisposable(synchronizationContext);
            bool namespaceLookup = serviceName.EndsWith(".*", StringComparison.Ordinal);
            bool _eventEmitted = false;
            var _gate = new object();
            var _emittedServices = namespaceLookup ? new List<string>() : null;

            Action<ServiceOwnerChangedEventArgs, Exception> handleEvent = (ownerChange, ex) => {
                if (ex != null)
                {
                    if (onError == null)
                    {
                        return;
                    }
                    wrappedDisposable.Call(onError, ex, disposes: true);
                    return;
                }
                bool first = false;
                lock (_gate)
                {
                    if (namespaceLookup)
                    {
                        first = _emittedServices?.Contains(ownerChange.ServiceName) == false;
                        _emittedServices?.Add(ownerChange.ServiceName);
                    }
                    else
                    {
                        first = _eventEmitted == false;
                        _eventEmitted = true;
                    }
                }
                if (first)
                {
                    if (ownerChange.NewOwner == null)
                    {
                        return;
                    }
                    ownerChange.OldOwner = null;
                }
                wrappedDisposable.Call(handler, ownerChange);
            };

            var connection = await GetConnectionTask().ConfigureAwait(false);
            wrappedDisposable.Disposable = await connection.WatchNameOwnerChangedAsync(serviceName, handleEvent).ConfigureAwait(false);
            if (namespaceLookup)
            {
                serviceName = serviceName.Substring(0, serviceName.Length - 2);
            }
            try
            {
                if (namespaceLookup)
                {
                    var services = await ListServicesAsync().ConfigureAwait(false);
                    foreach (var service in services)
                    {
                        if (service.StartsWith(serviceName, StringComparison.Ordinal)
                         && (   (service.Length == serviceName.Length)
                             || (service[serviceName.Length] == '.')
                             || (serviceName.Length == 0 && service[0] != ':')))
                        {
                            var currentName = await ResolveServiceOwnerAsync(service).ConfigureAwait(false);
                            lock (_gate)
                            {
                                if (currentName != null && !_emittedServices.Contains(serviceName))
                                {
                                    var e = new ServiceOwnerChangedEventArgs(service, null, currentName);
                                    handleEvent(e, null);
                                }
                            }
                        }
                    }
                    lock (_gate)
                    {
                        _emittedServices = null;
                    }
                }
                else
                {
                    var currentName = await ResolveServiceOwnerAsync(serviceName).ConfigureAwait(false);
                    lock (_gate)
                    {
                        if (currentName != null && !_eventEmitted)
                        {
                            var e = new ServiceOwnerChangedEventArgs(serviceName, null, currentName);
                            handleEvent(e, null);
                        }
                    }
                }
                return wrappedDisposable;
            }
            catch (Exception ex)
            {
                handleEvent(default(ServiceOwnerChangedEventArgs), ex);
            }

            return wrappedDisposable;
        }

        /// <summary>
        /// List services that are available.
        /// </summary>
        /// <returns>
        /// List of available services.
        /// </returns>
        /// <exception cref="ConnectException">There was an error establishing the connection.</exception>
        /// <exception cref="ObjectDisposedException">The connection has been disposed.</exception>
        /// <exception cref="InvalidOperationException">The operation is invalid in the current state.</exception>
        /// <exception cref="DisconnectedException">The connection is closed.</exception>
        public Task<string[]> ListServicesAsync()
            => DBus.ListNamesAsync();

        internal Task<string> StartServerAsync(string address)
        {
            lock (_gate)
            {
                ThrowIfNotConnected();
                return _dbusConnection.StartServerAsync(address);
            }
        }

        // Used by tests
        internal void Connect(DBusConnection dbusConnection)
        {
            lock (_gate)
            {
                if (_state != ConnectionState.Created)
                {
                    throw new InvalidOperationException("Can only connect once");
                }
                _dbusConnection = dbusConnection;
                _dbusConnectionTask = Task.FromResult(_dbusConnection);
                _state = ConnectionState.Connected;
            }
        }

        private object CreateProxy(Type interfaceType, string busName, ObjectPath path)
        {
            var assembly = DynamicAssembly.Instance;
            var implementationType = assembly.GetProxyTypeInfo(interfaceType);

            DBusObjectProxy instance = (DBusObjectProxy)Activator.CreateInstance(implementationType.AsType(),
                new object[] { this, _factory, busName, path });

            return instance;
        }

        private void OnDisconnect(Exception e)
        {
            Disconnect(dispose: false, exception: e);
        }

        private void ThrowIfNotConnected()
            => ThrowIfNotConnected(_disposed, _state, _disconnectReason);

        internal static void ThrowIfNotConnected(bool disposed, ConnectionState state, Exception disconnectReason)
        {
            if (disposed)
            {
                ThrowDisposed();
            }
            if (state == ConnectionState.Disconnected)
            {
                throw new DisconnectedException(disconnectReason);
            }
            else if (state == ConnectionState.Created)
            {
                throw new InvalidOperationException("Not Connected");
            }
            else if (state == ConnectionState.Connecting)
            {
                throw new InvalidOperationException("Connecting");
            }
        }

        internal static Exception CreateDisposedException()
            => new ObjectDisposedException(typeof(Connection).FullName);

        private static void ThrowDisposed()
        {
            throw CreateDisposedException();
        }

        internal static void ThrowIfNotConnecting(bool disposed, ConnectionState state, Exception disconnectReason)
        {
            if (disposed)
            {
                ThrowDisposed();
            }
            if (state == ConnectionState.Disconnected)
            {
                throw new DisconnectedException(disconnectReason);
            }
            else if (state == ConnectionState.Created)
            {
                throw new InvalidOperationException("Not Connected");
            }
            else if (state == ConnectionState.Connected)
            {
                throw new InvalidOperationException("Already Connected");
            }
        }

        private Task<DBusConnection> GetConnectionTask()
        {
            var connectionTask = Volatile.Read(ref _dbusConnectionTask);
            if (connectionTask != null)
            {
                return connectionTask;
            }
            if (_connectionType == ConnectionType.ClientAutoConnect)
            {
                return DoConnectAsync();
            }
            else
            {
                return Task.FromResult(GetConnectedConnection());
            }
        }

        private DBusConnection GetConnectedConnection()
        {
            var connection = Volatile.Read(ref _dbusConnection);
            if (connection != null)
            {
                return connection;
            }
            lock (_gate)
            {
                ThrowIfNotConnected();
                return _dbusConnection;
            }
        }

        private void CheckNotConnectionType(ConnectionType disallowed)
        {
            if ((_connectionType & disallowed) != ConnectionType.None)
            {
                if (_connectionType == ConnectionType.ClientAutoConnect)
                {
                    throw new InvalidOperationException($"Operation not supported for {nameof(ClientConnectionOptions.AutoConnect)} Connection.");
                }
                else if (_connectionType == ConnectionType.Server)
                {
                    throw new InvalidOperationException($"Operation not supported for Server-based Connection.");
                }
            }
        }

        private void Disconnect(bool dispose, Exception exception)
        {
            lock (_gate)
            {
                if (dispose)
                {
                    _disposed = true;
                }
                var previousState = _state;
                if (previousState == ConnectionState.Disconnecting || previousState == ConnectionState.Disconnected || previousState == ConnectionState.Created)
                {
                    return;
                }

                _disconnectReason = exception;

                var connection = _dbusConnection;
                var connectionCts = _connectCts;;
                var dbusConnectionTask = _dbusConnectionTask;
                var dbusConnectionTcs = _dbusConnectionTcs;
                var disposeUserToken = _disposeUserToken;
                _dbusConnection = null;
                _connectCts = null;
                _dbusConnectionTask = null;
                _dbusConnectionTcs = null;
                _disposeUserToken = NoDispose;

                foreach (var registeredObject in _registeredObjects)
                {
                    registeredObject.Value.Unregister();
                }
                _registeredObjects.Clear();

                _state = ConnectionState.Disconnecting;
                EmitConnectionStateChanged();

                connectionCts?.Cancel();
                connectionCts?.Dispose();
                dbusConnectionTcs?.SetException(
                    dispose ? CreateDisposedException() :
                    exception.GetType() == typeof(ConnectException) ? exception :
                    new DisconnectedException(exception));
                connection?.Disconnect(dispose, exception);
                if (disposeUserToken != NoDispose)
                {
                    _disposeAction?.Invoke(disposeUserToken);
                }

                if (_state == ConnectionState.Disconnecting)
                {
                    _state = ConnectionState.Disconnected;
                    EmitConnectionStateChanged();
                }
            }
        }

        private void EmitConnectionStateChanged(EventHandler<ConnectionStateChangedEventArgs> handler = null)
        {
            var disconnectReason = _disconnectReason;
            if (_state == ConnectionState.Connecting)
            {
                _disconnectReason = null;
            }

            if (handler == null)
            {
                handler = _stateChangedEvent;
            }

            if (handler == null)
            {
                return;
            }

            if (disconnectReason != null
             && disconnectReason.GetType() != typeof(ConnectException)
             && disconnectReason.GetType() != typeof(ObjectDisposedException)
             && disconnectReason.GetType() != typeof(DisconnectedException))
            {
                disconnectReason = new DisconnectedException(disconnectReason);
            }
            var connectionInfo = _state == ConnectionState.Connected ? _dbusConnection.ConnectionInfo : null;
            var stateChangeEvent = new ConnectionStateChangedEventArgs(_state, disconnectReason, connectionInfo);

            if (_synchronizationContext != null && SynchronizationContext.Current != _synchronizationContext)
            {
                _synchronizationContext.Post(_ => handler(this, stateChangeEvent), null);
            }
            else
            {
                handler(this, stateChangeEvent);
            }
        }

        internal async Task<Message> CallMethodAsync(Message message)
        {
            var connection = await GetConnectionTask().ConfigureAwait(false);
            try
            {
                return await connection.CallMethodAsync(message).ConfigureAwait(false);
            }
            catch (DisconnectedException) when (_connectionType == ConnectionType.ClientAutoConnect)
            {
                connection = await GetConnectionTask().ConfigureAwait(false);
                return await connection.CallMethodAsync(message).ConfigureAwait(false);
            }
        }

        internal async Task<IDisposable> WatchSignalAsync(ObjectPath path, string @interface, string signalName, SignalHandler handler)
        {
            var connection = await GetConnectionTask().ConfigureAwait(false);
            try
            {
                return await connection.WatchSignalAsync(path, @interface, signalName, handler).ConfigureAwait(false);
            }
            catch (DisconnectedException) when (_connectionType == ConnectionType.ClientAutoConnect)
            {
                connection = await GetConnectionTask().ConfigureAwait(false);
                return await connection.WatchSignalAsync(path, @interface, signalName, handler).ConfigureAwait(false);
            }
        }

        internal SynchronizationContext CaptureSynchronizationContext() => _synchronizationContext;

        private static Connection CreateSessionConnection() => CreateConnection(Address.Session, ref s_sessionConnection);

        private static Connection CreateSystemConnection() => CreateConnection(Address.System, ref s_systemConnection);

        private static Connection CreateConnection(string address, ref Connection connection)
        {
            address = address ?? "unix:";
            if (Volatile.Read(ref connection) != null)
            {
                return connection;
            }
            var newConnection = new Connection(new ClientConnectionOptions(address) { AutoConnect = true, SynchronizationContext = null });
            Interlocked.CompareExchange(ref connection, newConnection, null);
            return connection;
        }
    }
}


text:
import {DOWNLOADER, Downloader} from "./Downloader";
import {injectAll, registry, singleton} from "tsyringe";
import {GitLabDownloader} from "./gitlab/GitLabDownloader";
import {GitHubDownloader} from "./github/GitHubDownloader";
import {DownloaderMetadata} from "../../model/DownloaderMetadata";

@singleton()
@registry([
    {token: DOWNLOADER, useToken: GitHubDownloader},
    {token: DOWNLOADER, useToken: GitLabDownloader},
    // Add new downloader classes here
])
export class DownloaderRegistry {
    private downloaders: Map<string, Downloader> = new Map();

    constructor(@injectAll(DOWNLOADER) private downloaderList: Downloader[]) {
        for (const downloader of downloaderList) {
            const metadata = downloader.getMetadata();

            if (!metadata || this.downloaders.has(metadata.id)) {
                throw new Error("Invalid downloader configuration" + JSON.stringify(metadata));
            }

            this.downloaders.set(metadata.id, downloader);
        }
    }

    public getDownloader(downloaderId: string): Downloader {
        if (this.downloaders.has(downloaderId)) {
            return this.downloaders.get(downloaderId);
        } else {
            throw new Error("No downloader found for id " + downloaderId);
        }
    }

    public getAllDownloadersMetadata(): DownloaderMetadata[] {
        const allMetadata = [];

        for (const downloader of this.downloaders.values()) {
            let metadata = downloader.getMetadata();

            if (metadata && metadata.id) {
                allMetadata.push(metadata);
            }
        }

        return allMetadata;
    }

}

redpajama_set_name: RedPajamaGithub


text:
class Clamxav < Cask
  url 'http://www.clamxav.com/downloads/ClamXav_2.6.3.dmg'
  homepage 'http://www.clamxav.com/'
  version '2.6.3'
  sha256 '34791173e31b297353025013e0296f7014e34310542a6e1cdf46e83a0254691f'
  link 'ClamXav.app'
  after_install do
    # Don't ask to move the app bundle to /Applications
    system '/usr/bin/defaults', 'write', 'uk.co.markallan.clamxav', 'moveToApplicationsFolderAlertSuppress', '-bool', 'true'
  end
  caveats do
    # this happens sometime after installation, but still worth warning about
    files_in_usr_local
  end
end


text:
<?php

namespace Swaggest\GoCodeBuilder\JsonSchema;

use Swaggest\GoCodeBuilder\Templates\Code;
use Swaggest\GoCodeBuilder\Templates\GoTemplate;

class UnmarshalUnion extends GoTemplate
{
    /** @var GoBuilder */
    public $goBuilder;

    public $withPatternProperties;

    public $patterns = [];
    public $regexNames = [];

    public function patternVarName($pattern)
    {
        if (isset($this->patterns[$pattern])) {
            return $this->patterns[$pattern];
        }
        $regexName = $this->goBuilder->codeBuilder->privateName('regex_' . $pattern);
        $i = 0;
        while (isset($this->regexNames[$regexName]) && $pattern !== $this->regexNames[$regexName]) {
            $i++;
            $regexName = $this->goBuilder->codeBuilder->privateName('regex_' . $pattern) . $i;
        }
        $this->patterns[$pattern] = $regexName;
        $this->regexNames[$regexName] = $pattern;
        return $regexName;
    }

    protected function toString()
    {
        $code = new Code();
        $code->imports()
            ->addByName('encoding/json');

        if ($this->withPatternProperties) {
            $code->imports()
                ->addByName('regexp');

            $var = '';
            foreach ($this->patterns as $pattern => $regexName) {
                // var regex = regexp.MustCompile(`^[a-zA-Z0-9\.\-_]+$`)
                $var .= "\t$regexName = regexp.MustCompile({$this->escapeValue($pattern)})\n";
            }
            $code->addSnippet(<<<GO
// Regular expressions for pattern properties.
var (
$var)

GO
            );
        }

        return $code;
    }
}


text:
namespace Aspose.BarCode.Examples.CSharp.BarcodeRecognition
{
    internal class ReadMultiThreadingBase
    {
        protected const string _RecognitionPath = "Recognition";
        protected static string GetFolder()
        {
            return BarcodePathUtils.GetDataDir_Folders(_RecognitionPath, "Main");
        }
    }
}


text:
from .. import Tractography
from .. import (
    tractography_from_trackvis_file, tractography_to_trackvis_file,
    tractography_from_files, tractography_to_file
)

try:
    VTK = True
    from ..vtkInterface import (
        tractography_from_vtk_files, tractography_to_vtk_file,
    )
except ImportError:
    VTK = False

from nose.tools import with_setup
import copy
from itertools import chain

from numpy import all, eye, ones, allclose
from numpy.random import randint, randn
from numpy.testing import assert_array_equal

dimensions = None
tracts = None
tracts_data = None
tractography = None
max_tract_length = 50
n_tracts = 50

def equal_tracts(a, b):
    for t1, t2 in zip(a, b):
        if not (len(t1) == len(t2) and allclose(t1, t2)):
            return False

    return True

def equal_tracts_data(a, b):
    if set(a.keys()) != set(b.keys()):
        return False

    for k in a.keys():
        v1 = a[k]
        v2 = b[k]
        if isinstance(v1, str) and isinstance(v2, str) and v1 == v2:
            continue
        elif not isinstance(v1, str) and not isinstance(v2, str):
            for t1, t2 in zip(a[k], b[k]):
                if not (len(t1) == len(t2) and allclose(t1, t2)):
                    return False
        else:
            return False
    return True

def equal_tractography(a, b):
    return (
        equal_tracts(a.tracts(), b.tracts()) and
        equal_tracts_data(a.tracts_data(), b.tracts_data())
    )

def setup(*args, **kwargs):
    global dimensions
    global tracts
    global tracts_data
    global tractography

    if 'test_active_data' in kwargs:
        test_active_data = kwargs['test_active_data']
    else:
        test_active_data = False

    dimensions = [(randint(5, max_tract_length), 3) for _ in range(n_tracts)]
    tracts = [randn(*d) for d in dimensions]
    tracts_data = {
        'a%d' % i: [
            randn(d[0], k)
            for d in dimensions
        ]
        for i, k in zip(range(4), randint(1, 3, 9))
    }

    if test_active_data:
        mask = 0
        for k, v in tracts_data.items():
            if mask & (1 + 2 + 4):
                break
            if v[0].shape[1] == 1 and mask & 1 == 0:
                tracts_data['ActiveScalars'] = k
                mask |= 1
            if v[0].shape[1] == 3 and mask & 2 == 0:
                tracts_data['ActiveVectors'] = k
                mask |= 2
            if v[0].shape[1] == 9 and mask & 4 == 0:
                tracts_data['ActiveTensors'] = k
                mask |= 4

    tractography = Tractography(tracts, tracts_data)

@with_setup(setup)
def test_creation():
    assert(equal_tracts(tractography.tracts(), tracts))
    assert(equal_tracts_data(tractography.tracts_data(), tracts_data))
    assert(not tractography.are_tracts_subsampled())
    assert(not tractography.are_tracts_filtered())

@with_setup(setup)
def test_subsample_tracts():
    tractography.subsample_tracts(5)

    assert(all(tract.shape[0] <= 5 for tract in tractography.tracts()))
    assert(
        all(
            all(values.shape[0] <= 5 for values in value)
            for value in tractography.tracts_data().values()
        )
    )

    assert(not equal_tracts(tractography.tracts(), tractography.original_tracts()))
    assert(equal_tracts(tracts, tractography.original_tracts()))
    assert(not equal_tracts_data(tractography.tracts_data(), tractography.original_tracts_data()))
    assert(equal_tracts_data(tracts_data, tractography.original_tracts_data()))
    assert(tractography.are_tracts_subsampled())

    tractography.unsubsample_tracts()
    assert(equal_tracts(tractography.tracts(), tracts))
    assert(equal_tracts_data(tractography.tracts_data(), tracts_data))
    assert(not tractography.are_tracts_subsampled())
    assert(not tractography.are_tracts_filtered())

@with_setup(setup)
def test_append():
    old_tracts = copy.deepcopy(tractography.tracts())
    new_data = {}
    for k, v in tracts_data.items():
        new_data[k] = v + v

    tractography.append(tracts, tracts_data)

    assert(equal_tracts(tractography.tracts(), chain(old_tracts, old_tracts)))
    assert(equal_tracts_data(tractography.tracts_data(), new_data))

if VTK:
    @with_setup(setup)
    def test_saveload_vtk():
        import tempfile
        import os
        fname = tempfile.mkstemp('.vtk')[1]
        tractography_to_vtk_file(fname, tractography)

        new_tractography = tractography_from_vtk_files(fname)

        assert(equal_tracts(tractography.tracts(), new_tractography.tracts()))
        assert(equal_tracts_data(
            tractography.tracts_data(),
            new_tractography.tracts_data())
        )

        os.remove(fname)

    @with_setup(setup)
    def test_saveload_vtp():
        import tempfile
        import os
        fname = tempfile.mkstemp('.vtp')[1]
        tractography_to_vtk_file(fname, tractography)

        new_tractography = tractography_from_vtk_files(fname)

        assert(equal_tracts(tractography.tracts(), new_tractography.tracts()))
        assert(equal_tracts_data(tractography.tracts_data(), new_tractography.tracts_data()))

        os.remove(fname)

@with_setup(setup)
def test_saveload_trk():
    import tempfile
    import os
    fname = tempfile.mkstemp('.trk')[1]

    tract_data_new = {
        k: v
        for k, v in tractography.tracts_data().items()
        if (v[0].ndim == 1) or (v[0].ndim == 2 and v[0].shape[1] == 1)
    }

    tractography_ = Tractography(tractography.tracts(), tract_data_new)

    tractography_to_trackvis_file(
        fname, tractography_,
        affine=eye(4), image_dimensions=ones(3)
    )

    new_tractography = tractography_from_trackvis_file(fname)

    assert(equal_tracts(tractography_.tracts(), new_tractography.tracts()))
    assert(equal_tracts_data(tractography_.tracts_data(), new_tractography.tracts_data()))
    assert_array_equal(eye(4), new_tractography.affine)
    assert_array_equal(ones(3), new_tractography.image_dims)

    os.remove(fname)

@with_setup(setup)
def test_saveload():
    import tempfile
    import os

    extensions = ('.trk',)
    if VTK:
        extensions += ('.vtk', '.vtp')

    for ext in extensions:
        fname = tempfile.mkstemp(ext)[1]

        kwargs = {}

        if ext == '.trk':
            kwargs['affine'] = eye(4)
            kwargs['image_dimensions'] = ones(3)

            tract_data_new = {
                k: v
                for k, v in tractography.tracts_data().items()
                if (v[0].ndim == 1) or (v[0].ndim == 2 and v[0].shape[1] == 1)
            }

            tractography_ = Tractography(tractography.tracts(), tract_data_new)
        else:
            tractography_ = tractography

        tractography_to_file(
            fname, tractography_,
            **kwargs
        )

        new_tractography = tractography_from_files(fname)

        assert(equal_tracts(tractography_.tracts(), new_tractography.tracts()))
        assert(equal_tracts_data(
            tractography_.tracts_data(),
            new_tractography.tracts_data()
        ))

        os.remove(fname)


text:
require 'rails_helper'

# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator.  If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails.  There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec.  Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.

RSpec.describe AdTypesController, :type => :controller do

  # This should return the minimal set of attributes required to create a valid
  # AdType. As you add validations to AdType, be sure to
  # adjust the attributes here as well.
  let(:valid_attributes) {
    skip("Add a hash of attributes valid for your model")
  }

  let(:invalid_attributes) {
    skip("Add a hash of attributes invalid for your model")
  }

  # This should return the minimal set of values that should be in the session
  # in order to pass any filters (e.g. authentication) defined in
  # AdTypesController. Be sure to keep this updated too.
  let(:valid_session) { {} }

  describe "GET index" do
    it "assigns all ad_types as @ad_types" do
      ad_type = AdType.create! valid_attributes
      get :index, {}, valid_session
      expect(assigns(:ad_types)).to eq([ad_type])
    end
  end

  describe "GET show" do
    it "assigns the requested ad_type as @ad_type" do
      ad_type = AdType.create! valid_attributes
      get :show, {:id => ad_type.to_param}, valid_session
      expect(assigns(:ad_type)).to eq(ad_type)
    end
  end

  describe "GET new" do
    it "assigns a new ad_type as @ad_type" do
      get :new, {}, valid_session
      expect(assigns(:ad_type)).to be_a_new(AdType)
    end
  end

  describe "GET edit" do
    it "assigns the requested ad_type as @ad_type" do
      ad_type = AdType.create! valid_attributes
      get :edit, {:id => ad_type.to_param}, valid_session
      expect(assigns(:ad_type)).to eq(ad_type)
    end
  end

  describe "POST create" do
    describe "with valid params" do
      it "creates a new AdType" do
        expect {
          post :create, {:ad_type => valid_attributes}, valid_session
        }.to change(AdType, :count).by(1)
      end

      it "assigns a newly created ad_type as @ad_type" do
        post :create, {:ad_type => valid_attributes}, valid_session
        expect(assigns(:ad_type)).to be_a(AdType)
        expect(assigns(:ad_type)).to be_persisted
      end

      it "redirects to the created ad_type" do
        post :create, {:ad_type => valid_attributes}, valid_session
        expect(response).to redirect_to(AdType.last)
      end
    end

    describe "with invalid params" do
      it "assigns a newly created but unsaved ad_type as @ad_type" do
        post :create, {:ad_type => invalid_attributes}, valid_session
        expect(assigns(:ad_type)).to be_a_new(AdType)
      end

      it "re-renders the 'new' template" do
        post :create, {:ad_type => invalid_attributes}, valid_session
        expect(response).to render_template("new")
      end
    end
  end

  describe "PUT update" do
    describe "with valid params" do
      let(:new_attributes) {
        skip("Add a hash of attributes valid for your model")
      }

      it "updates the requested ad_type" do
        ad_type = AdType.create! valid_attributes
        put :update, {:id => ad_type.to_param, :ad_type => new_attributes}, valid_session
        ad_type.reload
        skip("Add assertions for updated state")
      end

      it "assigns the requested ad_type as @ad_type" do
        ad_type = AdType.create! valid_attributes
        put :update, {:id => ad_type.to_param, :ad_type => valid_attributes}, valid_session
        expect(assigns(:ad_type)).to eq(ad_type)
      end

      it "redirects to the ad_type" do
        ad_type = AdType.create! valid_attributes
        put :update, {:id => ad_type.to_param, :ad_type => valid_attributes}, valid_session
        expect(response).to redirect_to(ad_type)
      end
    end

    describe "with invalid params" do
      it "assigns the ad_type as @ad_type" do
        ad_type = AdType.create! valid_attributes
        put :update, {:id => ad_type.to_param, :ad_type => invalid_attributes}, valid_session
        expect(assigns(:ad_type)).to eq(ad_type)
      end

      it "re-renders the 'edit' template" do
        ad_type = AdType.create! valid_attributes
        put :update, {:id => ad_type.to_param, :ad_type => invalid_attributes}, valid_session
        expect(response).to render_template("edit")
      end
    end
  end

  describe "DELETE destroy" do
    it "destroys the requested ad_type" do
      ad_type = AdType.create! valid_attributes
      expect {
        delete :destroy, {:id => ad_type.to_param}, valid_session
      }.to change(AdType, :count).by(-1)
    end

    it "redirects to the ad_types list" do
      ad_type = AdType.create! valid_attributes
      delete :destroy, {:id => ad_type.to_param}, valid_session
      expect(response).to redirect_to(ad_types_url)
    end
  end

end


text:
import argparse
import csv
import sys

def get_data(input_file, before_column, after_column):

    def get_selected_csv_rows(input_file, before_column, after_column):
        for row in csv.DictReader(input_file):
            before = float(row[before_column])
            after = float(row[after_column])
            if before > 0:
                delta = after / before
            else:
                delta = 1
            yield delta

    def f(input_data):
        result = list(enumerate(sorted(input_data)))
        count = float(len(result) - 1)
        return [(x[0] / count, x[1]) for x in result]

    return f(get_selected_csv_rows(input_file, before_column, after_column))

def main():
    p = argparse.ArgumentParser(description="""

    A script that reads in a csv file, splices out selected before/after
    column, and then outputs a new csv file with that data in s-curve form. An
    s-curve is a graph where one sorts the output %-change and graphs the %-n
    vs %-change.

    NOTE: We assume that the csv has a csv header that maps to the before and
    after column names passed in.
    """)

    p.add_argument('input_file', type=argparse.FileType('r'))
    p.add_argument('before_column_name', type=str)
    p.add_argument('after_column_name', type=str)

    args = p.parse_args()

    data = get_data(args.input_file, args.before_column_name,
                    args.after_column_name)
    w = csv.DictWriter(sys.stdout, fieldnames=['N/total', 'New/Old'])
    w.writeheader()
    for d in data:
        w.writerow({'N/total': d[0], 'New/Old': d[1]})

if __name__ == "__main__":
    main()


text:
package org.apache.pulsar.broker.service.schema;

import static com.google.common.base.Preconditions.checkArgument;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.util.Collections;
import java.util.LinkedList;
import lombok.extern.slf4j.Slf4j;
import org.apache.avro.Schema;
import org.apache.avro.SchemaParseException;
import org.apache.avro.SchemaValidationException;
import org.apache.avro.SchemaValidator;
import org.apache.avro.SchemaValidatorBuilder;
import org.apache.pulsar.broker.service.schema.exceptions.IncompatibleSchemaException;
import org.apache.pulsar.common.policies.data.SchemaCompatibilityStrategy;
import org.apache.pulsar.common.protocol.schema.SchemaData;

/**
 * The abstract implementation of {@link SchemaCompatibilityCheck} using Avro Schema.
 */
@Slf4j
abstract class AvroSchemaBasedCompatibilityCheck implements SchemaCompatibilityCheck {

    @Override
    public void checkCompatible(SchemaData from, SchemaData to, SchemaCompatibilityStrategy strategy)
            throws IncompatibleSchemaException {
        checkCompatible(Collections.singletonList(from), to, strategy);
    }

    @Override
    public void checkCompatible(Iterable<SchemaData> from, SchemaData to, SchemaCompatibilityStrategy strategy)
            throws IncompatibleSchemaException {
        LinkedList<Schema> fromList = new LinkedList<>();
        checkArgument(from != null, "check compatibility list is null");
        try {
            for (SchemaData schemaData : from) {
                Schema.Parser parser = new Schema.Parser();
                parser.setValidateDefaults(false);
                fromList.addFirst(parser.parse(new String(schemaData.getData(), UTF_8)));
            }
            Schema.Parser parser = new Schema.Parser();
            parser.setValidateDefaults(false);
            Schema toSchema = parser.parse(new String(to.getData(), UTF_8));
            SchemaValidator schemaValidator = createSchemaValidator(strategy);
            schemaValidator.validate(toSchema, fromList);
        } catch (SchemaParseException e) {
            log.warn("Error during schema parsing: {}", e.getMessage());
            throw new IncompatibleSchemaException(e);
        } catch (SchemaValidationException e) {
            log.warn("Error during schema compatibility check: {}", e.getMessage());
            throw new IncompatibleSchemaException(e);
        }
    }

    static SchemaValidator createSchemaValidator(SchemaCompatibilityStrategy compatibilityStrategy) {
        final SchemaValidatorBuilder validatorBuilder = new SchemaValidatorBuilder();
        switch (compatibilityStrategy) {
            case BACKWARD_TRANSITIVE:
                return createLatestOrAllValidator(validatorBuilder.canReadStrategy(), false);
            case BACKWARD:
                return createLatestOrAllValidator(validatorBuilder.canReadStrategy(), true);
            case FORWARD_TRANSITIVE:
                return createLatestOrAllValidator(validatorBuilder.canBeReadStrategy(), false);
            case FORWARD:
                return createLatestOrAllValidator(validatorBuilder.canBeReadStrategy(), true);
            case FULL_TRANSITIVE:
                return createLatestOrAllValidator(validatorBuilder.mutualReadStrategy(), false);
            case FULL:
                return createLatestOrAllValidator(validatorBuilder.mutualReadStrategy(), true);
            case ALWAYS_COMPATIBLE:
                return AlwaysSchemaValidator.INSTANCE;
            default:
                return NeverSchemaValidator.INSTANCE;
        }
    }

    static SchemaValidator createLatestOrAllValidator(SchemaValidatorBuilder validatorBuilder, boolean onlyLatest) {
        return onlyLatest ? validatorBuilder.validateLatest() : validatorBuilder.validateAll();
    }
}


text:
from casexml.apps.case.models import CommCareCase
from dimagi.utils.decorators.memoized import memoized
from touchforms.formplayer.api import post_data
import json
from django.conf import settings
from corehq.apps.cloudcare import CLOUDCARE_DEVICE_ID
from django.core.urlresolvers import reverse
from corehq.apps.users.models import CommCareUser

DELEGATION_STUB_CASE_TYPE = "cc_delegation_stub"

class SessionDataHelper(object):
    def __init__(self, domain, couch_user, case_id=None, delegation=False, offline=False):
        self.domain = domain
        self.couch_user = couch_user
        self.case_id = case_id
        self._delegation = delegation
        self.offline = offline

    @property
    @memoized
    def case(self):
        return CommCareCase.get(self.case_id)

    @property
    def case_type(self):
        return self.case.type

    @property
    def _case_parent_id(self):
        """Only makes sense if the case is a delegation stub"""
        return self.case.get_index_map().get('parent')['case_id']

    @property
    def delegation(self):
        if self._delegation and self.case_id:
            assert self.case_type == DELEGATION_STUB_CASE_TYPE
        return self._delegation

    def get_session_data(self, device_id=CLOUDCARE_DEVICE_ID):
        """
        Get session data used by touchforms.
        """
        # NOTE: Better to use isinstance(self.couch_user, CommCareUser) here rather than
        # self.couch_user.is_commcare_user() since this function is reused by smsforms where
        # the recipient can be a case.
        session_data = {
            'device_id': device_id,
            'app_version': '2.0',
            'username': self.couch_user.raw_username,
            'user_id': self.couch_user.get_id,
            'domain': self.domain,
            'user_data': self.couch_user.user_data if isinstance(self.couch_user, CommCareUser) else {},
        }
        if self.case_id:
            if self.delegation:
                session_data["delegation_id"] = self.case_id
                session_data["case_id"] = self._case_parent_id
            else:
                session_data["case_id"] = self.case_id

        return session_data

    def filter_cases(self, xpath, additional_filters=None, auth=None):
        """
        Filter a list of cases by an xpath expression + additional filters
        """
        session_data = self.get_session_data()
        session_data["additional_filters"] = additional_filters or {}

        data = {
            "action": "touchcare-filter-cases",
            "filter_expr": xpath,
            "session_data": session_data,
        }

        response = post_data(
            json.dumps(data),
            url=settings.XFORMS_PLAYER_URL,
            content_type="text/json", auth=auth
        )

        return json.loads(response)

    def get_full_context(self, form_url):
        """
        Get the entire touchforms context for a given user/app/module/form/case
        """
        session_data = self.get_session_data()
        # always tell touchforms to include footprinted cases in its case db
        session_data["additional_filters"] = {"footprint": True}

        online_url = reverse("xform_player_proxy")
        offline_url = 'http://localhost:%d' % settings.OFFLINE_TOUCHFORMS_PORT

        return {
            "form_url": form_url,
            "session_data": session_data,
            "xform_url": offline_url if self.offline else online_url,
        }

def get_session_data(domain, couch_user, case_id=None, device_id=CLOUDCARE_DEVICE_ID, delegation=False):
    return SessionDataHelper(domain, couch_user, case_id, delegation=delegation).get_session_data(device_id)

def filter_cases(domain, couch_user, xpath, additional_filters=None, auth=None, delegation=False):
    return SessionDataHelper(domain, couch_user, delegation=delegation).filter_cases(xpath, additional_filters, auth)

def get_full_context(domain, user, app, form_url, case_id=None, delegation=False, offline=False):
    return SessionDataHelper(domain, user, case_id, delegation=delegation, offline=offline).get_full_context(form_url)


text:
<?php
// contributed by "Heinz Hombergs" <opn@hhombergs.de>
$ADODB_LANG_ARRAY = array (
			'LANG'                      => 'de',
			DB_ERROR                    => 'Unbekannter Fehler',
            DB_ERROR_ALREADY_EXISTS     => 'existiert bereits',
            DB_ERROR_CANNOT_CREATE      => 'kann nicht erstellen',
            DB_ERROR_CANNOT_DELETE      => 'kann nicht löschen',
            DB_ERROR_CANNOT_DROP        => 'Tabelle oder Index konnte nicht gelöscht werden',
            DB_ERROR_CONSTRAINT         => 'Constraint Verletzung',
            DB_ERROR_DIVZERO            => 'Division durch Null',
            DB_ERROR_INVALID            => 'ung¨ltig',
            DB_ERROR_INVALID_DATE       => 'ung¨ltiges Datum oder Zeit',
            DB_ERROR_INVALID_NUMBER     => 'ung¨ltige Zahl',
            DB_ERROR_MISMATCH           => 'Unverträglichkeit',
            DB_ERROR_NODBSELECTED       => 'keine Dantebank ausgewählt',
            DB_ERROR_NOSUCHFIELD        => 'Feld nicht vorhanden',
            DB_ERROR_NOSUCHTABLE        => 'Tabelle nicht vorhanden',
            DB_ERROR_NOT_CAPABLE        => 'Funktion nicht installiert',
            DB_ERROR_NOT_FOUND          => 'nicht gefunden',
            DB_ERROR_NOT_LOCKED         => 'nicht gesperrt',
            DB_ERROR_SYNTAX             => 'Syntaxfehler',
            DB_ERROR_UNSUPPORTED        => 'nicht Unterst¨tzt',
            DB_ERROR_VALUE_COUNT_ON_ROW => 'Anzahl der zur¨ckgelieferten Felder entspricht nicht der Anzahl der Felder in der Abfrage',
            DB_ERROR_INVALID_DSN        => 'ung¨ltiger DSN',
            DB_ERROR_CONNECT_FAILED     => 'Verbindung konnte nicht hergestellt werden',
            0	                       => 'kein Fehler', // DB_OK
            DB_ERROR_NEED_MORE_DATA     => 'Nicht gen¨gend Daten geliefert',
            DB_ERROR_EXTENSION_NOT_FOUND=> 'erweiterung nicht gefunden',
            DB_ERROR_NOSUCHDB           => 'keine Datenbank',
            DB_ERROR_ACCESS_VIOLATION   => 'ungen¨gende Rechte'
);


text:
<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$filder = array(12, 20, 40, 60, 100);
$sort	= array('id'=>'Default', 'title'=>'Name', 'price'=>'Price', 'created'=>'Date');

$orderby	= $this->input->get('orderby');
if ($orderby == '' || empty($sort[$orderby])) $orderby = 'id';

$order	= $this->input->get('order');
if ($order == '' || ($order != 'asc' && $order != 'desc')) $order = 'asc';
if ($order == 'asc') $new_order = 'desc';
else $new_order = 'asc';

$limit		= $this->input->get('limit');
if ($limit == '') $limit = 12;

$link = site_url('categories/'.$category->id.'-'.$category->slug).'/'.$page;
?>

		<a href="<?php echo $link . '?orderby='. $orderby .'&order='.$new_order.'&limit='.$limit; ?>" class="btn btn-default btn-sm" title="<?php echo $order; ?>">
			<i class="fa fa-sort-amount-<?php echo $new_order; ?>">

			<button type="button" class="btn btn-default btn-sm"><?php echo lang('sort_by'); ?> <?php echo $sort[$orderby]; ?></button>

			<button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">

				<?php echo lang('categories_filter_toggle_dropdown'); ?>
			</button>

				<?php foreach($sort as $key => $title) { ?>

<a href="<?php echo $link . '?orderby='. $key .'&order='.$order.'&limit='.$limit; ?>"><?php echo lang('sort_by'); ?> <?php echo $title; ?>

				<?php } ?>

		<button type="button" class="btn btn-default btn-sm"><?php echo lang('show'); ?> <?php echo $limit; ?> <?php echo lang('product'); ?></button>

		<button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">

			<?php echo lang('categories_filter_toggle_dropdown'); ?>
		</button>

			<?php foreach($filder as $key) { ?>

<a href="<?php echo $link . '?orderby='. $orderby .'&order='.$order.'&limit='.$key; ?>"><?php echo lang('show'); ?> <?php echo $key; ?> <?php echo lang('product'); ?>

			<?php } ?>


text:
"See PluginDonnezmoi"
from toflib import Plugin
import time
from unidecode import unidecode

class PluginDonnezmoi(Plugin):
    "A 'gimme a xxx' banner generator plugin"

    def handle_msg(self, msg_text, _chan, _nick):
        "Write a banner if input looks like a banner query"
        msg = msg_text.split(" ")
        if msg[0:2] == ['donnez', 'moi'] and msg[2] in ('un', 'une'):
            what = unidecode((' '.join(msg[3:])).decode("utf-8"))
            for char in what:
                self.say(char.upper())
                time.sleep(0.5)


text:
<ParaViewReaders>
  <Reader name="SVTKReader" extensions="svtk"
    file_description="Separated Variables Files">
  </Reader>
</ParaViewReaders>