text:
package org.elasticsearch.index.query;

import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.test.ESTestCase;

import static org.hamcrest.Matchers.equalTo;

public class OperatorTests extends ESTestCase {

    public void testValidOrdinals() {
        assertThat(Operator.OR.ordinal(), equalTo(0));
        assertThat(Operator.AND.ordinal(), equalTo(1));
    }

    public void testWriteTo() throws Exception {
        try (BytesStreamOutput out = new BytesStreamOutput()) {
            Operator.OR.writeTo(out);
            try (StreamInput in = out.bytes().streamInput()) {
                assertThat(in.readVInt(), equalTo(0));
            }
        }

        try (BytesStreamOutput out = new BytesStreamOutput()) {
            Operator.AND.writeTo(out);
            try (StreamInput in = out.bytes().streamInput()) {
                assertThat(in.readVInt(), equalTo(1));
            }
        }
    }

    public void testReadFrom() throws Exception {
        try (BytesStreamOutput out = new BytesStreamOutput()) {
            out.writeVInt(0);
            try (StreamInput in = out.bytes().streamInput()) {
                assertThat(Operator.readFromStream(in), equalTo(Operator.OR));
            }
        }
        try (BytesStreamOutput out = new BytesStreamOutput()) {
            out.writeVInt(1);
            try (StreamInput in = out.bytes().streamInput()) {
                assertThat(Operator.readFromStream(in), equalTo(Operator.AND));
            }
        }
    }

    public void testToBooleanClauseOccur() {
        assertThat(Operator.AND.toBooleanClauseOccur(), equalTo(BooleanClause.Occur.MUST));
        assertThat(Operator.OR.toBooleanClauseOccur(), equalTo(BooleanClause.Occur.SHOULD));
    }

    public void testToQueryParserOperator() {
        assertThat(Operator.AND.toQueryParserOperator(), equalTo(QueryParser.Operator.AND));
        assertThat(Operator.OR.toQueryParserOperator(), equalTo(QueryParser.Operator.OR));
    }

    public void testFromString() {
        assertThat(Operator.fromString("and"), equalTo(Operator.AND));
        assertThat(Operator.fromString("AND"), equalTo(Operator.AND));
        assertThat(Operator.fromString("AnD"), equalTo(Operator.AND));
        assertThat(Operator.fromString("or"), equalTo(Operator.OR));
        assertThat(Operator.fromString("OR"), equalTo(Operator.OR));
        assertThat(Operator.fromString("Or"), equalTo(Operator.OR));
    }
}


text:
package com.garymcgowan.stockpricetrail.priceTrailList;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.garymcgowan.stockpricetrail.App;
import com.garymcgowan.stockpricetrail.DataManager;
import com.garymcgowan.stockpricetrail.R;
import com.garymcgowan.stockpricetrail.model.Stock;
import com.garymcgowan.stockpricetrail.stockdetails.StockDetailsActivity;
import com.garymcgowan.stockpricetrail.watchlist.IWatchListProvider;
import com.jakewharton.rxbinding2.support.v4.widget.RxSwipeRefreshLayout;
import com.jakewharton.rxbinding2.support.v7.widget.RxSearchView;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

public class PriceTrailListListActivity extends AppCompatActivity implements PriceTrailListActivityView, View.OnClickListener {

    @Inject IWatchListProvider watchlistProvider;
    @Inject DataManager dataManager;

    PriceTrailListActivityPresenter presenter;
    @BindView(R.id.stockSymbol) TextView stockSymbol;
    @BindView(R.id.stockName) TextView stockName;
    @BindView(R.id.stockPriceTrail) TextView stockPriceTrail;
    @BindView(R.id.stockPrice) TextView stockPrice;
    @BindView(R.id.stockLow) TextView stockLow;
    @BindView(R.id.stockHigh) TextView stockHigh;
    @BindView(R.id.recycler_view) RecyclerView recyclerView;
    @BindView(R.id.swipe_refresh_layout) SwipeRefreshLayout swipeRefreshLayout;
    CompositeDisposable disposables = new CompositeDisposable();
    Subject<Integer> sortFlowable = PublishSubject.create();
    private PriceTrailListAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private SearchView searchView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_price_trail);
        ButterKnife.bind(this);
        App.getApplicationComponent().inject(this);
        presenter = new PriceTrailListActivityPresenter(this, dataManager, watchlistProvider, AndroidSchedulers.mainThread());

//        recyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));

        mAdapter = new PriceTrailListAdapter(null);
        recyclerView.setAdapter(mAdapter);

//        disposables.add(presenter.setRefreshObservable(
//                RxSwipeRefreshLayout.refreshes(swipeRefreshLayout)
//                        .toFlowable(BackpressureStrategy.LATEST)
//        ));

        //setup header
        stockSymbol.setText(R.string.company);
        stockName.setText(null);
        stockPriceTrail.setText(R.string.price_trail);
        stockPrice.setText(R.string.price);
        stockLow.setText(R.string.low52);
        stockHigh.setText(R.string.high52);

        stockSymbol.setOnClickListener(this);
        stockName.setOnClickListener(this);
        stockPriceTrail.setOnClickListener(this);
        stockPrice.setOnClickListener(this);
        stockLow.setOnClickListener(this);
        stockHigh.setOnClickListener(this);

        //disposables.add(presenter.refreshData());

        setupFlowable();
    }

    private void setupFlowable() {
        if (searchView != null && swipeRefreshLayout != null) {
            presenter.onCreate();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_list, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchManager searchManager = (SearchManager) PriceTrailListListActivity.this.getSystemService(Context.SEARCH_SERVICE);

        if (searchItem != null) {
            setSearchView((SearchView) searchItem.getActionView());
        }
        if (searchView != null) {
            searchView.setSearchableInfo(searchManager.getSearchableInfo(PriceTrailListListActivity.this.getComponentName()));
        }
        return super.onCreateOptionsMenu(menu);
    }

    private void setSearchView(final SearchView searchView) {

        if (this.searchView != searchView) {
            this.searchView = searchView;

            //TODO
            setupFlowable();

//            if (searchView != null) {
//
//                if (presenter != null)
//                    disposables.add(presenter.setSearchTermObservable(RxSearchView.queryTextChanges(searchView)
//                            .toFlowable(BackpressureStrategy.LATEST)
//                            .map(CharSequence::toString)));
//            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();

        if (disposables != null) {
            disposables.dispose();
        }
    }

    @Override
    public Flowable<String> filterChanged() {
        return RxSearchView.queryTextChanges(searchView)
                .toFlowable(BackpressureStrategy.LATEST)
                .map(CharSequence::toString);
    }

    @Override
    public Flowable<Object> refreshList() {
        return Flowable.just(new Object()).mergeWith(RxSwipeRefreshLayout.refreshes(swipeRefreshLayout)
                .toFlowable(BackpressureStrategy.LATEST));
    }

    @Override
    public Flowable<Integer> sortList() {
        return sortFlowable.toFlowable(BackpressureStrategy.LATEST);
    }

    @Override
    public void displayStocks(List<Stock> stocks) {
        // update adapter
        swipeRefreshLayout.setRefreshing(false);
        mAdapter = new PriceTrailListAdapter(stocks);
        recyclerView.setAdapter(mAdapter);
        mAdapter.getItemClickObservable()
                .map(i -> stocks.get(i))
                .subscribe(this::displayStockDetails);
    }

    public void displayStockDetails(Stock stock) {
        StockDetailsActivity.startActivityWithStock(this, stock);
    }

    @Override
    public void onError(String description) {
        // show snackbar
        swipeRefreshLayout.setRefreshing(false);
        Snackbar snackbar = Snackbar
                .make(swipeRefreshLayout, description, Snackbar.LENGTH_LONG);
        snackbar.show();
    }

    @Override
    public void onClick(View v) {
        if (v == stockPrice)
            sortFlowable.onNext(PriceTrailListActivityPresenter.SORT_CURRENT_PRICE);
        else if (v == stockPriceTrail)
            sortFlowable.onNext(PriceTrailListActivityPresenter.SORT_PRICE_TRAIL);
        else if (v == stockLow)
            sortFlowable.onNext(PriceTrailListActivityPresenter.SORT_LOW_52);
        else if (v == stockHigh)
            sortFlowable.onNext(PriceTrailListActivityPresenter.SORT_HIGH_52);
        else if (v == stockName || v == stockSymbol)
            sortFlowable.onNext(PriceTrailListActivityPresenter.SORT_SYMBOL);

    }
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import Navbar from './navbar';
import PostsIndex from './postsIndex';
import SideBar from './sideBar';

export default class App extends Component {
  render() {
    return (
      <div>
        <Navbar />
        <SideBar />
        {/* only one job show children component */}
        {/* {this.props.children} */}
        {React.cloneElement(this.props.children, this.props)}
      </div>
    );
  }
}


text:
package org.camunda.bpm.engine.rest;

import org.camunda.bpm.engine.AuthorizationException;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.rest.dto.telemetry.TelemetryDataDto;
import org.camunda.bpm.engine.rest.helper.MockProvider;
import org.camunda.bpm.engine.rest.util.container.TestContainerRule;
import org.camunda.bpm.engine.telemetry.ApplicationServer;
import org.camunda.bpm.engine.telemetry.Database;
import org.camunda.bpm.engine.telemetry.Internals;
import org.camunda.bpm.engine.telemetry.Jdk;
import org.camunda.bpm.engine.telemetry.Product;
import org.camunda.bpm.engine.telemetry.TelemetryData;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.restassured.http.ContentType;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import javax.ws.rs.core.Response.Status;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class TelemetryRestServiceTest extends AbstractRestServiceTest {

  @ClassRule
  public static TestContainerRule rule = new TestContainerRule();

  protected static final String TELEMETRY_URL = TEST_RESOURCE_ROOT_PATH +  TelemetryRestService.PATH;
  protected static final String TELEMETRY_CONFIG_URL = TELEMETRY_URL + "/configuration";
  protected static final String TELEMETRY_DATA_URL = TELEMETRY_URL + "/data";

  protected ManagementService managementServiceMock;

  @Before
  public void setupMocks() {
    managementServiceMock = mock(ManagementService.class);
    when(processEngine.getManagementService()).thenReturn(managementServiceMock);
  }

  @Test
  public void shouldDisableTelemetry() {
    Map<String, Object> requestBody = new HashMap<>();
    requestBody.put("enableTelemetry", false);

    given()
      .contentType(POST_JSON_CONTENT_TYPE)
      .body(requestBody)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
    .post(TELEMETRY_CONFIG_URL);

    verify(managementServiceMock).toggleTelemetry(false);
  }

  @Test
  public void shouldEnableTelemetry() {
    Map<String, Object> requestBody = new HashMap<>();
    requestBody.put("enableTelemetry", true);

    given()
      .contentType(POST_JSON_CONTENT_TYPE)
      .body(requestBody)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
      .post(TELEMETRY_CONFIG_URL);

    verify(managementServiceMock).toggleTelemetry(true);
  }

  @Test
  public void shouldThrowAuthorizationExceptionOnEnablingTelemetry() {
    String message = "Required admin authenticated group or user.";
    doThrow(new AuthorizationException(message)).when(managementServiceMock).toggleTelemetry(anyBoolean());

    Map<String, Object> requestBody = new HashMap<>();
    requestBody.put("enableTelemetry", true);

    given()
      .contentType(POST_JSON_CONTENT_TYPE)
      .body(requestBody)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .contentType(ContentType.JSON)
        .body("type", equalTo(AuthorizationException.class.getSimpleName()))
        .body("message", equalTo(message))
    .when()
      .post(TELEMETRY_CONFIG_URL);
  }

  @Test
  public void shouldFetchEnabledTelemetryConfiguration() {
    when(managementServiceMock.isTelemetryEnabled()).thenReturn(true);

    given()
      .contentType(POST_JSON_CONTENT_TYPE)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
        .body("enableTelemetry", equalTo(true))
    .when()
      .get(TELEMETRY_CONFIG_URL);

    verify(managementServiceMock).isTelemetryEnabled();
  }

  @Test
  public void shouldFetchDisabledTelemetryConfiguration() {
    when(managementServiceMock.isTelemetryEnabled()).thenReturn(false);

    given()
      .contentType(POST_JSON_CONTENT_TYPE)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
        .body("enableTelemetry", equalTo(false))
    .when()
      .get(TELEMETRY_CONFIG_URL);

    verify(managementServiceMock).isTelemetryEnabled();
  }

  @Test
  public void shouldFetchEmptyTelemetryConfiguration() {
    when(managementServiceMock.isTelemetryEnabled()).thenReturn(null);

    given()
      .contentType(POST_JSON_CONTENT_TYPE)
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
        .body("enableTelemetry", equalTo(null))
    .when()
      .get(TELEMETRY_CONFIG_URL);

    verify(managementServiceMock).isTelemetryEnabled();
  }

  @Test
  public void shouldThrowAuthorizationExceptionOnFetchingTelemetryConfig() {
    String message = "Required admin authenticated group or user.";
    doThrow(new AuthorizationException(message)).when(managementServiceMock).isTelemetryEnabled();

    given()
      .contentType(POST_JSON_CONTENT_TYPE)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .contentType(ContentType.JSON)
        .body("type", equalTo(AuthorizationException.class.getSimpleName()))
        .body("message", equalTo(message))
    .when()
      .get(TELEMETRY_CONFIG_URL);

    verify(managementServiceMock).isTelemetryEnabled();
  }

  @Test
  public void shouldGetTelemetryData() throws JsonProcessingException {
    when(managementServiceMock.getTelemetryData()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_DATA);

    given()
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
        .contentType(ContentType.JSON)
        .body("installation", equalTo(MockProvider.EXAMPLE_TELEMETRY_INSTALLATION_ID))
        .body("product.name", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_NAME))
        .body("product.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_VERSION))
        .body("product.edition", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_EDITION))
        .body("product.internals.database.vendor", equalTo(MockProvider.EXAMPLE_TELEMETRY_DB_VENDOR))
        .body("product.internals.database.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_DB_VERSION))
        .body("product.internals.commands.FetchExternalTasksCmd.count", equalTo(100))
        .body("product.internals.commands.StartProcessInstanceCmd.count", equalTo(40))
        .body("product.internals.metrics.process-instances.count", equalTo(936))
        .body("product.internals.metrics.flow-node-instances.count", equalTo(6125))
        .body("product.internals.metrics.executed-decision-elements.count", equalTo(732))
        .body("product.internals.metrics.decision-instances.count", equalTo(140))
        .body("product.internals.webapps[0]", equalTo("cockpit"))
        .body("product.internals.jdk.vendor", equalTo(MockProvider.EXAMPLE_TELEMETRY_JDK_VENDOR))
        .body("product.internals.jdk.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_JDK_VERSION))
        .body("product.internals.application-server.vendor", equalTo(MockProvider.EXAMPLE_TELEMETRY_APP_SERVER_VENDOR))
        .body("product.internals.application-server.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_APP_SERVER_VERSION))
        .body("product.internals.license-key.customer", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_CUSTOMER_NAME))
        .body("product.internals.license-key.type", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_TYPE))
        .body("product.internals.license-key.features.camundaBPM", equalTo("true"))
        .body("product.internals.license-key.raw", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_RAW))
        .body("product.internals.license-key.unlimited", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_UNLIMITED))
        .body("product.internals.license-key.valid-until", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_VALID_UNTIL))
        .body("product.internals.camunda-integration[0]", equalTo("spring-boot"))
    .when()
      .get(TELEMETRY_DATA_URL);

    verify(managementServiceMock).getTelemetryData();
  }

  @Test
  public void shouldGetMinimalTelemetryData() {

    TelemetryData telemetryData = mock(TelemetryData.class);
    when(telemetryData.getInstallation()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_INSTALLATION_ID);

    Product product = mock(Product.class);
    when(product.getName()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_NAME);
    when(product.getVersion()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_VERSION);
    when(product.getEdition()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_EDITION);
    when(telemetryData.getProduct()).thenReturn(product);

    Internals internals = mock(Internals.class);
    when(product.getInternals()).thenReturn(internals);

    when(internals.getApplicationServer()).thenReturn(mock(ApplicationServer.class));
    when(internals.getCamundaIntegration()).thenReturn(new HashSet<>());
    when(internals.getCommands()).thenReturn(new HashMap<>());
    when(internals.getDatabase()).thenReturn(mock(Database.class));
    when(internals.getJdk()).thenReturn(mock(Jdk.class));
    when(internals.getMetrics()).thenReturn(new HashMap<>());
    when(internals.getWebapps()).thenReturn(new HashSet<>());
    // license key may be null and is therefore not mocked

    when(managementServiceMock.getTelemetryData()).thenReturn(telemetryData);

    given()
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
        .contentType(ContentType.JSON)
        .body("installation", equalTo(MockProvider.EXAMPLE_TELEMETRY_INSTALLATION_ID))
        .body("product.name", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_NAME))
        .body("product.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_VERSION))
        .body("product.edition", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_EDITION))
    .when()
      .get(TELEMETRY_DATA_URL);

    verify(managementServiceMock).getTelemetryData();
  }

}


text:
<?php $this->setLayoutVar('title',$status['user_name']) ?>

<?php echo $this->render('status/status',array('status' => $status)); ?>


text:
using content::BrowserThread;

namespace extensions {

extern const char kSerialConnectionNotFoundError[];

// Encapsulates an open serial port. Platform-specific implementations are in
// _win and _posix versions of the the .cc file.
class SerialConnection : public ApiResource {
 public:
  SerialConnection(const std::string& port,
                   int bitrate,
                   const std::string& owner_extension_id);
  virtual ~SerialConnection();

  virtual bool Open();
  virtual void Close();
  virtual void Flush();

  virtual int Read(scoped_refptr<net::IOBufferWithSize> io_buffer);
  virtual int Write(scoped_refptr<net::IOBuffer> io_buffer, int byte_count);

  struct ControlSignals {
    // Sent from workstation to device. The should_set_ values indicate whether
    // SetControlSignals should change the given signal (true) or else leave it
    // as-is (false).
    bool should_set_dtr;
    bool dtr;
    bool should_set_rts;
    bool rts;

    // Received by workstation from device. DCD (Data Carrier Detect) is
    // equivalent to RLSD (Receive Line Signal Detect) on some platforms.
    bool dcd;
    bool cts;
  };

  virtual bool GetControlSignals(ControlSignals &control_signals);
  virtual bool SetControlSignals(const ControlSignals &control_signals);

 protected:
  // Do platform-specific work after a successful Open().
  bool PostOpen();

 private:
  std::string port_;
  int bitrate_;
  base::PlatformFile file_;
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_SERIAL_SERIAL_CONNECTION_H_


text:
/*eslint-env mocha*/
/*global BOOMR_test,assert*/

describe("e2e/21-continuity/05-longtasks", function() {
	var tf = BOOMR.plugins.TestFramework;
	var t = BOOMR_test;

	// finds LongTasks that we know we triggered (since we caused a 1500ms loop)
	function findMyLongTasks(b, type) {
		return BOOMR.utils.Compression.jsUrlDecompress(b["c.lt"]).filter(function(o) {
			return parseInt(o.d, 36) >= 1000 && o.n === type;
		})[0];
	}

	it("Should have sent a single beacon validation", function(done) {
		t.validateBeaconWasSent(done);
	});

	it("Should have set the LongTask count (c.lt.n) of at least 2 (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		assert.isDefined(b["c.lt.n"]);

		// we caused at least 2
		assert.operator(parseInt(b["c.lt.n"], 10), ">=", 2);
	});

	it("Should have set the LongTask time (c.lt.tt) (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		assert.isDefined(b["c.lt.tt"]);

		// we caused 3000ms
		assert.operator(parseInt(b["c.lt.tt"], 10), ">=", 2900);

		// should be less less than 10 seconds
		assert.operator(parseInt(b["c.lt.tt"], 10), "<=", 10000);
	});

	it("Should have set the LongTask data (c.lt) start time for the 'self' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 1);
		assert.operator(parseInt(ltData.s, 36), ">", 0);
		assert.operator(parseInt(ltData.s, 36), "<=", 5000);
	});

	it("Should have set the LongTask data (c.lt) duration for the 'self' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 1);
		assert.operator(parseInt(ltData.d, 36), ">=", 1400);
		assert.operator(parseInt(ltData.d, 36), "<=", 3000);
	});

	it("Should have set the LongTask data (c.lt) type for the 'self' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 1);
		assert.equal(ltData.n, "1");
	});

	it("Should have set the LongTask data (c.lt) start time for the 'same-origin-descendant' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 3);
		assert.operator(parseInt(ltData.s, 36), ">", 0);
		assert.operator(parseInt(ltData.s, 36), "<=", 10000);
	});

	it("Should have set the LongTask data (c.lt) duration for the 'same-origin-descendant' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 3);
		assert.operator(parseInt(ltData.d, 36), ">=", 1400);
		assert.operator(parseInt(ltData.d, 36), "<=", 3000);
	});

	it("Should have set the LongTask data (c.lt) type for the 'same-origin-descendant' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 3);
		assert.equal(ltData.n, "3");
	});

	it("Should have set the LongTask data (c.lt) attribution culprit attribution for the 'same-origin-descendant' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 3);
		assert.equal(ltData.a[0].a, "1");
	});

	it("Should have set the LongTask data (c.lt) attribution culprit name for the 'same-origin-descendant' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 3);
		assert.equal(ltData.a[0].t, "1");
	});

	it("Should have set the LongTask data (c.lt) attribution container id for the 'same-origin-descendant' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 3);
		assert.equal(ltData.a[0].i, "longtaskframeid");
	});

	it("Should have set the LongTask data (c.lt) attribution container name for the 'same-origin-descendant' task (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		var ltData = findMyLongTasks(b, 3);
		assert.equal(ltData.a[0].n, "longtaskframename");
	});

	it("Should have the LongTask timeline (c.t.longtask) (if LongTasks are supported)", function() {
		if (!t.isLongTasksSupported()) {
			return this.skip();
		}

		var b = tf.lastBeacon();

		assert.isDefined(b["c.t.fps"]);
		assert.operator(b["c.t.fps"].length, ">=", 1);
	});
});


text:
Bups
====

Simple GUI for [Bup](https://github.com/bup/bup), a very efficient backup system.

![Main window](https://cloud.githubusercontent.com/assets/506932/8412281/2b916e6e-1e89-11e5-9b78-dbb6c55367de.png)

# Purposes

I personaly use it to backup my files to a hard disk drive plugged into my ISP box (it's a Livebox).

Features:
* Multiple directories support
* Backup, with a nice progressbar
* Show current backups in your favorite file manager
* Backups on local filesystem or over Samba, SSH and [Google Drive](https://github.com/astrada/google-drive-ocamlfuse)
* Backup scheduling (using `systemd` or `anacron`)
* Exclude paths/patterns
* Restore backups

Changelog: https://github.com/emersion/bups/releases

# How to use

Requires Python 2, GTK 3 and Bup. Tested on Archlinux and elementary OS (so it should run on Ubuntu and Debian).

Installation:
* If you are running on a Debian-based system, you can install the `.deb` package from here: https://github.com/emersion/bups/releases
* If you are using Archlinux, install it from the AUR: https://aur.archlinux.org/packages/bups/
* For development, you can download the source:

  ```shell
  git clone https://github.com/emersion/bups.git
  cd bups
  bin/bups
  ```

When installed, you can start Bups by running `bups`. A launcher will also be added to your desktop's app menu.

# Configuration

You can edit config with the GUI. You can also manually edit `~/.config/bups/config.json`.

# Translating

The project is on Transifex: https://www.transifex.com/emersion/bups/

You can also email me `.po` files if you don't want to register on Transifex. Download the source and run `tools/makepot.sh` to generate `lang/messages.pot`.


text:
require "merb-fixtures/extensions/object_space"

module Merb
  module Fixtures
    module ORM
      # Get array of model classes.
      #
      # ==== Parameters
      # orm<Symbol>::
      #   Name of ORM. The ORM choosen in use_orm is used by default.
      #   Possibilities: :datamapper, :activerecord or :sequel
      #
      # ==== Returns
      # Array[Class]:: Array of model classes.
      #
      # @semipublic
      def self.models(orm = ::ORM)
        models = Array.new
        case orm
        when :datamapper
          ObjectSpace.each_class do |klass|
            if klass.included_modules.include?(DataMapper::Resource)
              models.push(klass)
            end
          end
        when :sequel
          ObjectSpace.each_class do |klass|
            if klass < Sequel::Model
              models.push(klass)
            end
          end
        when :activerecord
          ObjectSpace.each_class do |klass|
            if klass < ActiveRecord::Base
              models.push(klass)
            end
          end
        end
        return models
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ComponentModel;
using System.IO;
using Ionic.Zip;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
using System.Text;
using Octokit;
using SemVer;
using Version = SemVer.Version;

namespace Aurora_Updater
{
    public class LogEntry
    {
        private String message;
        private Color color;

        public LogEntry()
        {
            this.message = "";
            this.color = Color.Black;
        }

        public LogEntry(String message)
        {
            this.message = message;
            this.color = Color.Black;
        }

        public LogEntry(String message, Color color)
        {
            this.message = message;
            this.color = color;
        }

        public Color GetColor()
        {
            return color;
        }

        public String GetMessage()
        {
            return message;
        }

        public override string ToString()
        {
            return message.ToString();
        }
    }

    public enum UpdateStatus
    {
        None,
        InProgress,
        Complete,
        Error
    }

    public class UpdateManager
    {
        private string infoUrl = @"http://project-aurora.com/vcheck.php";
        private string[] ignoreFiles = { };
        //public UpdateResponse response = new UpdateResponse();
        private Queue<LogEntry> log = new Queue<LogEntry>();
        private float downloadProgess = 0.0f;
        private float extractProgess = 0.0f;
        public UpdateStatus updateState = UpdateStatus.None;
        private int downloadProgressCheck = 0;
        private int secondsLeft = 15;
        private Aurora.Settings.Configuration Config;
        private GitHubClient gClient = new GitHubClient(new ProductHeaderValue("aurora-updater"));
        public Release LatestRelease;

        public UpdateManager(Version version)
        {
            LoadSettings();
            PerformCleanup();
            FetchData(version);
        }

        public void LoadSettings()
        {
            try
            {
                Config = Aurora.Settings.ConfigManager.Load();
            }
            catch (Exception e)
            {
                Config = new Aurora.Settings.Configuration();
            }
        }

        public void ClearLog()
        {
            log.Clear();
        }

        public LogEntry[] GetLog()
        {
            return log.ToArray();
        }

        public int GetTotalProgress()
        {
            return (int)((downloadProgess + extractProgess) / 2.0f * 100.0f);
        }

        private bool FetchData(Version version)
        {

            try
            {
                if (Config.GetDevReleases || !String.IsNullOrWhiteSpace(version.PreRelease))
                    LatestRelease = gClient.Repository.Release.GetAll("antonpup", "Aurora", new ApiOptions { PageCount = 1, PageSize = 1 }).Result[0];
                else
                    LatestRelease = gClient.Repository.Release.GetLatest("antonpup", "Aurora").Result;

                //Console.WriteLine(reply);
            }
            catch (Exception exc)
            {
                updateState = UpdateStatus.Error;
                return false;
            }

            return true;
        }

        public bool RetrieveUpdate(UpdateType type)
        {
            //string url = @"http://project-aurora.com/download.php?id=" + (type == UpdateType.Major ? response.Major.ID : response.Minor.ID);
            //updateState = UpdateStatus.InProgress;
            try
            {
                string url = LatestRelease.Assets.First(s => s.Name.StartsWith("release") || s.Name.StartsWith("Aurora-v")).BrowserDownloadUrl;

                if (!String.IsNullOrWhiteSpace(url))
                {
                    this.log.Enqueue(new LogEntry("Starting download... "));

                    WebClient client = new WebClient();
                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                    client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

                    // Starts the download
                    client.DownloadFileAsync(new Uri(url), Path.Combine(Program.exePath, "update.zip"));

                }

            }
            catch (Exception exc)
            {
                log.Enqueue(new LogEntry(exc.Message, Color.Red));
                updateState = UpdateStatus.Error;
                return false;
            }
            return false;
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes;

            downloadProgressCheck++;

            if (downloadProgressCheck % 10 == 0)
            {
                log.Enqueue(new LogEntry("Download " + Math.Truncate(percentage * 100) + "%"));
                this.downloadProgess = (float)(Math.Truncate(percentage * 100) / 100.0f);
            }
        }

        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            this.log.Enqueue(new LogEntry("Download complete."));
            this.log.Enqueue(new LogEntry());
            this.downloadProgess = 1.0f;

            if (ExtractUpdate())
            {
                System.Timers.Timer shutdownTimer = new System.Timers.Timer(1000);
                shutdownTimer.Elapsed += ShutdownTimerElapsed;
                shutdownTimer.Start();

                updateState = UpdateStatus.Complete;
            }
            else
                updateState = UpdateStatus.Error;
        }

        private void ShutdownTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (secondsLeft > 0)
            {
                this.log.Enqueue(new LogEntry($"Restarting Aurora in {secondsLeft} second{(secondsLeft == 1 ? "" : "s")}..."));
                secondsLeft--;
            }
            else
            {
                //Kill all Aurora instances
                foreach (Process proc in Process.GetProcessesByName("Aurora"))
                    proc.Kill();

                try
                {
                    ProcessStartInfo auroraProc = new ProcessStartInfo();
                    auroraProc.FileName = Path.Combine(Program.exePath, "Aurora.exe");
                    Process.Start(auroraProc);

                    Environment.Exit(0); //Exit, no further action required
                }
                catch (Exception exc)
                {
                    this.log.Enqueue(new LogEntry($"Could not restart Aurora. Error:\r\n{exc}", Color.Red));
                    this.log.Enqueue(new LogEntry("Please restart Aurora manually.", Color.Red));

                    MessageBox.Show(
                        $"Could not restart Aurora.\r\nPlease restart Aurora manually.\r\nError:\r\n{exc}",
                        "Aurora Updater - Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
        }

        private bool ExtractUpdate()
        {
            if (File.Exists(Path.Combine(Program.exePath, "update.zip")))
            {
                log.Enqueue(new LogEntry("Unpacking update..."));

                try
                {
                    ZipFile updateFile = new ZipFile(Path.Combine(Program.exePath, "update.zip"));
                    log.Enqueue(new LogEntry(updateFile.Count + " files detected."));

                    for (int i = 0; i < updateFile.Count; i++)
                    {
                        float percentage = ((float)i / (float)updateFile.Count);

                        ZipEntry fileEntry = updateFile[i];
                        log.Enqueue(new LogEntry("[" + Math.Truncate(percentage * 100) + "%] Updating: " + fileEntry.FileName));
                        this.extractProgess = (float)(Math.Truncate(percentage * 100) / 100.0f);

                        if (ignoreFiles.Contains(fileEntry.FileName))
                            continue;

                        try
                        {
                            if (File.Exists(Path.Combine(Program.exePath, fileEntry.FileName)))
                                File.Move(Path.Combine(Program.exePath, fileEntry.FileName), Path.Combine(Program.exePath, fileEntry.FileName + ".updateremove"));
                            fileEntry.Extract(Program.exePath);
                        }
                        catch (IOException e)
                        {
                            log.Enqueue(new LogEntry(fileEntry.FileName + " is inaccessible.", Color.Red));

                            MessageBox.Show(fileEntry.FileName + " is inaccessible.\r\nPlease close Aurora.\r\n\r\n" + e.Message);
                            i--;
                            continue;
                        }
                    }

                    updateFile.Dispose();
                    File.Delete(Path.Combine(Program.exePath, "update.zip"));
                }
                catch (Exception exc)
                {
                    log.Enqueue(new LogEntry(exc.Message, Color.Red));

                    return false;
                }

                log.Enqueue(new LogEntry("All files updated."));
                log.Enqueue(new LogEntry());
                log.Enqueue(new LogEntry("Updater will automatically restart Aurora."));
                this.extractProgess = 1.0f;

                return true;
            }
            else
            {
                this.log.Enqueue(new LogEntry("Update file not found.", Color.Red));
                return false;
            }
        }

        private void PerformCleanup()
        {
            string[] _messyFiles = Directory.GetFiles(Program.exePath, "*.updateremove", SearchOption.AllDirectories);

            foreach (string file in _messyFiles)
            {
                try
                {
                    File.Delete(file);
                }
                catch (Exception exc)
                {
                    log.Enqueue(new LogEntry("Unable to delete file - " + file, Color.Red));
                }
            }

            if (File.Exists(Path.Combine(Program.exePath, "update.zip")))
                File.Delete(Path.Combine(Program.exePath, "update.zip"));
        }
    }

    public class UpdateResponse
    {
        protected Newtonsoft.Json.Linq.JObject _ParsedData;
        protected string json;

        private UpdateInfoNode _Major;
        public UpdateInfoNode Major
        {
            get
            {
                if (_Major == null)
                {
                    _Major = new UpdateInfoNode(_ParsedData["major"]?.ToString() ?? "");
                }

                return _Major;
            }
        }

        private UpdateInfoNode _Minor;
        public UpdateInfoNode Minor
        {
            get
            {
                if (_Minor == null)
                {
                    _Minor = new UpdateInfoNode(_ParsedData["minor"]?.ToString() ?? "");
                }

                return _Minor;
            }
        }

        public UpdateResponse()
        {
            json = "{}";
            _ParsedData = Newtonsoft.Json.Linq.JObject.Parse(json);
        }

        public UpdateResponse(string json_data)
        {
            if (String.IsNullOrWhiteSpace(json_data))
            {
                json_data = "{}";
            }

            json = json_data;
            _ParsedData = Newtonsoft.Json.Linq.JObject.Parse(json_data);
        }

        public UpdateResponse(UpdateResponse other_state)
        {
            _ParsedData = other_state._ParsedData;
            json = other_state.json;
        }

        internal String GetNode(string name)
        {
            Newtonsoft.Json.Linq.JToken value;

            if (_ParsedData.TryGetValue(name, out value))
                return value.ToString();
            else
                return "";
        }

        public override string ToString()
        {
            return json;
        }
    }

    public class Node
    {
        protected Newtonsoft.Json.Linq.JObject _ParsedData;

        internal Node(string json_data)
        {
            if (String.IsNullOrWhiteSpace(json_data))
            {
                json_data = "{}";
            }
            _ParsedData = Newtonsoft.Json.Linq.JObject.Parse(json_data);
        }

        internal string GetString(string Name)
        {
            Newtonsoft.Json.Linq.JToken value;

            if (_ParsedData.TryGetValue(Name, out value))
                return value.ToString();
            else
                return "";
        }

        internal int GetInt(string Name)
        {
            Newtonsoft.Json.Linq.JToken value;

            if (_ParsedData.TryGetValue(Name, out value))
                return Convert.ToInt32(value.ToString());
            else
                return -1;
        }

        internal float GetFloat(string Name)
        {
            Newtonsoft.Json.Linq.JToken value;

            if (_ParsedData.TryGetValue(Name, out value))
                return Convert.ToSingle(value.ToString());
            else
                return -1.0f;
        }

        internal long GetLong(string Name)
        {
            Newtonsoft.Json.Linq.JToken value;

            if (_ParsedData.TryGetValue(Name, out value))
                return Convert.ToInt64(value.ToString());
            else
                return -1;
        }

        internal T GetEnum<T>(string Name)
        {
            Newtonsoft.Json.Linq.JToken value;

            if (_ParsedData.TryGetValue(Name, out value) && !String.IsNullOrWhiteSpace(value.ToString()))
            {
                var type = typeof(T);
                if (!type.IsEnum) throw new InvalidOperationException();
                foreach (var field in type.GetFields())
                {
                    var attribute = Attribute.GetCustomAttribute(field,
                        typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attribute != null)
                    {
                        if (attribute.Description.ToLowerInvariant().Equals(Name))
                            return (T)field.GetValue(null);
                    }

                    if (field.Name.ToLowerInvariant().Equals(Name))
                        return (T)field.GetValue(null);
                }

                return (T)Enum.Parse(typeof(T), "Undefined", true);
            }
            else
                return (T)Enum.Parse(typeof(T), "Undefined", true);
        }

        internal bool GetBool(string Name)
        {
            Newtonsoft.Json.Linq.JToken value;

            if (_ParsedData.TryGetValue(Name, out value) && value.ToObject<bool>())
                return value.ToObject<bool>();
            else
                return false;
        }

        internal T[] GetArray<T>(string Name)
        {
            Newtonsoft.Json.Linq.JToken value;

            if (_ParsedData.TryGetValue(Name, out value))
                return value.ToObject<T[]>();
            else
                return new T[] { };
        }
    }

    public enum UpdateType
    {
        Undefined,
        Major,
        Minor
    }

    public class UpdateInfoNode : Node
    {
        public readonly int ID;
        public readonly Version Version;
        public readonly string Title;
        public readonly string Description;
        public readonly string Changelog;
        public readonly string File;
        public readonly UpdateType Type;
        public readonly long FileSize;
        public readonly bool PreRelease;

        internal UpdateInfoNode(string JSON)
            : base(JSON)
        {
            ID = GetInt("id");
            Version = new Version(GetString("vnr"), true);
            Title = GetString("title");
            Description = GetString("desc").Replace("\\r\\n", "\r\n");
            Changelog = GetString("clog").Replace("\\r\\n", "\r\n");
            File = GetString("file");
            Type = GetEnum<UpdateType>("type");
            FileSize = GetLong("size");
            PreRelease = GetInt("prerelease") == 1 ? true : false;
        }
    }
}


text:
<?php

namespace Sistema\Bundle\FrontendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ClienteType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('razon_social')
            ->add('ruc')
            ->add('direccion')
            ->add('estado')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Sistema\Bundle\FrontendBundle\Entity\Cliente'
        ));
    }

    public function getName()
    {
        return 'sistema_bundle_frontendbundle_clientetype';
    }
}


text:
#include "tensorflow/core/kernels/data/experimental/directed_interleave_dataset_op.h"

#include "tensorflow/core/data/dataset_test_base.h"

namespace tensorflow {
namespace data {
namespace experimental {
namespace {

constexpr char kNodeName[] = "directed_interleave_dataset";

class DirectedInterleaveDatasetParams : public DatasetParams {
 public:
  template <typename S, typename T>
  DirectedInterleaveDatasetParams(S selector_input_dataset_params,
                                  std::vector<T> input_dataset_params_vec,
                                  bool stop_on_empty_dataset,
                                  DataTypeVector output_dtypes,
                                  std::vector<PartialTensorShape> output_shapes,
                                  int num_input_datasets, string node_name)
      : DatasetParams(std::move(output_dtypes), std::move(output_shapes),
                      std::move(node_name)),
        stop_on_empty_dataset_(stop_on_empty_dataset),
        num_input_datasets_(input_dataset_params_vec.size()) {
    input_dataset_params_.push_back(
        absl::make_unique<S>(selector_input_dataset_params));
    for (auto input_dataset_params : input_dataset_params_vec) {
      input_dataset_params_.push_back(
          absl::make_unique<T>(input_dataset_params));
    }

    if (!input_dataset_params_vec.empty()) {
      iterator_prefix_ = name_utils::IteratorPrefix(
          input_dataset_params_vec[0].dataset_type(),
          input_dataset_params_vec[0].iterator_prefix());
    }
  }

  std::vector<Tensor> GetInputTensors() const override { return {}; }

  Status GetInputNames(std::vector<string>* input_names) const override {
    input_names->clear();
    input_names->emplace_back(
        DirectedInterleaveDatasetOp::kSelectorInputDataset);
    for (int i = 0; i < num_input_datasets_; ++i) {
      input_names->emplace_back(absl::StrCat(
          DirectedInterleaveDatasetOp::kDataInputDatasets, "_", i));
    }
    return Status::OK();
  }

  Status GetAttributes(AttributeVector* attr_vector) const override {
    attr_vector->clear();
    attr_vector->emplace_back(DirectedInterleaveDatasetOp::kOutputTypes,
                              output_dtypes_);
    attr_vector->emplace_back(DirectedInterleaveDatasetOp::kOutputShapes,
                              output_shapes_);
    attr_vector->emplace_back(DirectedInterleaveDatasetOp::kNumInputDatasets,
                              num_input_datasets_);
    attr_vector->emplace_back(DirectedInterleaveDatasetOp::kStopOnEmptyDataset,
                              stop_on_empty_dataset_);
    return Status::OK();
  }

  string dataset_type() const override {
    return DirectedInterleaveDatasetOp::kDatasetType;
  }

 private:
  bool stop_on_empty_dataset_;
  int32 num_input_datasets_;
};

class DirectedInterleaveDatasetOpTest : public DatasetOpsTestBase {};

DirectedInterleaveDatasetParams AlternateInputsParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 1, 0, 1, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
                                      RangeDatasetParams(10, 13, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/2,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams SelectExhaustedInputParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 1, 0, 1, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 2, 1),
                                      RangeDatasetParams(10, 13, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/2,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams OneInputDatasetParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 0, 0, 0, 0, 0})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 6, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64},
      /*output_shapes=*/{PartialTensorShape({})},
      /*num_input_datasets=*/1,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams ZeroInputDatasetParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 0, 0, 0, 0, 0})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/std::vector<RangeDatasetParams>{},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64},
      /*output_shapes=*/{PartialTensorShape({})},
      /*num_input_datasets=*/0,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams StopOnEmptyDatasetParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 0, 0, 0, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
                                      RangeDatasetParams(10, 50, 1)},
      /*stop_on_empty_dataset=*/true,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/2,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams SkipEmptyDatasetParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 0, 0, 0, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
                                      RangeDatasetParams(10, 50, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/2,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams EmptyInputDatasetParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 0, 0, 0, 0, 0})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 0, 1),
                                      RangeDatasetParams(10, 50, 1)},
      /*stop_on_empty_dataset=*/true,
      /*output_dtypes=*/{DT_INT64},
      /*output_shapes=*/{PartialTensorShape({})},
      /*num_input_datasets=*/0,
      /*node_name=*/kNodeName);
}

// Test case: `num_input_datasets` is larger than the size of
// `input_dataset_params_vec`.
DirectedInterleaveDatasetParams LargeNumInputDatasetsParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 1, 0, 1, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
                                      RangeDatasetParams(10, 13, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/5,
      /*node_name=*/kNodeName);
}

// Test case: `num_input_datasets` is smaller than the size of
// `input_dataset_params_vec`.
DirectedInterleaveDatasetParams SmallNumInputDatasetsParams() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 1, 0, 1, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
                                      RangeDatasetParams(10, 13, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/1,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams InvalidSelectorOuputDataType() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int32>(TensorShape{6}, {0, 1, 0, 1, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
                                      RangeDatasetParams(10, 13, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/2,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams InvalidSelectorOuputShape() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6, 1},
                                          {0, 1, 0, 1, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
                                      RangeDatasetParams(10, 13, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/2,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams InvalidSelectorValues() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {2, 1, 0, 1, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{RangeDatasetParams(0, 3, 1),
                                      RangeDatasetParams(10, 13, 1)},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/2,
      /*node_name=*/kNodeName);
}

DirectedInterleaveDatasetParams InvalidInputDatasetsDataType() {
  auto selector_input_dataset_params = TensorSliceDatasetParams(
      /*components=*/{CreateTensor<int64>(TensorShape{6}, {0, 1, 0, 1, 0, 1})},
      /*node_name=*/"tensor_slice");
  return DirectedInterleaveDatasetParams(
      selector_input_dataset_params,
      /*input_dataset_params_vec=*/
      std::vector<RangeDatasetParams>{
          RangeDatasetParams(0, 3, 1, {DT_INT32}),
          RangeDatasetParams(10, 13, 1, {DT_INT64})},
      /*stop_on_empty_dataset=*/false,
      /*output_dtypes=*/{DT_INT64, DT_INT64},
      /*output_shapes=*/{PartialTensorShape({}), PartialTensorShape({})},
      /*num_input_datasets=*/2,
      /*node_name=*/kNodeName);
}

std::vector<GetNextTestCase<DirectedInterleaveDatasetParams>>
GetNextTestCases() {
  return {{/*dataset_params=*/AlternateInputsParams(),
           /*expected_outputs=*/{CreateTensors<int64>(
               TensorShape({}), {{0}, {10}, {1}, {11}, {2}, {12}})}},
          {/*dataset_params=*/SelectExhaustedInputParams(),
           /*expected_outputs=*/{CreateTensors<int64>(
               TensorShape({}), {{0}, {10}, {1}, {11}, {12}})}},
          {/*dataset_params=*/OneInputDatasetParams(),
           /*expected_outputs=*/{CreateTensors<int64>(
               TensorShape({}), {{0}, {1}, {2}, {3}, {4}, {5}})}},
          {/*dataset_params=*/StopOnEmptyDatasetParams(),
           /*expected_outputs=*/{CreateTensors<int64>(TensorShape({}),
                                                      {{0}, {1}, {2}})}},
          {/*dataset_params=*/SkipEmptyDatasetParams(),
           /*expected_outputs=*/{CreateTensors<int64>(TensorShape({}),
                                                      {{0}, {1}, {2}, {10}})}},
          {/*dataset_params=*/EmptyInputDatasetParams(),
           /*expected_outputs=*/{CreateTensors<int64>(TensorShape({}), {})}},
          {/*dataset_params=*/LargeNumInputDatasetsParams(),
           /*expected_outputs=*/{CreateTensors<int64>(
               TensorShape({}), {{0}, {10}, {1}, {11}, {2}, {12}})}},
          {/*dataset_params=*/SmallNumInputDatasetsParams(),
           /*expected_outputs=*/{CreateTensors<int64>(
               TensorShape({}), {{0}, {10}, {1}, {11}, {2}, {12}})}}};
}

ITERATOR_GET_NEXT_TEST_P(DirectedInterleaveDatasetOpTest,
                         DirectedInterleaveDatasetParams, GetNextTestCases())

TEST_F(DirectedInterleaveDatasetOpTest, DatasetNodeName) {
  auto dataset_params = AlternateInputsParams();
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK(CheckDatasetNodeName(dataset_params.node_name()));
}

TEST_F(DirectedInterleaveDatasetOpTest, DatasetTypeString) {
  auto dataset_params = AlternateInputsParams();
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK(CheckDatasetTypeString(
      name_utils::OpName(DirectedInterleaveDatasetOp::kDatasetType)));
}

TEST_F(DirectedInterleaveDatasetOpTest, DatasetOutputDtypes) {
  auto dataset_params = AlternateInputsParams();
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK(CheckDatasetOutputDtypes({DT_INT64}));
}

TEST_F(DirectedInterleaveDatasetOpTest, DatasetOutputShapes) {
  auto dataset_params = AlternateInputsParams();
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK(CheckDatasetOutputShapes({PartialTensorShape({})}));
}

TEST_F(DirectedInterleaveDatasetOpTest, Cardinality) {
  auto dataset_params = AlternateInputsParams();
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK(CheckDatasetCardinality(kUnknownCardinality));
}

TEST_F(DirectedInterleaveDatasetOpTest, IteratorOutputDtypes) {
  auto dataset_params = AlternateInputsParams();
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK(CheckIteratorOutputDtypes({DT_INT64}));
}

TEST_F(DirectedInterleaveDatasetOpTest, IteratorOutputShapes) {
  auto dataset_params = AlternateInputsParams();
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK(CheckIteratorOutputShapes({PartialTensorShape({})}));
}

TEST_F(DirectedInterleaveDatasetOpTest, IteratorPrefix) {
  auto dataset_params = AlternateInputsParams();
  TF_ASSERT_OK(Initialize(dataset_params));
  TF_ASSERT_OK(CheckIteratorPrefix(
      name_utils::IteratorPrefix(DirectedInterleaveDatasetOp::kDatasetType,
                                 dataset_params.iterator_prefix())));
}

std::vector<IteratorSaveAndRestoreTestCase<DirectedInterleaveDatasetParams>>
IteratorSaveAndRestoreTestCases() {
  return {
      {/*dataset_params=*/AlternateInputsParams(),
       /*breakpoints=*/{0, 5, 8},
       /*expected_outputs=*/
       CreateTensors<int64>(TensorShape{}, {{0}, {10}, {1}, {11}, {2}, {12}}),
       /*compare_order=*/true},
      {/*dataset_params=*/SelectExhaustedInputParams(),
       /*breakpoints=*/{0, 4, 8},
       /*expected_outputs=*/
       CreateTensors<int64>(TensorShape{}, {{0}, {10}, {1}, {11}, {12}}),
       /*compare_order=*/true},
      {/*dataset_params=*/OneInputDatasetParams(),
       /*breakpoints=*/{0, 5, 8},
       /*expected_outputs=*/
       {CreateTensors<int64>(TensorShape({}), {{0}, {1}, {2}, {3}, {4}, {5}})}},
      {/*dataset_params=*/StopOnEmptyDatasetParams(),
       /*breakpoints=*/{0, 2, 4},
       /*expected_outputs=*/
       {CreateTensors<int64>(TensorShape({}), {{0}, {1}, {2}})}},
      {/*dataset_params=*/SkipEmptyDatasetParams(),
       /*breakpoints=*/{0, 2, 4},
       /*expected_outputs=*/
       {CreateTensors<int64>(TensorShape({}), {{0}, {1}, {2}, {10}})}},
      {/*dataset_params=*/EmptyInputDatasetParams(),
       /*breakpoints=*/{0, 2, 4},
       /*expected_outputs=*/
       {CreateTensors<int64>(TensorShape({}), {})}},
      {/*dataset_params=*/LargeNumInputDatasetsParams(),
       /*breakpoints=*/{0, 5, 8},
       /*expected_outputs=*/
       {CreateTensors<int64>(TensorShape({}),
                             {{0}, {10}, {1}, {11}, {2}, {12}})}},
      {/*dataset_params=*/SmallNumInputDatasetsParams(),
       /*breakpoints=*/{0, 5, 8},
       /*expected_outputs=*/
       {CreateTensors<int64>(TensorShape({}),
                             {{0}, {10}, {1}, {11}, {2}, {12}})}}};
}

ITERATOR_SAVE_AND_RESTORE_TEST_P(DirectedInterleaveDatasetOpTest,
                                 DirectedInterleaveDatasetParams,
                                 IteratorSaveAndRestoreTestCases())

TEST_F(DirectedInterleaveDatasetOpTest, InvalidArguments) {
  std::vector<DirectedInterleaveDatasetParams> invalid_params_vec = {
      InvalidSelectorOuputDataType(), InvalidSelectorOuputShape(),
      InvalidInputDatasetsDataType(), ZeroInputDatasetParams()};
  for (auto& dataset_params : invalid_params_vec) {
    EXPECT_EQ(Initialize(dataset_params).code(),
              tensorflow::error::INVALID_ARGUMENT);
  }
}

TEST_F(DirectedInterleaveDatasetOpTest, InvalidSelectorValues) {
  auto dataset_params = InvalidSelectorValues();
  TF_ASSERT_OK(Initialize(dataset_params));
  bool end_of_sequence = false;
  std::vector<Tensor> next;
  EXPECT_EQ(
      iterator_->GetNext(iterator_ctx_.get(), &next, &end_of_sequence).code(),
      tensorflow::error::INVALID_ARGUMENT);
}

}  // namespace
}  // namespace experimental
}  // namespace data
}  // namespace tensorflow


text:
<?php

/**
 * @package    calcinai/php-imagick
 * @author     Michael Calcinai <michael@calcin.ai>
 */
class ImagickPixelException extends Exception  {
}


text:
module RSpec
  module Core
    # @private
    # Wrapper around Ruby's `DidYouMean::SpellChecker` when available to provide file name suggestions.
    class DidYouMean
      attr_reader :relative_file_name

      def initialize(relative_file_name)
        @relative_file_name = relative_file_name
      end

      if defined?(::DidYouMean::SpellChecker)
        # provide probable suggestions
        def call
          checker = ::DidYouMean::SpellChecker.new(:dictionary => Dir["spec/**/*.rb"])
          probables = checker.correct(relative_file_name.sub('./', ''))[0..2]
          return '' unless probables.any?

          formats probables
        end
      else
        # return a hint if API for ::DidYouMean::SpellChecker not supported
        def call
          "\nHint: Install the `did_you_mean` gem in order to provide suggestions for similarly named files."
        end
      end

      private

      def formats(probables)
        rspec_format = probables.map { |s, _| "rspec ./#{s}" }
        red_font(top_and_tail rspec_format)
      end

      def top_and_tail(rspec_format)
        spaces = ' ' * 20
        rspec_format.insert(0, ' - Did you mean?').join("\n#{spaces}") + "\n"
      end

      def red_font(mytext)
        colorizer = ::RSpec::Core::Formatters::ConsoleCodes
        colorizer.wrap mytext, :failure
      end
    end
  end
end


text:
/*
 * Do not modify this file. This file is generated from the cloudsearch-2013-01-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.CloudSearch.Model
{
    ///
    /// Container for the parameters to the DescribeExpressions operation.
    /// Gets the expressions configured for the search domain. Can be limited to specific
    /// expressions by name. By default, shows all expressions and includes any pending changes
    /// to the configuration. Set the Deployed option to true to
    /// show the active configuration and exclude pending changes. For more information, see
    /// Configuring Expressions in the Amazon CloudSearch Developer
    /// Guide.
    ///
    public partial class DescribeExpressionsRequest : AmazonCloudSearchRequest
    {
        private bool? _deployed;
        private string _domainName;
        private List<string> _expressionNames = new List<string>();

        ///
        /// Gets and sets the property Deployed.
        /// <para>
        /// Whether to display the deployed configuration (true) or include any pending
        /// changes (false). Defaults to false.
        /// </para>
        ///
        public bool Deployed
        {
            get { return this._deployed.GetValueOrDefault(); }
            set { this._deployed = value; }
        }

        // Check to see if Deployed property is set
        internal bool IsSetDeployed()
        {
            return this._deployed.HasValue;
        }

        ///
        /// Gets and sets the property DomainName.
        /// <para>
        /// The name of the domain you want to describe.
        /// </para>
        ///
        public string DomainName
        {
            get { return this._domainName; }
            set { this._domainName = value; }
        }

        // Check to see if DomainName property is set
        internal bool IsSetDomainName()
        {
            return this._domainName != null;
        }

        ///
        /// Gets and sets the property ExpressionNames.
        /// <para>
        /// Limits the DescribeExpressions response to the specified expressions.
        /// If not specified, all expressions are shown.
        /// </para>
        ///
        public List<string> ExpressionNames
        {
            get { return this._expressionNames; }
            set { this._expressionNames = value; }
        }

        // Check to see if ExpressionNames property is set
        internal bool IsSetExpressionNames()
        {
            return this._expressionNames != null && this._expressionNames.Count > 0;
        }

    }
}


text:
package server

import (
	"bytes"
	"context"
	"database/sql"
	"encoding/base64"
	"encoding/gob"
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gofrs/uuid"
	"github.com/heroiclabs/nakama-common/api"
	"github.com/heroiclabs/nakama/v3/iap"
	"github.com/jackc/pgtype"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/timestamppb"
)

var ErrPurchasesListInvalidCursor = errors.New("purchases list cursor invalid")

var httpc = &http.Client{Timeout: 5 * time.Second}

func ValidatePurchasesApple(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, password, receipt string, persist bool) (*api.ValidatePurchaseResponse, error) {
	validation, raw, err := iap.ValidateReceiptApple(ctx, httpc, receipt, password)
	if err != nil {
		var vErr *iap.ValidationError
		if err != context.Canceled {
			if errors.As(err, &vErr) {
				logger.Error("Error validating Apple receipt", zap.Error(vErr.Err), zap.Int("status_code", vErr.StatusCode), zap.String("payload", vErr.Payload))
				return nil, vErr.Err
			} else {
				logger.Error("Error validating Apple receipt", zap.Error(err))
			}
		}
		return nil, err
	}

	if validation.Status != iap.AppleReceiptIsValid {
		if validation.IsRetryable == true {
			return nil, status.Error(codes.Unavailable, "Apple IAP verification is currently unavailable. Try again later.")
		}
		return nil, status.Error(codes.FailedPrecondition, fmt.Sprintf("Invalid Receipt. Status: %d", validation.Status))
	}

	env := api.StoreEnvironment_PRODUCTION
	if validation.Environment == iap.AppleSandboxEnvironment {
		env = api.StoreEnvironment_SANDBOX
	}

	storagePurchases := make([]*storagePurchase, 0, len(validation.Receipt.InApp))
	for _, purchase := range validation.Receipt.InApp {
		if purchase.ExpiresDateMs != "" {
			continue
		}

		purchaseTime, err := strconv.ParseInt(purchase.PurchaseDateMs, 10, 64)
		if err != nil {
			return nil, err
		}

		storagePurchases = append(storagePurchases, &storagePurchase{
			userID:        userID,
			store:         api.StoreProvider_APPLE_APP_STORE,
			productId:     purchase.ProductID,
			transactionId: purchase.TransactionId,
			rawResponse:   string(raw),
			purchaseTime:  parseMillisecondUnixTimestamp(purchaseTime),
			environment:   env,
		})
	}

	if len(storagePurchases) == 0 && len(validation.Receipt.InApp) > 0 {
		// All purchases in this receipt are subscriptions.
		return nil, status.Error(codes.FailedPrecondition, "Subscription Receipt. Use the appropriate function instead.")
	}

	if !persist {
		// Skip storing the receipts
		validatedPurchases := make([]*api.ValidatedPurchase, 0, len(storagePurchases))
		for _, p := range storagePurchases {
			validatedPurchases = append(validatedPurchases, &api.ValidatedPurchase{
				ProductId:        p.productId,
				TransactionId:    p.transactionId,
				Store:            p.store,
				PurchaseTime:     timestamppb.New(p.purchaseTime),
				ProviderResponse: string(raw),
				Environment:      p.environment,
			})
		}

		return &api.ValidatePurchaseResponse{ValidatedPurchases: validatedPurchases}, nil
	}

	purchases, err := storePurchases(ctx, db, storagePurchases)
	if err != nil {
		return nil, err
	}

	validatedPurchases := make([]*api.ValidatedPurchase, 0, len(purchases))
	for _, p := range purchases {
		validatedPurchases = append(validatedPurchases, &api.ValidatedPurchase{
			ProductId:        p.productId,
			TransactionId:    p.transactionId,
			Store:            p.store,
			PurchaseTime:     timestamppb.New(p.purchaseTime),
			CreateTime:       timestamppb.New(p.createTime),
			UpdateTime:       timestamppb.New(p.updateTime),
			ProviderResponse: string(raw),
			SeenBefore:       p.seenBefore,
			Environment:      p.environment,
		})
	}

	return &api.ValidatePurchaseResponse{
		ValidatedPurchases: validatedPurchases,
	}, nil
}

func ValidatePurchaseGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, config *IAPGoogleConfig, receipt string, persist bool) (*api.ValidatePurchaseResponse, error) {
	gResponse, gReceipt, raw, err := iap.ValidateReceiptGoogle(ctx, httpc, config.ClientEmail, config.PrivateKey, receipt)
	if err != nil {
		var vErr *iap.ValidationError
		if err != context.Canceled {
			if errors.As(err, &vErr) {
				logger.Error("Error validating Google receipt", zap.Error(vErr.Err), zap.Int("status_code", vErr.StatusCode), zap.String("payload", vErr.Payload))
				return nil, vErr.Err
			} else {
				logger.Error("Error validating Google receipt", zap.Error(err))
			}
		}
		return nil, err
	}

	purchaseEnv := api.StoreEnvironment_PRODUCTION
	if gResponse.PurchaseType == 0 {
		purchaseEnv = api.StoreEnvironment_SANDBOX
	}

	sPurchase := &storagePurchase{
		userID:        userID,
		store:         api.StoreProvider_GOOGLE_PLAY_STORE,
		productId:     gReceipt.ProductID,
		transactionId: gReceipt.PurchaseToken,
		rawResponse:   string(raw),
		purchaseTime:  parseMillisecondUnixTimestamp(gReceipt.PurchaseTime),
		environment:   purchaseEnv,
	}

	if !persist {
		validatedPurchases := []*api.ValidatedPurchase{
			{
				ProductId:        sPurchase.productId,
				TransactionId:    sPurchase.transactionId,
				Store:            sPurchase.store,
				PurchaseTime:     timestamppb.New(sPurchase.purchaseTime),
				ProviderResponse: string(raw),
				Environment:      sPurchase.environment,
			},
		}

		return &api.ValidatePurchaseResponse{ValidatedPurchases: validatedPurchases}, nil
	}

	purchases, err := storePurchases(ctx, db, []*storagePurchase{sPurchase})
	if err != nil {
		if err != context.Canceled {
			logger.Error("Error storing Google receipt", zap.Error(err))
		}
		return nil, err
	}

	validatedPurchases := make([]*api.ValidatedPurchase, 0, len(purchases))
	for _, p := range purchases {
		validatedPurchases = append(validatedPurchases, &api.ValidatedPurchase{
			ProductId:        p.productId,
			TransactionId:    p.transactionId,
			Store:            p.store,
			PurchaseTime:     timestamppb.New(p.purchaseTime),
			CreateTime:       timestamppb.New(p.createTime),
			UpdateTime:       timestamppb.New(p.updateTime),
			ProviderResponse: string(raw),
			SeenBefore:       p.seenBefore,
			Environment:      p.environment,
		})
	}

	return &api.ValidatePurchaseResponse{
		ValidatedPurchases: validatedPurchases,
	}, nil
}

func ValidatePurchaseHuawei(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, config *IAPHuaweiConfig, inAppPurchaseData, signature string, persist bool) (*api.ValidatePurchaseResponse, error) {
	validation, data, raw, err := iap.ValidateReceiptHuawei(ctx, httpc, config.PublicKey, config.ClientID, config.ClientSecret, inAppPurchaseData, signature)
	if err != nil {
		var vErr *iap.ValidationError
		if err != context.Canceled {
			if errors.As(err, &vErr) {
				logger.Error("Error validating Huawei receipt", zap.Error(vErr.Err), zap.Int("status_code", vErr.StatusCode), zap.String("payload", vErr.Payload))
				return nil, vErr.Err
			} else {
				logger.Error("Error validating Huawei receipt", zap.Error(err))
			}
		}
		return nil, err
	}

	if validation.ResponseCode != strconv.Itoa(iap.HuaweiReceiptIsValid) {
		return nil, status.Error(codes.FailedPrecondition, fmt.Sprintf("Invalid Receipt. Code: %s", validation.ResponseCode))
	}

	env := api.StoreEnvironment_PRODUCTION
	if data.PurchaseType == iap.HuaweiSandboxPurchaseType {
		env = api.StoreEnvironment_SANDBOX
	}

	sPurchase := &storagePurchase{
		userID:        userID,
		store:         api.StoreProvider_HUAWEI_APP_GALLERY,
		productId:     validation.PurchaseTokenData.ProductId,
		transactionId: validation.PurchaseTokenData.PurchaseToken,
		rawResponse:   string(raw),
		purchaseTime:  parseMillisecondUnixTimestamp(data.PurchaseTime),
		environment:   env,
	}

	if !persist {
		validatedPurchases := []*api.ValidatedPurchase{
			{
				ProductId:        sPurchase.productId,
				TransactionId:    sPurchase.transactionId,
				Store:            sPurchase.store,
				PurchaseTime:     timestamppb.New(sPurchase.purchaseTime),
				ProviderResponse: string(raw),
				Environment:      sPurchase.environment,
			},
		}

		return &api.ValidatePurchaseResponse{ValidatedPurchases: validatedPurchases}, nil
	}

	purchases, err := storePurchases(ctx, db, []*storagePurchase{sPurchase})
	if err != nil {
		if err != context.Canceled {
			logger.Error("Error storing Huawei receipt", zap.Error(err))
		}
		return nil, err
	}

	validatedPurchases := make([]*api.ValidatedPurchase, 0, len(purchases))
	for _, p := range purchases {
		validatedPurchases = append(validatedPurchases, &api.ValidatedPurchase{
			ProductId:        p.productId,
			TransactionId:    p.transactionId,
			Store:            p.store,
			PurchaseTime:     timestamppb.New(p.purchaseTime),
			CreateTime:       timestamppb.New(p.createTime),
			UpdateTime:       timestamppb.New(p.updateTime),
			ProviderResponse: string(raw),
			SeenBefore:       p.seenBefore,
			Environment:      p.environment,
		})
	}

	return &api.ValidatePurchaseResponse{
		ValidatedPurchases: validatedPurchases,
	}, nil
}

func GetPurchaseByTransactionID(ctx context.Context, logger *zap.Logger, db *sql.DB, transactionID string) (string, *api.ValidatedPurchase, error) {
	query := `
SELECT
    user_id,
    transaction_id,
    product_id,
    store,
    raw_response,
    purchase_time,
    create_time,
    update_time,
    environment
FROM
    purchase
WHERE
    transaction_id = $1
`
	var userID uuid.UUID
	var transactionId string
	var productId string
	var store api.StoreProvider
	var rawResponse string
	var purchaseTime pgtype.Timestamptz
	var createTime pgtype.Timestamptz
	var updateTime pgtype.Timestamptz
	var environment api.StoreEnvironment

	if err := db.QueryRowContext(ctx, query, transactionID).Scan(&userID, &transactionId, &productId, &store, &rawResponse, &purchaseTime, &createTime, &updateTime, &environment); err != nil {
		logger.Error("Error retrieving purchase.", zap.Error(err))
		return "", nil, err
	}

	return userID.String(), &api.ValidatedPurchase{
		ProductId:        productId,
		TransactionId:    transactionID,
		Store:            store,
		ProviderResponse: rawResponse,
		PurchaseTime:     timestamppb.New(purchaseTime.Time),
		CreateTime:       timestamppb.New(createTime.Time),
		UpdateTime:       timestamppb.New(updateTime.Time),
		Environment:      environment,
	}, nil
}

type purchasesListCursor struct {
	TransactionId string
	PurchaseTime  *timestamppb.Timestamp
	UserId        string
	IsNext        bool
}

func ListPurchases(ctx context.Context, logger *zap.Logger, db *sql.DB, userID string, limit int, cursor string) (*api.PurchaseList, error) {
	var incomingCursor *purchasesListCursor
	if cursor != "" {
		cb, err := base64.URLEncoding.DecodeString(cursor)
		if err != nil {
			return nil, ErrPurchasesListInvalidCursor
		}
		incomingCursor = &purchasesListCursor{}
		if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil {
			return nil, ErrPurchasesListInvalidCursor
		}
		if userID != "" && userID != incomingCursor.UserId {
			// userID filter was set and has changed, cursor is now invalid
			return nil, ErrPurchasesListInvalidCursor
		}
	}

	comparationOp := "<="
	sortConf := "DESC"
	if incomingCursor != nil && !incomingCursor.IsNext {
		comparationOp = ">"
		sortConf = "ASC"
	}

	params := make([]interface{}, 0, 4)
	predicateConf := ""
	if incomingCursor != nil {
		if userID == "" {
			predicateConf = fmt.Sprintf(" WHERE (user_id, purchase_time, transaction_id) %s ($1, $2, $3)", comparationOp)
		} else {
			predicateConf = fmt.Sprintf(" WHERE user_id = $1 AND (purchase_time, transaction_id) %s ($2, $3)", comparationOp)
		}
		params = append(params, incomingCursor.UserId, incomingCursor.PurchaseTime.AsTime(), incomingCursor.TransactionId)
	} else {
		if userID != "" {
			predicateConf = " WHERE user_id = $1"
			params = append(params, userID)
		}
	}

	if limit > 0 {
		params = append(params, limit+1)
	} else {
		params = append(params, 101) // Default limit to 100 purchases if not set
	}

	query := fmt.Sprintf(`
	SELECT
			user_id,
			transaction_id,
			product_id,
			store,
			raw_response,
			purchase_time,
			create_time,
			update_time,
			environment
	FROM
			purchase
	%s
	ORDER BY purchase_time %s LIMIT $%v`, predicateConf, sortConf, len(params))

	rows, err := db.QueryContext(ctx, query, params...)
	if err != nil {
		logger.Error("Error retrieving purchases.", zap.Error(err))
		return nil, err
	}
	defer rows.Close()

	var nextCursor *purchasesListCursor
	var prevCursor *purchasesListCursor
	purchases := make([]*api.ValidatedPurchase, 0, limit)

	for rows.Next() {
		var userID uuid.UUID
		var transactionId string
		var productId string
		var store api.StoreProvider
		var rawResponse string
		var purchaseTime pgtype.Timestamptz
		var createTime pgtype.Timestamptz
		var updateTime pgtype.Timestamptz
		var environment api.StoreEnvironment

		if err = rows.Scan(&userID, &transactionId, &productId, &store, &rawResponse, &purchaseTime, &createTime, &updateTime, &environment); err != nil {
			logger.Error("Error retrieving purchases.", zap.Error(err))
			return nil, err
		}

		if len(purchases) >= limit {
			nextCursor = &purchasesListCursor{
				TransactionId: transactionId,
				PurchaseTime:  timestamppb.New(purchaseTime.Time),
				UserId:        userID.String(),
				IsNext:        true,
			}
			break
		}

		purchase := &api.ValidatedPurchase{
			ProductId:        productId,
			TransactionId:    transactionId,
			Store:            store,
			PurchaseTime:     timestamppb.New(purchaseTime.Time),
			CreateTime:       timestamppb.New(createTime.Time),
			UpdateTime:       timestamppb.New(updateTime.Time),
			ProviderResponse: rawResponse,
			Environment:      environment,
		}

		purchases = append(purchases, purchase)

		if incomingCursor != nil && prevCursor == nil {
			prevCursor = &purchasesListCursor{
				TransactionId: transactionId,
				PurchaseTime:  timestamppb.New(purchaseTime.Time),
				UserId:        userID.String(),
				IsNext:        false,
			}
		}
	}
	if err = rows.Err(); err != nil {
		logger.Error("Error retrieving purchases.", zap.Error(err))
		return nil, err
	}

	if incomingCursor != nil && !incomingCursor.IsNext {
		if nextCursor != nil && prevCursor != nil {
			nextCursor, nextCursor.IsNext, prevCursor, prevCursor.IsNext = prevCursor, prevCursor.IsNext, nextCursor, nextCursor.IsNext
		} else if nextCursor != nil {
			nextCursor, prevCursor = nil, nextCursor
			prevCursor.IsNext = !prevCursor.IsNext
		} else if prevCursor != nil {
			nextCursor, prevCursor = prevCursor, nil
			nextCursor.IsNext = !nextCursor.IsNext
		}

		for i, j := 0, len(purchases)-1; i < j; i, j = i+1, j-1 {
			purchases[i], purchases[j] = purchases[j], purchases[i]
		}
	}

	var nextCursorStr string
	if nextCursor != nil {
		cursorBuf := new(bytes.Buffer)
		if err := gob.NewEncoder(cursorBuf).Encode(nextCursor); err != nil {
			logger.Error("Error creating purchases list cursor", zap.Error(err))
			return nil, err
		}
		nextCursorStr = base64.URLEncoding.EncodeToString(cursorBuf.Bytes())
	}

	var prevCursorStr string
	if prevCursor != nil {
		cursorBuf := new(bytes.Buffer)
		if err := gob.NewEncoder(cursorBuf).Encode(prevCursor); err != nil {
			logger.Error("Error creating purchases list cursor", zap.Error(err))
			return nil, err
		}
		prevCursorStr = base64.URLEncoding.EncodeToString(cursorBuf.Bytes())
	}

	return &api.PurchaseList{ValidatedPurchases: purchases, Cursor: nextCursorStr, PrevCursor: prevCursorStr}, nil
}

type storagePurchase struct {
	userID        uuid.UUID
	store         api.StoreProvider
	productId     string
	transactionId string
	rawResponse   string
	purchaseTime  time.Time
	createTime    time.Time // Set by storePurchases
	updateTime    time.Time // Set by storePurchases
	environment   api.StoreEnvironment
	seenBefore    bool // Set by storePurchases
}

func storePurchases(ctx context.Context, db *sql.DB, purchases []*storagePurchase) ([]*storagePurchase, error) {
	if len(purchases) < 1 {
		return nil, errors.New("expects at least one receipt")
	}

	statements := make([]string, 0, len(purchases))
	params := make([]interface{}, 0, len(purchases)*7)
	transactionIDsToPurchase := make(map[string]*storagePurchase)
	offset := 0
	for _, purchase := range purchases {
		statement := fmt.Sprintf("($%d, $%d, $%d, $%d, $%d, $%d, $%d)", offset+1, offset+2, offset+3, offset+4, offset+5, offset+6, offset+7)
		offset += 7
		statements = append(statements, statement)
		params = append(params, purchase.userID, purchase.store, purchase.transactionId, purchase.productId, purchase.purchaseTime, purchase.rawResponse, purchase.environment)
		transactionIDsToPurchase[purchase.transactionId] = purchase
	}

	query := `
INSERT
INTO
    purchase
        (
            user_id,
            store,
            transaction_id,
            product_id,
            purchase_time,
            raw_response,
            environment
        )
VALUES
    ` + strings.Join(statements, ", ") + `
ON CONFLICT
    (transaction_id)
DO
    NOTHING
RETURNING
    transaction_id, create_time, update_time
`
	insertedTransactionIDs := make(map[string]struct{})
	rows, err := db.QueryContext(ctx, query, params...)
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		// Newly inserted purchases
		var transactionId string
		var createTime pgtype.Timestamptz
		var updateTime pgtype.Timestamptz
		if err = rows.Scan(&transactionId, &createTime, &updateTime); err != nil {
			rows.Close()
			return nil, err
		}
		storedPurchase, _ := transactionIDsToPurchase[transactionId]
		storedPurchase.createTime = createTime.Time
		storedPurchase.updateTime = updateTime.Time
		storedPurchase.seenBefore = false
		insertedTransactionIDs[storedPurchase.transactionId] = struct{}{}
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return nil, err
	}

	// Go over purchases that have not been inserted (already exist in the DB) and fetch createTime and updateTime
	if len(transactionIDsToPurchase) > len(insertedTransactionIDs) {
		seenIDs := make([]string, 0, len(transactionIDsToPurchase))
		for tID, _ := range transactionIDsToPurchase {
			if _, ok := insertedTransactionIDs[tID]; !ok {
				seenIDs = append(seenIDs, tID)
			}
		}

		rows, err = db.QueryContext(ctx, "SELECT transaction_id, create_time, update_time FROM purchase WHERE transaction_id IN ($1)", strings.Join(seenIDs, ", "))
		if err != nil {
			return nil, err
		}
		for rows.Next() {
			// Already seen purchases
			var transactionId string
			var createTime pgtype.Timestamptz
			var updateTime pgtype.Timestamptz
			if err = rows.Scan(&transactionId, &createTime, &updateTime); err != nil {
				rows.Close()
				return nil, err
			}
			storedPurchase, _ := transactionIDsToPurchase[transactionId]
			storedPurchase.createTime = createTime.Time
			storedPurchase.updateTime = updateTime.Time
			storedPurchase.seenBefore = true
		}
		rows.Close()
		if err := rows.Err(); err != nil {
			return nil, err
		}
	}

	storedPurchases := make([]*storagePurchase, 0, len(transactionIDsToPurchase))
	for _, purchase := range transactionIDsToPurchase {
		storedPurchases = append(storedPurchases, purchase)
	}

	return storedPurchases, nil
}

func parseMillisecondUnixTimestamp(t int64) time.Time {
	return time.Unix(0, 0).Add(time.Duration(t) * time.Millisecond)
}


text:
This large leopard has six colorful snakes, hissing and ready to strike, sprouting from its shoulders.

Kamadan CR 4

XP 1,200

NE Large magical beast

**Init** +2; **Senses** darkvision 60 ft., low-light vision, [scent](monsters/universalMonsterRules#_scent); [Perception](skills/perception#_perception) +8

Defense

**AC** 17, touch 12, flat-footed 14 (+2 Dex, +1 dodge, +5 natural, –1 size)

**hp** 42 (5d10+15)

**Fort** +7, **Ref** +6, **Will** +2

Offense

**Speed** 40 ft.

**Melee** bite +7 (1d6+3), 2 claws +7 (1d3+3), snakes +2 (1d4+1)

**Space** 10 ft.; **Reach** 5 ft. (10 ft. with snakes)

**Special Attacks** [breath weapon](monsters/universalMonsterRules#_breath-weapon) (30-ft. cone, sleep, Fortitude DC 15 negates, usable every 1d4 rounds), [pounce](monsters/universalMonsterRules#_pounce)

Statistics

**Str** 17, **Dex** 15, **Con** 16, **Int** 5, **Wis** 12, **Cha** 9

**Base Atk** +5; **CMB** +9; **CMD** 22 (26 vs. trip)

**Feats** [Combat Reflexes](feats#_combat-reflexes), [Dodge](feats#_dodge), [Mobility](feats#_mobility)

**Skills** [Acrobatics](skills/acrobatics#_acrobatics) +6 (+10 when jumping), [Perception](skills/perception#_perception) +8, [Stealth](skills/stealth#_stealth) +6; **Racial Modifiers** +4 [Stealth](skills/stealth#_stealth)

**Languages** Aklo

Ecology

**Environment** temperate or warm plains

**Organization** solitary, pair, or pack (3–9)

**Treasure** standard

Special Abilities

**[Breath Weapon](monsters/universalMonsterRules#_breath-weapon) (Su)** A kamadan can exhale a cone of gas that makes living creatures fall asleep for 5 minutes (Fortitude DC 15 negates). Slapping or wounding awakens a creature put to sleep by this attack, but normal noise does not. This is a sleep effect. The save DC is Constitution-based.

**Snakes (Ex)** A kamadan's snakes attack simultaneously; this is always a secondary attack.

Kamadans are wicked hunters that enjoy stalking and toying with prey, especially when their quarry is relatively intelligent. When a kamadan attacks, it first uses its soporific breath, then pounces on any targets that remain awake. Kamadans stand about 3 feet at the shoulder, about 9 feet long and weighing up to 500 pounds.

Although kamadans are certainly magical creatures, they share many psychological and sociological traits with other big cats. Even when hunting alone to avoid competition, a kamadan is often a member of a larger pride. In areas where wildlife or natives are more powerful, kamadan packs are more likely to hunt as a unit.

Kamadans prefer underground lairs, but settle for rocky outcroppings or dens inside brambles or other thick bushes, and they use their snakes to manipulate the bones and baubles of their prey into decorative arrangements. Occasionally, a kamadan shares its lair with another creature, but only if the other creature is more powerful or plies the kamadan regularly with tributes of food and treasure.

Though the above statistics represent the most common breed of kamadan, two rarer but more dangerous variants are detailed in brief below.

**Dusk Kamadan (CR +1)** : A dusk kamadan has midnight black fur and snakes bearing black and red ring patterns on their bodies. A dusk kamadan has the advanced creature template, and its snakes have a poisonous bite: Snakes—injury; _save_ Fort DC 17; _frequency_ 1/round for 6 rounds; _effect_ 1d2 Con; _cure_ 2 consecutive saves.

**Polar Kamadan (CR +2)** : A polar kamadan has white fur with black spots like a snow leopard. Its snakes are furred as well. A polar kamadan has the advanced creature template and batlike wings that grant it a fly speed of 60 ft. (average). The breath weapon of a polar kamadan is particularly cold—those who succumb to it also suffer 1d4 points of Dexterity damage from numbness.


text:
layout: post
status: publish
published: true
title: !binary |-
  V2lsbCBGZXJyZWxsIGNvbnRyYXJpw6kgcGFyIEtyaXN0ZW4gU3Rld2FydA==
author: mick
author_login: mick
author_email: mickael@flochlay.com
wordpress_id: 2398
wordpress_url: http://morningcoffee.deadrooster.org/?p=2398
date: 2012-08-06 07:09:22.000000000 +02:00
categories:
- Fun
- !binary |-
  Q2luw6ltYQ==
tags:
- Will Ferrell
- kristen stewart
- conan o'brian
- robert pattinson
comments: []
---

via Will Ferrell Is All Busted Up Over Kristen Stewart & Robert Pattinson - CONAN on TBS - YouTube.


text: module.exports = require('./virtual-tour')