text:
require 'spec_helper'

describe Appilf::Listing do
  include Appilf::TestData

  describe '.new' do
    let(:listing) { Appilf::Listing.new(load_test_json_data(mocked_response_file_path('listing/listing.json'))) }

    it 'should respond to id' do
      listing.id.should == "6046240"
    end

    it 'should respond to app_downloads_per_month' do
      listing.app_downloads_per_month.should == nil
    end

    it 'should respond to bid_count' do
      listing.bid_count.should == 0
    end

    it 'should respond to buy_it_now_price' do
      listing.buy_it_now_price.should == nil
    end

    it 'should respond to confidential' do
      listing.confidential.should == false
    end

    it 'should respond to current_price' do
      listing.current_price.should == 50
    end

    it 'should respond to ends_at' do
      listing.ends_at.should == "2016-02-16T07:43:54+11:00"
    end

    it 'should respond to established_at' do
      listing.established_at.should == "2001-01-31T11:00:00+11:00"
    end

    it 'should respond to has_verified_revenue' do
      listing.has_verified_revenue.should == false
    end

    it 'should respond to has_verified_traffic' do
      listing.has_verified_traffic.should == false
    end

    it 'should respond to page_views_per_month' do
      listing.page_views_per_month.should == nil
    end

    it 'should respond to post_auction_negotiable' do
      listing.post_auction_negotiable.should == false
    end

    it 'should respond to post_auction_negotiable' do
      listing.post_auction_negotiable.should == false
    end

    it 'should respond to profit_per_month' do
      listing.profit_per_month.should == 0
    end

    it 'should respond to property_name' do
      listing.property_name.should == "digamatic.com"
    end

    it 'should respond to reserve_met' do
      listing.reserve_met.should == false
    end

    it 'should respond to revenue_per_month' do
      listing.revenue_per_month.should == 0
    end

    it 'should respond to revenue_sources' do
      listing.revenue_sources.should == []
    end

    it 'should respond to sale_method' do
      listing.sale_method.should == 'auction'
    end

    it 'should respond to starts_at' do
      listing.starts_at.should == "2016-02-10T07:43:54+11:00"
    end

    it 'should respond to status' do
      listing.status.should == "open"
    end

    it 'should respond to summary' do
      listing.summary.should == nil
    end

    it 'should respond to title' do
      listing.title.should == 'cool company name !'
    end

    it 'should respond to uniques_per_month' do
      listing.uniques_per_month.should == nil
    end

    it 'should respond to watching' do
      listing.watching.should == false
    end

    it 'should respond to images fields' do
      listing.images.thumbnail.url.should == nil
      listing.images.thumbnail.targets.should == []
    end

    it 'should contain an User within the seller relationship' do
      listing.seller.class.should == Appilf::User
    end

    it 'should contain a link pointing to itself' do
      listing.links.self.should == "https://api.flippa.com/v3/listings/6046240"
    end

  end

  describe '.retrieve' do
    let(:listing) { Appilf::Listing.retrieve(6046240) }
    before { stub_api_get_request(Appilf::Listing.listings_path(6046240), 'listing/listing.json') }

    it 'should return a Listing' do
      listing.class.should == Appilf::Listing
    end
  end

  describe '.list' do

    context 'without arguments' do
      let(:resource_page) { Appilf::Listing.list }
      before { stub_api_get_request(Appilf::Listing.listings_path, 'listing/listing_page_1.json') }

      it 'should be a Appilf::ResourcePage' do
        resource_page.class.should == Appilf::ResourcePage
      end

      it 'should contain 30 entries' do
        resource_page.count.should == 30
      end

      specify 'page meta should contain page_number, page_size, total_results' do
        resource_page.page_meta.page_number.should == 1
        resource_page.page_meta.page_size.should == 30
        resource_page.page_meta.total_results.should == 1657436
      end

      specify 'all entries should be of type Appilf::Listing' do
        resource_page.all?{ |listing| listing.class.should == Appilf::Listing  }.should be_truthy
      end

      context 'navigating to another page' do
        let(:next_page) { resource_page.next }
        before { stub_api_get_request(resource_page.page_links.next, 'listing/listing_page_2.json') }

        it 'should retrieve another page' do
          next_page.class.should == Appilf::ResourcePage
        end

        it 'new page should be the second page' do
          next_page.page_meta.page_number.should == 2
        end
      end

      context 'navigating to non existent page' do
        it 'should return nil' do
          resource_page.previous.should be_nil
        end
      end
    end

    context 'with pagination arguments' do
      let(:resource_page) { Appilf::Listing.list(page_number: 5, page_size: 100) }
      before { stub_api_get_request(Appilf::Listing.listings_path, 'listing/listing_page_5.json', 200,
                                    {'page[number]' => 5, 'page[size]' => 100}) }

      it 'should return page 5 with 100 entries' do
        resource_page.page_meta.page_number.should == 5
        resource_page.count.should == 100
      end
    end

  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Buellia antillarum B. de Lesd.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
@font-face {
  font-family: 'lato';
  font-style: normal;
  font-weight: lighter;
  src: url(/static/fonts/lato-light-webfont.woff) format('woff');
}
@font-face {
  font-family: 'lato';
  font-style: normal;
  font-weight: normal;
  src: url(/static/fonts/lato-regular-webfont.woff) format('woff');
}
@font-face {
  font-family: 'lato';
  font-style: normal;
  font-weight: bold;
  src: url(/static/fonts/lato-bold-webfont.woff) format('woff');
}
@font-face {
  font-family: 'nexa';
  font-style: normal;
  font-weight: lighter;
  src: url(/static/fonts/nexa-light-webfont.woff) format('woff');
}
@font-face {
  font-family: 'nexa';
  font-style: normal;
  font-weight: normal;
  src: url(/static/fonts/nexa-bold-webfont.woff) format('woff');
}
@font-face {
  font-family: 'iconfont';
  src: url('/static/fonts/iconfont.eot');
  src: url('/static/fonts/iconfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('/static/fonts/iconfont.woff') format('woff'), /* chrome、firefox */ url('/static/fonts/iconfont.ttf') format('truetype'), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/ url('/static/fonts/iconfont.svg#uxiconfont') format('svg');

  /* IE9*/
  /* iOS 4.1- */
}
.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;
}
html {
  position: relative;
  min-height: 100%;
}
body {
  margin-top: 81px;
  margin-bottom: 249px;
}
a {
  color: #333333;
}
a:hover {
  color: #36a9e5;
}
.flash-message {
  background-color: #36a9e5;
  border: 0;
  color: #ffffff;
  margin-bottom: 0;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 100000;
  border-radius: 0;
  text-align: center;
  display: none;
  padding: 27.5px;
  font-size: 18px;
}
#page-search-students #nav-search-students a,
#page-search-teachers #nav-search-teachers a,
#page-user-dialogs #nav-dialogs a,
#page-user-dialog #nav-dialogs a,
#page-user-teacher-settings #nav-settings a,
#page-user-student-settings #nav-settings a,
#page-account-signin #nav-signin a,
#page-account-signup-select-role #nav-signup a,
#page-account-signup #nav-signup a {
  color: #555;
  background-color: #e7e7e7;
}
.navbar {
  margin-bottom: 0;
  background-color: rgba(255, 255, 255, 0.95);
  border-bottom: 1px solid #dddddd;
}
.navbar.condensed .navbar-header {
  padding-top: 0px;
}
.navbar.condensed .navbar-collapse {
  padding-top: 0px;
  padding-bottom: 0px;
}
.navbar .navbar-header {
  padding-top: 0px;
  transition: all 200ms ease-out;
  -webkit-transition: all 200ms ease-out;
  -moz-transition: all 200ms ease-out;
  -ms-transition: all 200ms ease-out;
  -o-transition: all 200ms ease-out;
}
.navbar .navbar-header .navbar-brand {
  display: inline-block;
  padding: 10px 0 0 20px;
  font-size: 22px;
}
.navbar .navbar-header .navbar-brand img {
  width: 60px;
}
.navbar .navbar-header .navbar-brand sup {
  font-size: 12px;
  line-height: 1;
  top: -1em;
}
.navbar .navbar-collapse {
  padding-top: 15px;
  padding-bottom: 15px;
  transition: all 200ms ease-out;
  -webkit-transition: all 200ms ease-out;
  -moz-transition: all 200ms ease-out;
  -ms-transition: all 200ms ease-out;
  -o-transition: all 200ms ease-out;
}
.navbar .navbar-collapse .navbar-nav > li > a {
  padding: 15px;
}
.navbar .navbar-collapse .navbar-nav > li > a:hover {
  background-color: transparent;
}
.navbar .navbar-collapse .navbar-nav.navbar-right:last-child {
  margin-right: 20px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 249px;
}
.footer .footer-header .container {
  height: 77px;
  background: url('/static/image/footer-bg-header.png') no-repeat top right;
}
.footer .footer-content {
  background: url('/static/image/footer-bg.png') no-repeat;
  background-size: 100% 100%;
  padding: 45px 0 45px 0;
  line-height: 1;
  margin-top: 0px;
  color: white;
}
.footer .footer-content .footer-left .links {
  margin-bottom: 18px;
}
.footer .footer-content .footer-left .links li {
  padding-right: 15px;
}
.footer .footer-content .footer-left .links li a {
  cursor: pointer;
  color: white;
}
.footer .footer-content .footer-left .links li a:hover {
  text-decoration: underline;
}
.footer .footer-content .footer-left .usa {
  display: block;
  margin-left: 12px;
  height: 16px;
  margin-top: 0px;
}
.footer .footer-content .footer-left .cp {
  margin-bottom: 18px;
}
.footer .footer-content .footer-left .icons {
  font-size: 18px;
  margin-bottom: 0;
}
.footer .footer-content .footer-left .icons li {
  padding-right: 8px;
}
.footer .footer-content .footer-left .icons li a {
  color: white;
}
.footer .footer-content .footer-right {
  text-align: right;
}
.footer .footer-content .footer-right .logo {
  font-size: 22px;
  font-weight: lighter;
  margin-bottom: 15px;
}
.footer .footer-content .footer-right .slogan {
  line-height: 20px;
}


text:
#include "private-libwebsockets.h"

int lws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len)
{
	unsigned int n;

	switch (wsi->mode) {
	case LWSCM_WSCL_WAITING_PROXY_REPLY:
	case LWSCM_WSCL_ISSUE_HANDSHAKE:
	case LWSCM_WSCL_WAITING_SERVER_REPLY:
	case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
	case LWSCM_WS_CLIENT:
		for (n = 0; n < len; n++)
			if (lws_client_rx_sm(wsi, *(*buf)++)) {
				lwsl_debug("client_rx_sm failed\n");
				return 1;
			}
		return 0;
	default:
		break;
	}
	return 0;
}

int lws_client_socket_service(struct lws_context *context,
			      struct lws *wsi, struct lws_pollfd *pollfd)
{
	char *p = (char *)&context->serv_buf[0];
	unsigned char c;
	int n, len;

	switch (wsi->mode) {

	case LWSCM_WSCL_WAITING_CONNECT:

		/*
		 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
		 * timeout protection set in client-handshake.c
		 */

               if (lws_client_connect_2(wsi) == NULL) {
			/* closed */
			lwsl_client("closed\n");
			return -1;
		}

		/* either still pending connection, or changed mode */
		return 0;

	case LWSCM_WSCL_WAITING_PROXY_REPLY:

		/* handle proxy hung up on us */

		if (pollfd->revents & LWS_POLLHUP) {

			lwsl_warn("Proxy connection %p (fd=%d) dead\n",
				  (void *)wsi, pollfd->fd);

			lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
			return 0;
		}

		n = recv(wsi->sock, (char *)context->serv_buf,
					sizeof(context->serv_buf), 0);
		if (n < 0) {

			if (LWS_ERRNO == LWS_EAGAIN) {
				lwsl_debug("Proxy read returned EAGAIN... retrying\n");
				return 0;
			}

			lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
			lwsl_err("ERROR reading from proxy socket\n");
			return 0;
		}

		context->serv_buf[13] = '\0';
		if (strcmp((char *)context->serv_buf, "HTTP/1.0 200 ") &&
		    strcmp((char *)context->serv_buf, "HTTP/1.1 200 ")
		) {
			lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
			lwsl_err("ERROR proxy: %s\n", context->serv_buf);
			return 0;
		}

		/* clear his proxy connection timeout */

		lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);

		/* fallthru */

	case LWSCM_WSCL_ISSUE_HANDSHAKE:

		/*
		 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
		 * timeout protection set in client-handshake.c
		 */

		/*
		 * take care of our lws_callback_on_writable
		 * happening at a time when there's no real connection yet
		 */
		if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
			return -1;
		lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE);

#ifdef LWS_OPENSSL_SUPPORT
		/* we can retry this... just cook the SSL BIO the first time */

		if (wsi->use_ssl && !wsi->ssl) {
#if defined(CYASSL_SNI_HOST_NAME) || defined(WOLFSSL_SNI_HOST_NAME) || defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
			const char *hostname = lws_hdr_simple_ptr(wsi,
						_WSI_TOKEN_CLIENT_HOST);
#endif

			wsi->ssl = SSL_new(context->ssl_client_ctx);
#ifndef USE_WOLFSSL
			SSL_set_mode(wsi->ssl,
					SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
#endif
			/*
			 * use server name indication (SNI), if supported,
			 * when establishing connection
			 */
#ifdef USE_WOLFSSL
#ifdef USE_OLD_CYASSL
#ifdef CYASSL_SNI_HOST_NAME
			CyaSSL_UseSNI(wsi->ssl, CYASSL_SNI_HOST_NAME,
				hostname, strlen(hostname));
#endif
#else
#ifdef WOLFSSL_SNI_HOST_NAME
			wolfSSL_UseSNI(wsi->ssl, WOLFSSL_SNI_HOST_NAME,
				hostname, strlen(hostname));
#endif
#endif
#else
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
			SSL_set_tlsext_host_name(wsi->ssl, hostname);
#endif
#endif

#ifdef USE_WOLFSSL
			/*
			 * wolfSSL/CyaSSL does certificate verification differently
			 * from OpenSSL.
			 * If we should ignore the certificate, we need to set
			 * this before SSL_new and SSL_connect is called.
			 * Otherwise the connect will simply fail with error
			 * code -155
			 */
#ifdef USE_OLD_CYASSL
			if (wsi->use_ssl == 2)
				CyaSSL_set_verify(wsi->ssl,
							SSL_VERIFY_NONE, NULL);
#else
			if (wsi->use_ssl == 2)
				wolfSSL_set_verify(wsi->ssl,
							SSL_VERIFY_NONE, NULL);
#endif
#endif /* USE_WOLFSSL */

			wsi->client_bio =
				BIO_new_socket(wsi->sock, BIO_NOCLOSE);
			SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);

#ifdef USE_WOLFSSL
#ifdef USE_OLD_CYASSL
			CyaSSL_set_using_nonblock(wsi->ssl, 1);
#else
			wolfSSL_set_using_nonblock(wsi->ssl, 1);
#endif
#else
			BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
#endif

			SSL_set_ex_data(wsi->ssl,
					openssl_websocket_private_data_index,
								       context);
		}

		if (wsi->use_ssl) {
			lws_latency_pre(context, wsi);
			n = SSL_connect(wsi->ssl);
			lws_latency(context, wsi,
			  "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE",
								      n, n > 0);

			if (n < 0) {
				n = SSL_get_error(wsi->ssl, n);

				if (n == SSL_ERROR_WANT_READ)
					goto some_wait;

				if (n == SSL_ERROR_WANT_WRITE) {
					/*
					 * wants us to retry connect due to
					 * state of the underlying ssl layer...
					 * but since it may be stalled on
					 * blocked write, no incoming data may
					 * arrive to trigger the retry.
					 * Force (possibly many times if the SSL
					 * state persists in returning the
					 * condition code, but other sockets
					 * are getting serviced inbetweentimes)
					 * us to get called back when writable.
					 */

					lwsl_info(
					     "SSL_connect WANT_WRITE... retrying\n");
					lws_callback_on_writable(wsi);
some_wait:
					wsi->mode = LWSCM_WSCL_WAITING_SSL;

					return 0; /* no error */
				}
				n = -1;
			}

			if (n <= 0) {
				/*
				 * retry if new data comes until we
				 * run into the connection timeout or win
				 */

				n = ERR_get_error();
				if (n != SSL_ERROR_NONE) {
					lwsl_err("SSL connect error %lu: %s\n",
						n,
						ERR_error_string(n,
							  (char *)context->serv_buf));
					return 0;
				}
			}
		} else
			wsi->ssl = NULL;

		/* fallthru */

	case LWSCM_WSCL_WAITING_SSL:

		if (wsi->use_ssl) {

			if (wsi->mode == LWSCM_WSCL_WAITING_SSL) {
				lws_latency_pre(context, wsi);
				n = SSL_connect(wsi->ssl);
				lws_latency(context, wsi,
					    "SSL_connect LWSCM_WSCL_WAITING_SSL",
					    n, n > 0);

				if (n < 0) {
					n = SSL_get_error(wsi->ssl, n);

					if (n == SSL_ERROR_WANT_READ)
						goto some_wait;

					if (n == SSL_ERROR_WANT_WRITE) {
						/*
						 * wants us to retry connect due to
						 * state of the underlying ssl layer...
						 * but since it may be stalled on
						 * blocked write, no incoming data may
						 * arrive to trigger the retry.
						 * Force (possibly many times if the SSL
						 * state persists in returning the
						 * condition code, but other sockets
						 * are getting serviced inbetweentimes)
						 * us to get called back when writable.
						 */

						lwsl_info("SSL_connect WANT_WRITE... retrying\n");
						lws_callback_on_writable(wsi);

						goto some_wait;
					}
					n = -1;
				}

				if (n <= 0) {
					/*
					 * retry if new data comes until we
					 * run into the connection timeout or win
					 */
					n = ERR_get_error();
					if (n != SSL_ERROR_NONE) {
						lwsl_err("SSL connect error %lu: %s\n",
							 n, ERR_error_string(n,
							 (char *)context->serv_buf));
						return 0;
					}
				}
			}

			#ifndef USE_WOLFSSL
			/*
			 * See comment above about wolfSSL certificate
			 * verification
			 */
			lws_latency_pre(context, wsi);
			n = SSL_get_verify_result(wsi->ssl);
			lws_latency(context, wsi,
				"SSL_get_verify_result LWS_CONNMODE..HANDSHAKE",
								      n, n > 0);

			if (n != X509_V_OK) {
				if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
				     n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) && wsi->use_ssl == 2) {
					lwsl_notice("accepting self-signed certificate\n");
				} else {
					lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n",
						 n, ERR_error_string(n, (char *)context->serv_buf));
					lws_close_free_wsi(wsi,
						LWS_CLOSE_STATUS_NOSTATUS);
					return 0;
				}
			}
#endif /* USE_WOLFSSL */
		} else
			wsi->ssl = NULL;
#endif

		wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
		lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
				AWAITING_TIMEOUT);

		/* fallthru */

	case LWSCM_WSCL_ISSUE_HANDSHAKE2:
		p = lws_generate_client_handshake(wsi, p);
		if (p == NULL) {
			lwsl_err("Failed to generate handshake for client\n");
			lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
			return 0;
		}

		/* send our request to the server */

		lws_latency_pre(context, wsi);

		n = lws_ssl_capable_write(wsi, context->serv_buf,
					  p - (char *)context->serv_buf);
		lws_latency(context, wsi, "send lws_issue_raw", n,
			    n == p - (char *)context->serv_buf);
		switch (n) {
		case LWS_SSL_CAPABLE_ERROR:
			lwsl_debug("ERROR writing to client socket\n");
			lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
			return 0;
		case LWS_SSL_CAPABLE_MORE_SERVICE:
			lws_callback_on_writable(wsi);
			break;
		}

		wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
		wsi->u.hdr.lextable_pos = 0;
		wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
		lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
				AWAITING_TIMEOUT);
		break;

	case LWSCM_WSCL_WAITING_SERVER_REPLY:

		/* handle server hung up on us */

		if (pollfd->revents & LWS_POLLHUP) {

			lwsl_debug("Server connection %p (fd=%d) dead\n",
				(void *)wsi, pollfd->fd);

			goto bail3;
		}

		if (!(pollfd->revents & LWS_POLLIN))
			break;

		/* interpret the server response */

		/*
		 *  HTTP/1.1 101 Switching Protocols
		 *  Upgrade: websocket
		 *  Connection: Upgrade
		 *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
		 *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
		 *  Sec-WebSocket-Protocol: chat
		 */

		/*
		 * we have to take some care here to only take from the
		 * socket bytewise.  The browser may (and has been seen to
		 * in the case that onopen() performs websocket traffic)
		 * coalesce both handshake response and websocket traffic
		 * in one packet, since at that point the connection is
		 * definitively ready from browser pov.
		 */
		len = 1;
		while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
		       len > 0) {
			n = lws_ssl_capable_read(wsi, &c, 1);
			lws_latency(context, wsi, "send lws_issue_raw", n,
				    n == 1);
			switch (n) {
			case LWS_SSL_CAPABLE_ERROR:
				goto bail3;
			case LWS_SSL_CAPABLE_MORE_SERVICE:
				return 0;
			}

			if (lws_parse(wsi, c)) {
				lwsl_warn("problems parsing header\n");
				goto bail3;
			}
		}

		/*
		 * hs may also be coming in multiple packets, there is a 5-sec
		 * libwebsocket timeout still active here too, so if parsing did
		 * not complete just wait for next packet coming in this state
		 */

		if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
			break;

		/*
		 * otherwise deal with the handshake.  If there's any
		 * packet traffic already arrived we'll trigger poll() again
		 * right away and deal with it that way
		 */

		return lws_client_interpret_server_handshake(wsi);

bail3:
		lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
		lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
		return -1;

	case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
		lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
		break;

	case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
		lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
		break;
	default:
		break;
	}

	return 0;
}

/*
 * In-place str to lower case
 */

static void
strtolower(char *s)
{
	while (*s) {
		*s = tolower((int)*s);
		s++;
	}
}

int
lws_client_interpret_server_handshake(struct lws *wsi)
{
	struct lws_context *context = wsi->context;
	int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
	int n, len, okay = 0, isErrorCodeReceived = 0;
	const char *pc;
	char *p;
#ifndef LWS_NO_EXTENSIONS
	const struct lws_extension *ext;
	char ext_name[128];
	const char *c;
	int more = 1;
	void *v;
#endif

	/*
	 * well, what the server sent looked reasonable for syntax.
	 * Now let's confirm it sent all the necessary headers
	 */

	p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
	if (!p) {
		lwsl_info("no URI\n");
		goto bail3;
	}

	if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
		lwsl_info("no ACCEPT\n");
		isErrorCodeReceived = 1;
		goto bail3;
	}

	if (p && strncmp(p, "101", 3)) {
		lwsl_warn(
		       "lws_client_handshake: got bad HTTP response '%s'\n", p);
		goto bail3;
	}

	p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
	if (!p) {
		lwsl_info("no UPGRADE\n");
		goto bail3;
	}
	strtolower(p);
	if (strcmp(p, "websocket")) {
		lwsl_warn(
		      "lws_client_handshake: got bad Upgrade header '%s'\n", p);
		goto bail3;
	}

	p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
	if (!p) {
		lwsl_info("no Connection hdr\n");
		goto bail3;
	}
	strtolower(p);
	if (strcmp(p, "upgrade")) {
		lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
		goto bail3;
	}

	pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
	if (!pc) {
		lwsl_parser("lws_client_int_s_hs: no protocol list\n");
	} else
		lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);

	/*
	 * confirm the protocol the server wants to talk was in the list
	 * of protocols we offered
	 */

	len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
	if (!len) {

		lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
		/*
		 * no protocol name to work from,
		 * default to first protocol
		 */
		wsi->protocol = &context->protocols[0];
		goto check_extensions;
	}

	p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
	len = strlen(p);

	while (pc && *pc && !okay) {
		if (!strncmp(pc, p, len) &&
		    (pc[len] == ',' || pc[len] == '\0')) {
			okay = 1;
			continue;
		}
		while (*pc && *pc++ != ',')
			;
		while (*pc && *pc == ' ')
			pc++;
	}

	if (!okay) {
		lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
		goto bail2;
	}

	/*
	 * identify the selected protocol struct and set it
	 */
	n = 0;
	wsi->protocol = NULL;
	while (context->protocols[n].callback && !wsi->protocol) {
		if (strcmp(p, context->protocols[n].name) == 0) {
			wsi->protocol = &context->protocols[n];
			break;
		}
		n++;
	}

	if (wsi->protocol == NULL) {
		lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
		goto bail2;
	}

check_extensions:
#ifndef LWS_NO_EXTENSIONS
	/* instantiate the accepted extensions */

	if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
		lwsl_ext("no client extenstions allowed by server\n");
		goto check_accept;
	}

	/*
	 * break down the list of server accepted extensions
	 * and go through matching them or identifying bogons
	 */

	if (lws_hdr_copy(wsi, (char *)context->serv_buf,
		   sizeof(context->serv_buf), WSI_TOKEN_EXTENSIONS) < 0) {
		lwsl_warn("ext list from server failed to copy\n");
		goto bail2;
	}

	c = (char *)context->serv_buf;
	n = 0;
	while (more) {

		if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
			ext_name[n] = *c++;
			if (n < sizeof(ext_name) - 1)
				n++;
			continue;
		}
		ext_name[n] = '\0';
		if (!*c)
			more = 0;
		else {
			c++;
			if (!n)
				continue;
		}

		/* check we actually support it */

		lwsl_ext("checking client ext %s\n", ext_name);

		n = 0;
		ext = lws_get_context(wsi)->extensions;
		while (ext && ext->callback) {
			if (strcmp(ext_name, ext->name)) {
				ext++;
				continue;
			}

			n = 1;
			lwsl_ext("instantiating client ext %s\n", ext_name);

			/* instantiate the extension on this conn */

			wsi->active_extensions_user[
				wsi->count_active_extensions] =
					 lws_zalloc(ext->per_session_data_size);
			if (wsi->active_extensions_user[
				wsi->count_active_extensions] == NULL) {
				lwsl_err("Out of mem\n");
				goto bail2;
			}
			wsi->active_extensions[
				  wsi->count_active_extensions] = ext;

			/* allow him to construct his context */

			ext->callback(lws_get_context(wsi), ext, wsi,
				      LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
				      wsi->active_extensions_user[
					 wsi->count_active_extensions],
				      NULL, 0);

			wsi->count_active_extensions++;

			ext++;
		}

		if (n == 0) {
			lwsl_warn("Unknown ext '%s'!\n", ext_name);
			goto bail2;
		}

		n = 0;
	}

check_accept:
#endif

	/*
	 * Confirm his accept token is the one we precomputed
	 */

	p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
	if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
		lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
				  wsi->u.hdr.ah->initial_handshake_hash_base64);
		goto bail2;
	}

	/* allocate the per-connection user memory (if any) */
	if (lws_ensure_user_space(wsi)) {
		lwsl_err("Problem allocating wsi user mem\n");
		goto bail2;
	}

	/*
	 * we seem to be good to go, give client last chance to check
	 * headers and OK it
	 */
	if (wsi->protocol->callback(wsi,
				    LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
				    wsi->user_space, NULL, 0))
		goto bail2;

	/* clear his proxy connection timeout */

	lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);

	/* free up his parsing allocations */

	lws_free(wsi->u.hdr.ah);

	lws_union_transition(wsi, LWSCM_WS_CLIENT);
	wsi->state = LWSS_ESTABLISHED;

	wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;

	/*
	 * create the frame buffer for this connection according to the
	 * size mentioned in the protocol definition.  If 0 there, then
	 * use a big default for compatibility
	 */

	n = wsi->protocol->rx_buffer_size;
	if (!n)
		n = LWS_MAX_SOCKET_IO_BUF;
	n += LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING;
	wsi->u.ws.rx_user_buffer = lws_malloc(n);
	if (!wsi->u.ws.rx_user_buffer) {
		lwsl_err("Out of Mem allocating rx buffer %d\n", n);
		goto bail2;
	}
       wsi->u.ws.rx_ubuf_alloc = n;
	lwsl_info("Allocating client RX buffer %d\n", n);

	if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
		       sizeof n)) {
		lwsl_warn("Failed to set SNDBUF to %d", n);
		goto bail3;
	}

	lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);

	/* call him back to inform him he is up */

	if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
				    wsi->user_space, NULL, 0))
		goto bail3;
#ifndef LWS_NO_EXTENSIONS
	/*
	 * inform all extensions, not just active ones since they
	 * already know
	 */

	ext = context->extensions;

	while (ext && ext->callback) {
		v = NULL;
		for (n = 0; n < wsi->count_active_extensions; n++)
			if (wsi->active_extensions[n] == ext)
				v = wsi->active_extensions_user[n];

		ext->callback(context, ext, wsi,
			  LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
		ext++;
	}
#endif

	return 0;

bail3:
	close_reason = LWS_CLOSE_STATUS_NOSTATUS;

bail2:
	if (wsi->protocol) {
		if (isErrorCodeReceived && p) {
			wsi->protocol->callback(wsi,
				LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
						wsi->user_space, p,
						(unsigned int)strlen(p));
		} else {
			wsi->protocol->callback(wsi,
				LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
						wsi->user_space, NULL, 0);
		}
	}

	lwsl_info("closing connection due to bail2 connection error\n");

	/* closing will free up his parsing allocations */
	lws_close_free_wsi(wsi, close_reason);

	return 1;
}

char *
lws_generate_client_handshake(struct lws *wsi, char *pkt)
{
	char buf[128], hash[20], key_b64[40], *p = pkt;
	struct lws_context *context = wsi->context;
	int n;
#ifndef LWS_NO_EXTENSIONS
	const struct lws_extension *ext;
	int ext_count = 0;
#endif

	/*
	 * create the random key
	 */
	n = lws_get_random(context, hash, 16);
	if (n != 16) {
		lwsl_err("Unable to read from random dev %s\n",
			 SYSTEM_RANDOM_FILEPATH);
		lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
		return NULL;
	}

	lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));

	/*
	 * 00 example client handshake
	 *
	 * GET /socket.io/websocket HTTP/1.1
	 * Upgrade: WebSocket
	 * Connection: Upgrade
	 * Host: 127.0.0.1:9999
	 * Origin: http://127.0.0.1
	 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7  92 ^
	 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
	 * Cookie: socketio=websocket
	 *
	 * (Á®Ä0¶†≥
	 *
	 * 04 example client handshake
	 *
	 * GET /chat HTTP/1.1
	 * Host: server.example.com
	 * Upgrade: websocket
	 * Connection: Upgrade
	 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
	 * Sec-WebSocket-Origin: http://example.com
	 * Sec-WebSocket-Protocol: chat, superchat
	 * Sec-WebSocket-Version: 4
	 */

	p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a",
		     lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));

	p += sprintf(p, "Pragma: no-cache\x0d\x0a"
			"Cache-Control: no-cache\x0d\x0a");

	p += sprintf(p, "Host: %s\x0d\x0a",
		     lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
	p += sprintf(p, "Upgrade: websocket\x0d\x0a"
			"Connection: Upgrade\x0d\x0a"
			"Sec-WebSocket-Key: ");
	strcpy(p, key_b64);
	p += strlen(key_b64);
	p += sprintf(p, "\x0d\x0a");
	if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN))
		p += sprintf(p, "Origin: http://%s\x0d\x0a",
			     lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));

	if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
		p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
		     lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));

	/* tell the server what extensions we could support */

	p += sprintf(p, "Sec-WebSocket-Extensions: ");
#ifndef LWS_NO_EXTENSIONS
	ext = context->extensions;
	while (ext && ext->callback) {

		n = lws_ext_cb_all_exts(context, wsi,
			   LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
			   (char *)ext->name, 0);
		if (n) { /* an extension vetos us */
			lwsl_ext("ext %s vetoed\n", (char *)ext->name);
			ext++;
			continue;
		}

		n = context->protocols[0].callback(wsi,
			LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
				wsi->user_space, (char *)ext->name, 0);

		/*
		 * zero return from callback means
		 * go ahead and allow the extension,
		 * it's what we get if the callback is
		 * unhandled
		 */

		if (n) {
			ext++;
			continue;
		}

		/* apply it */

		if (ext_count)
			*p++ = ',';
		p += sprintf(p, "%s", ext->name);
		ext_count++;

		ext++;
	}
#endif
	p += sprintf(p, "\x0d\x0a");

	if (wsi->ietf_spec_revision)
		p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
			     wsi->ietf_spec_revision);

	/* give userland a chance to append, eg, cookies */

	context->protocols[0].callback(wsi,
				       LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
				       NULL, &p,
				       (pkt + sizeof(context->serv_buf)) - p - 12);

	p += sprintf(p, "\x0d\x0a");

	/* prepare the expected server accept response */

	key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
	n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);

	lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);

	lws_b64_encode_string(hash, 20,
			      wsi->u.hdr.ah->initial_handshake_hash_base64,
			      sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));

	return p;
}


text:
import unittest
import sys
sys.path.insert(0, '..')
from pvcheck.executor import *

class TestExecutor(unittest.TestCase):
    def test_exec_process1(self):
        r = Executor().exec_process(['echo', 'abc'], '')
        self.assertEqual(r.result, ER_OK)
        self.assertEqual(r.status, 0)
        self.assertEqual(r.output, 'abc\n')

    def test_exec_process2(self):
        r = Executor().exec_process(['cat'], 'test test test\n')
        self.assertEqual(r.result, ER_OK)
        self.assertEqual(r.status, 0)
        self.assertEqual(r.output, 'test test test\n')

    def test_exec_process3(self):
        r = Executor().exec_process(['cat', ARG_TMPFILE], '',
                                    tmpfile='1\n2\n3\n4')
        self.assertEqual(r.result, ER_OK)
        self.assertEqual(r.status, 0)
        self.assertEqual(r.output, '1\n2\n3\n4')

    def test_exec_process4(self):
        r = Executor().exec_process(['sleep', '10'], '', timeout=0.01)
        self.assertEqual(r.result, ER_TIMEOUT)

    def test_exec_process5(self):
        r = Executor().exec_process(['__zzzzz'], '')
        self.assertEqual(r.result, ER_NOTFILE)

    def test_exec_process6(self):
        r = Executor().exec_process(['grep', 'pattern'], '')
        self.assertEqual(r.result, ER_ERROR)
        self.assertNotEqual(r.status, 0)

    def test_exec_process7(self):
        r = Executor().exec_process(['seq', '10'], '', output_limit=5)
        self.assertEqual(r.result, ER_OUTPUT_LIMIT)
        self.assertEqual(r.output, '1\n2\n3\n4\n5\n')
        self.assertEqual(r.status, 0)

if __name__ == '__main__':
    unittest.main()


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ElephantHubConroller : MonoBehaviour {

	private KatkootiController Player;
	private ElephantController Elephant;

	//public MonkeyController[] Monkeys;

	public enum ElephantState{
		NONE,
		SCENE_INTRO,
		//		PARTY_FURNITURE,
		FINISH
	}
	private ElephantState currentElephantstate = ElephantState.NONE;
	public ElephantState getCurrentState(){
		return currentElephantstate;
	}

	public ElephantHubConroller(){
		GameManager.GameInitialize += OnGameInitialized;

	}

	~ElephantHubConroller(){
		GameManager.GameInitialize -= OnGameInitialized;
	}

	void OnGameInitialized(){

		if (GameManager.Instance.getCurrentGameState () + 1 >= GameManager.GameSate.ELEPHANT_HUB && Application.loadedLevelName == "ElephantHub") {

			//MainUIManager.Instance.hudController.gameObject.SetActive
			MainUIManager.Instance.hudController.mapIcon.SetActive (true);
			MainUIManager.Instance.hudController.EnableUIMapGlow ();
			MainUIManager.Instance.hudController.inventoryIcon.SetActive (true);
			Player = GameObject.FindObjectOfType<KatkootiController> ();
			Elephant = GameObject.FindObjectOfType<ElephantController> ();
			PlayCurrentState ();
		} else if(Application.loadedLevelName == "ElephantHub") {
			MainUIManager.Instance.hudController.mapIcon.SetActive (true);
			MainUIManager.Instance.hudController.EnableUIMapGlow ();
			MainUIManager.Instance.hudController.inventoryIcon.SetActive (true);
			Player = GameObject.FindObjectOfType<KatkootiController> ();
			Elephant = GameObject.FindObjectOfType<ElephantController> ();
			GameManager.Instance.StartCoroutine(GameManager.Instance.elephantcontroller.NotAvailable());
		}

	}

//	public void PopulateTigerBaloonQuest(){
//		//GameManager.Instance.CurrentQuest = new Quest ();
//
//		//GameManager.Instance.TogglePopulateQuest (GameManager.Instance.CurrentQuest);
//	}
	IEnumerator NotAvailable(){
		Player.WalkWithTransform ();
		yield return new WaitForSeconds (Player.animationController.GetCurrentPlayingClipLength ());
		MainUIManager.Instance.decisionUiController.PopDialogueIcon (GameObject.FindObjectOfType<ElephantHub>().elephantTalkPoint);
		yield return new WaitForSeconds (0.35f);
		GameObject.FindGameObjectWithTag ("Bubble").GetComponent<Image> ().color = new Color32 (255, 255, 255, 255);
		yield return new WaitUntil (() => (MainUIManager.Instance.decisionUiController.proceedStatus == true));
		GameObject.FindGameObjectWithTag ("Bubble").GetComponent<Image> ().color = new Color32 (255, 255, 255, 0);
		MainUIManager.Instance.decisionUiController.UnPopDialogueIcon ();

		Elephant.dialogController.PopDialogue("مرحبًا، لا أشعر بالرغبة\n في اللعب الآن");
		yield return new WaitForSeconds (3f);

		Elephant.dialogController.ChangeText ("ربما في المرة القادمة");
		yield return new WaitForSeconds (1f);
		Elephant.dialogController.UnPopDialogue ();

		yield return new WaitForSeconds (1f);

	}

	public void Reset(){
		currentElephantstate = ElephantState.NONE;
		GameManager.Instance.StopAllCoroutines ();

		MainUIManager.Instance.decisionUiController.UnPopDecisionBox ();
		MainUIManager.Instance.decisionUiController.UnPopDialogueIcon ();
		MainUIManager.Instance.decisionUiController.UnPopGenericTapIcon ();
		MainUIManager.Instance.decisionUiController.UnPopTap ();
	}
	void ProceedState(){
		currentElephantstate++;
		if (currentElephantstate == ElephantState.FINISH) {
			if (GameManager.Instance.getCurrentGameState () + 1 == GameManager.GameSate.FINISH) {
				GameManager.Instance.ProceedGameState ();
			}

		}
	}

	void PlayCurrentState(){
		ProceedState ();
		switch (currentElephantstate) {
		case ElephantState.SCENE_INTRO:
			GameManager.Instance.StartCoroutine(GameManager.Instance.elephantcontroller.SCENE_INTRO());
			break;
//			//		case TigerCaveState.PARTY_FURNITURE:
//			//GameManager.Instance.StartCoroutine(GameManager.Instance.tigerCaveController.PARTY_FURNITURE());
//			//			break;

		default:
			break;
		}

	}

	IEnumerator SCENE_INTRO(){
		MainUIManager.Instance.hudController.gameObject.SetActive (true);
		yield return new WaitForSeconds (0.4f);
		Player.WalkWithTransform ();
		yield return new WaitForSeconds (Player.animationController.GetCurrentPlayingClipLength ());

		MainUIManager.Instance.decisionUiController.PopDialogueIcon (GameObject.FindObjectOfType<ElephantHub>().elephantTalkPoint);
		yield return new WaitForSeconds (0.35f);
		GameObject.FindGameObjectWithTag ("Bubble").GetComponent<Image> ().color = new Color32 (255, 255, 255, 255);
		yield return new WaitUntil (() => (MainUIManager.Instance.decisionUiController.proceedStatus == true));
		GameObject.FindGameObjectWithTag ("Bubble").GetComponent<Image> ().color = new Color32 (255, 255, 255, 0);
		MainUIManager.Instance.decisionUiController.UnPopDialogueIcon ();

		Elephant.dialogController.PopDialogue("مرحبًا، لا أشعر بالرغبة\n في اللعب الآن");
		yield return new WaitForSeconds (3f);

		Elephant.dialogController.ChangeText ("ربما في المرة القادمة");
		yield return new WaitForSeconds (1f);
		Elephant.dialogController.UnPopDialogue ();

		yield return new WaitForSeconds (1f);

		PlayCurrentState ();

	}

}


text:
module Aviator

  define_request :bulk_delete_floating_ips, inherit: [:openstack, :common, :v2, :admin, :base] do

    meta :service, :compute

    link 'documentation',
         'http://docs.openstack.org/api/openstack-compute/2/content/POST_os-floating-ips-bulk-v2_DeleteFloatingIPBulk__v2__tenant_id__os-floating-ips-bulk_delete_ext-os-floating-ips-bulk.html'

    link 'Incorrect documentation: Method should have been PUT not POST',
         'https://github.com/openstack/nova/blob/master/nova/tests/integrated/test_api_samples.py#L1067'

    param :ip_range, required: true

    def body
      p = {
        "ip_range" => params[:ip_range]
      }

      p
    end

    def headers
      super
    end

    def http_method
      :put
    end

    def url
      "#{ base_url }/os-floating-ips-bulk/delete"
    end

  end

end


text:
class Identity < OmniAuth::Identity::Models::ActiveRecord
  attr_accessible :email, :password_digest, :password, :password_confirmation
  validates_uniqueness_of :email
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
end


text:
package com.bancvue.mongomigrate;

import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.*;

import java.net.UnknownHostException;

public class Main {

	public static void main( String[] args ) {
		Namespace namespace = parseArguments( args );

		//System.out.println( namespace );

		if ( namespace.getString( "command" ) == "create" ) {
			CreateCommand command = new CreateCommand( namespace.getString( "name" ), namespace.getString( "migration_folder" ) );
			System.exit( command.execute() );
		} else if ( namespace.getString( "command" ) == "migrate" ) {
			try {
				System.out.println( "Migrating database " + namespace.getString( "database" ) );

				MigrateCommand command = MigrateCommand.Create(
						namespace.getString( "mongo_host" ),
						namespace.getString( "database" ),
						namespace.getString( "migration_folder" ),
						namespace.getString( "mongo_exe_path" ) );

				System.exit( command.execute() );
			} catch ( UnknownHostException e ) {
				e.printStackTrace();
				System.exit( 1 );
			}
		}
	}

	private static Namespace parseArguments( String[] args ) {
		Namespace namespace = null;

		// Create and configure the parser for command line arguments.
		ArgumentParser parser = ArgumentParsers.newArgumentParser( "mongomigrate" )
				.usage( "mongomigrate COMMAND [options]\n" +
						"  use 'mongomigrate --help' to see a list of commands.\n" +
						"  use 'mongomigrate COMMAND --help' for help on individual commands." )
				.description( "MongoMigrate (c)2013 BancVue Ltd.\n" +
						"MongoMigrate is a database migrations tool for MongoDB." )
				.version( "${prog} v1.0" );

		// Create parser collection for sub-commands.
		Subparsers subparsers = parser.addSubparsers().metavar( "COMMAND" ).help( "Available Commands:" );

		// Configure the Create Command.
		Subparser createCommandParser = subparsers.addParser( "create" )
				.setDefault( "command", "create" )
				.description( "Create command:\n" +
						"---------------\n" +
						"The create command creates a new migration script with the specified name containing a default template." )
				.help( "creates a new migration script." );
		createCommandParser.addArgument( "name" ).setDefault( "migration" ).help( "optional name of the migration." );
		createCommandParser.addArgument( "-f", "--migration-folder" ).metavar( "PATH" ).setDefault( "." ).help( "folder containing migrations." );

		// Configure the Migrate Command.
		Subparser migrateCommandParser = subparsers.addParser( "migrate" )
				.setDefault( "command", "migrate" )
				.description( "Migrate command:\n" +
						"----------------\n" +
						"The migrate command migrates the specified database to the most recent version." )
				.help( "migrate a mongo database" );
		migrateCommandParser.addArgument( "database" ).required( true ).help( "the name of the database to migrate." );
		migrateCommandParser.addArgument( "-f", "--migration-folder" ).metavar( "PATH" ).setDefault( "." ).help( "folder containing migrations." );
		migrateCommandParser.addArgument( "-m", "--mongo-host" ).metavar( "MONGOHOST" ).setDefault( "localhost" ).help( "connection string to the mongo host." );
		//migrateCommandParser.addArgument( "-d", "--database" ).metavar( "DATABASE" ).setDefault( "localhost" ).help( "name of the mongo database to migrate." );
		migrateCommandParser.addArgument( "-p", "--mongo-exe-path" ).metavar( "MONGOPATH" ).setDefault( "mongo.exe" ).help( "path to mongo.exe." );

		try {
			namespace = parser.parseArgs( args );
		} catch ( ArgumentParserException e ) {
			parser.handleError( e );
			System.exit( 1 );
		}
		return namespace;
	}
}


text:
'''
This module provides an implementation of the Paxos algorithm as
a set of composable classes.
'''

import collections

# ProposalID
#
# In order for the Paxos algorithm to function, all proposal ids must be
# unique. A simple way to ensure this is to include the proposer's unique
# id in the proposal id.
#
# Python tuples allow the proposal number and the UID to be combined in a
# manner that supports comparison in the expected manner:
#
#   (4,'C') > (4,'B') > (3,'Z')
#
# Named tuples from the collections module support all of the regular
# tuple operations but additionally allow access to the contents by
# name so the numeric component of the proposal ID may be referred to
# via 'proposal_id.number' instead of 'proposal_id[0]'.
#
ProposalID = collections.namedtuple('ProposalID', ['number', 'uid'])

class PaxosMessage (object):
    '''
    Base class for all messages defined in this module
    '''
    from_uid = None # Set by subclass constructor

class Prepare (PaxosMessage):
    '''
    Prepare messages should be broadcast to all Acceptors.
    '''
    def __init__(self, from_uid, proposal_id):
        self.from_uid    = from_uid
        self.proposal_id = proposal_id

class Nack (PaxosMessage):
    '''
    NACKs are technically optional though few practical applications will
    want to omit their use. They are used to signal a proposer that their
    current proposal number is out of date and that a new one should be
    chosen. NACKs may be sent in response to both Prepare and Accept
    messages
    '''
    def __init__(self, from_uid, proposer_uid, proposal_id, promised_proposal_id):
        self.from_uid             = from_uid
        self.proposal_id          = proposal_id
        self.proposer_uid         = proposer_uid
        self.promised_proposal_id = promised_proposal_id

class Promise (PaxosMessage):
    '''
    Promise messages should be sent to at least the Proposer specified in
    the proposer_uid field
    '''
    def __init__(self, from_uid, proposer_uid, proposal_id, last_accepted_id, last_accepted_value):
        self.from_uid             = from_uid
        self.proposer_uid         = proposer_uid
        self.proposal_id          = proposal_id
        self.last_accepted_id     = last_accepted_id
        self.last_accepted_value  = last_accepted_value

class Accept (PaxosMessage):
    '''
    Accept messages should be broadcast to all Acceptors
    '''
    def __init__(self, from_uid, proposal_id, proposal_value):
        self.from_uid       = from_uid
        self.proposal_id    = proposal_id
        self.proposal_value = proposal_value

class Accepted (PaxosMessage):
    '''
    Accepted messages should be sent to all Learners
    '''
    def __init__(self, from_uid, proposal_id, proposal_value):
        self.from_uid       = from_uid
        self.proposal_id    = proposal_id
        self.proposal_value = proposal_value

class Resolution (PaxosMessage):
    '''
    Optional message used to indicate that the final value has been selected
    '''
    def __init__(self, from_uid, value):
        self.from_uid = from_uid
        self.value    = value

class InvalidMessageError (Exception):
    '''
    Thrown if a PaxosMessage subclass is passed to a class that does not
    support it
    '''

class MessageHandler (object):

    def receive(self, msg):
        '''
        Message dispatching function. This function accepts any PaxosMessage subclass and calls
        the appropriate handler function
        '''
        handler = getattr(self, 'receive_' + msg.__class__.__name__.lower(), None)
        if handler is None:
            raise InvalidMessageError('Receiving class does not support messages of type: ' + msg.__class__.__name__)
        return handler( msg )

class Proposer (MessageHandler):
    '''
    The 'leader' attribute is a boolean value indicating the Proposer's
    belief in whether or not it is the current leader. This is not a reliable
    value as multiple nodes may simultaneously believe themselves to be the
    leader.
    '''

    leader               = False
    proposed_value       = None
    proposal_id          = None
    highest_accepted_id  = None
    promises_received    = None
    nacks_received       = None
    current_prepare_msg  = None
    current_accept_msg   = None

    def __init__(self, network_uid, quorum_size):
        self.network_uid         = network_uid
        self.quorum_size         = quorum_size
        self.proposal_id         = ProposalID(0, network_uid)
        self.highest_proposal_id = ProposalID(0, network_uid)

    def propose_value(self, value):
        '''
        Sets the proposal value for this node iff this node is not already aware of
        a previous proposal value. If the node additionally believes itself to be
        the current leader, an Accept message will be returned
        '''
        if self.proposed_value is None:
            self.proposed_value = value

            if self.leader:
                self.current_accept_msg = Accept(self.network_uid, self.proposal_id, value)
                return self.current_accept_msg

    def prepare(self):
        '''
        Returns a new Prepare message with a proposal id higher than
        that of any observed proposals. A side effect of this method is
        to clear the leader flag if it is currently set.
        '''

        self.leader              = False
        self.promises_received   = set()
        self.nacks_received      = set()
        self.proposal_id         = ProposalID(self.highest_proposal_id.number + 1, self.network_uid)
        self.highest_proposal_id = self.proposal_id
        self.current_prepare_msg = Prepare(self.network_uid, self.proposal_id)

        return self.current_prepare_msg

    def observe_proposal(self, proposal_id):
        '''
        Optional method used to update the proposal counter as proposals are
        seen on the network.  When co-located with Acceptors and/or Learners,
        this method may be used to avoid a message delay when attempting to
        assume leadership (guaranteed NACK if the proposal number is too low).
        This method is automatically called for all received Promise and Nack
        messages.
        '''
        if proposal_id > self.highest_proposal_id:
            self.highest_proposal_id = proposal_id

    def receive_nack(self, msg):
        '''
        Returns a new Prepare message if the number of Nacks received reaches
        a quorum.
        '''
        self.observe_proposal( msg.promised_proposal_id )

        if msg.proposal_id == self.proposal_id and self.nacks_received is not None:
            self.nacks_received.add( msg.from_uid )

            if len(self.nacks_received) == self.quorum_size:
                return self.prepare() # Lost leadership or failed to acquire it

    def receive_promise(self, msg):
        '''
        Returns an Accept messages if a quorum of Promise messages is achieved
        '''
        self.observe_proposal( msg.proposal_id )

        if not self.leader and msg.proposal_id == self.proposal_id and msg.from_uid not in self.promises_received:

            self.promises_received.add( msg.from_uid )

            if msg.last_accepted_id > self.highest_accepted_id:
                self.highest_accepted_id = msg.last_accepted_id
                if msg.last_accepted_value is not None:
                    self.proposed_value = msg.last_accepted_value

            if len(self.promises_received) == self.quorum_size:
                self.leader = True

                if self.proposed_value is not None:
                    self.current_accept_msg = Accept(self.network_uid, self.proposal_id, self.proposed_value)
                    return self.current_accept_msg

class Acceptor (MessageHandler):
    '''
    Acceptors act as the fault-tolerant memory for Paxos. To ensure correctness
    in the presense of failure, Acceptors must be able to remember the promises
    they've made even in the event of power outages. Consequently, any changes
    to the promised_id, accepted_id, and/or accepted_value must be persisted to
    stable media prior to sending promise and accepted messages.

    When an Acceptor instance is composed alongside a Proposer instance, it
    is generally advantageous to call the proposer's observe_proposal()
    method when methods of this class are called.
    '''

    def __init__(self, network_uid, promised_id=None, accepted_id=None, accepted_value=None):
        '''
        promised_id, accepted_id, and accepted_value should be provided if and only if this
        instance is recovering from persistent state.
        '''
        self.network_uid    = network_uid
        self.promised_id    = promised_id
        self.accepted_id    = accepted_id
        self.accepted_value = accepted_value

    def receive_prepare(self, msg):
        '''
        Returns either a Promise or a Nack in response. The Acceptor's state must be persisted to disk
        prior to transmitting the Promise message.
        '''
        if msg.proposal_id >= self.promised_id:
            self.promised_id = msg.proposal_id
            return Promise(self.network_uid, msg.from_uid, self.promised_id, self.accepted_id, self.accepted_value)
        else:
            return Nack(self.network_uid, msg.from_uid, msg.proposal_id, self.promised_id)

    def receive_accept(self, msg):
        '''
        Returns either an Accepted or Nack message in response. The Acceptor's state must be persisted
        to disk prior to transmitting the Accepted message.
        '''
        if msg.proposal_id >= self.promised_id:
            self.promised_id     = msg.proposal_id
            self.accepted_id     = msg.proposal_id
            self.accepted_value  = msg.proposal_value
            return Accepted(self.network_uid, msg.proposal_id, msg.proposal_value)
        else:
            return Nack(self.network_uid, msg.from_uid, msg.proposal_id, self.promised_id)

class Learner (MessageHandler):
    '''
    This class listens to Accepted messages, determines when the final value is
    selected, and tracks which peers have accepted the final value.
    '''
    class ProposalStatus (object):
        __slots__ = ['accept_count', 'retain_count', 'acceptors', 'value']
        def __init__(self, value):
            self.accept_count = 0
            self.retain_count = 0
            self.acceptors    = set()
            self.value        = value

    def __init__(self, network_uid, quorum_size):
        self.network_uid       = network_uid
        self.quorum_size       = quorum_size
        self.proposals         = dict() # maps proposal_id => ProposalStatus
        self.acceptors         = dict() # maps from_uid => last_accepted_proposal_id
        self.final_value       = None
        self.final_acceptors   = None   # Will be a set of acceptor UIDs once the final value is chosen
        self.final_proposal_id = None

    def receive_accepted(self, msg):
        '''
        Called when an Accepted message is received from an acceptor. Once the final value
        is determined, the return value of this method will be a Resolution message containing
        the consentual value. Subsequent calls after the resolution is chosen will continue to add
        new Acceptors to the final_acceptors set and return Resolution messages.
        '''
        if self.final_value is not None:
            if msg.proposal_id >= self.final_proposal_id and msg.proposal_value == self.final_value:
                self.final_acceptors.add( msg.from_uid )
            return Resolution(self.network_uid, self.final_value)

        last_pn = self.acceptors.get(msg.from_uid)

        if msg.proposal_id <= last_pn:
            return # Old message

        self.acceptors[ msg.from_uid ] = msg.proposal_id

        if last_pn is not None:
            ps = self.proposals[ last_pn ]
            ps.retain_count -= 1
            ps.acceptors.remove(msg.from_uid)
            if ps.retain_count == 0:
                del self.proposals[ last_pn ]

        if not msg.proposal_id in self.proposals:
            self.proposals[ msg.proposal_id ] = Learner.ProposalStatus(msg.proposal_value)

        ps = self.proposals[ msg.proposal_id ]

        assert msg.proposal_value == ps.value, 'Value mismatch for single proposal!'

        ps.accept_count += 1
        ps.retain_count += 1
        ps.acceptors.add(msg.from_uid)

        if ps.accept_count == self.quorum_size:
            self.final_proposal_id = msg.proposal_id
            self.final_value       = msg.proposal_value
            self.final_acceptors   = ps.acceptors
            self.proposals         = None
            self.acceptors         = None

            return Resolution( self.network_uid, self.final_value )

class PaxosInstance (Proposer, Acceptor, Learner):
    '''
    Aggregate Proposer, Accepter, & Learner class.
    '''

    def __init__(self, network_uid, quorum_size, promised_id=None, accepted_id=None, accepted_value=None):
        Proposer.__init__(self, network_uid, quorum_size)
        Acceptor.__init__(self, network_uid, promised_id, accepted_id, accepted_value)
        Learner.__init__(self, network_uid, quorum_size)

    def receive_prepare(self, msg):
        self.observe_proposal( msg.proposal_id )
        return super(PaxosInstance,self).receive_prepare(msg)

    def receive_accept(self, msg):
        self.observe_proposal( msg.proposal_id )
        return super(PaxosInstance,self).receive_accept(msg)


text:
/**
 *
 * @file sg_wc_diff_utils.c
 *
 * @details routines to help with external diff/merge operations.
 * These are used by sg_diff_ext.c and sg_merge_ext.c
 *
 */

//////////////////////////////////////////////////////////////////

#include <sg.h>

#include "sg_wc__public_typedefs.h"
#include "sg_wc__public_prototypes.h"
#include "sg_wc__private.h"

//////////////////////////////////////////////////////////////////

/**
 * Create a label for one side of a UNIFIED DIFF.  This will appear on one of
 * the header lines after the "+++ " or "--- ".  (We DO NOT create the "+++ "
 * portion.)
 *
 * Gnu-diff (when --label is not used) creates something like:
 *      +++ %s\t%s		with the file's relative pathname and date-time-modified.
 *
 *      --- d1/date2	1970-01-01 00:00:00.000000000 +0000
 *      +++ d2/date2	2009-04-30 13:10:57.000000000 +0000
 *
 * BZR's diff command creates something like:
 *
 *      --- d2/date2	2009-04-30 12:38:41 +0000
 *      +++ d2/date2	2009-04-30 13:10:57 +0000
 *
 * GIT's diff command creates something like:
 *
 *      --- a/eeeeee.txt
 *      +++ b/eeeeee.txt
 *
 * So, we can pretty much do whatever we want here.
 *
 * I'm going to try the following and see if we like it:
 * [] for a historical version, print:
 *      +++ %s\t %s    with the repo-path and the HID.
 *
 *    we don't have a valid date-stamp to print. (our caller might have
 *    the date-stamp on the changeset, but that doesn't have anything to
 *    to with the date on an indivdual file (the file might not have even
 *    been modified in that changeset).
 *
 *    the HID may be useful later.
 *
 * [] for a working-directory version, print:
 *      +++ %s\t %s    with the repo-path and the live date-time-stamp.
 *
 *    since the file is in the working-directory, the date stamp has
 *    some validity (it doesn't mean that they changed the file or reflect
 *    the last change (it could be date of the last get-latest for all we
 *    know)).
 *
 * [] just for sanity, we allow a repo-path only version:
 *      +++ %s
 *
 * In all cases we print the complete repo-path of the item.
 *
 * TODO do we care about feeding this output to PATCH and how it digests
 * pathnames and with the various -p0 -p1 ... arguments?
 *
 * Note: It appears that PATCH requires the tab to delimit the end of
 *       the filename.  I added a space after the tab because several
 *       GUI diff/merge tools don't render the tab in their labels, so the
 *       space is needed to separate the filename from following details.
 *       Hopefully if there are other tools out there trying to parse data
 *       after the tab (like the date-time-stamp) then they will trim it first.
 *       Andy 20110912
 *
 * We return a string that you must free.
 */
void sg_wc_diff_utils__make_label(SG_context * pCtx,
								  const char * szRepoPath,
								  const char * szHid,
								  const char * szDate,
								  SG_string ** ppStringLabel)
{
	SG_string * pString = NULL;

	SG_NONEMPTYCHECK_RETURN(szRepoPath);

	if (szHid && szDate)			// allow zero or one, but not both
		SG_ERR_THROW_RETURN(  SG_ERR_INVALIDARG  );

	SG_NULLARGCHECK(ppStringLabel);

	SG_ERR_CHECK_RETURN(  SG_STRING__ALLOC(pCtx,&pString)  );

	//////////////////////////////////////////////////////////////////
	// WARNING: All of the input arguments are in our internal NFC UTF-8 format
	// WARNING: (as is everything).  SG_exec__() will convert whatever we construct
	// WARNING: here to an os-buffer (utf-8, locale, or wchar_t) before giving it
	// WARNING: to execvp() or CreateProcessW().
	// WARNING:
	// WARNING: I *think* this is what we want.
	// WARNING:
	// WARNING: We can't be sure how the child process will handle the label text
	// WARNING: when it prints it to its STDOUT.  This may cause some confusion.
	// WARNING: For example, NFC/NFD issues on MAC or some '?' characters getting
	// WARNING: printed by cygwin's version of gnu-diff and etc.
	// WARNING:
	// WARNING: I don't know if there are actually any issues here or not or if
	// WARNING: so whether they will cause a problem.
	//////////////////////////////////////////////////////////////////

	if (szHid)
		SG_ERR_CHECK(  SG_string__sprintf(pCtx,
										  pString,"%s\t %s",
										  szRepoPath,szHid)  );
	else if (szDate)
		SG_ERR_CHECK(  SG_string__sprintf(pCtx,
										  pString,"%s\t %s",
										  szRepoPath,szDate)  );
	else
		SG_ERR_CHECK(  SG_string__set__sz(pCtx,pString,szRepoPath)  );

	*ppStringLabel = pString;

	return;

fail:
	SG_STRING_NULLFREE(pCtx, pString);
}

//////////////////////////////////////////////////////////////////

/**
 * Export a blob-of-interest from the REPO into a temporary directory
 * so that we can let the external diff tool compare it with another
 * version somewhere.
 *
 * We create a file with a GID-based name rather than re-creating
 * the working-directory hierarchy in the temp directory.  This lets
 * us flatten the export in one directory without collisions and
 * avoids move/rename and added/deleted sub-directory issues.
 *
 * pPathTempSessionDir should be something like "$TMPDIR/gid_session/".
 * This should be a unique directory name such that everything being
 * exported is isolated from other runs.  (if we are doing a
 * changeset-vs-changeset diff, we may create lots of files on each
 * side -- and our command should not interfere with other diffs
 * in progress in other processes.)
 *
 * szVersion should be a value to let us group everything from cset[0]
 * in a different directory from stuff from cset[1].  this might be
 * simply "0" and "1" or it might be the cset's HIDs.
 *
 * szGidObject is the gid of the object.
 *
 * szHidBlob is the HID of the content.  Normally this is the content
 * of the file that will be compared (corresponding to a user-file
 * under version control).  However, we may also want to use this
 * to splat a data blob to a file so that they can be compared --
 * but this may be too weird.
 *
 * pszNameForSuffix is optional; if set we try to get a suffix
 * from it for the temp file.
 *
 * You are responsible for freeing the returned pathname and
 * deleting the file that we create.
 */
void sg_wc_diff_utils__export_to_temp_file(SG_context * pCtx,
										   SG_wc_tx * pWcTx,
										   const char * szVersion,	// an index (like 0 or 1, _older_ _newer_) or maybe cset HID
										   const char * szGidObject,
										   const char * szHidBlob,
										   const char * pszNameForSuffix,
										   SG_pathname ** ppPathTempFile)
{
	SG_pathname * pPathFile = NULL;
	SG_file * pFile = NULL;
	SG_bool bDirExists;
	SG_string * pStr = NULL;

	// create pathname for the temp
	// file: <tempdir>/version/gid7
	//   or: <tempdir>/version/gid7~name.suffix

	SG_ERR_CHECK(  sg_wc_tx__create_session_temp_dir(pCtx, pWcTx)  );

	SG_ERR_CHECK(  SG_PATHNAME__ALLOC__PATHNAME_SZ(pCtx, &pPathFile, pWcTx->pPathSessionTempDir,szVersion)  );
	SG_ERR_CHECK(  SG_fsobj__exists__pathname(pCtx,pPathFile,&bDirExists,NULL,NULL)  );
	if (!bDirExists)
		SG_ERR_CHECK(  SG_fsobj__mkdir_recursive__pathname(pCtx,pPathFile)  );

	SG_ERR_CHECK(  SG_STRING__ALLOC(pCtx, &pStr)  );
	SG_ERR_CHECK(  SG_string__sprintf(pCtx, pStr, "%.7s~", szGidObject)  );
	if (pszNameForSuffix)
	{
		// if given a path, extract the final filename.
		char * pSlash = strrchr(pszNameForSuffix, '/');
		if (pSlash)
			pszNameForSuffix = pSlash + 1;

		SG_ERR_CHECK(  SG_string__append__sz(pCtx, pStr, pszNameForSuffix)  );
	}
	SG_ERR_CHECK(  SG_pathname__append__from_sz(pCtx, pPathFile, SG_string__sz(pStr))  );
	SG_STRING_NULLFREE(pCtx, pStr);

	// open the file and copy the contents of the blob into it

	SG_ERR_CHECK(  SG_file__open__pathname(pCtx,pPathFile,SG_FILE_WRONLY|SG_FILE_CREATE_NEW,0600,&pFile)  );
	SG_ERR_CHECK(  SG_repo__fetch_blob_into_file(pCtx,pWcTx->pDb->pRepo,szHidBlob,pFile,NULL)  );
	SG_ERR_CHECK(  SG_file__close(pCtx,&pFile)  );

	// TODO 2012/05/04 Should we chmod(0400) on the tempfile ?

	*ppPathTempFile = pPathFile;
	return;

fail:
	if (pFile)				// only if **WE** created the file, do we try to delete it on an error.
	{
		SG_FILE_NULLCLOSE(pCtx,pFile);
		SG_ERR_IGNORE(  SG_fsobj__remove__pathname(pCtx,pPathFile)  );
	}
	SG_PATHNAME_NULLFREE(pCtx, pPathFile);
	SG_STRING_NULLFREE(pCtx, pStr);
}


text:
import '../../_version.js';
export const messages = {
    'invalid-value': ({ paramName, validValueDescription, value }) => {
        if (!paramName || !validValueDescription) {
            throw new Error(`Unexpected input to 'invalid-value' error.`);
        }
        return (`The '${paramName}' parameter was given a value with an ` +
            `unexpected value. ${validValueDescription} Received a value of ` +
            `${JSON.stringify(value)}.`);
    },
    'not-an-array': ({ moduleName, className, funcName, paramName }) => {
        if (!moduleName || !className || !funcName || !paramName) {
            throw new Error(`Unexpected input to 'not-an-array' error.`);
        }
        return (`The parameter '${paramName}' passed into ` +
            `'${moduleName}.${className}.${funcName}()' must be an array.`);
    },
    'incorrect-type': ({ expectedType, paramName, moduleName, className, funcName, }) => {
        if (!expectedType || !paramName || !moduleName || !funcName) {
            throw new Error(`Unexpected input to 'incorrect-type' error.`);
        }
        const classNameStr = className ? `${className}.` : '';
        return (`The parameter '${paramName}' passed into ` +
            `'${moduleName}.${classNameStr}` +
            `${funcName}()' must be of type ${expectedType}.`);
    },
    'incorrect-class': ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem, }) => {
        if (!expectedClassName || !moduleName || !funcName) {
            throw new Error(`Unexpected input to 'incorrect-class' error.`);
        }
        const classNameStr = className ? `${className}.` : '';
        if (isReturnValueProblem) {
            return (`The return value from ` +
                `'${moduleName}.${classNameStr}${funcName}()' ` +
                `must be an instance of class ${expectedClassName}.`);
        }
        return (`The parameter '${paramName}' passed into ` +
            `'${moduleName}.${classNameStr}${funcName}()' ` +
            `must be an instance of class ${expectedClassName}.`);
    },
    'missing-a-method': ({ expectedMethod, paramName, moduleName, className, funcName, }) => {
        if (!expectedMethod ||
            !paramName ||
            !moduleName ||
            !className ||
            !funcName) {
            throw new Error(`Unexpected input to 'missing-a-method' error.`);
        }
        return (`${moduleName}.${className}.${funcName}() expected the ` +
            `'${paramName}' parameter to expose a '${expectedMethod}' method.`);
    },
    'add-to-cache-list-unexpected-type': ({ entry }) => {
        return (`An unexpected entry was passed to ` +
            `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` +
            `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` +
            `strings with one or more characters, objects with a url property or ` +
            `Request objects.`);
    },
    'add-to-cache-list-conflicting-entries': ({ firstEntry, secondEntry }) => {
        if (!firstEntry || !secondEntry) {
            throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`);
        }
        return (`Two of the entries passed to ` +
            `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` +
            `${firstEntry} but different revision details. Workbox is ` +
            `unable to cache and version the asset correctly. Please remove one ` +
            `of the entries.`);
    },
    'plugin-error-request-will-fetch': ({ thrownErrorMessage }) => {
        if (!thrownErrorMessage) {
            throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`);
        }
        return (`An error was thrown by a plugins 'requestWillFetch()' method. ` +
            `The thrown error message was: '${thrownErrorMessage}'.`);
    },
    'invalid-cache-name': ({ cacheNameId, value }) => {
        if (!cacheNameId) {
            throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`);
        }
        return (`You must provide a name containing at least one character for ` +
            `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` +
            `'${JSON.stringify(value)}'`);
    },
    'unregister-route-but-not-found-with-method': ({ method }) => {
        if (!method) {
            throw new Error(`Unexpected input to ` +
                `'unregister-route-but-not-found-with-method' error.`);
        }
        return (`The route you're trying to unregister was not  previously ` +
            `registered for the method type '${method}'.`);
    },
    'unregister-route-route-not-registered': () => {
        return (`The route you're trying to unregister was not previously ` +
            `registered.`);
    },
    'queue-replay-failed': ({ name }) => {
        return `Replaying the background sync queue '${name}' failed.`;
    },
    'duplicate-queue-name': ({ name }) => {
        return (`The Queue name '${name}' is already being used. ` +
            `All instances of backgroundSync.Queue must be given unique names.`);
    },
    'expired-test-without-max-age': ({ methodName, paramName }) => {
        return (`The '${methodName}()' method can only be used when the ` +
            `'${paramName}' is used in the constructor.`);
    },
    'unsupported-route-type': ({ moduleName, className, funcName, paramName }) => {
        return (`The supplied '${paramName}' parameter was an unsupported type. ` +
            `Please check the docs for ${moduleName}.${className}.${funcName} for ` +
            `valid input types.`);
    },
    'not-array-of-class': ({ value, expectedClass, moduleName, className, funcName, paramName, }) => {
        return (`The supplied '${paramName}' parameter must be an array of ` +
            `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` +
            `Please check the call to ${moduleName}.${className}.${funcName}() ` +
            `to fix the issue.`);
    },
    'max-entries-or-age-required': ({ moduleName, className, funcName }) => {
        return (`You must define either config.maxEntries or config.maxAgeSeconds` +
            `in ${moduleName}.${className}.${funcName}`);
    },
    'statuses-or-headers-required': ({ moduleName, className, funcName }) => {
        return (`You must define either config.statuses or config.headers` +
            `in ${moduleName}.${className}.${funcName}`);
    },
    'invalid-string': ({ moduleName, funcName, paramName }) => {
        if (!paramName || !moduleName || !funcName) {
            throw new Error(`Unexpected input to 'invalid-string' error.`);
        }
        return (`When using strings, the '${paramName}' parameter must start with ` +
            `'http' (for cross-origin matches) or '/' (for same-origin matches). ` +
            `Please see the docs for ${moduleName}.${funcName}() for ` +
            `more info.`);
    },
    'channel-name-required': () => {
        return (`You must provide a channelName to construct a ` +
            `BroadcastCacheUpdate instance.`);
    },
    'invalid-responses-are-same-args': () => {
        return (`The arguments passed into responsesAreSame() appear to be ` +
            `invalid. Please ensure valid Responses are used.`);
    },
    'expire-custom-caches-only': () => {
        return (`You must provide a 'cacheName' property when using the ` +
            `expiration plugin with a runtime caching strategy.`);
    },
    'unit-must-be-bytes': ({ normalizedRangeHeader }) => {
        if (!normalizedRangeHeader) {
            throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`);
        }
        return (`The 'unit' portion of the Range header must be set to 'bytes'. ` +
            `The Range header provided was "${normalizedRangeHeader}"`);
    },
    'single-range-only': ({ normalizedRangeHeader }) => {
        if (!normalizedRangeHeader) {
            throw new Error(`Unexpected input to 'single-range-only' error.`);
        }
        return (`Multiple ranges are not supported. Please use a  single start ` +
            `value, and optional end value. The Range header provided was ` +
            `"${normalizedRangeHeader}"`);
    },
    'invalid-range-values': ({ normalizedRangeHeader }) => {
        if (!normalizedRangeHeader) {
            throw new Error(`Unexpected input to 'invalid-range-values' error.`);
        }
        return (`The Range header is missing both start and end values. At least ` +
            `one of those values is needed. The Range header provided was ` +
            `"${normalizedRangeHeader}"`);
    },
    'no-range-header': () => {
        return `No Range header was found in the Request provided.`;
    },
    'range-not-satisfiable': ({ size, start, end }) => {
        return (`The start (${start}) and end (${end}) values in the Range are ` +
            `not satisfiable by the cached response, which is ${size} bytes.`);
    },
    'attempt-to-cache-non-get-request': ({ url, method }) => {
        return (`Unable to cache '${url}' because it is a '${method}' request and ` +
            `only 'GET' requests can be cached.`);
    },
    'cache-put-with-no-response': ({ url }) => {
        return (`There was an attempt to cache '${url}' but the response was not ` +
            `defined.`);
    },
    'no-response': ({ url, error }) => {
        let message = `The strategy could not generate a response for '${url}'.`;
        if (error) {
            message += ` The underlying error is ${error}.`;
        }
        return message;
    },
    'bad-precaching-response': ({ url, status }) => {
        return (`The precaching request for '${url}' failed` +
            (status ? ` with an HTTP status of ${status}.` : `.`));
    },
    'non-precached-url': ({ url }) => {
        return (`createHandlerBoundToURL('${url}') was called, but that URL is ` +
            `not precached. Please pass in a URL that is precached instead.`);
    },
    'add-to-cache-list-conflicting-integrities': ({ url }) => {
        return (`Two of the entries passed to ` +
            `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` +
            `${url} with different integrity values. Please remove one of them.`);
    },
    'missing-precache-entry': ({ cacheName, url }) => {
        return `Unable to find a precached response in ${cacheName} for ${url}.`;
    },
    'cross-origin-copy-response': ({ origin }) => {
        return (`workbox-core.copyResponse() can only be used with same-origin ` +
            `responses. It was passed a response with origin ${origin}.`);
    },
    'opaque-streams-source': ({ type }) => {
        const message = `One of the workbox-streams sources resulted in an ` +
            `'${type}' response.`;
        if (type === 'opaqueredirect') {
            return (`${message} Please do not use a navigation request that results ` +
                `in a redirect as a source.`);
        }
        return `${message} Please ensure your sources are CORS-enabled.`;
    },
};


text:
__author__ = 'Andreas M. Wahl'

import sys
import os

runCommand = "chmod +x " + sys.argv[1]
os.system(runCommand)
runCommand = 'test "$SSH_AUTH_SOCK" || exec ssh-agent $SHELL -c "ssh-add; exec $SHELL -c "./' + sys.argv[1] +  '"' + '"'

print runCommand
os.system(runCommand)


text:
@implementation Utils

- (NSString*)getHour
{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString *dateString = [dateFormat stringFromDate:now];

    return dateString;
}

#pragma mark Lifecycle

+ (id)ibtRealTimeSJWithConfig
{
    return [[self class] alloc];
}

- (id)initWithConfig
{
    self = [super init];

    if (self) {
        // Do comething
    }

    return self;
}

@end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.01.15 at 04:16:28 PM PST
//

package com.per_colator.percolator_out._13;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the com.per_colator.percolator_out._13 package.
 *
An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    private final static QName _PValue_QNAME = new QName("http://per-colator.com/percolator_out/13", "p_value");
    private final static QName _ProteinId_QNAME = new QName("http://per-colator.com/percolator_out/13", "protein_id");
    private final static QName _QValue_QNAME = new QName("http://per-colator.com/percolator_out/13", "q_value");
    private final static QName _CalcMass_QNAME = new QName("http://per-colator.com/percolator_out/13", "calc_mass");
    private final static QName _SvmScore_QNAME = new QName("http://per-colator.com/percolator_out/13", "svm_score");
    private final static QName _ExpMass_QNAME = new QName("http://per-colator.com/percolator_out/13", "exp_mass");
    private final static QName _Pep_QNAME = new QName("http://per-colator.com/percolator_out/13", "pep");

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.per_colator.percolator_out._13
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link ProcessInfo }
     *
     */
    public ProcessInfo createProcessInfo() {
        return new ProcessInfo();
    }

    /**
     * Create an instance of {@link Peptide }
     *
     */
    public Peptide createPeptide() {
        return new Peptide();
    }

    /**
     * Create an instance of {@link RetentionTime }
     *
     */
    public RetentionTime createRetentionTime() {
        return new RetentionTime();
    }

    /**
     * Create an instance of {@link PsmIds }
     *
     */
    public PsmIds createPsmIds() {
        return new PsmIds();
    }

    /**
     * Create an instance of {@link PercolatorOutput }
     *
     */
    public PercolatorOutput createPercolatorOutput() {
        return new PercolatorOutput();
    }

    /**
     * Create an instance of {@link ProcessInfo.Comment }
     *
     */
    public ProcessInfo.Comment createProcessInfoComment() {
        return new ProcessInfo.Comment();
    }

    /**
     * Create an instance of {@link Psms }
     *
     */
    public Psms createPsms() {
        return new Psms();
    }

    /**
     * Create an instance of {@link Psm }
     *
     */
    public Psm createPsm() {
        return new Psm();
    }

    /**
     * Create an instance of {@link PeptideSeq }
     *
     */
    public PeptideSeq createPeptideSeq() {
        return new PeptideSeq();
    }

    /**
     * Create an instance of {@link Peptides }
     *
     */
    public Peptides createPeptides() {
        return new Peptides();
    }

    /**
     * Create an instance of {@link Proteins }
     *
     */
    public Proteins createProteins() {
        return new Proteins();
    }

    /**
     * Create an instance of {@link Protein }
     *
     */
    public Protein createProtein() {
        return new Protein();
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://per-colator.com/percolator_out/13", name = "p_value")
    public JAXBElement<String> createPValue(String value) {
        return new JAXBElement<String>(_PValue_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://per-colator.com/percolator_out/13", name = "protein_id")
    public JAXBElement<String> createProteinId(String value) {
        return new JAXBElement<String>(_ProteinId_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://per-colator.com/percolator_out/13", name = "q_value")
    public JAXBElement<String> createQValue(String value) {
        return new JAXBElement<String>(_QValue_QNAME, String.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Double }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://per-colator.com/percolator_out/13", name = "calc_mass")
    public JAXBElement<Double> createCalcMass(Double value) {
        return new JAXBElement<Double>(_CalcMass_QNAME, Double.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Double }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://per-colator.com/percolator_out/13", name = "svm_score")
    public JAXBElement<Double> createSvmScore(Double value) {
        return new JAXBElement<Double>(_SvmScore_QNAME, Double.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link Double }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://per-colator.com/percolator_out/13", name = "exp_mass")
    public JAXBElement<Double> createExpMass(Double value) {
        return new JAXBElement<Double>(_ExpMass_QNAME, Double.class, null, value);
    }

    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
     *
     */
    @XmlElementDecl(namespace = "http://per-colator.com/percolator_out/13", name = "pep")
    public JAXBElement<String> createPep(String value) {
        return new JAXBElement<String>(_Pep_QNAME, String.class, null, value);
    }

}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/beyondcorp/appconnectors/v1/app_connectors_service.proto

namespace Google\Cloud\BeyondCorp\AppConnectors\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request message for BeyondCorp.GetAppConnector.
 *
 * Generated from protobuf message google.cloud.beyondcorp.appconnectors.v1.GetAppConnectorRequest
 */
class GetAppConnectorRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. BeyondCorp AppConnector name using the form:
     * `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. BeyondCorp AppConnector name using the form:
     *           `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Beyondcorp\Appconnectors\V1\AppConnectorsService::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. BeyondCorp AppConnector name using the form:
     * `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. BeyondCorp AppConnector name using the form:
     * `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

}


text:
<?php

include_once(dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR."plugins.php");

if ($_REQUEST['action'] == 'clear' && !empty($_REQUEST['clearid'])) {

	$id = $_REQUEST['clearid'];

	if(!empty($_REQUEST['chatroommode'])) {
		$_SESSION['cometchat']['chatrooms_'.$id.'_clearId'] = getTimeStamp().rand(100,999);
	} elseif (!empty($_SESSION['cometchat']['cometchat_user_'.$id])) {
		$lastentry = 0;

		if (!empty($_SESSION['cometchat']['cometchat_user_'.$id]) && is_array($_SESSION['cometchat']['cometchat_user_'.$id])) {
			$lastentry = end($_SESSION['cometchat']['cometchat_user_'.$id]);
			$lastentry = $lastentry['id'];
		}

		unset($_SESSION['cometchat']['cometchat_user_'.$id]);

		$_SESSION['cometchat']['cometchat_user_'.$id.'_clear'] = array('timestamp' => getTimeStamp().'999', 'lastentry' => array('id' => $lastentry));
	}
}

if (!empty($_GET['callback'])) {
	header('content-type: application/json; charset=utf-8');
	echo $_GET['callback'].'()';
}

?>


text:
package com.intellij.openapi.progress.util;

import com.intellij.openapi.util.NlsContexts;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;

@ApiStatus.Internal
public interface TitledIndicator {
  void setTitle(@NotNull @NlsContexts.ProgressTitle String title);
}