text:
#region Foreign-License
// .Net40 Polyfill
#endregion
#if !CLR4
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace System.Threading
{
    /// <summary>
    /// CancellationTokenRegistration
    /// </summary>
    [StructLayout(LayoutKind.Sequential), HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
    public struct CancellationTokenRegistration : IEquatable<CancellationTokenRegistration>, IDisposable
    {
        private readonly CancellationCallbackInfo _callbackInfo;
        private readonly SparselyPopulatedArrayAddInfo<CancellationCallbackInfo> _registrationInfo;

        [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
        internal CancellationTokenRegistration(CancellationCallbackInfo callbackInfo, SparselyPopulatedArrayAddInfo<CancellationCallbackInfo> registrationInfo)
        {
            _callbackInfo = callbackInfo;
            _registrationInfo = registrationInfo;
        }

        [FriendAccessAllowed]
        internal bool TryDeregister()
        {
            if (_registrationInfo.Source == null)
                return false;
            if (_registrationInfo.Source.SafeAtomicRemove(_registrationInfo.Index, _callbackInfo) != _callbackInfo)
                return false;
            return true;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            var flag = TryDeregister();
            var callbackInfo = _callbackInfo;
            if (callbackInfo != null)
            {
                var cancellationTokenSource = callbackInfo.CancellationTokenSource;
                if (cancellationTokenSource.IsCancellationRequested && !cancellationTokenSource.IsCancellationCompleted && !flag && cancellationTokenSource.ThreadIDExecutingCallbacks != Thread.CurrentThread.ManagedThreadId)
                    cancellationTokenSource.WaitForCallbackToComplete(_callbackInfo);
            }
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>
        /// The result of the operator.
        /// </returns>
        public static bool operator ==(CancellationTokenRegistration left, CancellationTokenRegistration right)
        {
            return left.Equals(right);
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>
        /// The result of the operator.
        /// </returns>
        public static bool operator !=(CancellationTokenRegistration left, CancellationTokenRegistration right)
        {
            return !left.Equals(right);
        }

        /// <summary>
        /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
        /// <returns>
        ///   <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        public override bool Equals(object obj)
        {
            return (obj is CancellationTokenRegistration && Equals((CancellationTokenRegistration)obj));
        }

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>
        /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        public bool Equals(CancellationTokenRegistration other)
        {
            return (_callbackInfo == other._callbackInfo && _registrationInfo.Source == other._registrationInfo.Source && _registrationInfo.Index == other._registrationInfo.Index);
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
        /// </returns>
        public override int GetHashCode()
        {
            if (_registrationInfo.Source != null)
                return (_registrationInfo.Source.GetHashCode() ^ _registrationInfo.Index.GetHashCode());
            return _registrationInfo.Index.GetHashCode();
        }
    }
}
#endif


text:
package de.andrena.et14.spring.konferenz;

import java.io.Serializable;
import java.util.Objects;

import org.joda.time.LocalDate;

public class Konferenz implements Serializable {

	private static final long serialVersionUID = 1L;

	private final Long id;

	private String name;
	private String ort;
	private LocalDate datum;

	public Konferenz() {
		this(null);
	}

	public Konferenz(Long id) {
		this.id = id;
	}

	public Long getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getOrt() {
		return ort;
	}

	public void setOrt(String ort) {
		this.ort = ort;
	}

	public LocalDate getDatum() {
		return datum;
	}

	public void setDatum(LocalDate datum) {
		this.datum = datum;
	}

	@Override
	public int hashCode() {
		return Objects.hashCode(id);
	}

	@Override
	public boolean equals(Object obj) {
		return obj instanceof Konferenz && idEquals((Konferenz) obj);
	}

	private boolean idEquals(Konferenz other) {
		return Objects.equals(id, other.id);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.fastmongo.odm.mapping.core;

import java.util.Collection;

/**
 * Creates collection implementations of the specified size.
 * For now it's used in common code for Set and List collections.
 *
 * @author Alexander Gulko
 */
public interface CollectionFactory {
    /**
     * Creates specific collection implementation of the given size.
     *
     * @param size the size of the collection.
     * @return the specific collection implementation.
     */
    Collection<Object> create(int size);

    /**
     * Returns the collection implementation class.
     *
     * @return the collection implementation class.
     */
    Class<? extends Collection> getCollectionClass();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<imageIndex>
  <image>
    <originalFileName>kihon practice 2.jpg</originalFileName>
    <size>560503</size>
    <dateLastModified>Thu, 05 Jan 2012 05:02:31 GMT</dateLastModified>
    <width>2048</width>
    <height>1308</height>
    <cachedImage>
      <fileName>vwyerj3b.jpeg</fileName>
      <dateCreated>Thu, 05 Jan 2012 05:12:58 GMT</dateCreated>
      <dateLastAccessed>Wed, 04 Mar 2015 16:10:10 GMT</dateLastAccessed>
      <imageFormat>jpeg</imageFormat>
      <compression>90</compression>
      <width>100</width>
      <height>64</height>
      <bgColor>#FFFFFF</bgColor>
      <transparent>True</transparent>
      <border>0</border>
      <borderColor>#000000</borderColor>
      <constrain>True</constrain>
      <pad>False</pad>
    </cachedImage>
    <cachedImage>
      <fileName>utrwjhab.jpeg</fileName>
      <dateCreated>Thu, 05 Jan 2012 07:15:30 GMT</dateCreated>
      <dateLastAccessed>Thu, 12 Mar 2015 17:51:07 GMT</dateLastAccessed>
      <imageFormat>jpeg</imageFormat>
      <compression>90</compression>
      <width>600</width>
      <height>383</height>
      <bgColor>#FFFFFF</bgColor>
      <transparent>True</transparent>
      <border>0</border>
      <borderColor>#000000</borderColor>
      <constrain>True</constrain>
      <pad>False</pad>
    </cachedImage>
    <cachedImage>
      <fileName>apojfmw5.jpeg</fileName>
      <dateCreated>Wed, 21 Mar 2012 10:21:17 GMT</dateCreated>
      <dateLastAccessed>Fri, 09 Jan 2015 11:41:41 GMT</dateLastAccessed>
      <imageFormat>jpeg</imageFormat>
      <compression>90</compression>
      <width>2048</width>
      <height>1308</height>
      <bgColor>#FFFFFF</bgColor>
      <transparent>True</transparent>
      <border>0</border>
      <borderColor>#000000</borderColor>
      <constrain>False</constrain>
      <pad>False</pad>
    </cachedImage>
  </image>
</imageIndex>


text:
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Cowboy.Buffer;
using Logrila.Logging;

namespace Cowboy.Sockets
{
    public sealed class AsyncTcpSocketSession
    {
        #region Fields

        private static readonly ILog _log = Logger.Get<AsyncTcpSocketSession>();
        private TcpClient _tcpClient;
        private readonly AsyncTcpSocketServerConfiguration _configuration;
        private readonly ISegmentBufferManager _bufferManager;
        private readonly IAsyncTcpSocketServerEventDispatcher _dispatcher;
        private readonly AsyncTcpSocketServer _server;
        private readonly string _sessionKey;
        private Stream _stream;
        private ArraySegment<byte> _receiveBuffer = default(ArraySegment<byte>);
        private int _receiveBufferOffset = 0;
        private IPEndPoint _remoteEndPoint;
        private IPEndPoint _localEndPoint;

        private int _state;
        private const int _none = 0;
        private const int _connecting = 1;
        private const int _connected = 2;
        private const int _disposed = 5;

        #endregion

        #region Constructors

        public AsyncTcpSocketSession(
            TcpClient tcpClient,
            AsyncTcpSocketServerConfiguration configuration,
            ISegmentBufferManager bufferManager,
            IAsyncTcpSocketServerEventDispatcher dispatcher,
            AsyncTcpSocketServer server)
        {
            if (tcpClient == null)
                throw new ArgumentNullException("tcpClient");
            if (configuration == null)
                throw new ArgumentNullException("configuration");
            if (bufferManager == null)
                throw new ArgumentNullException("bufferManager");
            if (dispatcher == null)
                throw new ArgumentNullException("dispatcher");
            if (server == null)
                throw new ArgumentNullException("server");

            _tcpClient = tcpClient;
            _configuration = configuration;
            _bufferManager = bufferManager;
            _dispatcher = dispatcher;
            _server = server;

            _sessionKey = Guid.NewGuid().ToString();
            this.StartTime = DateTime.UtcNow;

            SetSocketOptions();

            _remoteEndPoint = this.RemoteEndPoint;
            _localEndPoint = this.LocalEndPoint;
        }

        #endregion

        #region Properties

        public string SessionKey { get { return _sessionKey; } }
        public DateTime StartTime { get; private set; }
        public TimeSpan ConnectTimeout { get { return _configuration.ConnectTimeout; } }

        private bool Connected { get { return _tcpClient != null && _tcpClient.Client.Connected; } }
        public IPEndPoint RemoteEndPoint { get { return Connected ? (IPEndPoint)_tcpClient.Client.RemoteEndPoint : _remoteEndPoint; } }
        public IPEndPoint LocalEndPoint { get { return Connected ? (IPEndPoint)_tcpClient.Client.LocalEndPoint : _localEndPoint; } }

        public Socket Socket { get { return Connected ? _tcpClient.Client : null; } }
        public Stream Stream { get { return _stream; } }
        public AsyncTcpSocketServer Server { get { return _server; } }

        public TcpSocketConnectionState State
        {
            get
            {
                switch (_state)
                {
                    case _none:
                        return TcpSocketConnectionState.None;
                    case _connecting:
                        return TcpSocketConnectionState.Connecting;
                    case _connected:
                        return TcpSocketConnectionState.Connected;
                    case _disposed:
                        return TcpSocketConnectionState.Closed;
                    default:
                        return TcpSocketConnectionState.Closed;
                }
            }
        }

        public override string ToString()
        {
            return string.Format("SessionKey[{0}], RemoteEndPoint[{1}], LocalEndPoint[{2}]",
                this.SessionKey, this.RemoteEndPoint, this.LocalEndPoint);
        }

        #endregion

        #region Process

        internal async Task Start()
        {
            int origin = Interlocked.CompareExchange(ref _state, _connecting, _none);
            if (origin == _disposed)
            {
                throw new ObjectDisposedException("This tcp socket session has been disposed when connecting.");
            }
            else if (origin != _none)
            {
                throw new InvalidOperationException("This tcp socket session is in invalid state when connecting.");
            }

            try
            {
                var negotiator = NegotiateStream(_tcpClient.GetStream());
                if (!negotiator.Wait(ConnectTimeout))
                {
                    await Close(false); // ssl negotiation timeout
                    throw new TimeoutException(string.Format(
                        "Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
                }
                _stream = negotiator.Result;

                if (_receiveBuffer == default(ArraySegment<byte>))
                    _receiveBuffer = _bufferManager.BorrowBuffer();
                _receiveBufferOffset = 0;

                if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting)
                {
                    await Close(false); // connected with wrong state
                    throw new ObjectDisposedException("This tcp socket session has been disposed after connected.");
                }

                _log.DebugFormat("Session started for [{0}] on [{1}] in dispatcher [{2}] with session count [{3}].",
                    this.RemoteEndPoint,
                    this.StartTime.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"),
                    _dispatcher.GetType().Name,
                    this.Server.SessionCount);
                bool isErrorOccurredInUserSide = false;
                try
                {
                    await _dispatcher.OnSessionStarted(this);
                }
                catch (Exception ex) // catch all exceptions from out-side
                {
                    isErrorOccurredInUserSide = true;
                    await HandleUserSideError(ex);
                }

                if (!isErrorOccurredInUserSide)
                {
                    await Process();
                }
                else
                {
                    await Close(true); // user side handle tcp connection error occurred
                }
            }
            catch (Exception ex) // catch exceptions then log then re-throw
            {
                _log.Error(string.Format("Session [{0}] exception occurred, [{1}].", this, ex.Message), ex);
                await Close(true); // handle tcp connection error occurred
                throw;
            }
        }

        private async Task Process()
        {
            try
            {
                int frameLength;
                byte[] payload;
                int payloadOffset;
                int payloadCount;
                int consumedLength = 0;

                while (State == TcpSocketConnectionState.Connected)
                {
                    int receiveCount = await _stream.ReadAsync(
                        _receiveBuffer.Array,
                        _receiveBuffer.Offset + _receiveBufferOffset,
                        _receiveBuffer.Count - _receiveBufferOffset);
                    if (receiveCount == 0)
                        break;

                    SegmentBufferDeflector.ReplaceBuffer(_bufferManager, ref _receiveBuffer, ref _receiveBufferOffset, receiveCount);
                    consumedLength = 0;

                    while (true)
                    {
                        frameLength = 0;
                        payload = null;
                        payloadOffset = 0;
                        payloadCount = 0;

                        if (_configuration.FrameBuilder.Decoder.TryDecodeFrame(
                            _receiveBuffer.Array,
                            _receiveBuffer.Offset + consumedLength,
                            _receiveBufferOffset - consumedLength,
                            out frameLength, out payload, out payloadOffset, out payloadCount))
                        {
                            try
                            {
                                await _dispatcher.OnSessionDataReceived(this, payload, payloadOffset, payloadCount);
                            }
                            catch (Exception ex) // catch all exceptions from out-side
                            {
                                await HandleUserSideError(ex);
                            }
                            finally
                            {
                                consumedLength += frameLength;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (_receiveBuffer != null && _receiveBuffer.Array != null)
                    {
                        SegmentBufferDeflector.ShiftBuffer(_bufferManager, consumedLength, ref _receiveBuffer, ref _receiveBufferOffset);
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // looking forward to a graceful quit from the ReadAsync but the inside EndRead will raise the ObjectDisposedException,
                // so a gracefully close for the socket should be a Shutdown, but we cannot avoid the Close triggers this happen.
            }
            catch (Exception ex)
            {
                await HandleReceiveOperationException(ex);
            }
            finally
            {
                await Close(true); // read async buffer returned, remote notifies closed
            }
        }

        private void SetSocketOptions()
        {
            _tcpClient.ReceiveBufferSize = _configuration.ReceiveBufferSize;
            _tcpClient.SendBufferSize = _configuration.SendBufferSize;
            _tcpClient.ReceiveTimeout = (int)_configuration.ReceiveTimeout.TotalMilliseconds;
            _tcpClient.SendTimeout = (int)_configuration.SendTimeout.TotalMilliseconds;
            _tcpClient.NoDelay = _configuration.NoDelay;
            _tcpClient.LingerState = _configuration.LingerState;

            if (_configuration.KeepAlive)
            {
                _tcpClient.Client.SetSocketOption(
                    SocketOptionLevel.Socket,
                    SocketOptionName.KeepAlive,
                    (int)_configuration.KeepAliveInterval.TotalMilliseconds);
            }

            _tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, _configuration.ReuseAddress);
        }

        private async Task<Stream> NegotiateStream(Stream stream)
        {
            if (!_configuration.SslEnabled)
                return stream;

            var validateRemoteCertificate = new RemoteCertificateValidationCallback(
                (object sender,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors)
                =>
                {
                    if (sslPolicyErrors == SslPolicyErrors.None)
                        return true;

                    if (_configuration.SslPolicyErrorsBypassed)
                        return true;
                    else
                        _log.ErrorFormat("Session [{0}] error occurred when validating remote certificate: [{1}], [{2}].",
                            this, this.RemoteEndPoint, sslPolicyErrors);

                    return false;
                });

            var sslStream = new SslStream(
                stream,
                false,
                validateRemoteCertificate,
                null,
                _configuration.SslEncryptionPolicy);

            if (!_configuration.SslClientCertificateRequired)
            {
                await sslStream.AuthenticateAsServerAsync(
                    _configuration.SslServerCertificate); // The X509Certificate used to authenticate the server.
            }
            else
            {
                await sslStream.AuthenticateAsServerAsync(
                    _configuration.SslServerCertificate, // The X509Certificate used to authenticate the server.
                    _configuration.SslClientCertificateRequired, // A Boolean value that specifies whether the client must supply a certificate for authentication.
                    _configuration.SslEnabledProtocols, // The SslProtocols value that represents the protocol used for authentication.
                    _configuration.SslCheckCertificateRevocation); // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
            }

            // When authentication succeeds, you must check the IsEncrypted and IsSigned properties
            // to determine what security services are used by the SslStream.
            // Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
            _log.DebugFormat(
                "Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
                + "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
                sslStream.SslProtocol,
                sslStream.IsServer,
                sslStream.IsAuthenticated,
                sslStream.IsEncrypted,
                sslStream.IsSigned,
                sslStream.IsMutuallyAuthenticated,
                sslStream.HashAlgorithm,
                sslStream.HashStrength,
                sslStream.KeyExchangeAlgorithm,
                sslStream.KeyExchangeStrength,
                sslStream.CipherAlgorithm,
                sslStream.CipherStrength);

            return sslStream;
        }

        #endregion

        #region Close

        public async Task Close()
        {
            await Close(true); // close by external
        }

        private async Task Close(bool shallNotifyUserSide)
        {
            if (Interlocked.Exchange(ref _state, _disposed) == _disposed)
            {
                return;
            }

            Shutdown();

            if (shallNotifyUserSide)
            {
                _log.DebugFormat("Session closed for [{0}] on [{1}] in dispatcher [{2}] with session count [{3}].",
                    this.RemoteEndPoint,
                    DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"),
                    _dispatcher.GetType().Name,
                    this.Server.SessionCount - 1);
                try
                {
                    await _dispatcher.OnSessionClosed(this);
                }
                catch (Exception ex) // catch all exceptions from out-side
                {
                    await HandleUserSideError(ex);
                }
            }

            Clean();
        }

        public void Shutdown()
        {
            // The correct way to shut down the connection (especially if you are in a full-duplex conversation)
            // is to call socket.Shutdown(SocketShutdown.Send) and give the remote party some time to close
            // their send channel. This ensures that you receive any pending data instead of slamming the
            // connection shut. ObjectDisposedException should never be part of the normal application flow.
            if (_tcpClient != null && _tcpClient.Connected)
            {
                _tcpClient.Client.Shutdown(SocketShutdown.Send);
            }
        }

        private void Clean()
        {
            try
            {
                try
                {
                    if (_stream != null)
                    {
                        _stream.Dispose();
                    }
                }
                catch { }
                try
                {
                    if (_tcpClient != null)
                    {
                        _tcpClient.Close();
                    }
                }
                catch { }
            }
            catch { }
            finally
            {
                _stream = null;
                _tcpClient = null;
            }

            if (_receiveBuffer != default(ArraySegment<byte>))
                _configuration.BufferManager.ReturnBuffer(_receiveBuffer);
            _receiveBuffer = default(ArraySegment<byte>);
            _receiveBufferOffset = 0;
        }

        #endregion

        #region Exception Handler

        private async Task HandleSendOperationException(Exception ex)
        {
            if (IsSocketTimeOut(ex))
            {
                await CloseIfShould(ex);
                throw new TcpSocketException(ex.Message, new TimeoutException(ex.Message, ex));
            }

            await CloseIfShould(ex);
            throw new TcpSocketException(ex.Message, ex);
        }

        private async Task HandleReceiveOperationException(Exception ex)
        {
            if (IsSocketTimeOut(ex))
            {
                await CloseIfShould(ex);
                throw new TcpSocketException(ex.Message, new TimeoutException(ex.Message, ex));
            }

            await CloseIfShould(ex);
            throw new TcpSocketException(ex.Message, ex);
        }

        private bool IsSocketTimeOut(Exception ex)
        {
            return ex is IOException
                && ex.InnerException != null
                && ex.InnerException is SocketException
                && (ex.InnerException as SocketException).SocketErrorCode == SocketError.TimedOut;
        }

        private async Task<bool> CloseIfShould(Exception ex)
        {
            if (ex is ObjectDisposedException
                || ex is InvalidOperationException
                || ex is SocketException
                || ex is IOException
                || ex is NullReferenceException // buffer array operation
                || ex is ArgumentException      // buffer array operation
                )
            {
                _log.Error(ex.Message, ex);

                await Close(true); // catch specified exception then intend to close the session

                return true;
            }

            return false;
        }

        private async Task HandleUserSideError(Exception ex)
        {
            _log.Error(string.Format("Session [{0}] error occurred in user side [{1}].", this, ex.Message), ex);
            await Task.CompletedTask;
        }

        #endregion

        #region Send

        public async Task SendAsync(byte[] data)
        {
            await SendAsync(data, 0, data.Length);
        }

        public async Task SendAsync(byte[] data, int offset, int count)
        {
            BufferValidator.ValidateBuffer(data, offset, count, "data");

            if (State != TcpSocketConnectionState.Connected)
            {
                throw new InvalidOperationException("This session has not connected.");
            }

            try
            {
                byte[] frameBuffer;
                int frameBufferOffset;
                int frameBufferLength;
                _configuration.FrameBuilder.Encoder.EncodeFrame(data, offset, count, out frameBuffer, out frameBufferOffset, out frameBufferLength);

                await _stream.WriteAsync(frameBuffer, frameBufferOffset, frameBufferLength);
            }
            catch (Exception ex)
            {
                await HandleSendOperationException(ex);
            }
        }

        #endregion
    }
}


text:
var snippetsModel = {

    snippets: ko.observableArray([]),
    content: ko.observable(''),
    cm: null,
    hasFile: ko.observable(false),
    name: ko.observable(''),
    title: ko.observable(''),

    current: null,
    toBeRemoved: null,

    init:function(){ // initializes the model
        snippetsModel.updateSnippets();

		ko.applyBindings(snippetsModel);  // apply bindings
	},

    updateSnippets:function(){  // updates the page types arr

        snippetsModel.snippets.removeAll();

		$.ajax({
    		url: 'api/snippet/list',
			type: 'GET',
			data: {},
			dataType: 'json',
			success: function(data){

                var i=0;
                var current = null;

                for(x in data){

                    var file = {
                        'file': data[x]
    				};

                    if(i==0){
                        current = file;
                    }

    				snippetsModel.snippets.push(file);

                    i++;
				}

                if(current!=null){
                	snippetsModel.hasFile(true);
                    snippetsModel.updateContent(current);
                }

			}
		});

	},

    updateContent:function(o){

        snippetsModel.current = o;

        var name = global.replaceAll(o.file, '.php', '');

        snippetsModel.name(name);

    	$('nav ul li').removeClass('active');
		$('nav ul li[data-file="'+o.file+'"]').addClass('active');

        $.ajax({
        	url: 'api/snippet/get',
			type: 'POST',
			data: {file: o.file},
			success: function(data){
                snippetsModel.content(data);

                // setup codemirror
                var content = $('#content').get(0);

                if(snippetsModel.cm==null){
                    snippetsModel.cm = CodeMirror.fromTextArea(content, {mode: 'text/css', lineNumbers: true});
                }
                else{
    		        snippetsModel.cm.setValue(data);
			    }

                snippetsModel.hasFile(true);

            }
		});

    },

    save:function(o, e){

		message.showMessage('progress', $('#msg-updating').val());

        var content = snippetsModel.cm.getValue();

        $.ajax({
            url: 'api/snippet/update',
			type: 'POST',
			data: {file: snippetsModel.current.file, content: content},
			success: function(data){
    			message.showMessage('success', $('#msg-updated').val());
			},
			error: function(data){
				message.showMessage('error', $('#msg-updating-error').val());
			}
		});

    },

    showAddDialog:function(o, e){
        $('#name').val('');

		$('#addDialog').modal('show');

		return false;
    },

    addSnippet:function(o, e){

        var name = jQuery.trim($('#name').val());

        name = global.replaceAll(name, '.php', '');

		if(name==''){
			message.showMessage('error', $('#msg-name-required').val());
			return false;
		}

		message.showMessage('progress', $('#msg-snippet-adding').val());

        $.ajax({
            url: 'api/snippet/add',
        	type: 'POST',
			dataType: 'json',
			data: {name: name},
			success: function(data){
                snippetsModel.snippets.push({
                	    'name': name,
                        'file': name+'.php'
    				});

    			message.showMessage('success', $('#msg-snippet-added').val());

                $('#addDialog').modal('hide');
			},
			error: function(data){
				message.showMessage('error', $('#msg-snippet-adding-error').val());
			}
		});

    },

    showRemoveDialog:function(o, e){
        snippetsModel.toBeRemoved = snippetsModel.current;

        $('#removeName').text(snippetsModel.toBeRemoved.file);

		$('#removeDialog').modal('show');

		return false;
    },

    removeSnippet: function(o, e){

    	message.showMessage('progress', $('#msg-snippet-removing').val());

        $.ajax({
            url: 'api/snippet/delete',
    		type: 'DELETE',
			data: {file: snippetsModel.toBeRemoved.file},
			success: function(data){
                snippetsModel.snippets.remove(snippetsModel.toBeRemoved); // remove the page from the model

    			message.showMessage('success', $('#msg-snippet-removed').val());

                $('#removeDialog').modal('hide');
			},
			error: function(data){
				message.showMessage('error', $('#msg-snippet-remove-error').val());
			}
		});

    }
}

snippetsModel.init();


text:
//******************************************************************************************************
//  ManageOtherDevices.xaml.cs - Gbtc
//
//  Copyright © 2010, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://www.opensource.org/licenses/eclipse-1.0.php
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  09/28/2009 - Mehulbhai P Thakkar
//       Generated original version of source code.
//
//******************************************************************************************************

using System;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace openPDCManager.Pages.Devices
{
	public partial class ManageOtherDevices : Page
	{
		#region [ Constructor ]

		public ManageOtherDevices()
		{
			InitializeComponent();
		}

		#endregion

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            UserControlManageOtherDevices.GetCompanies();
            UserControlManageOtherDevices.GetVendorDevices();
            UserControlManageOtherDevices.GetInterconnections();

            if (this.NavigationContext.QueryString.ContainsKey("did"))
            {
                UserControlManageOtherDevices.hasQueryString = true;
                UserControlManageOtherDevices.m_deviceID = Convert.ToInt32(this.NavigationContext.QueryString["did"]);
                UserControlManageOtherDevices.GetOtherDeviceByDeviceID(UserControlManageOtherDevices.m_deviceID);
            }
            else
                UserControlManageOtherDevices.ClearForm();
        }
	}
}


text:
""" Example of definition of a bore field using pre-defined configurations.

"""
import pygfunction as gt

def main():
    # -------------------------------------------------------------------------
    # Parameters
    # -------------------------------------------------------------------------

    # Borehole dimensions
    D = 4.0             # Borehole buried depth (m)
    H = 150.0           # Borehole length (m)
    r_b = 0.075         # Borehole radius (m)
    B = 7.5             # Borehole spacing (m)
    N_1 = 4             # Number of boreholes in the x-direction (columns)
    N_2 = 3             # Number of boreholes in the y-direction (rows)

    # Circular field
    N_b = 8     # Number of boreholes
    R = 5.0     # Distance of the boreholes from the center of the field (m)

    # -------------------------------------------------------------------------
    # Borehole fields
    # -------------------------------------------------------------------------

    # Rectangular field of 4 x 3 boreholes
    rectangularField = gt.boreholes.rectangle_field(N_1, N_2, B, B, H, D, r_b)

    # Box-shaped field of 4 x 3 boreholes
    boxField = gt.boreholes.box_shaped_field(N_1, N_2, B, B, H, D, r_b)

    # U-shaped field of 4 x 3 boreholes
    UField = gt.boreholes.U_shaped_field(N_1, N_2, B, B, H, D, r_b)

    # L-shaped field of 4 x 3 boreholes
    LField = gt.boreholes.L_shaped_field(N_1, N_2, B, B, H, D, r_b)

    # Circular field of 8 boreholes
    circleField = gt.boreholes.circle_field(N_b, R, H, D, r_b)

    # -------------------------------------------------------------------------
    # Draw bore fields
    # -------------------------------------------------------------------------
    for field in [rectangularField, boxField, UField, LField, circleField]:
        gt.boreholes.visualize_field(field)

    return

# Main function
if __name__ == '__main__':
    main()


text:
```sh
$ happy_seed plugin acts_as_awesome
```

The plugin generator runs `rails plugin new` and sets up a gem that can be used to extend Rails.  It sets up `rspec`, `factory-girl`, and `autotest` for testing.

```sh
$ happy_seed engines engine
```

This runs the plugin generator with the `--moutnable` flag.


text:
namespace Form_
{
    partial class Form1
    {
        /// <summary>
        /// 必要なデザイナ変数です。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 使用中のリソースをすべてクリーンアップします。
        /// </summary>
        /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows フォーム デザイナで生成されたコード

        /// <summary>
        /// デザイナ サポートに必要なメソッドです。このメソッドの内容を
        /// コード エディタで変更しないでください。
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(57, 55);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(35, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "label1";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(57, 123);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(35, 12);
            this.label2.TabIndex = 1;
            this.label2.Text = "label2";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(57, 189);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(35, 12);
            this.label3.TabIndex = 2;
            this.label3.Text = "label3";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.Activated += new System.EventHandler(this.Form1_Activated);
            this.ResumeLayout(false);
            this.PerformLayout();
            i++;    // iを1増やす.
            label1.Text = i.ToString(); // label1にi.ToStringをセット.
        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
    }
}


text:
/*
 * matrix.h
 *
 * Header file for matrix.c
 *
 * Author: Jeffrey Picard
 */
#ifndef _MATRIX_H
#define _MATRIX_H

typedef struct matrix_struct
{
  int rows;
  int columns;
  double ** values;
} matrix;

matrix *create_matrix( int, int );
void delete_matrix( matrix * );

#endif /* _MATRIX_H */


text:
#include "include/TweeFile.h"
#include "include/TweeParser.h"

#include "TweeScanner.h"
#include "include/ParseException.h"
#include <stdio.h>

using namespace Twee;
using namespace std;

class TweeParser::TweeParserImpl {
public:
    TweeParserImpl(std::istream* input) : scanner(input), parser(scanner) { }
    unique_ptr<TweeFile> parse();

private:
    TweeScanner scanner;
    BisonParser parser;
};

TweeParser::TweeParser(std::istream* input) {
    this->impl = new TweeParserImpl(input);
}

TweeParser::~TweeParser() {
    delete this->impl;
}

unique_ptr<TweeFile> TweeParser::parse() {
    return impl->parse();
}

/* impl */

unique_ptr<TweeFile> TweeParser::TweeParserImpl::parse() {
    parser.parse();

    if(!tweeStructure) {
        throw new ParseException();
    }

    unique_ptr<TweeFile> tweeFilePtr(tweeStructure);
    tweeStructure = nullptr;

    return tweeFilePtr;
}


text:
using Nestor.Models;
using Nestor.Models.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nestor.Data
{
    /// <summary>
    /// 栏目Repository
    /// </summary>
    public class ColumnRepository
    {
        #region Field
        /// <summary>
        /// 数据库连接
        /// </summary>
        private NestorEntities context;
        #endregion //Field

        #region Constructor
        /// <summary>
        /// 栏目Repository
        /// </summary>
        public ColumnRepository()
        {
            this.context = new NestorEntities();
        }
        #endregion //Constructor

        #region Method
        /// <summary>
        /// 获取所有栏目
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Column> Get()
        {
            return this.context.Columns;
        }

        /// <summary>
        /// 获取栏目
        /// </summary>
        /// <param name="id">栏目ID</param>
        /// <returns></returns>
        public Column Get(int id)
        {
            return this.context.Columns.SingleOrDefault(r => r.Id == id);
        }

        /// <summary>
        /// 添加栏目
        /// </summary>
        /// <param name="data">栏目对象</param>
        /// <returns></returns>
        public ErrorCode Create(Column data)
        {
            try
            {
                Column result = context.Columns.Add(data);
                this.context.SaveChanges();

                return ErrorCode.Success;
            }
            catch (Exception)
            {
                return ErrorCode.Exception;
            }
        }

        /// <summary>
        /// 编辑栏目
        /// </summary>
        /// <param name="data">栏目对象</param>
        /// <returns></returns>
        public ErrorCode Update(Column data)
        {
            try
            {
                this.context.Entry(data).State = EntityState.Modified;
                this.context.SaveChanges();
                return ErrorCode.Success;
            }
            catch(Exception e)
            {
                return ErrorCode.Exception;
            }
        }
        #endregion //Method
    }
}


text:
import { Tree } from 'react-wooden-tree';

/**
 * Helper
 * Changes class to className.
 * Sets undefined checkbox to null.
 * Moves the key to attr.key.
 */
const normalize = (tree, fn) => tree.map((n) => {
  let node = { ...n };
  if (node.class) {
    node = { ...node, classes: node.class };
    delete node.class;
  }

  // The server cannot send null, just undefined, this is why it is tested as a string.
  if (node.state.checked === 'undefined') {
    node = { ...node, state: { ...node.state, checked: null } };
  } else if (node.state.checked === null) {
    node = { ...node, state: { ...node.state, checked: false } };
  }

  if (node.key) {
    node = { ...node, attr: { key: node.key } };
    delete node.key;
  }

  if (node.nodes) {
    node = { ...node, nodes: normalize(node.nodes, fn) };
  }

  return fn ? fn(node) : node;
});

const flatten = (data) => Tree.convertHierarchicalTree(Tree.initHierarchicalTree(data));

// This function adjusts the nodes generated by the TreeBuilder for the usage with TreeView
const convert = (data, { check, select } = {}) => flatten(normalize(
  data,
  ({ state: { checked, selected, ...state } = {}, ...node }) => ({
    ...node,
    state: {
      ...state,
      checked: check ? check(node) : checked,
      selected: select ? select(node) : selected,
    },
  }),
));

/**
 * Helper
 * Activates the first active node in the tree, which is passed trought the props.
 *
 * FIXME Delete this function when bakcend is sending data where the initial node is activated,
 * or when all the trees calling a reducer if they want to have an activated node at the start.
 */

const activateNode = (tree, doActivate, key) => {
  if (!doActivate) {
    return tree;
  }

  let node = Tree.nodeSelector(tree, Tree.nodeSearch(tree, null, 'key', key)[0]);
  node = { ...node, state: { ...node.state, selected: true } };
  return { ...tree, [node.nodeId]: node };
};

const callBack = (nodeId, type, value, namespace) => ({
  nodeId, type, value, namespace,
});

export { convert, activateNode, callBack };


text:
<?php
/* @var $this StudentController */
/* @var $model Student */

$this->breadcrumbs=array(
	'Students'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'List Student', 'url'=>array('index')),
	array('label'=>'Manage Student', 'url'=>array('admin')),
);
?>

Create Student

<?php $this->renderPartial('_form', array('model'=>$model)); ?>


text:
.class public Landroid/filterpacks/videosink/MediaRecorderStopException;
.super Ljava/lang/RuntimeException;
.source "MediaRecorderStopException.java"

# static fields
.field private static final TAG:Ljava/lang/String; = "MediaRecorderStopException"

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 33
    invoke-direct {p0}, Ljava/lang/RuntimeException;-><init>()V

    .line 34
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;)V
    .locals 0
    .param p1, "msg"    # Ljava/lang/String;

    .prologue
    .line 29
    invoke-direct {p0, p1}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;)V

    .line 30
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;Ljava/lang/Throwable;)V
    .locals 0
    .param p1, "msg"    # Ljava/lang/String;
    .param p2, "t"    # Ljava/lang/Throwable;

    .prologue
    .line 37
    invoke-direct {p0, p1, p2}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    .line 38
    return-void
.end method

.method public constructor <init>(Ljava/lang/Throwable;)V
    .locals 0
    .param p1, "t"    # Ljava/lang/Throwable;

    .prologue
    .line 41
    invoke-direct {p0, p1}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/Throwable;)V

    .line 42
    return-void
.end method


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NoteOne_Core;
using NoteOne_Core.Common;
using NoteOne_Utility.Extensions;

namespace MagicLockScreen_Service_InterfaceLIFTService.Models
{
    public class InterfaceLIFTCollection : ModelBase
    {
        private readonly uint _maxCount;
        private RangeIncrementalLoadingClass<InterfaceLIFT> _interfaceLIFTs;

        private bool _isLoading;

        public InterfaceLIFTCollection(uint maxCount, IService[] services)
            : base(services)
        {
            _maxCount = maxCount;
            if (InterfaceLIFTs == null)
                InterfaceLIFTs = new RangeIncrementalLoadingClass<InterfaceLIFT>(maxCount,
                                                                                async (index, count) =>
                                                                                await
                                                                                LoadMoreInterfaceLIFTs(index, count));
        }

        public RangeIncrementalLoadingClass<InterfaceLIFT> InterfaceLIFTs
        {
            get { return _interfaceLIFTs; }
            private set { SetProperty(ref _interfaceLIFTs, value); }
        }

        public bool IsLoading
        {
            get { return _isLoading; }
            private set { SetProperty(ref _isLoading, value); }
        }

        public void RefreshCollection()
        {
            InterfaceLIFTs = new RangeIncrementalLoadingClass<InterfaceLIFT>(_maxCount,
                                                                             async (index, count) =>
                                                                             await LoadMoreInterfaceLIFTs(index, count));
        }

        private async Task<IList<InterfaceLIFT>> LoadMoreInterfaceLIFTs(uint index, uint count)
        {
            IsLoading = true;
            IList<InterfaceLIFT> interfaceLIFTs = null;
            try
            {
                var interfaceLIFTQueryService = this["ILQS"] as InterfaceLIFTQueryService;
                interfaceLIFTs = await interfaceLIFTQueryService.QueryDataAsync(index, count);
            }
            catch (Exception ex)
            {
                ex.WriteLog();
            }
            finally
            {
                IsLoading = false;
            }
            return interfaceLIFTs;
        }
    }
}


text:
<?php

namespace Genesis\API\Request\NonFinancial;

use Genesis\API\Traits\Request\AddressInfoAttributes;
use Genesis\API\Traits\Request\BaseAttributes;
use Genesis\API\Traits\Request\CreditCardAttributes;
use Genesis\API\Traits\Request\DocumentAttributes;
use Genesis\API\Traits\Request\Financial\CredentialOnFileAttributes;
use Genesis\API\Traits\Request\MotoAttributes;
use Genesis\API\Traits\Request\RiskAttributes;
use Genesis\Exceptions\InvalidArgument;
use Genesis\Utils\Common as CommonUtils;

/**
 * Account Verification Request
 *
 * @package    Genesis
 * @subpackage Request
 */
class AccountVerification extends \Genesis\API\Request
{
    use BaseAttributes, MotoAttributes, CreditCardAttributes, AddressInfoAttributes, RiskAttributes,
        DocumentAttributes, CredentialOnFileAttributes;

    /**
     * Set the per-request configuration
     *
     * @return void
     */
    protected function initConfiguration()
    {
        $this->initXmlConfiguration();

        $this->initApiGatewayConfiguration();
    }

    /**
     * Set the required fields
     *
     * @return void
     */
    protected function setRequiredFields()
    {
        $requiredFields = [
            'transaction_id',
            'card_holder',
            'card_number',
            'expiration_month',
            'expiration_year',
            'billing_address1',
            'billing_zip_code',
            'billing_city'
        ];

        $this->requiredFields = CommonUtils::createArrayObject($requiredFields);

        $requiredFieldValues = $this->getCCFieldValueFormatValidators();

        $this->requiredFieldValues = CommonUtils::createArrayObject($requiredFieldValues);
    }

    /**
     * Create the request's Tree structure
     *
     * @return void
     */
    protected function populateStructure()
    {
        $treeStructure = [
            'payment_transaction' => array_merge(
                [
                    'transaction_type' => \Genesis\API\Constants\Transaction\Types::ACCOUNT_VERIFICATION,
                    'transaction_id'   => $this->transaction_id,
                    'usage'            => $this->usage,
                    'moto'             => $this->moto,
                    'remote_ip'        => $this->remote_ip,
                    'card_holder'      => $this->card_holder,
                    'card_number'      => $this->card_number,
                    'cvv'              => $this->cvv,
                    'expiration_month' => $this->expiration_month,
                    'expiration_year'  => $this->expiration_year,
                    'customer_email'   => $this->customer_email,
                    'customer_phone'   => $this->customer_phone,
                    'document_id'      => $this->document_id,
                    'birth_date'       => $this->getBirthDate(),
                    'billing_address'  => $this->getBillingAddressParamsStructure(),
                    'shipping_address' => $this->getShippingAddressParamsStructure(),
                    'risk_params'      => $this->getRiskParamsStructure()
                ],
                $this->getCredentialOnFileAttributesStructure()
            )
        ];

        $this->treeStructure = CommonUtils::createArrayObject($treeStructure);
    }

    /**
     * Skip Credit Card validation if Client-Side Encryption is set
     * Add document_id conditional validation if it is present
     *
     * @return void
     * @throws InvalidArgument
     * @throws \Genesis\Exceptions\ErrorParameter
     * @throws \Genesis\Exceptions\InvalidClassMethod
     */
    protected function checkRequirements()
    {
        $this->removeCreditCardValidations();

        if ($this->document_id) {
            $this->requiredFieldValuesConditional = CommonUtils::createArrayObject(
                $this->getDocumentIdConditions()
            );
        }

        parent::checkRequirements();
    }
}


text:
package corehttp

import (
	"net/http"

	manners "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/braintree/manners"
	ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	manet "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr-net"
	core "github.com/ipfs/go-ipfs/core"
	eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog"
)

var log = eventlog.Logger("core/server")

// ServeOption registers any HTTP handlers it provides on the given mux.
// It returns the mux to expose to future options, which may be a new mux if it
// is interested in mediating requests to future options, or the same mux
// initially passed in if not.
type ServeOption func(*core.IpfsNode, *http.ServeMux) (*http.ServeMux, error)

// makeHandler turns a list of ServeOptions into a http.Handler that implements
// all of the given options, in order.
func makeHandler(n *core.IpfsNode, options ...ServeOption) (http.Handler, error) {
	topMux := http.NewServeMux()
	mux := topMux
	for _, option := range options {
		var err error
		mux, err = option(n, mux)
		if err != nil {
			return nil, err
		}
	}
	return topMux, nil
}

// ListenAndServe runs an HTTP server listening at |listeningMultiAddr| with
// the given serve options. The address must be provided in multiaddr format.
//
// TODO intelligently parse address strings in other formats so long as they
// unambiguously map to a valid multiaddr. e.g. for convenience, ":8080" should
// map to "/ip4/0.0.0.0/tcp/8080".
func ListenAndServe(n *core.IpfsNode, listeningMultiAddr string, options ...ServeOption) error {
	addr, err := ma.NewMultiaddr(listeningMultiAddr)
	if err != nil {
		return err
	}
	handler, err := makeHandler(n, options...)
	if err != nil {
		return err
	}
	return listenAndServe(n, addr, handler)
}

func listenAndServe(node *core.IpfsNode, addr ma.Multiaddr, handler http.Handler) error {
	_, host, err := manet.DialArgs(addr)
	if err != nil {
		return err
	}

	server := manners.NewServer()

	// if the server exits beforehand
	var serverError error
	serverExited := make(chan struct{})

	go func() {
		serverError = server.ListenAndServe(host, handler)
		close(serverExited)
	}()

	// wait for server to exit.
	select {
	case <-serverExited:

	// if node being closed before server exits, close server
	case <-node.Closing():
		log.Infof("server at %s terminating...", addr)
		server.Shutdown <- true
		<-serverExited // now, DO wait until server exit
	}

	log.Infof("server at %s terminated", addr)
	return serverError
}


text:
<?php

namespace Payum\Klarna\Checkout\Action;

use ArrayAccess;
use Payum\Core\Action\ActionInterface;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Request\GetStatusInterface;
use Payum\Klarna\Checkout\Constants;

class StatusAction implements ActionInterface
{
    /**
     * @param GetStatusInterface $request
     */
    public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $model = ArrayObject::ensureArrayObject($request->getModel());

        if ($model['error_code']) {
            $request->markFailed();

            return;
        }

        if ($model['invoice_number']) {
            $request->markCaptured();

            return;
        }

        if ($model['reservation']) {
            $request->markAuthorized();

            return;
        }

        if (false == $model['status'] || Constants::STATUS_CHECKOUT_INCOMPLETE == $model['status']) {
            $request->markNew();

            return;
        }

        if (Constants::STATUS_CHECKOUT_COMPLETE == $model['status']) {
            $request->markPending();

            return;
        }

        $request->markUnknown();
    }

    public function supports($request)
    {
        return $request instanceof GetStatusInterface &&
            $request->getModel() instanceof ArrayAccess
        ;
    }
}


text:
This is a starter kit for [Goose Parser](https://github.com/redco/goose-parser)

## Usage

First of all clone repo and start your project for it. And now there are two ways to run a project:

- inside a docker container
- directly on a local system

### Docker usage

Be aware that this way requires [Docker](https://docker.com) installed.

Start the project with command:

```bash
docker-compose up
```

### Local system usage

```bash
npm install
DEBUG=* node lib/index.js
```

## How it looks like

![](http://g.recordit.co/mP2fk9diYh.gif)


text:
package org.jetbrains.plugins.gradle.model.internal;

import org.gradle.tooling.model.GradleModuleVersion;
import org.gradle.tooling.model.idea.IdeaDependencyScope;
import org.gradle.tooling.model.idea.IdeaSingleEntryLibraryDependency;

import java.io.File;
import java.io.Serializable;

/**
 * @author Vladislav.Soroka
 * @since 11/25/13
 */
public class IdeaSingleEntryLibraryDependencyImpl extends AbstractGradleDependency
  implements IdeaSingleEntryLibraryDependency, Serializable {

  private File myFile;
  private File mySource;
  private File myJavadoc;

  public IdeaSingleEntryLibraryDependencyImpl(IdeaDependencyScope myScope,
                                              String dependencyName,
                                              String dependencyGroup, String dependencyVersion) {
    super(myScope, dependencyName, dependencyGroup, dependencyVersion);
  }

  @Override
  public File getFile() {
    return myFile;
  }

  @Override
  public File getSource() {
    return mySource;
  }

  @Override
  public File getJavadoc() {
    return myJavadoc;
  }

  public void setFile(File file) {
    myFile = file;
  }

  public void setSource(File source) {
    mySource = source;
  }

  public void setJavadoc(File javadoc) {
    myJavadoc = javadoc;
  }

  @Override
  public GradleModuleVersion getGradleModuleVersion() {
    return null;
  }
}


text:
module Issuable
  module Clone
    class BaseService < IssuableBaseService
      attr_reader :original_entity, :new_entity

      alias_method :old_project, :project

      def execute(original_entity, new_project = nil)
        @original_entity = original_entity

        # Using transaction because of a high resources footprint
        # on rewriting notes (unfolding references)
        #
        ActiveRecord::Base.transaction do
          @new_entity = create_new_entity

          update_new_entity
          update_old_entity
          create_notes
        end
      end

      private

      def copy_award_emoji
        AwardEmojis::CopyService.new(original_entity, new_entity).execute
      end

      def copy_notes
        Notes::CopyService.new(current_user, original_entity, new_entity).execute
      end

      def update_new_entity
        update_new_entity_description
        update_new_entity_attributes
        copy_award_emoji
        copy_notes
      end

      def update_new_entity_description
        rewritten_description = MarkdownContentRewriterService.new(
          current_user,
          original_entity.description,
          original_entity.project,
          new_parent
        ).execute

        new_entity.update!(description: rewritten_description)
      end

      def update_new_entity_attributes
        AttributesRewriter.new(current_user, original_entity, new_entity).execute
      end

      def update_old_entity
        close_issue
      end

      def create_notes
        add_note_from
        add_note_to
      end

      def close_issue
        close_service = Issues::CloseService.new(old_project, current_user)
        close_service.execute(original_entity, notifications: false, system_note: false)
      end

      def new_parent
        new_entity.resource_parent
      end

      def group
        if new_entity.project&.group && current_user.can?(:read_group, new_entity.project.group)
          new_entity.project.group
        end
      end
    end
  end
end

Issuable::Clone::BaseService.prepend_if_ee('EE::Issuable::Clone::BaseService')


text:
package org.gradle.buildinit.plugins.internal;

import org.gradle.util.internal.GFileUtils;

public class ResourceDirsGenerator implements BuildContentGenerator {

    @Override
    public void generate(InitSettings settings) {
        for (String subproject : settings.getSubprojects()) {
            GFileUtils.mkdirs(settings.getTarget().dir(subproject + "/src/main/resources").getAsFile());
            GFileUtils.mkdirs(settings.getTarget().dir(subproject + "/src/test/resources").getAsFile());
        }
    }
}


text:
import $ from 'jquery'
import 'modal'
import { quickModal } from 'func'

var defalutMsessageOptions = {
    extClass : 'info',
    duration : 0
}
$.message = options => {
    if (typeof options === 'string') options = {text: options}
    options = $.extend({}, defalutMsessageOptions, options)
    var extClass = options.extClass || ''
    var messageHtml = `

${options.text}

<svg class="close"><use xlink:href="svg/svg-symbols.svg#close"></use></svg>

`

    var mustCloseFunc = () => {
        if (window.messageTimeoutFlag) {
            clearTimeout(window.messageTimeoutFlag)
            delete window.messageTimeoutFlag
        }
    }

    if (options.close) {
        var oClose = options.close
        options.close = function () {
            mustCloseFunc()
            oClose()
        }
    } else {
        options.close = mustCloseFunc
    }

    $('.modal.message').remove()
    mustCloseFunc()

    var $message = quickModal(messageHtml, options)
    $message.modal(options).trigger('open.modal', {dimmer: 'message'})
    if (options.duration) {
        window.messageTimeoutFlag = setTimeout(() => {$message.trigger('close.modal')}, options.duration)
    }
}


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
    TrapApiError,
    Widget,
    WidgetHeader,
    WidgetBody,
    WidgetLoader,
    ExternalLink,
    TagIcon,
} from '@mozaik/ui'
import { countTypes, countLabel } from './counts'

export default class LabelsChart extends Component {
    static propTypes = {
        project: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
        countBy: PropTypes.oneOf(countTypes).isRequired,
        apiData: PropTypes.shape({
            project: PropTypes.shape({
                name: PropTypes.string.isRequired,
                web_url: PropTypes.string.isRequired,
            }).isRequired,
            labels: PropTypes.arrayOf(
                PropTypes.shape({
                    id: PropTypes.number.isRequired,
                    name: PropTypes.string.isRequired,
                    color: PropTypes.string.isRequired,
                    open_issues_count: PropTypes.number.isRequired,
                    closed_issues_count: PropTypes.number.isRequired,
                    open_merge_requests_count: PropTypes.number.isRequired,
                })
            ).isRequired,
        }),
        apiError: PropTypes.object,
        title: PropTypes.string,
        animate: PropTypes.bool.isRequired,
        children: PropTypes.func.isRequired,
        theme: PropTypes.object.isRequired,
    }

    static defaultProps = {
        countBy: 'open_issues_count',
        animate: false,
    }

    static getApiRequest({ project }) {
        return {
            id: `gitlab.projectLabels.${project}`,
            params: { project },
        }
    }

    render() {
        const { apiData, apiError, title, countBy, animate, children, theme } = this.props

        let body = <WidgetLoader />
        let subject = null
        let count = 0
        if (apiData) {
            const { project, labels } = apiData

            count = labels.length

            subject = <ExternalLink href={project.web_url}>{project.name}</ExternalLink>

            body = children({
                labels,
                countBy,
                animate,
                theme: theme.charts,
            })
        }

        return (
            <Widget>
                <WidgetHeader
                    title={title || `Labels by ${countLabel(countBy)}`}
                    subject={title ? null : subject}
                    count={count}
                    icon={TagIcon}
                />
                <WidgetBody>
                    <TrapApiError error={apiError}>{body}</TrapApiError>
                </WidgetBody>
            </Widget>
        )
    }
}


text:
title: Installing Calico CNI for the Unified Containerizer
---

This guide details how to add Calico networking to a Mesos Agent with CNI enabled.

- If you're looking for information on installing Calico with the Docker Containerizer, see [Docker Containerizer Manual Install Guide]({{site.baseurl}}/{{page.version}}/getting-started/mesos/installation/docker)
- If you're not sure the difference between the Unified and Docker Containerizers, see  [Mesos' information on Containerizers](http://mesos.apache.org/documentation/latest/containerizer/) and [Our Readme on Calico's integration for each]({{site.baseurl}}/{{page.version}}/getting-started/mesos/).

### Prerequisites
- **A Running Mesos v1.0.0+ cluster**  [with CNI enabled on each agent](http://mesos.apache.org/documentation/latest/cni/#usage).

  When enabling CNI in Mesos, you will have specified a `network_cni_config_dir` and `network_cni_plugins_dir`. We'll refer to these going forward as `$NETWORK_CNI_CONFIG_DIR` and `$NETWORK_CNI_PLUGINS_DIR`, respectively.

- **Docker** must be installed and running on each agent in order to run `calico/node`. Follow the relevant [docker installation guide](https://docs.docker.com/engine/installation/).
- **etcd** is used by Calico to store network configurations. See [etcd's docker standalone guide](https://coreos.com/etcd/docs/latest/docker_guide.html) for information on how to quickly get an instance running.

## Installation
Run the following steps on **each agent**.

1. Download the Calico CNI plugin to the `$NETWORK_CNI_PLUGINS_DIR` you configured for Mesos:

```shell
curl -L -o $NETWORK_CNI_PLUGINS_DIR/calico \
    https://github.com/projectcalico/calico-cni/releases/download/v1.3.0/calico
chmod +x $NETWORK_CNI_PLUGINS_DIR/calico
ln -s $NETWORK_CNI_PLUGINS_DIR/calico $NETWORK_CNI_PLUGINS_DIR/calico-ipam
```

2. Run `calico/node`, a Docker container with calico's core routing processes.
The `calico/node` container can easily be launched using
`calicoctl`, Calico's command line tool. When doing so,
we must provide the location of the running etcd instance
by setting the `ECTD_AUTHORITY` environment variable.

```shell
curl -L -O \
    https://github.com/projectcalico/calico-containers/releases/download/v0.18.0/calicoctl
chmod +x ./calicoctl
sudo ETCD_AUTHORITY=<etcd-ip:port> ./calicoctl node
```

## Next Steps
Now that you have all the necessary components in place, its time to configure a network and launch tasks. See [Calico's Mesos-CNI Usage Guide]({{site.baseurl}}/{{page.version}}/getting-started/mesos/tutorials/unified).


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <titles>
      <item>
        <titleType>Short Titles as Introduced</titleType>
        <title>DRAIN the Swamp Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Short Titles as Introduced</titleType>
        <title>Determining if Regulatory Actions are in the Interest of the Nation or the Swamp Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Official Title as Introduced</titleType>
        <title>To amend chapter 5 of title 31, United States Code, to require publication of information relating to regulatory conflicts of interest, and for other purposes.</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>Display Title</titleType>
        <title>DRAIN the Swamp Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <title>DRAIN the Swamp Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
      <item>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <title>Determining if Regulatory Actions are in the Interest of the Nation or the Swamp Act of 2017</title>
        <chamberCode />
        <parentTitleType />
        <chamberName />
      </item>
    </titles>
    <title>DRAIN the Swamp Act of 2017</title>
    <relatedBills />
    <originChamber>House</originChamber>
    <policyArea>
      <name>Government Operations and Politics</name>
    </policyArea>
    <version>1.0.0</version>
    <committees>
      <billCommittees>
        <item>
          <name>Judiciary Committee</name>
          <type>Standing</type>
          <chamber>House</chamber>
          <subcommittees />
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-10-11T14:00:19Z</date>
            </item>
          </activities>
          <systemCode>hsju00</systemCode>
        </item>
      </billCommittees>
    </committees>
    <billNumber>4014</billNumber>
    <cosponsors>
      <item>
        <identifiers>
          <lisID>229</lisID>
          <gpoId>7999</gpoId>
          <bioguideId>C000714</bioguideId>
        </identifiers>
        <bioguideId>C000714</bioguideId>
        <party>D</party>
        <district>13</district>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <middleName />
        <sponsorshipDate>2017-10-11</sponsorshipDate>
        <firstName>JOHN</firstName>
        <lastName>CONYERS</lastName>
        <sponsorshipWithdrawnDate />
        <fullName>Rep. Conyers, John, Jr. [D-MI-13]</fullName>
        <state>MI</state>
      </item>
      <item>
        <identifiers>
          <bioguideId>D000191</bioguideId>
          <lisID>279</lisID>
          <gpoId>8117</gpoId>
        </identifiers>
        <bioguideId>D000191</bioguideId>
        <party>D</party>
        <district>4</district>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <middleName>A.</middleName>
        <sponsorshipDate>2017-10-11</sponsorshipDate>
        <firstName>PETER</firstName>
        <lastName>DEFAZIO</lastName>
        <sponsorshipWithdrawnDate />
        <fullName>Rep. DeFazio, Peter A. [D-OR-4]</fullName>
        <state>OR</state>
      </item>
      <item>
        <identifiers>
          <lisID>1708</lisID>
          <gpoId>7804</gpoId>
          <bioguideId>G000551</bioguideId>
        </identifiers>
        <bioguideId>G000551</bioguideId>
        <party>D</party>
        <district>3</district>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <middleName>M.</middleName>
        <sponsorshipDate>2017-10-11</sponsorshipDate>
        <firstName>Raul</firstName>
        <lastName>Grijalva</lastName>
        <sponsorshipWithdrawnDate />
        <fullName>Rep. Grijalva, Raul M. [D-AZ-3]</fullName>
        <state>AZ</state>
      </item>
      <item>
        <identifiers>
          <lisID>1959</lisID>
          <bioguideId>C001078</bioguideId>
          <gpoId>8202</gpoId>
        </identifiers>
        <bioguideId>C001078</bioguideId>
        <party>D</party>
        <district>11</district>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <middleName>E.</middleName>
        <sponsorshipDate>2017-10-11</sponsorshipDate>
        <firstName>Gerald</firstName>
        <lastName>Connolly</lastName>
        <sponsorshipWithdrawnDate />
        <fullName>Rep. Connolly, Gerald E. [D-VA-11]</fullName>
        <state>VA</state>
      </item>
      <item>
        <identifiers>
          <bioguideId>D000399</bioguideId>
          <lisID>303</lisID>
          <gpoId>8181</gpoId>
        </identifiers>
        <bioguideId>D000399</bioguideId>
        <party>D</party>
        <district>35</district>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <middleName />
        <sponsorshipDate>2017-10-11</sponsorshipDate>
        <firstName>LLOYD</firstName>
        <lastName>DOGGETT</lastName>
        <sponsorshipWithdrawnDate />
        <fullName>Rep. Doggett, Lloyd [D-TX-35]</fullName>
        <state>TX</state>
      </item>
    </cosponsors>
    <updateDate>2017-10-13T14:45:10Z</updateDate>
    <amendments />
    <sponsors>
      <item>
        <lastName>Cicilline</lastName>
        <fullName>Rep. Cicilline, David N. [D-RI-1]</fullName>
        <party>D</party>
        <identifiers>
          <lisID>2055</lisID>
          <bioguideId>C001084</bioguideId>
          <gpoId>8139</gpoId>
        </identifiers>
        <bioguideId>C001084</bioguideId>
        <district>1</district>
        <middleName>N.</middleName>
        <firstName>David</firstName>
        <byRequestType />
        <state>RI</state>
      </item>
    </sponsors>
    <recordedVotes />
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Mr. CICILLINE:H.R. 4014.Congress has the power to enact this legislation pursuantto the following:Article I, section 8 of the U.S. Constitution.[Page H7975]
]]></constitutionalAuthorityStatementText>
    <notes />
    <laws />
    <summaries>
      <billSummaries />
    </summaries>
    <actions>
      <actionByCounts>
        <houseOfRepresentatives>3</houseOfRepresentatives>
      </actionByCounts>
      <actionTypeCounts>
        <introducedInTheHouse>1</introducedInTheHouse>
        <billReferrals>1</billReferrals>
        <introducedInHouse>1</introducedInHouse>
      </actionTypeCounts>
      <item>
        <sourceSystem>
          2
          <name>House floor actions</name>
        </sourceSystem>
        <committee>
          <systemCode>hsju00</systemCode>
          <name>Judiciary Committee</name>
        </committee>
        <text>Referred to the House Committee on the Judiciary.</text>
        <actionDate>2017-10-11</actionDate>
        <links />
        <actionCode>H11100</actionCode>
        <type>IntroReferral</type>
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <committee />
        <text>Introduced in House</text>
        <actionDate>2017-10-11</actionDate>
        <links />
        <actionCode>Intro-H</actionCode>
        <type>IntroReferral</type>
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <committee />
        <text>Introduced in House</text>
        <actionDate>2017-10-11</actionDate>
        <links />
        <actionCode>1000</actionCode>
        <type>IntroReferral</type>
      </item>
    </actions>
    <calendarNumbers />
    <createDate>2017-10-12T03:11:23Z</createDate>
    <billType>HR</billType>
    <cboCostEstimates />
    <subjects>
      <billSubjects>
        <policyArea>
          <name>Government Operations and Politics</name>
        </policyArea>
        <legislativeSubjects />
      </billSubjects>
    </subjects>
    <latestAction>
      <links />
      <actionDate>2017-10-11</actionDate>
      <text>Referred to the House Committee on the Judiciary.</text>
    </latestAction>
    <committeeReports />
    <congress>115</congress>
    <introducedDate>2017-10-11</introducedDate>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
title: Generate an Array of All Object Keys with Object.keys()
localeTitle: Generar una matriz de todas las claves de objeto con Object.keys ()
---
## Generar una matriz de todas las claves de objeto con Object.keys ()

### Método:

*   Para devolver la matriz de usuarios, el método `Object.keys()` debe tomar un argumento.
*   Este desafío se puede resolver utilizando una sola línea de declaración de retorno.

### Solución:

```javascript
let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
 };

 function getArrayOfUsers(obj) {
  // change code below this line
  return Object.keys(obj);
  // change code above this line
 }

 console.log(getArrayOfUsers(users));

```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Options (AspectJ(tm) weaver API)
</TITLE>

<META NAME="date" CONTENT="2013-02-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.aspectj.weaver.loadtime

Class Options

java.lang.Object
  org.aspectj.weaver.loadtime.Options

public class Options
extends java.lang.Object

A class that hanldes LTW options. Note: AV - I choosed to not reuse AjCompilerOptions and alike since those implies too many
 dependancies on jdt and ajdt modules.

Author:

Alexandre Vasseur

Nested Class Summary

static class
Options.WeaverOption

Constructor Summary

Options()

Method Summary

static Options.WeaverOption
parse(java.lang.String options,
      java.lang.ClassLoader laoder,
      org.aspectj.bridge.IMessageHandler imh)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Options

public Options()

Method Detail

parse

public static Options.WeaverOption parse(java.lang.String options,
                                         java.lang.ClassLoader laoder,
                                         org.aspectj.bridge.IMessageHandler imh)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
using System;
using System.Reflection.Emit;
using JetBrains.Annotations;

namespace ILGeneratorExtensions
{
    /// <summary>
    /// Contains extension methods for the manipulation of objects
    /// </summary>
    [PublicAPI]
    public static class ObjectManipulation
    {
        /// <summary>
        /// Pops two addresses from the evaluation stack and copies the value type object (of the given type) in the first into the second
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type of the value type object</param>
        [PublicAPI]
        public static ILGenerator CopyObject(this ILGenerator generator, Type type)
        {
            if (!type.IsValueType)
            {
                throw new InvalidOperationException("Copying a non-value-type results in unspecified runtime behaviour");
            }

            return generator.FluentEmit(OpCodes.Cpobj, type);
        }

        /// <summary>
        /// Pops two addresses from the evaluation stack and copies the value type object (of the given type) in the first into the second
        /// </summary>
        /// <typeparam name="T">The type of the value type object</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator CopyObject<T>(this ILGenerator generator) where T : struct => generator.CopyObject(typeof (T));

        /// <summary>
        /// Pops two addresses and an integer from the evaluation stack, and copies that number of bytes from the first address to the second
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator CopyBlock(this ILGenerator generator) => generator.FluentEmit(OpCodes.Cpblk);

        /// <summary>
        /// Pops two address from the evaluation stack and copies the given number of bytes from the first to the second
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="bytes">The number of bytes to copy</param>
        [PublicAPI]
        public static ILGenerator CopyBlock(this ILGenerator generator, uint bytes)
        {
            return generator.LoadConstant(bytes)
                            .CopyBlock();
        }

        /// <summary>
        /// Pops two addresses and an integer from the evaluation stack, and copies that number of bytes from the first address to the second, with volatile semantics
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator CopyBlockVolatile(this ILGenerator generator)
        {
            return generator.FluentEmit(OpCodes.Volatile)
                            .CopyBlock();
        }

        /// <summary>
        /// Pops two address from the evaluation stack and copies the given number of bytes from the first to the second, with volatile semantics
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="bytes">The number of bytes to copy</param>
        [PublicAPI]
        public static ILGenerator CopyBlockVolatile(this ILGenerator generator, uint bytes)
        {
            return generator.FluentEmit(OpCodes.Volatile)
                            .CopyBlock(bytes);
        }

        /// <summary>
        /// Pops an address from the evaluation stack and pushes the value type object (of the given type) at that location onto the evaluation stack
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type of the value type object</param>
        [PublicAPI]
        public static ILGenerator LoadValueTypeOntoStack(this ILGenerator generator, Type type)
        {
            if (!type.IsValueType)
            {
                throw new InvalidOperationException("This operation is not valid on reference types");
            }

            if (type == typeof (sbyte))
            {
                return generator.FluentEmit(OpCodes.Ldind_I1);
            }
            else if (type == typeof (byte))
            {
                return generator.FluentEmit(OpCodes.Ldind_U1);
            }
            else if (type == typeof (short))
            {
                return generator.FluentEmit(OpCodes.Ldind_I2);
            }
            else if (type == typeof (ushort))
            {
                return generator.FluentEmit(OpCodes.Ldind_U2);
            }
            else if (type == typeof (int))
            {
                return generator.FluentEmit(OpCodes.Ldind_I4);
            }
            else if (type == typeof (uint))
            {
                return generator.FluentEmit(OpCodes.Ldind_U4);
            }
            else if (type == typeof(long) || type == typeof(ulong))
            {
                return generator.FluentEmit(OpCodes.Ldind_I8);
            }
            else if (type == typeof (float))
            {
                return generator.FluentEmit(OpCodes.Ldind_R4);
            }
            else if (type == typeof (double))
            {
                return generator.FluentEmit(OpCodes.Ldind_R8);
            }
            else
            {
                return generator.FluentEmit(OpCodes.Ldobj, type);
            }
        }

        /// <summary>
        /// Pops an address from the evaluation stack and pushes the value type object (of the given type) at that location onto the evaluation stack
        /// </summary>
        /// <typeparam name="T">The type of the value type object</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator LoadValueTypeOntoStack<T>(this ILGenerator generator) where T : struct
            => generator.LoadValueTypeOntoStack(typeof (T));

        /// <summary>
        /// Pops an address from the evaluation stack and pushes the value type object (of the given type) at that location onto the evaluation stack, with volatile semantics
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type of the value type object</param>
        [PublicAPI]
        public static ILGenerator LoadValueTypeOntoStackVolatile(this ILGenerator generator, Type type)
        {
            if (!type.IsValueType)
            {
                throw new InvalidOperationException("This operation is not valid on reference types");
            }

            return generator.FluentEmit(OpCodes.Volatile)
                            .LoadValueTypeOntoStack(type);
        }

        /// <summary>
        /// Pops an address from the evaluation stack and pushes the value type object (of the given type) at that location onto the evaluation stack, with volatile semantics
        /// </summary>
        /// <typeparam name="T">The type of the value type object</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator LoadValueTypeOntoStackVolatile<T>(this ILGenerator generator) where T : struct
            => generator.LoadValueTypeOntoStackVolatile(typeof(T));

        /// <summary>
        /// Pops an address and a value type object (of the given type) from the evaluation stack, and copies the object into the address
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type of the value type object</param>
        [PublicAPI]
        public static ILGenerator StoreValueTypeFromStack(this ILGenerator generator, Type type)
        {
            if (!type.IsValueType)
            {
                throw new InvalidOperationException("This operation is not valid on reference types");
            }

            if (type == typeof(sbyte) || type == typeof(byte))
            {
                return generator.FluentEmit(OpCodes.Ldind_I1);
            }
            else if (type == typeof(short) || type == typeof(ushort))
            {
                return generator.FluentEmit(OpCodes.Ldind_I2);
            }
            else if (type == typeof(int) || type == typeof(uint))
            {
                return generator.FluentEmit(OpCodes.Ldind_I4);
            }
            else if (type == typeof(long) || type == typeof(ulong))
            {
                return generator.FluentEmit(OpCodes.Ldind_I8);
            }
            else if (type == typeof(float))
            {
                return generator.FluentEmit(OpCodes.Ldind_R4);
            }
            else if (type == typeof(double))
            {
                return generator.FluentEmit(OpCodes.Ldind_R8);
            }
            else
            {
                return generator.FluentEmit(OpCodes.Ldobj, type);
            }
        }

        /// <summary>
        /// Pops an address and a value type object (of the given type) from the evaluation stack, and copies the object into the address
        /// </summary>
        /// <typeparam name="T">The type of the value type object</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator StoreValueTypeFromStack<T>(this ILGenerator generator) where T : struct
            => generator.StoreValueTypeFromStack(typeof (T));

        /// <summary>
        /// Pops an address and a value type object (of the given type) from the evaluation stack, and copies the object into the address, with volatile semantics
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="type">The type of the value type object</param>
        [PublicAPI]
        public static ILGenerator StoreValueTypeFromStackVolatile(this ILGenerator generator, Type type)
        {
            if (!type.IsValueType)
            {
                throw new InvalidOperationException("This operation is not valid on a reference type");
            }

            return generator.FluentEmit(OpCodes.Volatile)
                            .FluentEmit(OpCodes.Stobj, type);
        }

        /// <summary>
        /// Pops an address and a value type object (of the given type) from the evaluation stack, and copies the object into the address, with volatile semantics
        /// </summary>
        /// <typeparam name="T">The type of the value type object</typeparam>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator StoreValueTypeFromStackVolatile<T>(this ILGenerator generator) where T : struct
            => generator.StoreValueTypeFromStack(typeof(T));

        /// <summary>
        /// Pops an address from the evaluation stack, and pushes the object reference located at that address
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        [PublicAPI]
        public static ILGenerator LoadReferenceFromAddress(this ILGenerator generator) => generator.FluentEmit(OpCodes.Ldind_Ref);
    }
}


text:
from django.apps import AppConfig

class UseradminConfig(AppConfig):
    name = 'useradmin'


text:
//snippet-sourcedescription:[ListStateMachines.java demonstrates how to List existing state machines for AWS Step Functions.]
//snippet-keyword:[AWS SDK for Java v2]
//snippet-service:[AWS Step Functions]

package com.example.stepfunctions;

// snippet-start:[stepfunctions.java2.list_machines.import]
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.ListStateMachinesResponse;
import software.amazon.awssdk.services.sfn.model.SfnException;
import software.amazon.awssdk.services.sfn.model.StateMachineListItem;
import java.util.List;
// snippet-end:[stepfunctions.java2.list_machines.import]

/**
 * Before running this Java V2 code example, set up your development environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class ListStateMachines {

    public static void main(String[] args) {

        Region region = Region.US_EAST_1;
        SfnClient sfnClient = SfnClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create())
            .build();

        listMachines(sfnClient);
        sfnClient.close();
    }

    // snippet-start:[stepfunctions.java2.list_machines.main]
    public static void listMachines(SfnClient sfnClient) {

        try {
            ListStateMachinesResponse response = sfnClient.listStateMachines();
            List<StateMachineListItem> machines = response.stateMachines();
            for (StateMachineListItem machine :machines) {
                System.out.println("The name of the state machine is: "+machine.name());
                System.out.println("The ARN value is : "+machine.stateMachineArn());
            }

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
    // snippet-end:[stepfunctions.java2.list_machines.main]
}