text:
package com.opengamma.strata.finance.rate.swap;

import java.io.Serializable;
import java.time.LocalDate;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.Set;

import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.ImmutableValidator;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.opengamma.strata.basics.index.IborIndex;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.finance.rate.FixedRateObservation;
import com.opengamma.strata.finance.rate.IborInterpolatedRateObservation;
import com.opengamma.strata.finance.rate.IborRateObservation;
import com.opengamma.strata.finance.rate.RateObservation;

/**
 * Defines the rates applicable in the initial or final stub of an IBOR-like swap leg.
 *

 * A standard swap leg consists of a regular periodic schedule and one or two stub periods at each end.
 * This class defines what floating rate to use during a stub.
 *

 * The rate may be specified in three ways.
 *

 *
A fixed rate, applicable for the whole stub
 *
A single IBOR-like floating rate
 *
Linear interpolation between two IBOR-like floating rates
 *

 */
@BeanDefinition
public final class StubCalculation
    implements ImmutableBean, Serializable {

  /**
   * An instance that has no special rate handling.
   */
  public static final StubCalculation NONE = new StubCalculation(null, null, null);

  /**
   * The fixed rate to use in the stub.
   * A 5% rate will be expressed as 0.05.
   *

   * In certain circumstances two counterparties agree a fixed rate for the stub.
   * It is used in place of an observed fixing.
   * Other calculation elements, such as gearing or spread, still apply.
   *

   * If the fixed rate is present, then {@code index} and {@code indexInterpolated} must not be present.
   */
  @PropertyDefinition(get = "optional")
  private final Double fixedRate;
  /**
   * The IBOR-like index to be used for the stub.
   *

   * This will be used throughout the stub unless {@code indexInterpolated} is present.
   *

   * If the index is present, then {@code rate} must not be present.
   */
  @PropertyDefinition(get = "optional")
  private final IborIndex index;
  /**
   * The second IBOR-like index to be used for the stub, linearly interpolated.
   *

   * This will be used with {@code index} to linearly interpolate the rate.
   * This index may be shorter or longer than {@code index}, but not the same.
   *

   * If the interpolated index is present, then {@code index} must also be present
   * and {@code rate} must not be present.
   */
  @PropertyDefinition(get = "optional")
  private final IborIndex indexInterpolated;

  //-------------------------------------------------------------------------
  /**
   * Obtains a {@code StubCalculation} with a single fixed rate.
   *
   * @param fixedRate  the fixed rate for the stub
   * @return the stub
   */
  public static StubCalculation ofFixedRate(double fixedRate) {
    return new StubCalculation(fixedRate, null, null);
  }

  /**
   * Obtains a {@code StubCalculation} with a single floating rate.
   *
   * @param index  the index that applies to the stub
   * @return the stub
   * @throws IllegalArgumentException if the index is null
   */
  public static StubCalculation ofIborRate(IborIndex index) {
    ArgChecker.notNull(index, "index");
    return new StubCalculation(null, index, null);
  }

  /**
   * Obtains a {@code StubCalculation} with linear interpolation of two floating rates.
   *

   * The two indices must be different, typically with one longer than another.
   * The order of input of the indices does not matter.
   *
   * @param index1  the first index
   * @param index2  the second index
   * @return the stub
   * @throws IllegalArgumentException if the two indices are the same or either is null
   */
  public static StubCalculation ofIborInterpolatedRate(IborIndex index1, IborIndex index2) {
    ArgChecker.notNull(index1, "index1");
    ArgChecker.notNull(index2, "index2");
    return new StubCalculation(null, index1, index2);
  }

  //-------------------------------------------------------------------------
  @ImmutableValidator
  private void validate() {
    if (fixedRate != null && index != null) {
      throw new IllegalArgumentException("Either rate or index may be specified, not both");
    }
    if (indexInterpolated != null) {
      if (index == null) {
        throw new IllegalArgumentException("When indexInterpolated is present, index must also be present");
      }
      if (indexInterpolated.equals(index)) {
        throw new IllegalArgumentException("Interpolation requires two different indices");
      }
    }
  }

  //-------------------------------------------------------------------------
  /**
   * Creates the {@code RateObservation} for the stub.
   *
   * @param fixingDate  the fixing date
   * @param defaultIndex  the default index to use if the stub has no rules
   * @return the rate observation
   */
  RateObservation createRateObservation(LocalDate fixingDate, IborIndex defaultIndex) {
    if (isInterpolated()) {
      return IborInterpolatedRateObservation.of(index, indexInterpolated, fixingDate);
    } else if (isFloatingRate()) {
      return IborRateObservation.of(index, fixingDate);
    } else if (isFixedRate()) {
      return FixedRateObservation.of(fixedRate);
    } else {
      return IborRateObservation.of(defaultIndex, fixingDate);
    }
  }

  //-------------------------------------------------------------------------
  /**
   * Checks if the stub has a fixed rate.
   *
   * @return true if a fixed stub rate applies
   */
  public boolean isFixedRate() {
    return fixedRate != null;
  }

  /**
   * Checks if the stub has a floating rate.
   *
   * @return true if a floating stub rate applies
   */
  public boolean isFloatingRate() {
    return index != null;
  }

  /**
   * Checks if the stub has an interpolated rate.
   *

   * An interpolated rate exists when there are two different rates that need linear interpolation.
   *
   * @return true if linear interpolation applies
   */
  public boolean isInterpolated() {
    return index != null && indexInterpolated != null;
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code StubCalculation}.
   * @return the meta-bean, not null
   */
  public static StubCalculation.Meta meta() {
    return StubCalculation.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(StubCalculation.Meta.INSTANCE);
  }

  /**
   * The serialization version id.
   */
  private static final long serialVersionUID = 1L;

  /**
   * Returns a builder used to create an instance of the bean.
   * @return the builder, not null
   */
  public static StubCalculation.Builder builder() {
    return new StubCalculation.Builder();
  }

  private StubCalculation(
      Double fixedRate,
      IborIndex index,
      IborIndex indexInterpolated) {
    this.fixedRate = fixedRate;
    this.index = index;
    this.indexInterpolated = indexInterpolated;
    validate();
  }

  @Override
  public StubCalculation.Meta metaBean() {
    return StubCalculation.Meta.INSTANCE;
  }

  @Override
  public <R> Property<R> property(String propertyName) {
    return metaBean().<R>metaProperty(propertyName).createProperty(this);
  }

  @Override
  public Set<String> propertyNames() {
    return metaBean().metaPropertyMap().keySet();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the fixed rate to use in the stub.
   * A 5% rate will be expressed as 0.05.
   *

   * In certain circumstances two counterparties agree a fixed rate for the stub.
   * It is used in place of an observed fixing.
   * Other calculation elements, such as gearing or spread, still apply.
   *

   * If the fixed rate is present, then {@code index} and {@code indexInterpolated} must not be present.
   * @return the optional value of the property, not null
   */
  public OptionalDouble getFixedRate() {
    return fixedRate != null ? OptionalDouble.of(fixedRate) : OptionalDouble.empty();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the IBOR-like index to be used for the stub.
   *

   * This will be used throughout the stub unless {@code indexInterpolated} is present.
   *

   * If the index is present, then {@code rate} must not be present.
   * @return the optional value of the property, not null
   */
  public Optional<IborIndex> getIndex() {
    return Optional.ofNullable(index);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the second IBOR-like index to be used for the stub, linearly interpolated.
   *

   * This will be used with {@code index} to linearly interpolate the rate.
   * This index may be shorter or longer than {@code index}, but not the same.
   *

   * If the interpolated index is present, then {@code index} must also be present
   * and {@code rate} must not be present.
   * @return the optional value of the property, not null
   */
  public Optional<IborIndex> getIndexInterpolated() {
    return Optional.ofNullable(indexInterpolated);
  }

  //-----------------------------------------------------------------------
  /**
   * Returns a builder that allows this bean to be mutated.
   * @return the mutable builder, not null
   */
  public Builder toBuilder() {
    return new Builder(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      StubCalculation other = (StubCalculation) obj;
      return JodaBeanUtils.equal(fixedRate, other.fixedRate) &&
          JodaBeanUtils.equal(index, other.index) &&
          JodaBeanUtils.equal(indexInterpolated, other.indexInterpolated);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(fixedRate);
    hash = hash * 31 + JodaBeanUtils.hashCode(index);
    hash = hash * 31 + JodaBeanUtils.hashCode(indexInterpolated);
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(128);
    buf.append("StubCalculation{");
    buf.append("fixedRate").append('=').append(fixedRate).append(',').append(' ');
    buf.append("index").append('=').append(index).append(',').append(' ');
    buf.append("indexInterpolated").append('=').append(JodaBeanUtils.toString(indexInterpolated));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code StubCalculation}.
   */
  public static final class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code fixedRate} property.
     */
    private final MetaProperty<Double> fixedRate = DirectMetaProperty.ofImmutable(
        this, "fixedRate", StubCalculation.class, Double.class);
    /**
     * The meta-property for the {@code index} property.
     */
    private final MetaProperty<IborIndex> index = DirectMetaProperty.ofImmutable(
        this, "index", StubCalculation.class, IborIndex.class);
    /**
     * The meta-property for the {@code indexInterpolated} property.
     */
    private final MetaProperty<IborIndex> indexInterpolated = DirectMetaProperty.ofImmutable(
        this, "indexInterpolated", StubCalculation.class, IborIndex.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "fixedRate",
        "index",
        "indexInterpolated");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 747425396:  // fixedRate
          return fixedRate;
        case 100346066:  // index
          return index;
        case -1934091915:  // indexInterpolated
          return indexInterpolated;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public StubCalculation.Builder builder() {
      return new StubCalculation.Builder();
    }

    @Override
    public Class<? extends StubCalculation> beanType() {
      return StubCalculation.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code fixedRate} property.
     * @return the meta-property, not null
     */
    public MetaProperty<Double> fixedRate() {
      return fixedRate;
    }

    /**
     * The meta-property for the {@code index} property.
     * @return the meta-property, not null
     */
    public MetaProperty<IborIndex> index() {
      return index;
    }

    /**
     * The meta-property for the {@code indexInterpolated} property.
     * @return the meta-property, not null
     */
    public MetaProperty<IborIndex> indexInterpolated() {
      return indexInterpolated;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 747425396:  // fixedRate
          return ((StubCalculation) bean).fixedRate;
        case 100346066:  // index
          return ((StubCalculation) bean).index;
        case -1934091915:  // indexInterpolated
          return ((StubCalculation) bean).indexInterpolated;
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code StubCalculation}.
   */
  public static final class Builder extends DirectFieldsBeanBuilder<StubCalculation> {

    private Double fixedRate;
    private IborIndex index;
    private IborIndex indexInterpolated;

    /**
     * Restricted constructor.
     */
    private Builder() {
    }

    /**
     * Restricted copy constructor.
     * @param beanToCopy  the bean to copy from, not null
     */
    private Builder(StubCalculation beanToCopy) {
      this.fixedRate = beanToCopy.fixedRate;
      this.index = beanToCopy.index;
      this.indexInterpolated = beanToCopy.indexInterpolated;
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case 747425396:  // fixedRate
          return fixedRate;
        case 100346066:  // index
          return index;
        case -1934091915:  // indexInterpolated
          return indexInterpolated;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case 747425396:  // fixedRate
          this.fixedRate = (Double) newValue;
          break;
        case 100346066:  // index
          this.index = (IborIndex) newValue;
          break;
        case -1934091915:  // indexInterpolated
          this.indexInterpolated = (IborIndex) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Builder set(MetaProperty<?> property, Object value) {
      super.set(property, value);
      return this;
    }

    @Override
    public Builder setString(String propertyName, String value) {
      setString(meta().metaProperty(propertyName), value);
      return this;
    }

    @Override
    public Builder setString(MetaProperty<?> property, String value) {
      super.setString(property, value);
      return this;
    }

    @Override
    public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
      super.setAll(propertyValueMap);
      return this;
    }

    @Override
    public StubCalculation build() {
      return new StubCalculation(
          fixedRate,
          index,
          indexInterpolated);
    }

    //-----------------------------------------------------------------------
    /**
     * Sets the fixed rate to use in the stub.
     * A 5% rate will be expressed as 0.05.
     *

     * In certain circumstances two counterparties agree a fixed rate for the stub.
     * It is used in place of an observed fixing.
     * Other calculation elements, such as gearing or spread, still apply.
     *

     * If the fixed rate is present, then {@code index} and {@code indexInterpolated} must not be present.
     * @param fixedRate  the new value
     * @return this, for chaining, not null
     */
    public Builder fixedRate(Double fixedRate) {
      this.fixedRate = fixedRate;
      return this;
    }

    /**
     * Sets the IBOR-like index to be used for the stub.
     *

     * This will be used throughout the stub unless {@code indexInterpolated} is present.
     *

     * If the index is present, then {@code rate} must not be present.
     * @param index  the new value
     * @return this, for chaining, not null
     */
    public Builder index(IborIndex index) {
      this.index = index;
      return this;
    }

    /**
     * Sets the second IBOR-like index to be used for the stub, linearly interpolated.
     *

     * This will be used with {@code index} to linearly interpolate the rate.
     * This index may be shorter or longer than {@code index}, but not the same.
     *

     * If the interpolated index is present, then {@code index} must also be present
     * and {@code rate} must not be present.
     * @param indexInterpolated  the new value
     * @return this, for chaining, not null
     */
    public Builder indexInterpolated(IborIndex indexInterpolated) {
      this.indexInterpolated = indexInterpolated;
      return this;
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(128);
      buf.append("StubCalculation.Builder{");
      buf.append("fixedRate").append('=').append(JodaBeanUtils.toString(fixedRate)).append(',').append(' ');
      buf.append("index").append('=').append(JodaBeanUtils.toString(index)).append(',').append(' ');
      buf.append("indexInterpolated").append('=').append(JodaBeanUtils.toString(indexInterpolated));
      buf.append('}');
      return buf.toString();
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
// import the base Herschend class
const Moment = require('moment-timezone');
const HerschendBase = require('./herschendparkbase');

/**
 * Dollywood
 * @class
 * @extends HerschendBase
 */
class Dollywood extends HerschendBase {
  /**
   * Create a new Dollywood object
   */
  constructor(options = {}) {
    options.name = options.name || 'Dollywood';
    options.timezone = options.timezone || 'America/New_York';

    // set resort's general center point
    options.latitude = options.latitude || 35.795329;
    options.longitude = options.longitude || -83.530886;

    options.parkID = 1;
    options.calendarUrl = 'www.dollywood.com';
    options.parkIDs = 'A8F3517D-4606-4387-B275-DC607DCD6DDE';

    // inherit from base class
    super(options);
  }

  // override calendar fetching for Dollywood
  async FetchOpeningTimes() {
    const calendarHTML = await this.Cache.Wrap('dollywoodCalendarAPI', () => {
      return this.HTTP({
        url: 'https://www.dollywood.com/calendar?mapp=1',
      });
    }, 60 * 60 * 12);

    if (!calendarHTML) return Promise.reject(new Error('Unable to fetch Dollywood calendar HTML'));

    // find our calendarDatasourceItemId token for API requests
    const match = /value="([^"]+)" id="calendarDatasourceItemId/.exec(calendarHTML);
    if (!match) return Promise.reject(new Error('Unable to find calendarDatasourceItemId token in Dollywood calendar HTML'));

    const APItoken = match[1];

    const rangeStart = Moment.tz(this.Timezone);
    const rangeEnd = rangeStart.clone().add(3, 'months');

    // fetch each month we want from the API
    for (let date = rangeStart.clone(); date.isSameOrBefore(rangeEnd); date.add(1, 'month')) {
      const monthToFetch = `${date.month() + 1}-1-${date.year()}`;
      // eslint-disable-next-line no-await-in-loop
      const monthData = await this.HTTP({
        url: 'https://www.dollywood.com/api/cxa/Calendar/GetCalendarHoursAndEvents',
        data: {
          did: APItoken,
          sd: monthToFetch,
        },
      });
      if (!monthData) return Promise.reject(new Error(`Unable to fetch Dollywood calendar for month ${monthToFetch}`));

      monthData.forEach((event) => {
        // skip non Theme Park times
        if (event.eventName !== 'Theme Park') return;

        const eventDate = Moment.tz(event.d, 'MM/DD/YYYY', this.Timezone);

        if (event.hours === 'Closed') {
          this.Schedule.SetDate({
            date: eventDate,
            type: 'Closed',
          });
        } else {
          const timeMatch = /(\d{1,2}):(\d{2})\s([AP]M)\s*-\s*(\d{1,2}):(\d{2})\s([AP]M)/.exec(event.hours);
          if (!timeMatch) {
            this.Log(`Unable to parse Dollywood calendar time string: ${event.hours}`);
            return;
          }

          const openingHour = (Number(timeMatch[1]) + ((timeMatch[3] === 'PM') ? 12 : 0)) % 24;
          const closingHour = (Number(timeMatch[4]) + ((timeMatch[6] === 'PM') ? 12 : 0)) % 24;

          const openingTime = eventDate.clone()
            .hours(openingHour)
            .minutes(Number(timeMatch[2]));
          const closingTime = eventDate.clone()
            .hours(closingHour)
            .minutes(Number(timeMatch[5]));

          this.Schedule.SetDate({
            date: eventDate,
            openingTime,
            closingTime,
          });
        }
      });
    }

    return Promise.resolve();
  }
}

module.exports = Dollywood;

redpajama_set_name: RedPajamaGithub


text:
package edu.hm.hafner.analysis;

import org.junit.Test;

import static edu.hm.hafner.analysis.IssueTest.*;
import static edu.hm.hafner.analysis.assertj.Assertions.assertThat;

/**
 * Unit test for {@link IssueBuilder}.
 *
 * @author Marcel Binder
 */
class IssueBuilderTest {
    private static final Issue DEFAULT_ISSUE = new Issue(null, 0, 0, 0, 0,
            null, null, null, null, null, null, null, null, null);
    private static final Issue FILLED_ISSUE = new Issue(FILE_NAME, LINE_START, LINE_END, COLUMN_START, COLUMN_END,
            CATEGORY, TYPE, PACKAGE_NAME, MODULE_NAME, PRIORITY, MESSAGE, DESCRIPTION, ORIGIN, FINGERPRINT);

    @Test
    void testDefaultValues() {
        Issue issue = new IssueBuilder().build();

        assertThat(issue).isEqualTo(DEFAULT_ISSUE);
    }

    @Test
    void testFilledIssue() {
        Issue issue = new IssueBuilder()
                .setFileName(FILE_NAME)
                .setLineStart(LINE_START)
                .setLineEnd(LINE_END)
                .setColumnStart(COLUMN_START)
                .setColumnEnd(COLUMN_END)
                .setCategory(CATEGORY)
                .setType(TYPE)
                .setPackageName(PACKAGE_NAME)
                .setModuleName(MODULE_NAME)
                .setPriority(PRIORITY)
                .setMessage(MESSAGE)
                .setDescription(DESCRIPTION)
                .setOrigin(ORIGIN)
                .build();

        assertThat(issue).isEqualTo(FILLED_ISSUE);
    }

    @Test
    void testCopy() {
        Issue copy = new IssueBuilder()
                .copy(FILLED_ISSUE)
                .build();

        assertThat(copy).isNotSameAs(FILLED_ISSUE);
        assertThat(copy).isEqualTo(FILLED_ISSUE);
    }

    @Test
    void testBuildNewInstance() {
        IssueBuilder builder = new IssueBuilder().copy(FILLED_ISSUE);
        Issue issue1 = builder.build();
        Issue issue2 = builder.build();

        assertThat(issue1).isNotSameAs(issue2);
        assertThat(issue1).isEqualTo(issue2);
    }
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.net.urlconnection;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import android.support.test.runner.AndroidJUnit4;

import androidx.test.filters.SmallTest;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.util.Feature;
import org.chromium.net.CronetTestRule;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

/**
 * Tests the MessageLoop implementation.
 */
@RunWith(AndroidJUnit4.class)
public class MessageLoopTest {
    @Rule
    public final CronetTestRule mTestRule = new CronetTestRule();

    private Thread mTestThread;
    private final ExecutorService mExecutorService =
            Executors.newSingleThreadExecutor(new ExecutorThreadFactory());
    private class ExecutorThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            mTestThread = new Thread(r);
            return mTestThread;
        }
    }
    private boolean mFailed;

    @Test
    @SmallTest
    @Feature({"Cronet"})
    public void testInterrupt() throws Exception {
        final MessageLoop loop = new MessageLoop();
        assertFalse(loop.isRunning());
        Future future = mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    loop.loop();
                    mFailed = true;
                } catch (IOException e) {
                    // Expected interrupt.
                }
            }
        });
        Thread.sleep(1000);
        assertTrue(loop.isRunning());
        assertFalse(loop.hasLoopFailed());
        mTestThread.interrupt();
        future.get();
        assertFalse(loop.isRunning());
        assertTrue(loop.hasLoopFailed());
        assertFalse(mFailed);
        // Re-spinning the message loop is not allowed after interrupt.
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    loop.loop();
                    fail();
                } catch (Exception e) {
                    if (!(e instanceof InterruptedIOException)) {
                        fail();
                    }
                }
            }
        }).get();
    }

    @Test
    @SmallTest
    @Feature({"Cronet"})
    public void testTaskFailed() throws Exception {
        final MessageLoop loop = new MessageLoop();
        assertFalse(loop.isRunning());
        Future future = mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    loop.loop();
                    mFailed = true;
                } catch (Exception e) {
                    if (!(e instanceof NullPointerException)) {
                        mFailed = true;
                    }
                }
            }
        });
        Runnable failedTask = new Runnable() {
            @Override
            public void run() {
                throw new NullPointerException();
            }
        };
        Thread.sleep(1000);
        assertTrue(loop.isRunning());
        assertFalse(loop.hasLoopFailed());
        loop.execute(failedTask);
        future.get();
        assertFalse(loop.isRunning());
        assertTrue(loop.hasLoopFailed());
        assertFalse(mFailed);
        // Re-spinning the message loop is not allowed after exception.
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    loop.loop();
                    fail();
                } catch (Exception e) {
                    if (!(e instanceof NullPointerException)) {
                        fail();
                    }
                }
            }
        }).get();
    }

    @Test
    @SmallTest
    @Feature({"Cronet"})
    public void testLoopWithTimeout() throws Exception {
        final MessageLoop loop = new MessageLoop();
        assertFalse(loop.isRunning());
        // The MessageLoop queue is empty. Use a timeout of 100ms to check that
        // it doesn't block forever.
        try {
            loop.loop(100);
            fail();
        } catch (SocketTimeoutException e) {
            // Expected.
        }
        assertFalse(loop.isRunning());
    }
}


text:
namespace TextRazor.Net.Models
{
    using System.Collections.Generic;
    using Newtonsoft.Json;

    public class NounPhrase : TextRazorEntity
    {
        /// <summary>
        /// List of the positions of the words in this phrase within their sentence.
        /// </summary>
        [JsonProperty("wordPositions")]
        public IEnumerable<int> WordPositions { get; set; }
    }
}


text:
namespace swift {
namespace instrumenter_support {

template <class E> class Added {
private:
  E Contents;

public:
  Added() {}
  Added(E NewContents) { Contents = NewContents; }
  const Added<E> &operator=(const Added<E> &rhs) {
    Contents = rhs.Contents;
    return *this;
  }
  E &operator*() { return Contents; }
  E &operator->() { return Contents; }
};

class InstrumenterBase {

protected:
  InstrumenterBase() : CF(*this) {}
  virtual ~InstrumenterBase() = default;
  virtual void anchor();
  virtual BraceStmt *transformBraceStmt(BraceStmt *BS,
                                        bool TopLevel = false) = 0;

  class ClosureFinder : public ASTWalker {
  private:
    InstrumenterBase &I;

  public:
    ClosureFinder(InstrumenterBase &Inst) : I(Inst) {}
    std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
      if (isa<BraceStmt>(S)) {
        return {false, S}; // don't walk into brace statements; we
                           // need to respect nesting!
      } else {
        return {true, S};
      }
    }
    std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
      if (auto *CE = dyn_cast<ClosureExpr>(E)) {
        BraceStmt *B = CE->getBody();
        if (B) {
          BraceStmt *NB = I.transformBraceStmt(B);
          CE->setBody(NB, false);
          // just with the entry and exit logging this is going to
          // be more than a single expression!
        }
      }
      return {true, E};
    }
  };

  ClosureFinder CF;

  template <class T>
  bool doTypeCheck(ASTContext &Ctx, DeclContext *DC, Added<T *> &parsedExpr) {
    Expr *E = *parsedExpr;
    bool result = doTypeCheckImpl(Ctx, DC, E);
    parsedExpr = Added<T *>(dyn_cast<T>(E));
    return result;
  }

private:
  bool doTypeCheckImpl(ASTContext &Ctx, DeclContext *DC, Expr * &parsedExpr);
};
}
}


text:
module Java.Imports (
  getImports,
  getImportsNonQualified
) where

import Language.Java.Syntax
import Data.List (isPrefixOf)
import Java.Helper (concatIdent)

getImports :: CompilationUnit -> [String]
getImports (CompilationUnit _ imports _) = getImportsFromAst imports
  where getImportsFromAst = map getImportDeclName

getImportsNonQualified :: CompilationUnit -> [String]
getImportsNonQualified (CompilationUnit _ imports _) = getImportsFromAst imports
  where getImportsFromAst = map getImportNonQualifyingDeclName

getImportDeclName :: ImportDecl -> String
getImportDeclName (ImportDecl False name _) = concatIdent name
getImportDeclName (ImportDecl True (Name ids) _) = concatIdent $ Name (init ids)

getImportNonQualifyingDeclName :: ImportDecl -> String
getImportNonQualifyingDeclName (ImportDecl False (Name ids) _) = concatIdent $ Name [last ids]
getImportNonQualifyingDeclName (ImportDecl True (Name ids) _) = concatIdent $ Name [(last.init) ids]


text:
title:  Vibrant Bible Study Ministry
date:  17/08/2020
---

#### inTerpret

To ensure that spiritual interest is being cultivated in preparation for a bountiful harvest, a vibrant Bible study ministry should be at the heart of every local church's evangelistic activities. Vibrant means more than the pastor, Bible worker, and a few eloquent church members giving Bible studies. It means involving every member in some enthusiastic and comprehensive way. The reality is that every local church should be a training ground for discipleship as well as a Bible school for everyone who has a desire to learn and become like Jesus. Here are some practical ways to get this started:

1.         ELECT a Bible school coordinator to oversee the Bible study ministry.

2.         CHOOSE a Bible study plan or lessons/videos/media for members to use in giving Bible studies.

3.         TRAIN every member to be involved in some way—offering, advertising, hosting, giving, and/or inviting to Bible studies.

4.         GENERATE Bible study interests using every means possible (ask people you know, ask door-to-door, offer at events, advertise using tracts, advertise online, on social media, by a mail offer, and so on).

5.         RECORD and TRACK Bible study interests.

6.         PROVIDE leadership support—promotion, financial support, and participation.

7.         PRAY for laborers and for the salvation of souls through the Bible study ministry.

The more members are involved in the ministry of Bible study, the greater potential there is for growth. Bible studies are not just another program, but the actual core/meat/essence/nucleus of evangelism. Too often, churches have some ministry that they favor. Some are the health ministry church; others are VBS oriented. While some limit themselves to friendship evangelism, others merely conduct evangelistic programs to get decisions.

Every church is different, and all are wonderful and needed! But at the end of the day, Bible study is the means by which we all start and grow in Christ—through abiding in Him. In the discipleship process, all the other ministries are the funnel by which all are directed to Bible study! The Bible study ministry initiative is more than just another program. It is the stage of fostering, strengthening, deepening, and enriching faith. It is the opportunity to ask all sorts of questions, to receive answers from the Word of God, and to make the teachings of the Bible your own—all through the vibrancy of the local church Bible study ministry.

For more information on the cultivation stage and the Grow cycle, visit https://grow.adventist.org/cultivate/.

``


text:
package com.alternativepayments.apimocks;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;

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

import com.alternativepayments.AlternativePaymentClient;
import com.alternativepayments.http.ObjectMapperProvider;
import com.alternativepayments.models.Pagination;
import com.alternativepayments.models.subscription.Subscription;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.client.WireMock;

// Headers are matching as containing as otherwise we need to write custom ResponseTransformer
// See: https://groups.google.com/forum/#!topic/wiremock-user/pSbIn_qMu00
public class SubscriptionApiMock {

    private SubscriptionApiMock() {

    }

    public static void expectGet(final String id) {
        WireMock.stubFor(
                get(urlMatching("/api/subscriptions/" + id))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.OK.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("subscription/subscription.json")));
    }

    public static void expectGetAll() {
        WireMock.stubFor(
                get(urlMatching("/api/subscriptions/"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.OK.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("subscription/subscriptions.json")));
    }

    public static void expectGetWithPagination() {
        WireMock.stubFor(
                get(urlPathEqualTo("/api/subscriptions/"))
                .withQueryParam(Pagination.LIMIT, containing("3"))
                .withQueryParam(Pagination.OFFSET, containing("10"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .willReturn(aResponse()
                        .withStatus(Status.OK.getStatusCode())
                        .withHeader("Content-Type", "application/json")
                        .withBodyFile("subscription/subscriptions_pagination.json")));
    }

    public static void expectPost(final Subscription subscription) {
        try {
            WireMock.stubFor(
                post(urlMatching("/api/subscriptions/"))
                .withHeader("Authorization", containing(""))
                .withHeader("User-Agent", equalTo("AlternativePayments Java SDK v" + AlternativePaymentClient.VERSION))
                .withRequestBody(containing(new ObjectMapperProvider()
                        .getContext(ObjectMapper.class).writeValueAsString(subscription)))
                .willReturn(aResponse()
                        .withStatus(Status.OK.getStatusCode())
                                .withHeader("Content-Type", "application/json")
                                .withBodyFile("subscription/subscription.json")));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

}


text:
<secondary-menu-directive></secondary-menu-directive>

Admin Panel

                User Menu

                Projects

                Messages


text:
package st.zudamue.support.android.component.model;

import android.support.v4.app.Fragment;

/**
 * Created by xdaniel
 *
 * @author Daniel Costa <costa.xdaniel@gmail.com>
 */
public interface ItemFragment extends Identified
{
	/**
	 * 	Obter o tiitulo para o fragmento
	 * @return
	 */
	CharSequence getTitle();

	/**
	 * Obter o fragmento
	 * @return
	 */
	Fragment getFragment();
}


text:
title: Selection Sort
localeTitle: Seleção de seleção
---
## Seleção de seleção

A seleção de classificação é um dos algoritmos de classificação mais simples. Funciona da seguinte maneira,

1.  Encontre o menor elemento. Troque com o primeiro elemento.
2.  Encontre o segundo menor elemento. Troque com o segundo elemento.
3.  Encontre o terceiro menor elemento. Troque com o terceiro elemento.
4.  Repita encontrando o próximo elemento menor e trocando-o para a posição correta correspondente até que o array esteja classificado.

Como você pode imaginar, esse algoritmo é chamado de Seleção de Seleção porque seleciona repetidamente o próximo elemento menor e o troca para o seu lugar.

Mas, como você escreveria o código para encontrar o índice do segundo menor valor em uma matriz?

*   Uma maneira fácil é notar que o menor valor já foi trocado para o índice 0, então o problema se reduz a encontrar o menor elemento na matriz, começando no índice 1.

### Implementação em C / C ++

```C
for(int i = 0; i < n; i++)
 {
    int min_index = i;
    int min_element = a[i];

    for(int j = i +1; j < n; j++)
    {
        if(a[j] < min_element)
        {
            min_element = a[j];
            min_index = j;
        }
    }

    swap(&a[i], &a[min_index]);
 }
```

### Implementação em Javascript

\`\` \`Javascript seleção de função _sort (A) { var len =_ comprimento do _array_ (A); para (var i = 0; i <len - 1; i = i + 1) { var j _min = i; para (var j = i + 1; j <len; j = j + 1) { if (A \[j\] <A \[j_ min\]) { j _min = j; } outro {} } if (j_ min! == i) { trocar (A, i, j\_min); } outro {} } }

troca de funções (A, x, y) { var temp = A \[x\]; A \[x\] = A \[y\]; A \[y\] = temp; }
```
### Implementation in Python
```

python _sort de_ seleção de def _(arr): se não for: return arr para eu na faixa (len (arr)): min_ i = i para j no intervalo (i + 1, len (arr)): se arr \[j\] <arr \[min _i\]: min_ i = j arr \[i\], arr \[min _i\] = arr \[min_ i\], arr \[i\] \`\` \`

### Propriedades

*   Complexidade do espaço: **O (n)**
*   Complexidade do Tempo: **O (n 2 )**
*   Ordenando no Lugar: **Sim**
*   Estável: **não**

### Visualização

*   [USFCA](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html)
*   [HackerEarth](https://www.hackerearth.com/practice/algorithms/sorting/selection-sort/visualize/)

### Referências

*   [Wikipedia](https://en.wikipedia.org/wiki/Selection_sort)
*   [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms#sorting-algorithms)


text:
@interface MainViewController ()<UIGestureRecognizerDelegate,chanelViewDelegate,UIScrollViewDelegate>
@end

@implementation MainViewController{
    UIView *_headerV;
    MTChanelView *_chanelV;
    UIScrollView *_scrollV;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发现";

    [self setupUI];
    [self setupGesture];

}

//添加手势
-(void)setupGesture{
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
    pan.delegate = self;
    [self.view addGestureRecognizer: pan];
}
//添加主视图
-(void)setupUI{
    UIView *headerV = [[UIView alloc] init];
    headerV.backgroundColor = [UIColor redColor];
    [self.view addSubview:headerV];
    [headerV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(128);
    }];
    _headerV = headerV;
    MTChanelView *channelV = [[MTChanelView alloc] init];
    channelV.delegate = self;
    [self.view addSubview:channelV];
    [channelV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerV.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(35);
    }];
    _chanelV = channelV;
    UIScrollView *scrollV = [self setScrollV];
    scrollV.backgroundColor = [UIColor whiteColor];
    scrollV.delegate = self;
    [self.view addSubview:scrollV];
    [scrollV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(channelV.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    _scrollV = scrollV;
}
//搭建底部的滚动视图
-(UIScrollView*)setScrollV{
    UIScrollView *scrollV = [[UIScrollView alloc] init];
    scrollV.showsHorizontalScrollIndicator = NO;
    scrollV.bounces = NO;
    scrollV.pagingEnabled = YES;

    NSArray *array = @[@"MTSopViewController",@"MTCommanViewController",@"MTInfoViewController"];

    //遍历数组,将字符串转化为控制器
    NSMutableArray *temp = [NSMutableArray arrayWithCapacity:array.count];

    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        Class clz = NSClassFromString(obj);
        UIViewController *vc = [[clz alloc] init];
        NSAssert([vc isKindOfClass:[UIViewController class]], @"%@不存在",obj);
        vc.view.backgroundColor = [UIColor cz_randomColor];

        [self addChildViewController:vc];

        [scrollV addSubview:vc.view];

        [vc didMoveToParentViewController:self];

        [temp addObject:vc.view];
    }];

    [temp mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];

    [temp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.equalTo(scrollV);
        make.size.equalTo(scrollV);

    }];

    return  scrollV;

}

//监听手势

-(void)panGesture:(UIPanGestureRecognizer*)recognizer{
    CGPoint p = [recognizer translationInView:self.view];

    //判断x轴方向不改变,y轴方向改变
    if (ABS(p.x) >ABS(p.y)){
        return;
    }
    //重置
    [recognizer setTranslation:CGPointZero inView:self.view];
    //根据顶部视图计算出一个高度
    CGFloat height = p.y + _headerV.bounds.size.height;
    //计算单位透明度的变化量
    CGFloat percent = 1.0/(kHeaderHeight - 64);
    //计算需要的透明度
    CGFloat needAlpha = (height - 64)*percent;
    //需要的alpha
    CGFloat alpha = 1 - needAlpha;
    self.navigationController.navigationBar.alpha = alpha;
    if (height > 128){
        height = 128;
    }
    if (height < 64){
        height = 64;
    }

    [_headerV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];

    //重写布局子控件
    [self.view layoutIfNeeded];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return  YES;
}
#pragma mark chanelViewDelegate
-(void)chanelViewDidSelectbu:(NSInteger)index{
    CGRect rect = CGRectMake(index*self.view.frame.size.width, 0, self.view.frame.size.width, _scrollV.frame.size.height);
    [_scrollV scrollRectToVisible:rect animated:NO];
}

//底部的scrollView滚动的时候,按钮的索引页改变

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    CGFloat contentOffX = scrollView.contentOffset.x;

    NSInteger index = (contentOffX / scrollView.frame.size.width);

    _chanelV.index = index;

}

@end


text:
Extract Table of Content
========================

A Pelican plugin to extract table of contents (ToC) from `article.content` and
place it in its own `article.toc` variable.

Copyright (c) Talha Mansoor

Author          | Talha Mansoor
----------------|-----
Author Email    | talha131@gmail.com
Author Homepage | http://onCrashReboot.com
Github Account  | https://github.com/talha131

Acknowledgement
---------------

Thanks to [Avaris](https://github.com/avaris) for going out of the way to help
me fix Unicode issues and doing a thorough code review.

Why do you need it?
===================

Pelican can generate ToC of reST and Markdown files, using markup's respective
directive and extension. ToC is generated and placed at the beginning of
`article.content`. You cannot place the ToC in `<nav>` HTML5 tag, nor can you
place the ToC at the end of your article's content because ToC is part of
`article.content`.

This plugin extracts ToC from `article.content` and places it in `article.toc`.

Requirements
============

`extract_toc` requires BeautifulSoup.

```bash
pip install beautifulsoup4
```

How to Use
==========

**Important!** This plugin only works with reST and Markdown files. reST files
should have `.rst` extension. Markdown files can have `.md`, `.mkd` or
`markdown`.

If ToC appears in your article at more than one places, `extract_toc` will
remove only the first occurrence. You shouldn't probably need to have multiple
ToC in your article. In case you need to display it multiple times, you can
print it via your template.

ToC generated by Markdown is enclosed in `<div class="toc">`. On the other hand
ToC generated by reST is enclosed in `<div class="contents topic">`.
`extract_toc` relies on this behavior to work.

reStructuredText Example
------------------------

To add a table of contents to your reStructuredText document you need to add a 'contents directive' at the place where you want the table of contents to appear. See the [documentation](http://docutils.sourceforge.net/docs/ref/rst/directives.html#table-of-contents) for more details.

```rst
My super title
##############

:date: 2010-10-03
:tags: thats, awesome

.. contents::
..
   1  Head 1
     1.1  Head 2
   2  Head 3
   3  head 4

Heading 1
---------

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.
```

Markdown Example
----------------

To add a table of contents to your Markdown document you need to place the 'TOC marker' at the place where you would like the table of contents to appear. See the Python Markdown  [documentation](http://pythonhosted.org/Markdown/extensions/toc.html) for more details.

Important! To enable table of contents generation for the markdown reader you need to set `MD_EXTENSIONS = (['toc'])` in your pelican configuration file.

```Markdown
title: My super title
date: 4-4-2013
tags: thats, awesome

[TOC]

# Heading 1 #

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.
```

Template Example
================

```python
{% if article.toc %}
    <nav class="affix">
    {{ article.toc }}
    </nav>
{% endif %}
```


text:
#include "mscl/MicroStrain/Wireless/Commands/BaseStation_Ping.h"
#include "mscl/MicroStrain/ResponseCollector.h"
#include "mscl/MicroStrain/DataBuffer.h"

#include <boost/test/unit_test.hpp>

using namespace mscl;

BOOST_AUTO_TEST_SUITE(BaseStationPing_Test)

BOOST_AUTO_TEST_CASE(BaseStationPing_BuildCommand)
{
    //create a LongPing command
    ByteStream b = BaseStation_Ping::buildCommand();

    //Check all the bytes in the ByteStream
    BOOST_CHECK_EQUAL(b.read_uint8(0), 0x01);
}

BOOST_AUTO_TEST_CASE(BaseStationPing_Match_Success)
{
    std::shared_ptr<ResponseCollector> rc(new ResponseCollector);
    BaseStation_Ping::Response response(rc);

    Bytes bytes;
    bytes.push_back(0x01);    //success response

    DataBuffer buffer(bytes);

    //check that match returns true
    BOOST_CHECK_EQUAL(response.match(buffer), true);

    //check that the result of the ping is true
    BOOST_CHECK_EQUAL(response.success(), true);
}

BOOST_AUTO_TEST_CASE(BaseStationPing_Match_Fail)
{
    std::shared_ptr<ResponseCollector> rc(new ResponseCollector);
    BaseStation_Ping::Response response(rc);

    Bytes bytes;
    bytes.push_back(0x45);    //fail response

    DataBuffer buffer(bytes);

    //check that match returns false
    BOOST_CHECK_EQUAL(response.match(buffer), false);

    //check that the result of the ping is false
    BOOST_CHECK_EQUAL(response.success(), false);
}

BOOST_AUTO_TEST_CASE(BaseStationPing_Match_Fail_ByteSize)
{
    std::shared_ptr<ResponseCollector> rc(new ResponseCollector);
    BaseStation_Ping::Response response(rc);

    Bytes bytes;    //empty bytes

    DataBuffer buffer(bytes);

    //check that match returns false
    BOOST_CHECK_EQUAL(response.match(buffer), false);

    //check that the result of the ping is false
    BOOST_CHECK_EQUAL(response.success(), false);
}

BOOST_AUTO_TEST_SUITE_END()


text:
require 'rails_helper'

module Cms
  RSpec.describe ContentCategory, type: :model do

    it "can have content_nodes" do
      c = create(:content_category, :with_node)
      c.content_nodes << [create(:content_node)]
      c.save
      expect(c.content_nodes.unscoped.count).to eq 2
    end

  end
end


text:
namespace Envoy {
namespace Config {

GrpcMuxImpl::GrpcMuxImpl(const envoy::api::v2::core::Node& node, Grpc::AsyncClientPtr async_client,
                         Event::Dispatcher& dispatcher,
                         const Protobuf::MethodDescriptor& service_method)
    : node_(node), async_client_(std::move(async_client)), service_method_(service_method) {
  retry_timer_ = dispatcher.createTimer([this]() -> void { establishNewStream(); });
}

GrpcMuxImpl::~GrpcMuxImpl() {
  for (const auto& api_state : api_state_) {
    for (auto watch : api_state.second.watches_) {
      watch->inserted_ = false;
    }
  }
}

void GrpcMuxImpl::start() { establishNewStream(); }

void GrpcMuxImpl::setRetryTimer() {
  retry_timer_->enableTimer(std::chrono::milliseconds(RETRY_DELAY_MS));
}

void GrpcMuxImpl::establishNewStream() {
  ENVOY_LOG(debug, "Establishing new gRPC bidi stream for {}", service_method_.DebugString());
  stream_ = async_client_->start(service_method_, *this);
  if (stream_ == nullptr) {
    ENVOY_LOG(warn, "Unable to establish new stream");
    handleFailure();
    return;
  }

  for (const auto type_url : subscriptions_) {
    sendDiscoveryRequest(type_url);
  }
}

void GrpcMuxImpl::sendDiscoveryRequest(const std::string& type_url) {
  if (stream_ == nullptr) {
    ENVOY_LOG(debug, "No stream available to sendDiscoveryRequest for {}", type_url);
    return;
  }

  ApiState& api_state = api_state_[type_url];
  if (api_state.paused_) {
    ENVOY_LOG(trace, "API {} paused during sendDiscoveryRequest(), setting pending.", type_url);
    api_state.pending_ = true;
    return;
  }

  auto& request = api_state.request_;
  request.mutable_resource_names()->Clear();

  // Maintain a set to avoid dupes.
  std::unordered_set<std::string> resources;
  for (const auto* watch : api_state.watches_) {
    for (const std::string& resource : watch->resources_) {
      if (resources.count(resource) == 0) {
        resources.emplace(resource);
        request.add_resource_names(resource);
      }
    }
  }

  ENVOY_LOG(trace, "Sending DiscoveryRequest for {}: {}", type_url, request.DebugString());
  stream_->sendMessage(request, false);

  // clear error_detail after the request is sent if it exists.
  if (api_state_[type_url].request_.has_error_detail()) {
    api_state_[type_url].request_.clear_error_detail();
  }
}

void GrpcMuxImpl::handleFailure() {
  for (const auto& api_state : api_state_) {
    for (auto watch : api_state.second.watches_) {
      watch->callbacks_.onConfigUpdateFailed(nullptr);
    }
  }
  setRetryTimer();
}

GrpcMuxWatchPtr GrpcMuxImpl::subscribe(const std::string& type_url,
                                       const std::vector<std::string>& resources,
                                       GrpcMuxCallbacks& callbacks) {
  auto watch =
      std::unique_ptr<GrpcMuxWatch>(new GrpcMuxWatchImpl(resources, callbacks, type_url, *this));
  ENVOY_LOG(debug, "gRPC mux subscribe for " + type_url);

  // Lazily kick off the requests based on first subscription. This has the
  // convenient side-effect that we order messages on the channel based on
  // Envoy's internal dependency ordering.
  if (!api_state_[type_url].subscribed_) {
    api_state_[type_url].request_.set_type_url(type_url);
    api_state_[type_url].request_.mutable_node()->MergeFrom(node_);
    api_state_[type_url].subscribed_ = true;
    subscriptions_.emplace_back(type_url);
  }

  // This will send an updated request on each subscription.
  // TODO(htuch): For RDS/EDS, this will generate a new DiscoveryRequest on each resource we added.
  // Consider in the future adding some kind of collation/batching during CDS/LDS updates so that we
  // only send a single RDS/EDS update after the CDS/LDS update.
  sendDiscoveryRequest(type_url);

  return watch;
}

void GrpcMuxImpl::pause(const std::string& type_url) {
  ENVOY_LOG(debug, "Pausing discovery requests for {}", type_url);
  ApiState& api_state = api_state_[type_url];
  ASSERT(!api_state.paused_);
  ASSERT(!api_state.pending_);
  api_state.paused_ = true;
}

void GrpcMuxImpl::resume(const std::string& type_url) {
  ENVOY_LOG(debug, "Resuming discovery requests for {}", type_url);
  ApiState& api_state = api_state_[type_url];
  ASSERT(api_state.paused_);
  api_state.paused_ = false;

  if (api_state.pending_) {
    ASSERT(api_state.subscribed_);
    sendDiscoveryRequest(type_url);
    api_state.pending_ = false;
  }
}

void GrpcMuxImpl::onCreateInitialMetadata(Http::HeaderMap& metadata) {
  UNREFERENCED_PARAMETER(metadata);
}

void GrpcMuxImpl::onReceiveInitialMetadata(Http::HeaderMapPtr&& metadata) {
  UNREFERENCED_PARAMETER(metadata);
}

void GrpcMuxImpl::onReceiveMessage(std::unique_ptr<envoy::api::v2::DiscoveryResponse>&& message) {
  const std::string& type_url = message->type_url();
  ENVOY_LOG(debug, "Received gRPC message for {} at version {}", type_url, message->version_info());
  if (api_state_.count(type_url) == 0) {
    ENVOY_LOG(warn, "Ignoring unknown type URL {}", type_url);
    return;
  }
  if (api_state_[type_url].watches_.empty()) {
    ENVOY_LOG(warn, "Ignoring unwatched type URL {}", type_url);
    return;
  }
  try {
    // To avoid O(n^2) explosion (e.g. when we have 1000s of EDS watches), we
    // build a map here from resource name to resource and then walk watches_.
    // We have to walk all watches (and need an efficient map as a result) to
    // ensure we deliver empty config updates when a resource is dropped.
    std::unordered_map<std::string, ProtobufWkt::Any> resources;
    GrpcMuxCallbacks& callbacks = api_state_[type_url].watches_.front()->callbacks_;
    for (const auto& resource : message->resources()) {
      if (type_url != resource.type_url()) {
        throw EnvoyException(fmt::format("{} does not match {} type URL is DiscoveryResponse {}",
                                         resource.type_url(), type_url, message->DebugString()));
      }
      const std::string resource_name = callbacks.resourceName(resource);
      resources.emplace(resource_name, resource);
    }
    for (auto watch : api_state_[type_url].watches_) {
      if (watch->resources_.empty()) {
        watch->callbacks_.onConfigUpdate(message->resources(), message->version_info());
        continue;
      }
      Protobuf::RepeatedPtrField<ProtobufWkt::Any> found_resources;
      for (auto watched_resource_name : watch->resources_) {
        auto it = resources.find(watched_resource_name);
        if (it != resources.end()) {
          found_resources.Add()->MergeFrom(it->second);
        }
      }
      watch->callbacks_.onConfigUpdate(found_resources, message->version_info());
    }
    api_state_[type_url].request_.set_version_info(message->version_info());
  } catch (const EnvoyException& e) {
    ENVOY_LOG(warn, "gRPC config for {} update rejected: {}", message->type_url(), e.what());
    for (auto watch : api_state_[type_url].watches_) {
      watch->callbacks_.onConfigUpdateFailed(&e);
    }
    ::google::rpc::Status* error_detail = api_state_[type_url].request_.mutable_error_detail();
    error_detail->set_code(Grpc::Status::GrpcStatus::Internal);
    error_detail->set_message(e.what());
  }
  api_state_[type_url].request_.set_response_nonce(message->nonce());
  sendDiscoveryRequest(type_url);
}

void GrpcMuxImpl::onReceiveTrailingMetadata(Http::HeaderMapPtr&& metadata) {
  UNREFERENCED_PARAMETER(metadata);
}

void GrpcMuxImpl::onRemoteClose(Grpc::Status::GrpcStatus status, const std::string& message) {
  ENVOY_LOG(warn, "gRPC config stream closed: {}, {}", status, message);
  stream_ = nullptr;
  handleFailure();
}

} // namespace Config
} // namespace Envoy


text:
package com.jkoolcloud.tnt4j.logger;

/**
 * <p>
 * Common constants used by all logging appenders: tags & qualifiers.
 * </p>
 *
 * @version $Revision: 11 $
 *
 */
public interface AppenderConstants {
	String PARAM_BEGIN_LABEL = "beg";
	String PARAM_END_LABEL = "end";

	String PARAM_APPL_LABEL = "app";
	String PARAM_USER_LABEL = "usr";
	String PARAM_CORRELATOR_LABEL = "cid";
	String PARAM_TAG_LABEL = "tag";
	String PARAM_LOCATION_LABEL = "loc";
	String PARAM_OP_NAME_LABEL = "opn";
	String PARAM_OP_TYPE_LABEL = "opt";
	String PARAM_RESOURCE_LABEL = "rsn";
	String PARAM_MSG_DATA_LABEL = "msg";
	String PARAM_EXCEPTION_LABEL = "exc";
	String PARAM_SEVERITY_LABEL = "sev";
	String PARAM_COMP_CODE_LABEL = "ccd";
	String PARAM_REASON_CODE_LABEL = "rcd";
	String PARAM_START_TIME_LABEL = "stt";
	String PARAM_END_TIME_LABEL = "ent";
	String PARAM_ELAPSED_TIME_LABEL = "elt";
	String PARAM_AGE_TIME_LABEL = "age";

	String TAG_TYPE_QUALIFIER = "%";
	String TAG_TYPE_INTEGER = "%i";
	String TAG_TYPE_LONG = "%l";
	String TAG_TYPE_DOUBLE = "%d";
	String TAG_TYPE_FLOAT = "%f";
	String TAG_TYPE_NUMBER = "%n";
	String TAG_TYPE_BOOLEAN = "%b";
	String TAG_TYPE_STRING = "%s";
}


text:
def stub_vmdb_util_methods_for_collection_log
  allow(VMDB::Util).to receive(:zip_logs)
  allow(VMDB::Util).to receive(:compressed_log_patterns).and_return(["log/evm.1122.gz"])
  allow(VMDB::Util).to receive(:get_evm_log_for_date).and_return("20151209_141429_20151217_140845")
  allow(VMDB::Util).to receive(:get_log_start_end_times).and_return([Time.zone.now, Time.zone.now])
end

shared_examples "post_[type_of_log]_logs" do |type, type_of_log|
  it "uses #{type} file_depot in LogFile for upload" do
    @zone.log_file_depot = zone_depot
    @miq_server.log_file_depot = server_depot

    stub_vmdb_util_methods_for_collection_log
    allow_any_instance_of(LogFile).to receive(:upload)
    allow_any_instance_of(MiqServer).to receive(:current_log_patterns)

    method = "post_#{type_of_log}_logs".to_sym
    @miq_server.send(method, miq_task.id, @miq_server.log_depot(type))
    log_file_depot = LogFile.first.file_depot

    if type == "Zone"
      expect(log_file_depot).to eq(zone_depot)
      expect(log_file_depot).not_to eq(server_depot)
    else
      expect(log_file_depot).not_to eq(zone_depot)
      expect(log_file_depot).to eq(server_depot)
    end

    expect(LogFile.first.miq_task).to eq(miq_task)
  end
end

shared_examples "post_logs_uses_depot" do |is_zone_depot, is_server_depot, context|
  it "uses #{context} depot" do
    if is_zone_depot
      @zone.log_file_depot = zone_depot
    end

    if is_server_depot
      @miq_server.log_file_depot = server_depot
    end

    stub_vmdb_util_methods_for_collection_log
    allow_any_instance_of(LogFile).to receive(:upload)
    allow_any_instance_of(MiqServer).to receive(:current_log_patterns)

    @miq_server.post_logs(:taskid => miq_task.id, :context => context)

    log_file_depot = LogFile.first.file_depot

    if context == "Zone"
      expect(log_file_depot).to eq(zone_depot)
    else
      expect(log_file_depot).to eq(server_depot)
    end
  end
end

shared_examples "post_logs_fails" do |is_zone_depot, is_server_depot, context|
  it "raises error 'Log depot settings not configured'" do
    if is_zone_depot
      @zone.log_file_depot = zone_depot
    end

    if is_server_depot
      @miq_server.log_file_depot = server_depot
    end

    stub_vmdb_util_methods_for_collection_log
    allow_any_instance_of(LogFile).to receive(:upload)
    allow_any_instance_of(MiqServer).to receive(:current_log_patterns)

    expect do
      @miq_server.post_logs(:taskid => miq_task.id, :context => context)
    end.to raise_error(RuntimeError, "Log depot settings not configured")
  end
end

describe MiqServer do
  context "LogManagement" do
    let(:server_depot) { FactoryBot.create(:file_depot) }
    let(:zone_depot) { FactoryBot.create(:file_depot) }
    let(:miq_task) { FactoryBot.create(:miq_task) }

    before do
      _, @miq_server, @zone = EvmSpecHelper.create_guid_miq_server_zone
      @miq_server2          = FactoryBot.create(:miq_server, :zone => @zone)
    end

    context "#pg_data_log_patterns" do
      it "nil pg_data_dir" do
        allow(@miq_server).to receive_messages(:pg_data_dir => nil)
        expect(@miq_server.pg_log_patterns).to eql []
      end

      it "pg_data_dir set" do
        allow(@miq_server).to receive_messages(:pg_data_dir => '/var/lib/pgsql/data')
        expected = %w(/var/lib/pgsql/data/*.conf /var/lib/pgsql/data/pg_log/* /etc/manageiq/postgresql.conf.d/*)
        expect(@miq_server.pg_log_patterns.collect(&:to_s)).to match_array expected
      end
    end

    it "#current_log_patterns" do
      stub_settings(:log => {:collection => {:current => {:pattern => %w(/var/log/syslog*)}}})
      allow(@miq_server).to receive_messages(:pg_log_patterns => %w(/var/lib/pgsql/data/*.conf))
      expect(@miq_server.current_log_patterns).to match_array %w(/var/log/syslog* /var/lib/pgsql/data/*.conf)
    end

    it "#current_log_patterns with pg_logs duplicated in current_log_pattern_configuration" do
      stub_settings(
        :log => {:collection => {:current => {:pattern => %w(/var/log/syslog* /var/lib/pgsql/data/*.conf)}}})
      allow(@miq_server).to receive_messages(:pg_log_patterns => %w(/var/lib/pgsql/data/*.conf))
      expect(@miq_server.current_log_patterns).to match_array %w(/var/log/syslog* /var/lib/pgsql/data/*.conf)
    end

    context "post current/historical/models/dialogs" do
      let(:task)                      { FactoryBot.create(:miq_task) }
      let(:compressed_log_patterns)   { [Rails.root.join("log", "evm*.log.gz").to_s] }
      let(:current_log_patterns)      { [Rails.root.join("log", "evm.log").to_s] }
      let(:compressed_evm_log)        { Rails.root.join("evm.log-20180319.gz").to_s }
      let(:log_start)                 { Time.zone.parse("2018-05-11 11:33:12 UTC") }
      let(:log_end)                   { Time.zone.parse("2018-05-11 15:34:16 UTC") }
      let(:daily_log)                 { Rails.root.join("data", "user", "system", "evm_server_daily.zip").to_s }
      let(:log_depot)                 { FactoryBot.create(:file_depot) }
      let!(:region)                   { MiqRegion.seed }
      let(:zone)                      { @miq_server.zone }
      before do
        require 'vmdb/util'
        allow(VMDB::Util).to receive(:compressed_log_patterns).and_return(compressed_log_patterns)
        allow(VMDB::Util).to receive(:get_evm_log_for_date).and_return(compressed_evm_log)
        allow(VMDB::Util).to receive(:get_log_start_end_times).and_return([log_start, log_end])
        allow(VMDB::Util).to receive(:zip_logs).and_return(daily_log)
        allow(@miq_server).to receive(:current_log_patterns).and_return(current_log_patterns)
        allow(@miq_server).to receive(:backup_automate_dialogs)
        allow(@miq_server).to receive(:backup_automate_models)
        %w(historical_logfile current_logfile).each do |kind|
          logfile = FactoryBot.create(:log_file, :historical => kind == "historical_logfile")
          allow(logfile).to receive(:upload)
          allow(LogFile).to receive(kind).and_return(logfile)
        end
      end

      %w(
        Archive post_historical_logs
        Current post_current_logs
        Models post_automate_models
        Dialogs post_automate_dialogs
      ).each_slice(2) do |name, method|
        it "##{method}" do
          @miq_server.send(method, task.id, log_depot)
          logfile = @miq_server.reload.log_files.first
          expected_name = [name, "region", region.region, zone.name, zone.id, @miq_server.name, @miq_server.id, "20180511_113312 20180511_153416"].join(" ")
          expect(logfile).to have_attributes(
            :file_depot         => log_depot,
            :local_file         => daily_log,
            :logging_started_on => log_start,
            :logging_ended_on   => log_end,
            :name               => expected_name,
            :description        => "Logs for Zone #{@miq_server.zone.name} Server #{@miq_server.name} 20180511_113312 20180511_153416",
            :miq_task_id        => task.id
          )

          expected_filename = "#{name}_region_#{region.region}_#{zone.name}_#{zone.id}_#{@miq_server.name}_#{@miq_server.id}_20180511_113312_20180511_153416.zip"
          expected_filename.gsub!(/\s+/, "_")
          expect(logfile.destination_file_name).to eq(expected_filename)

          expect(task.reload).to have_attributes(
            :message => "#{name} log files from #{@miq_server.name} #{@miq_server.zone.name} MiqServer #{@miq_server.id} are posted",
            :state   => "Active",
            :status  => "Ok",
          )
        end
      end
    end

    context "#synchronize_logs" do
      it "passes along server override" do
        @miq_server.synchronize_logs("system", @miq_server2)
        expect(MiqTask.first.miq_server_id).to eql @miq_server2.id
        expect(MiqQueue.first.args.first[:id]).to eql @miq_server2.id
      end

      it "passes 'self' server if no server arg" do
        @miq_server2.synchronize_logs("system")
        expect(MiqTask.first.miq_server_id).to eql @miq_server2.id
        expect(MiqQueue.first.args.first[:id]).to eql @miq_server2.id
      end
    end

    describe "#log_depot" do
      it "server log_file_depot configured" do
        @miq_server.log_file_depot = server_depot
        expect(@miq_server.log_depot("MiqServer")).to eq(server_depot)
      end

      it "zone log_file_depot configured" do
        @zone.log_file_depot = zone_depot
        expect(@miq_server.log_depot("Zone")).to eq(zone_depot)
      end

      it "server and zone log_file_depot configured" do
        @miq_server.log_file_depot = server_depot
        @zone.log_file_depot = zone_depot
        expect(@miq_server.log_depot("Zone")).to eq(zone_depot)
        expect(@miq_server.log_depot("MiqServer")).to eq(server_depot)
      end
    end

    describe "#post_historical_logs" do
      context "Server" do
        include_examples "post_[type_of_log]_logs", "MiqServer", :historical
      end

      context "Zone" do
        include_examples "post_[type_of_log]_logs", "Zone", :historical
      end
    end

    describe "#post_current_logs" do
      context "Server" do
        include_examples "post_[type_of_log]_logs", "MiqServer", :current
      end

      context "Zone" do
        include_examples "post_[type_of_log]_logs", "Zone", :current
      end
    end

    describe "#post_logs" do
      context "Zone collection log requested, Zone depot is defined, MiqServer is defined" do
        include_examples "post_logs_uses_depot", true, true, "Zone"
      end

      context "Zone collection log requested, Zone depot is defined, MiqServer is not defined" do
        include_examples "post_logs_uses_depot", true, false, "Zone"
      end

      context "Zone collection log requested, zone depot is not defined, MiqServer defined" do
        include_examples "post_logs_fails", false, true, "Zone"
      end

      context "Zone collection log requested, zone depot is not defined, MiqServer is not defined" do
        include_examples "post_logs_fails", false, false, "Zone"
      end

      context "MiqServer collection log requested, Zone depot is defined, MiqServer is defined" do
        include_examples "post_logs_uses_depot", true, true, "MiqServer"
      end

      context "MiqServer collection log requested, Zone depot is defined, MiqServer is not defined" do
        include_examples "post_logs_fails", true, false, "MiqServer"
      end

      context "MiqServer collection log requested, zone depot is not defined, server defined" do
        include_examples "post_logs_uses_depot", false, true, "MiqServer"
      end

      context "MiqServer collection log requested, zone depot is not defined, MiqServer is not defined" do
        include_examples "post_logs_fails", false, false, "MiqServer"
      end
    end
  end
end


text:
typedef uint8_t uint8;
typedef uint32_t uint32;
typedef uint64_t uint64;
typedef std::pair<uint64, uint64> uint128;

inline uint64 Uint128Low64(const uint128& x) { return x.first; }
inline uint64 Uint128High64(const uint128& x) { return x.second; }

// Hash function for a byte array.
uint64 CityHash64(const char *buf, size_t len);

// Hash function for a byte array.  For convenience, a 64-bit seed is also
// hashed into the result.
uint64 CityHash64WithSeed(const char *buf, size_t len, uint64 seed);

// Hash function for a byte array.  For convenience, two seeds are also
// hashed into the result.
uint64 CityHash64WithSeeds(const char *buf, size_t len,
                           uint64 seed0, uint64 seed1);

// Hash function for a byte array.
uint128 CityHash128(const char *s, size_t len);

// Hash function for a byte array.  For convenience, a 128-bit seed is also
// hashed into the result.
uint128 CityHash128WithSeed(const char *s, size_t len, uint128 seed);

// Hash 128 input bits down to 64 bits of output.
// This is intended to be a reasonably good hash function.
inline uint64 Hash128to64(const uint128& x) {
  // Murmur-inspired hashing.
  const uint64 kMul = 0x9ddfea08eb382d69ULL;
  uint64 a = (Uint128Low64(x) ^ Uint128High64(x)) * kMul;
  a ^= (a >> 47);
  uint64 b = (Uint128High64(x) ^ a) * kMul;
  b ^= (b >> 47);
  b *= kMul;
  return b;
}

#endif  // CITY_HASH_H_


text:
package net.cyanwool.platform.lang.impl;

import java.util.HashMap;

import net.cyanwool.platform.lang.ILanguageFile;

public class CWLanguageFile implements ILanguageFile {

	private String localeCode;
	private HashMap<String, String> values = new HashMap<String, String>();

	public CWLanguageFile(String localeCode) {
		this.localeCode = localeCode;
	}

	@Override
	public String getValue(String unlocalizedName) {
		return values.get(unlocalizedName);
	}

	@Override
	public void setValue(String unlocalizedName, String value) {
		values.put(unlocalizedName, value);
	}

	@Override
	public boolean hasValue(String unlocalizeName) {
		return values.containsKey(unlocalizeName);
	}

	@Override
	public String getLocaleCode() {
		return localeCode;
	}

}


text:
using media::VideoCaptureFormat;
using media::VideoFrame;
using media::VideoFrameMetadata;

namespace content {

// Class combining a Client::Buffer interface implementation and a pool buffer
// implementation to guarantee proper cleanup on destruction on our side.
class AutoReleaseBuffer : public media::VideoCaptureDevice::Client::Buffer {
 public:
  AutoReleaseBuffer(const scoped_refptr<VideoCaptureBufferPool>& pool,
                    int buffer_id)
      : id_(buffer_id),
        pool_(pool),
        buffer_handle_(pool_->GetBufferHandle(buffer_id)) {
    DCHECK(pool_.get());
  }
  int id() const override { return id_; }
  gfx::Size dimensions() const override { return buffer_handle_->dimensions(); }
  size_t mapped_size() const override { return buffer_handle_->mapped_size(); }
  void* data(int plane) override { return buffer_handle_->data(plane); }
  ClientBuffer AsClientBuffer(int plane) override {
    return buffer_handle_->AsClientBuffer(plane);
  }
#if defined(OS_POSIX) && !defined(OS_MACOSX)
  base::FileDescriptor AsPlatformFile() override {
    return buffer_handle_->AsPlatformFile();
  }
#endif

 private:
  ~AutoReleaseBuffer() override { pool_->RelinquishProducerReservation(id_); }

  const int id_;
  const scoped_refptr<VideoCaptureBufferPool> pool_;
  const std::unique_ptr<VideoCaptureBufferPool::BufferHandle> buffer_handle_;
};

VideoCaptureDeviceClient::VideoCaptureDeviceClient(
    const base::WeakPtr<VideoCaptureController>& controller,
    const scoped_refptr<VideoCaptureBufferPool>& buffer_pool)
    : controller_(controller),
      external_jpeg_decoder_initialized_(false),
      buffer_pool_(buffer_pool),
      use_gpu_memory_buffers_(base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kUseGpuMemoryBuffersForCapture)),
      last_captured_pixel_format_(media::PIXEL_FORMAT_UNKNOWN) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
}

VideoCaptureDeviceClient::~VideoCaptureDeviceClient() {
  // This should be on the platform auxiliary thread since
  // |external_jpeg_decoder_| need to be destructed on the same thread as
  // OnIncomingCapturedData.
}

void VideoCaptureDeviceClient::OnIncomingCapturedData(
    const uint8_t* data,
    int length,
    const VideoCaptureFormat& frame_format,
    int rotation,
    const base::TimeTicks& timestamp) {
  TRACE_EVENT0("video", "VideoCaptureDeviceClient::OnIncomingCapturedData");
  DCHECK_EQ(media::PIXEL_STORAGE_CPU, frame_format.pixel_storage);

  if (last_captured_pixel_format_ != frame_format.pixel_format) {
    OnLog("Pixel format: " +
          media::VideoPixelFormatToString(frame_format.pixel_format));
    last_captured_pixel_format_ = frame_format.pixel_format;

    if (frame_format.pixel_format == media::PIXEL_FORMAT_MJPEG &&
        !external_jpeg_decoder_initialized_) {
      external_jpeg_decoder_initialized_ = true;
      external_jpeg_decoder_.reset(new VideoCaptureGpuJpegDecoder(base::Bind(
          &VideoCaptureController::DoIncomingCapturedVideoFrameOnIOThread,
          controller_)));
      external_jpeg_decoder_->Initialize();
    }
  }

  if (!frame_format.IsValid())
    return;

  // |chopped_{width,height} and |new_unrotated_{width,height}| are the lowest
  // bit decomposition of {width, height}, grabbing the odd and even parts.
  const int chopped_width = frame_format.frame_size.width() & 1;
  const int chopped_height = frame_format.frame_size.height() & 1;
  const int new_unrotated_width = frame_format.frame_size.width() & ~1;
  const int new_unrotated_height = frame_format.frame_size.height() & ~1;

  int destination_width = new_unrotated_width;
  int destination_height = new_unrotated_height;
  if (rotation == 90 || rotation == 270)
    std::swap(destination_width, destination_height);

  DCHECK_EQ(0, rotation % 90)
      << " Rotation must be a multiple of 90, now: " << rotation;
  libyuv::RotationMode rotation_mode = libyuv::kRotate0;
  if (rotation == 90)
    rotation_mode = libyuv::kRotate90;
  else if (rotation == 180)
    rotation_mode = libyuv::kRotate180;
  else if (rotation == 270)
    rotation_mode = libyuv::kRotate270;

  const gfx::Size dimensions(destination_width, destination_height);
  const media::VideoPixelStorage output_pixel_storage =
      use_gpu_memory_buffers_ ? media::PIXEL_STORAGE_GPUMEMORYBUFFER
                              : media::PIXEL_STORAGE_CPU;
  uint8_t *y_plane_data, *u_plane_data, *v_plane_data;
  std::unique_ptr<Buffer> buffer(
      ReserveI420OutputBuffer(dimensions, output_pixel_storage, &y_plane_data,
                              &u_plane_data, &v_plane_data));
  if (!buffer.get()) {
    DLOG(ERROR) << "Failed to reserve I420 output buffer.";
    return;
  }

  const int yplane_stride = dimensions.width();
  const int uv_plane_stride = yplane_stride / 2;
  int crop_x = 0;
  int crop_y = 0;
  libyuv::FourCC origin_colorspace = libyuv::FOURCC_ANY;

  bool flip = false;
  switch (frame_format.pixel_format) {
    case media::PIXEL_FORMAT_UNKNOWN:  // Color format not set.
      break;
    case media::PIXEL_FORMAT_I420:
      DCHECK(!chopped_width && !chopped_height);
      origin_colorspace = libyuv::FOURCC_I420;
      break;
    case media::PIXEL_FORMAT_YV12:
      DCHECK(!chopped_width && !chopped_height);
      origin_colorspace = libyuv::FOURCC_YV12;
      break;
    case media::PIXEL_FORMAT_NV12:
      DCHECK(!chopped_width && !chopped_height);
      origin_colorspace = libyuv::FOURCC_NV12;
      break;
    case media::PIXEL_FORMAT_NV21:
      DCHECK(!chopped_width && !chopped_height);
      origin_colorspace = libyuv::FOURCC_NV21;
      break;
    case media::PIXEL_FORMAT_YUY2:
      DCHECK(!chopped_width && !chopped_height);
      origin_colorspace = libyuv::FOURCC_YUY2;
      break;
    case media::PIXEL_FORMAT_UYVY:
      DCHECK(!chopped_width && !chopped_height);
      origin_colorspace = libyuv::FOURCC_UYVY;
      break;
    case media::PIXEL_FORMAT_RGB24:
      // Linux RGB24 defines red at lowest byte address,
      // see http://linuxtv.org/downloads/v4l-dvb-apis/packed-rgb.html.
      // Windows RGB24 defines blue at lowest byte,
      // see https://msdn.microsoft.com/en-us/library/windows/desktop/dd407253
#if defined(OS_LINUX)
      origin_colorspace = libyuv::FOURCC_RAW;
#elif defined(OS_WIN)
      origin_colorspace = libyuv::FOURCC_24BG;
#else
      NOTREACHED() << "RGB24 is only available in Linux and Windows platforms";
#endif
#if defined(OS_WIN)
      // TODO(wjia): Currently, for RGB24 on WIN, capture device always passes
      // in positive src_width and src_height. Remove this hardcoded value when
      // negative src_height is supported. The negative src_height indicates
      // that vertical flipping is needed.
      flip = true;
#endif
      break;
    case media::PIXEL_FORMAT_RGB32:
// Fallback to PIXEL_FORMAT_ARGB setting |flip| in Windows
// platforms.
#if defined(OS_WIN)
      flip = true;
#endif
    case media::PIXEL_FORMAT_ARGB:
      origin_colorspace = libyuv::FOURCC_ARGB;
      break;
    case media::PIXEL_FORMAT_MJPEG:
      origin_colorspace = libyuv::FOURCC_MJPG;
      break;
    default:
      NOTREACHED();
  }

  // The input |length| can be greater than the required buffer size because of
  // paddings and/or alignments, but it cannot be smaller.
  DCHECK_GE(static_cast<size_t>(length), frame_format.ImageAllocationSize());

  if (external_jpeg_decoder_) {
    const VideoCaptureGpuJpegDecoder::STATUS status =
        external_jpeg_decoder_->GetStatus();
    if (status == VideoCaptureGpuJpegDecoder::FAILED) {
      external_jpeg_decoder_.reset();
    } else if (status == VideoCaptureGpuJpegDecoder::INIT_PASSED &&
        frame_format.pixel_format == media::PIXEL_FORMAT_MJPEG &&
        rotation == 0 && !flip) {
      external_jpeg_decoder_->DecodeCapturedData(data, length, frame_format,
                                                 timestamp, std::move(buffer));
      return;
    }
  }

  if (libyuv::ConvertToI420(data,
                            length,
                            y_plane_data,
                            yplane_stride,
                            u_plane_data,
                            uv_plane_stride,
                            v_plane_data,
                            uv_plane_stride,
                            crop_x,
                            crop_y,
                            frame_format.frame_size.width(),
                            (flip ? -1 : 1) * frame_format.frame_size.height(),
                            new_unrotated_width,
                            new_unrotated_height,
                            rotation_mode,
                            origin_colorspace) != 0) {
    DLOG(WARNING) << "Failed to convert buffer's pixel format to I420 from "
                  << media::VideoPixelFormatToString(frame_format.pixel_format);
    return;
  }

  const VideoCaptureFormat output_format = VideoCaptureFormat(
      dimensions, frame_format.frame_rate,
      media::PIXEL_FORMAT_I420, output_pixel_storage);
  OnIncomingCapturedBuffer(std::move(buffer), output_format, timestamp);
}

std::unique_ptr<media::VideoCaptureDevice::Client::Buffer>
VideoCaptureDeviceClient::ReserveOutputBuffer(
    const gfx::Size& frame_size,
    media::VideoPixelFormat pixel_format,
    media::VideoPixelStorage pixel_storage) {
  DCHECK_GT(frame_size.width(), 0);
  DCHECK_GT(frame_size.height(), 0);
  // Currently, only I420 pixel format is supported.
  DCHECK_EQ(media::PIXEL_FORMAT_I420, pixel_format);

  // TODO(mcasas): For PIXEL_STORAGE_GPUMEMORYBUFFER, find a way to indicate if
  // it's a ShMem GMB or a DmaBuf GMB.
  int buffer_id_to_drop = VideoCaptureBufferPool::kInvalidId;
  const int buffer_id = buffer_pool_->ReserveForProducer(
      frame_size, pixel_format, pixel_storage, &buffer_id_to_drop);
  if (buffer_id_to_drop != VideoCaptureBufferPool::kInvalidId) {
    BrowserThread::PostTask(BrowserThread::IO,
        FROM_HERE,
        base::Bind(&VideoCaptureController::DoBufferDestroyedOnIOThread,
                   controller_, buffer_id_to_drop));
  }
  if (buffer_id == VideoCaptureBufferPool::kInvalidId)
    return nullptr;
  return base::WrapUnique<Buffer>(
      new AutoReleaseBuffer(buffer_pool_, buffer_id));
}

void VideoCaptureDeviceClient::OnIncomingCapturedBuffer(
    std::unique_ptr<Buffer> buffer,
    const VideoCaptureFormat& frame_format,
    const base::TimeTicks& timestamp) {
  // Currently, only I420 pixel format is supported.
  DCHECK_EQ(media::PIXEL_FORMAT_I420, frame_format.pixel_format);

  scoped_refptr<VideoFrame> frame;
  switch (frame_format.pixel_storage) {
    case media::PIXEL_STORAGE_GPUMEMORYBUFFER: {
      // Create a VideoFrame to set the correct storage_type and pixel_format.
      gfx::GpuMemoryBufferHandle handle;
      frame = VideoFrame::WrapExternalYuvGpuMemoryBuffers(
          media::PIXEL_FORMAT_I420, frame_format.frame_size,
          gfx::Rect(frame_format.frame_size), frame_format.frame_size, 0, 0, 0,
          reinterpret_cast<uint8_t*>(buffer->data(media::VideoFrame::kYPlane)),
          reinterpret_cast<uint8_t*>(buffer->data(media::VideoFrame::kUPlane)),
          reinterpret_cast<uint8_t*>(buffer->data(media::VideoFrame::kVPlane)),
          handle, handle, handle, base::TimeDelta());
      break;
    }
    case media::PIXEL_STORAGE_CPU:
      frame = VideoFrame::WrapExternalSharedMemory(
          media::PIXEL_FORMAT_I420, frame_format.frame_size,
          gfx::Rect(frame_format.frame_size), frame_format.frame_size,
          reinterpret_cast<uint8_t*>(buffer->data()),
          VideoFrame::AllocationSize(media::PIXEL_FORMAT_I420,
                                     frame_format.frame_size),
          base::SharedMemory::NULLHandle(), 0u, base::TimeDelta());
      break;
  }
  if (!frame)
    return;
  frame->metadata()->SetDouble(media::VideoFrameMetadata::FRAME_RATE,
                               frame_format.frame_rate);
  OnIncomingCapturedVideoFrame(std::move(buffer), frame, timestamp);
}

void VideoCaptureDeviceClient::OnIncomingCapturedVideoFrame(
    std::unique_ptr<Buffer> buffer,
    const scoped_refptr<VideoFrame>& frame,
    const base::TimeTicks& timestamp) {
  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(
          &VideoCaptureController::DoIncomingCapturedVideoFrameOnIOThread,
          controller_,
          base::Passed(&buffer),
          frame,
          timestamp));
}

std::unique_ptr<media::VideoCaptureDevice::Client::Buffer>
VideoCaptureDeviceClient::ResurrectLastOutputBuffer(
    const gfx::Size& dimensions,
    media::VideoPixelFormat format,
    media::VideoPixelStorage storage) {
  const int buffer_id =
      buffer_pool_->ResurrectLastForProducer(dimensions, format, storage);
  if (buffer_id == VideoCaptureBufferPool::kInvalidId)
    return nullptr;
  return base::WrapUnique<Buffer>(
      new AutoReleaseBuffer(buffer_pool_, buffer_id));
}

void VideoCaptureDeviceClient::OnError(
    const tracked_objects::Location& from_here,
    const std::string& reason) {
  const std::string log_message = base::StringPrintf(
      "error@ %s, %s, OS message: %s", from_here.ToString().c_str(),
      reason.c_str(),
      logging::SystemErrorCodeToString(logging::GetLastSystemErrorCode())
          .c_str());
  DLOG(ERROR) << log_message;
  OnLog(log_message);
  BrowserThread::PostTask(BrowserThread::IO,
      FROM_HERE,
      base::Bind(&VideoCaptureController::DoErrorOnIOThread, controller_));
}

void VideoCaptureDeviceClient::OnLog(
    const std::string& message) {
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&VideoCaptureController::DoLogOnIOThread,
                                     controller_, message));
}

double VideoCaptureDeviceClient::GetBufferPoolUtilization() const {
  // VideoCaptureBufferPool::GetBufferPoolUtilization() is thread-safe.
  return buffer_pool_->GetBufferPoolUtilization();
}

std::unique_ptr<media::VideoCaptureDevice::Client::Buffer>
VideoCaptureDeviceClient::ReserveI420OutputBuffer(
    const gfx::Size& dimensions,
    media::VideoPixelStorage storage,
    uint8_t** y_plane_data,
    uint8_t** u_plane_data,
    uint8_t** v_plane_data) {
  DCHECK(storage == media::PIXEL_STORAGE_GPUMEMORYBUFFER ||
         storage == media::PIXEL_STORAGE_CPU);
  DCHECK(dimensions.height());
  DCHECK(dimensions.width());

  const media::VideoPixelFormat format = media::PIXEL_FORMAT_I420;
  std::unique_ptr<Buffer> buffer(
      ReserveOutputBuffer(dimensions, media::PIXEL_FORMAT_I420, storage));
  if (!buffer)
    return std::unique_ptr<Buffer>();

  switch (storage) {
    case media::PIXEL_STORAGE_CPU:
      // TODO(emircan): See http://crbug.com/521068, move this pointer
      // arithmetic inside Buffer::data() when this bug is resolved.
      *y_plane_data = reinterpret_cast<uint8_t*>(buffer->data());
      *u_plane_data =
          *y_plane_data +
          VideoFrame::PlaneSize(format, VideoFrame::kYPlane, dimensions)
              .GetArea();
      *v_plane_data =
          *u_plane_data +
          VideoFrame::PlaneSize(format, VideoFrame::kUPlane, dimensions)
              .GetArea();
      return buffer;
    case media::PIXEL_STORAGE_GPUMEMORYBUFFER:
      *y_plane_data =
          reinterpret_cast<uint8_t*>(buffer->data(VideoFrame::kYPlane));
      *u_plane_data =
          reinterpret_cast<uint8_t*>(buffer->data(VideoFrame::kUPlane));
      *v_plane_data =
          reinterpret_cast<uint8_t*>(buffer->data(VideoFrame::kVPlane));
      return buffer;
  }
  NOTREACHED();
  return std::unique_ptr<Buffer>();
}

}  // namespace content