text:
namespace content {

SpeechRecognitionAudioSink::SpeechRecognitionAudioSink(
    const blink::WebMediaStreamTrack& track,
    const media::AudioParameters& params,
    const base::SharedMemoryHandle memory,
    scoped_ptr<base::SyncSocket> socket,
    const OnStoppedCB& on_stopped_cb)
    : track_(track),
      shared_memory_(memory, false),
      socket_(socket.Pass()),
      output_params_(params),
      track_stopped_(false),
      buffer_index_(0),
      on_stopped_cb_(on_stopped_cb) {
  DCHECK(socket_.get());
  DCHECK(main_render_thread_checker_.CalledOnValidThread());
  DCHECK(params.IsValid());
  DCHECK(IsSupportedTrack(track));
  const size_t kSharedMemorySize = sizeof(media::AudioInputBufferParameters) +
                                   media::AudioBus::CalculateMemorySize(params);
  CHECK(shared_memory_.Map(kSharedMemorySize));

  media::AudioInputBuffer* buffer =
      static_cast<media::AudioInputBuffer*>(shared_memory_.memory());

  // The peer must manage their own counter and reset it to 0.
  DCHECK_EQ(0U, buffer->params.size);
  output_bus_ = media::AudioBus::WrapMemory(params, buffer->audio);

  // Connect this audio sink to the track
  MediaStreamAudioSink::AddToAudioTrack(this, track_);
}

SpeechRecognitionAudioSink::~SpeechRecognitionAudioSink() {
  DCHECK(main_render_thread_checker_.CalledOnValidThread());
  if (audio_converter_.get())
    audio_converter_->RemoveInput(this);

  // Notify the track before this sink goes away.
  if (!track_stopped_)
    MediaStreamAudioSink::RemoveFromAudioTrack(this, track_);
}

// static
bool SpeechRecognitionAudioSink::IsSupportedTrack(
    const blink::WebMediaStreamTrack& track) {
  if (track.source().type() != blink::WebMediaStreamSource::TypeAudio)
    return false;

  MediaStreamAudioSource* native_source =
      static_cast<MediaStreamAudioSource*>(track.source().extraData());
  if (!native_source)
    return false;

  const StreamDeviceInfo& device_info = native_source->device_info();
  // Purposely only support tracks from an audio device. Dissallow WebAudio.
  return (device_info.device.type == content::MEDIA_DEVICE_AUDIO_CAPTURE);
}

void SpeechRecognitionAudioSink::OnSetFormat(
    const media::AudioParameters& input_params) {
  DCHECK(input_params.IsValid());
  DCHECK_LE(
      input_params.frames_per_buffer() * 1000 / input_params.sample_rate(),
      output_params_.frames_per_buffer() * 1000 / output_params_.sample_rate());

  // Detach the thread here because it will be a new capture thread
  // calling OnSetFormat() and OnData() if the source is restarted.
  capture_thread_checker_.DetachFromThread();

  input_params_ = input_params;
  fifo_buffer_size_ =
      std::ceil(output_params_.frames_per_buffer() *
                static_cast<double>(input_params_.sample_rate()) /
                    output_params_.sample_rate());
  DCHECK_GE(fifo_buffer_size_, input_params_.frames_per_buffer());

  // Allows for some delays on the peer.
  static const int kNumberOfBuffersInFifo = 2;
  int frames_in_fifo = kNumberOfBuffersInFifo * fifo_buffer_size_;
  fifo_.reset(new media::AudioFifo(input_params.channels(), frames_in_fifo));

  // Create the audio converter with |disable_fifo| as false so that the
  // converter will request input_params.frames_per_buffer() each time.
  // This will not increase the complexity as there is only one client to
  // the converter.
  audio_converter_.reset(
      new media::AudioConverter(input_params, output_params_, false));
  audio_converter_->AddInput(this);
}

void SpeechRecognitionAudioSink::OnReadyStateChanged(
    blink::WebMediaStreamSource::ReadyState state) {
  DCHECK(main_render_thread_checker_.CalledOnValidThread());
  DCHECK(!track_stopped_);

  if (state == blink::WebMediaStreamSource::ReadyStateEnded) {
    track_stopped_ = true;

    if (!on_stopped_cb_.is_null())
      on_stopped_cb_.Run();
  }
}

void SpeechRecognitionAudioSink::OnData(
    const media::AudioBus& audio_bus,
    base::TimeTicks estimated_capture_time) {
  DCHECK(capture_thread_checker_.CalledOnValidThread());
  DCHECK_EQ(audio_bus.frames(), input_params_.frames_per_buffer());
  DCHECK_EQ(audio_bus.channels(), input_params_.channels());
  if (fifo_->frames() + audio_bus.frames() > fifo_->max_frames()) {
    // This would indicate a serious issue with the browser process or the
    // SyncSocket and/or SharedMemory. We drop any previous buffers and try to
    // recover by resuming where the peer left of.
    DLOG(ERROR) << "Audio FIFO overflow";
    fifo_->Clear();
    buffer_index_ = GetAudioInputBuffer()->params.size;
  }

  fifo_->Push(&audio_bus);
  // Wait for FIFO to have at least |fifo_buffer_size_| frames ready.
  if (fifo_->frames() < fifo_buffer_size_)
    return;

  // Make sure the previous output buffer was consumed by the peer before we
  // send the next buffer.
  // The peer must write to it (incrementing by 1) once the the buffer was
  // consumed. This is intentional not to block this audio capturing thread.
  if (buffer_index_ != GetAudioInputBuffer()->params.size) {
    DVLOG(1) << "Buffer synchronization lag";
    return;
  }

  audio_converter_->Convert(output_bus_.get());

  // Notify peer to consume buffer |buffer_index_| on |output_bus_|.
  const size_t bytes_sent =
      socket_->Send(&buffer_index_, sizeof(buffer_index_));
  if (bytes_sent != sizeof(buffer_index_)) {
    // The send ocasionally fails if the user changes their input audio device.
    DVLOG(1) << "Failed sending buffer index to peer";
    // We have discarded this buffer, but could still recover on the next one.
    return;
  }

  // Count the sent buffer. We expect the peer to do the same on their end.
  ++buffer_index_;
}

double SpeechRecognitionAudioSink::ProvideInput(media::AudioBus* audio_bus,
                                                base::TimeDelta buffer_delay) {
  DCHECK(capture_thread_checker_.CalledOnValidThread());
  if (fifo_->frames() >= audio_bus->frames())
    fifo_->Consume(audio_bus, 0, audio_bus->frames());
  else
    audio_bus->Zero();

  // Return volume greater than zero to indicate we have more data.
  return 1.0;
}

media::AudioInputBuffer*
SpeechRecognitionAudioSink::GetAudioInputBuffer() const {
  DCHECK(capture_thread_checker_.CalledOnValidThread());
  DCHECK(shared_memory_.memory());
  return static_cast<media::AudioInputBuffer*>(shared_memory_.memory());
}

}  // namespace content


text:
package org.apache.myfaces.trinidadinternal.renderkit;

import java.awt.Color;

import java.beans.IntrospectionException;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.el.VariableResolver;

import org.apache.myfaces.trinidad.logging.TrinidadLogger;
import org.apache.myfaces.trinidad.model.ChartModel;
import org.apache.myfaces.trinidad.model.ChildPropertyTreeModel;
import org.apache.myfaces.trinidad.model.DefaultBoundedRangeModel;
import org.apache.myfaces.trinidad.model.ProcessMenuModel;
import org.apache.myfaces.trinidad.model.RowKeySet;
import org.apache.myfaces.trinidad.model.RowKeySetImpl;
import org.apache.myfaces.trinidad.model.RowKeySetTreeImpl;
import org.apache.myfaces.trinidad.model.TreeModel;

import org.apache.myfaces.trinidadinternal.renderkit.testData.Person;

public class MVariableResolver extends VariableResolver
{
  @Override
  public Object resolveVariable(FacesContext context, String name)
  {
    Object o =  context.getExternalContext().getRequestMap().get(name);
    if (o != null)
      return o;

    if ("pageList".equals(name))
    {
      try
      {
        if (_pageList == null)
        {
          List<PageImpl> al = _createPageList();
          _pageList = new MenuModelImpl(al, "viewId", "/1.jspx");
        }

        return _pageList;
      }
      catch(IntrospectionException e)
      {
        _LOG.severe(e);
        return null;
      }
    }
    else if ("menu".equals(name))
    {
      try
      {
        if (_menu == null)
        {
          List<PageImpl> al = _createPageList();
          TreeModel treeModel = new ChildPropertyTreeModel(al, "children");
          _menu = new MenuModelImpl(treeModel, "viewId", "/4.jspx");
        }

        return _menu;
      }
      catch(IntrospectionException e)
      {
        _LOG.severe(e);
        return null;
      }
    }
    else if ("navigationpath".equals(name))
    {
      try
      {
        if (_navigationpath == null)
        {
          List<PageImpl> al = _createPageList();
          TreeModel treeModel = new ChildPropertyTreeModel(al, "children");
          _navigationpath = new MenuModelImpl(treeModel, "viewId", "/7.jspx");
        }

        return _navigationpath;
      }
      catch(IntrospectionException e)
      {
        _LOG.severe(e);
        return null;
      }
    }
    else if ("simpleList".equals(name))
    {
      if (_simpleList == null)
      {
        _simpleList = new ArrayList<Map<String, Object>>();
        _simpleList.add(_createHashMap("First", 1));
        _simpleList.add(_createHashMap("Second", 2));
        _simpleList.add(_createHashMap("Three", 3));
        _simpleList.add(_createHashMap("Four", 4));
        _simpleList.add(_createHashMap("Five", 5));
        _simpleList.add(_createHashMap("Six", 6));
      }

      return _simpleList;
    }
    else if ("numberList".equals(name))
    {
      // A simple out-of-order list of numeric strings,
      // for use in the selectManyListbox test
      List<String> list = new ArrayList<String>(2);
      list.add("8");
      list.add("2");
      return list;
    }
    else if("iteratorList".equals(name))
    {
      if (_iteratorList == null)
      {
        // -= Simon Lessard =-
        // FIXME: _iteratorList will contains 5 null value since
        //        put return the value before the insertion at
        //        specified key.
        // Ref: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#put(K, V)
        _iteratorList = new ArrayList<String>();
        _iteratorList.add(new HashMap<String, String>().put("data","One"));
        _iteratorList.add(new HashMap<String, String>().put("data","Two"));
        _iteratorList.add(new HashMap<String, String>().put("data","Three"));
        _iteratorList.add(new HashMap<String, String>().put("data","Four"));
        _iteratorList.add(new HashMap<String, String>().put("data","Five"));
      }

      return _iteratorList;
    }
    else if("colorList".equals(name))
    {
      ArrayList<Color> colorList = new ArrayList<Color>();
      colorList.add(new Color(255, 0, 0));
      colorList.add(new Color(0, 0, 255));
      colorList.add(new Color(255, 255, 0));
      colorList.add(new Color(0, 255, 0));
      return colorList;
    }
    else if("treeModel".equals(name))
    {
      if (_treeModel == null)
      {
        Person john = new Person("John Smith");
        Person kim = new Person("Kim Smith");
        Person tom = new Person("Tom Smith");
        Person zoe = new Person("Zoe Smith");
        Person ira = new Person("Ira Wickrememsinghe");
        Person mallika = new Person("Mallika Wickremesinghe");

        john.getKids().add(kim);
        john.getKids().add(tom);
        tom.getKids().add(zoe);
        ira.getKids().add(mallika);

        List<Person> people = new ArrayList<Person>();
        people.add(john);
        people.add(ira);

        _treeModel = new ChildPropertyTreeModel(people, "kids");
      }

      return _treeModel;
    }
    else if("pathSet".equals(name))
    {
      if (_treeState == null)
      {
        _treeState = new RowKeySetTreeImpl(true);

      }
      return _treeState;
    }
    else if("disclosureState".equals(name))
    {
      if(_disclosureState == null)
        _disclosureState = new RowKeySetImpl(true);
      return _disclosureState;
    }
    else if("arrayString".equals(name))
    {
      String stringArray[] = {"id1","id2","id3"};
      return stringArray;
    }
    else if("rangeModel".equals(name))
    {
      return new DefaultBoundedRangeModel(2,4);
    }
    else if ("bigList".equals(name))
    {
      return new BigList();
    }
    else if("rangeChoiceBarModel".equals(name))
    {
      return new RangeChoiceBarModelImpl();
    }
    else if ("oldDate".equals(name))
    {
      // FIXME: Should be able to use Calendar for non deprecated calls.
      return new Date(70, 5, 10);
    }
    else if ("midDate".equals(name))
    {
      // FIXME: Should be able to use Calendar for non deprecated calls.
      return new Date(105, 6, 27);
    }
    else if ("newDate".equals(name))
    {
      // FIXME: Should be able to use Calendar for non deprecated calls.
      return new Date(130, 0, 5);
    }
    else if ("currTime".equals(name))
    {
      return new Date(109,0,1);
    }
    else if("simpleDocument".equals(name))
    {
      return "First paragraph followed by \\r\r" +
             "Second paragraph followed by \\n\n" +
             "Third paragraph followed by \\n\\r\n\r" +
             "Fourth paragraph";
    }
    else if("chartModel".equals(name))
    {
      return new MyChartModel();
    }
    return null;
  }

  public class MenuModelImpl extends ProcessMenuModel
  {
    public MenuModelImpl(
      Object instance,
      String viewIdProperty,
      String currentViewId
    )throws IntrospectionException
    {
      super(instance, viewIdProperty, null);
      _currentViewId = currentViewId;
    }

    @Override
    protected String getCurrentViewId()
    {
      return _currentViewId;
    }

    private String _currentViewId;
  }

  static private Map<String, Object> _createHashMap(String s, int i)
  {
    HashMap<String, Object> m = new HashMap<String, Object>();
    m.put("string", s);
    m.put("int", new Integer(i));
    return m;
  }

  public static class PageImpl
  {
    public PageImpl(String viewId, String label, boolean disabled)
    {
      _viewId = viewId;
      _label = label;
      _disabled = disabled;
    }

    public void setViewId(String viewId)
    {
      _viewId = viewId;
    }

    public void setLabel(String label)
    {
      _label = label;
    }

    public void setDisabled(boolean disabled)
    {
      _disabled = disabled;
    }

    public void setChildren(List<Object> children)
    {
      _children = children;
    }

    public String getViewId()
    {
      return _viewId;
    }

    public String getLabel()
    {
      return _label;
    }

    public boolean isDisabled()
    {
      return _disabled;
    }

    public List<Object> getChildren()
    {
      return _children;
    }

    private String _viewId;
    private String _label;
    private boolean _disabled;
    private List<Object> _children;
  }

  public static class BigList extends AbstractList<Integer>
  {
    @Override
    public int size()
    {
      return 10000;
    }

    @Override
    public Integer get(int i)
    {
      return new Integer(i);
    }
  }

  private static List<PageImpl> _createPageList()
  {
    ArrayList<PageImpl> al = new ArrayList<PageImpl>();
    PageImpl page1 = new PageImpl("/1.jspx", "First", false);

    al.add(page1);
    al.add(new PageImpl("/2.jspx", "Second", false));
    al.add(new PageImpl("/3.jspx", "Third", false));

    PageImpl page5 = new PageImpl("/5.jspx", "fifth", false);
    ArrayList<Object> p1 = new ArrayList<Object>();
    p1.add(new PageImpl("/4.jspx", "fourth", false));
    p1.add(page5);

    ArrayList<Object> p2 = new ArrayList<Object>();
    p2.add(new PageImpl("/6.jspx", "sixth", false));
    p2.add(new PageImpl("/7.jspx", "seventh", false));

    page1.setChildren(p1);
    page5.setChildren(p2);

    return al;
  }

  private static class RangeChoiceBarModelImpl
  {
    private List<String> _names;
    private int _start;
    private int _end;

    public RangeChoiceBarModelImpl()
    {
      _names = new ArrayList<String>();
      _names.add("vox");
      _names.add("populi");
      _names.add("en");
      _names.add("vogue");
    }
    public void setNames(List<String> names)
    {
      this._names = names;
    }

    public List<String> getNames()
    {
      return _names;
    }

    public void setStart(int start)
    {
      this._start = start;
    }

    public int getStart()
    {
      return _start;
    }

    public void setEnd(int end)
    {
      this._end = end;
    }

    public int getEnd()
    {
      return _end;
    }
  }

  private class MyChartModel extends ChartModel
  {
    @Override
    public List<String> getSeriesLabels()
    {
      return _seriesLabels;
    }

    @Override
    public List<String> getGroupLabels()
    {
      return _groupLabels;
    }

    @Override
    public List<List<Double>> getXValues()
    {
      return _chartXValues;
    }

    @Override
    public List<List<Double>> getYValues()
    {
      return _chartYValues;
    }

    @Override
    public Double getMaxYValue()
    {
      return 500000.0;
    }

    @Override
    public Double getMinYValue()
    {
      return 0.0;
    }

    @Override
    public Double getMaxXValue()
    {
      return 10.0;
    }

    @Override
    public Double getMinXValue()
    {
      return 6.0;
    }

    @Override
    public String getTitle()
    {
      return "Title";
    }

    @Override
    public String getSubTitle()
    {
      return "SubTitle";
    }

    @Override
    public String getFootNote()
    {
      return "FootNote";
    }

    private final List<String> _groupLabels =
      Arrays.asList(new String[]{"June", "July", "August", "September","October"});

    private final List<String> _seriesLabels =
      Arrays.asList(new String[]{"Previous", "Target", "Actual"});

    private final ArrayList<List<Double>> _chartYValues;
    private final ArrayList<List<Double>> _chartXValues;
    {
      _chartYValues = new ArrayList<List<Double>>();
      _chartYValues.add(Arrays.asList(new Double[]{135235., 155535., 141725.}));
      _chartYValues.add(Arrays.asList(new Double[]{106765., 131725., 127868.}));
      _chartYValues.add(Arrays.asList(new Double[]{108456., 119326., 139326.}));
      _chartYValues.add(Arrays.asList(new Double[]{136765., 147265., 184349.}));
      _chartYValues.add(Arrays.asList(new Double[]{107868., 113968., 174349.}));

      _chartXValues = new ArrayList<List<Double>>();
      _chartXValues.add(Arrays.asList(new Double[]{6.1, 6.3, 6.5}));
      _chartXValues.add(Arrays.asList(new Double[]{6.8, 7.1, 7.3}));
      _chartXValues.add(Arrays.asList(new Double[]{7.6, 7.8, 8.0}));
      _chartXValues.add(Arrays.asList(new Double[]{8.25, 8.55, 8.78}));
      _chartXValues.add(Arrays.asList(new Double[]{9.23, 9.48, 9.88}));
    }
  }
  private MenuModelImpl _pageList;
  private MenuModelImpl _menu;
  private MenuModelImpl _navigationpath;

  private List<String> _iteratorList;
  private List<Map<String, Object>> _simpleList;

  private ChildPropertyTreeModel _treeModel;

  private RowKeySet _treeState = null;
  private RowKeySet _disclosureState = null;

  private static final TrinidadLogger _LOG =
    TrinidadLogger.createTrinidadLogger(MVariableResolver.class);
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.storm.starter;

import org.apache.storm.starter.bolt.IntermediateRankingsBolt;
import org.apache.storm.starter.bolt.RollingCountBolt;
import org.apache.storm.starter.bolt.TotalRankingsBolt;
import org.apache.storm.testing.TestWordSpout;
import org.apache.storm.topology.ConfigurableTopology;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.tuple.Fields;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This topology does a continuous computation of the top N words that the
 * topology has seen in terms of cardinality. The top N computation is done in a
 * completely scalable way, and a similar approach could be used to compute
 * things like trending topics or trending images on Twitter.
 */
public class RollingTopWords extends ConfigurableTopology {

    private static final Logger LOG = LoggerFactory.getLogger(RollingTopWords.class);
    private static final int TOP_N = 5;

    private RollingTopWords() {
    }

    public static void main(String[] args) throws Exception {
        ConfigurableTopology.start(new RollingTopWords(), args);
    }

    /**
     * Submits (runs) the topology.
     *
     *
Usage: "RollingTopWords [topology-name] [-local]"
     *
     *
By default, the topology is run locally under the name
     * "slidingWindowCounts".
     *
     *
Examples:
     * ```
     * # Runs in remote/cluster mode, with topology name "production-topology"
     * $ storm jar storm-starter-jar-with-dependencies.jar org.apache.storm.starter.RollingTopWords production-topology ```
     *
     * @param args
     *          First positional argument (optional) is topology name, second
     *          positional argument (optional) defines whether to run the topology
     *          locally ("-local") or remotely, i.e. on a real cluster.
     */
    @Override
    protected int run(String[] args) {
        String topologyName = "slidingWindowCounts";
        if (args.length >= 1) {
            topologyName = args[0];
        }
        TopologyBuilder builder = new TopologyBuilder();
        String spoutId = "wordGenerator";
        String counterId = "counter";
        String intermediateRankerId = "intermediateRanker";
        builder.setSpout(spoutId, new TestWordSpout(), 5);
        builder.setBolt(counterId, new RollingCountBolt(9, 3), 4).fieldsGrouping(spoutId, new Fields("word"));
        builder.setBolt(intermediateRankerId, new IntermediateRankingsBolt(TOP_N), 4).fieldsGrouping(counterId,
                                                                                new Fields("obj"));
        String totalRankerId = "finalRanker";
        builder.setBolt(totalRankerId, new TotalRankingsBolt(TOP_N)).globalGrouping(intermediateRankerId);
        LOG.info("Topology name: " + topologyName);

        return submit(topologyName, conf, builder);
    }
}


text:
class SearchTermsData;

// A helper class that watches for changes to the base URL of the default search
// engine. Typically this changes when a different DSE is selected. For Google,
// it can also change without changing the DSE, when the Google base URL is
// updated. This can happen in the case of country (i.e. TLD) changes.
class SearchEngineBaseURLTracker : public TemplateURLServiceObserver {
 public:
  enum class ChangeReason {
    DEFAULT_SEARCH_PROVIDER,
    GOOGLE_BASE_URL,
  };

  using BaseURLChangedCallback = base::RepeatingCallback<void(ChangeReason)>;

  SearchEngineBaseURLTracker(
      TemplateURLService* template_url_service,
      std::unique_ptr<SearchTermsData> search_terms_data,
      const BaseURLChangedCallback& base_url_changed_callback);

  SearchEngineBaseURLTracker(const SearchEngineBaseURLTracker&) = delete;
  SearchEngineBaseURLTracker& operator=(const SearchEngineBaseURLTracker&) =
      delete;

  ~SearchEngineBaseURLTracker() override;

 private:
  // TemplateURLServiceObserver implementation.
  void OnTemplateURLServiceChanged() override;

  // Returns true if the base URL of the current search engine is Google.
  bool HasGoogleBaseURL();

  raw_ptr<TemplateURLService> template_url_service_;
  std::unique_ptr<SearchTermsData> search_terms_data_;
  BaseURLChangedCallback base_url_changed_callback_;

  base::ScopedObservation<TemplateURLService, TemplateURLServiceObserver>
      observation_{this};

  // Used to check whether notifications from TemplateURLService indicate a
  // change that affects the default search provider.
  GURL previous_google_base_url_;
  absl::optional<TemplateURLData> previous_default_search_provider_data_;
};

#endif  // CHROME_BROWSER_SEARCH_SEARCH_ENGINE_BASE_URL_TRACKER_H_


text:
package com.dji.DjiPocketFly;

import android.app.Application;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import dji.common.error.DJIError;
import dji.common.error.DJISDKError;
import dji.sdk.base.BaseComponent;
import dji.sdk.base.BaseProduct;
import dji.sdk.camera.Camera;
import dji.sdk.products.Aircraft;
import dji.sdk.products.HandHeld;
import dji.sdk.sdkmanager.DJISDKManager;

public class DjiPocketFlyApplication extends Application{

    public static final String FLAG_CONNECTION_CHANGE = "fpv_connection_change";

    private static BaseProduct mProduct;

    public Handler mHandler;

    public static synchronized BaseProduct getProductInstance() {
        if (null == mProduct) {
            mProduct = DJISDKManager.getInstance().getProduct();
        }
        return mProduct;
    }

    public static boolean isAircraftConnected() {
        return getProductInstance() != null && getProductInstance() instanceof Aircraft;
    }

    public static boolean isHandHeldConnected() {
        return getProductInstance() != null && getProductInstance() instanceof HandHeld;
    }

    public static synchronized Camera getCameraInstance() {

        if (getProductInstance() == null) return null;

        Camera camera = null;

        if (getProductInstance() instanceof Aircraft){
            camera = ((Aircraft) getProductInstance()).getCamera();

        } else if (getProductInstance() instanceof HandHeld) {
            camera = ((HandHeld) getProductInstance()).getCamera();
        }

        return camera;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler(Looper.getMainLooper());

        // On initialise le sdk pour l'utilisation des services
        DJISDKManager.getInstance().registerApp(this, mDJISDKManagerCallback);
    }

    private DJISDKManager.SDKManagerCallback mDJISDKManagerCallback = new DJISDKManager.SDKManagerCallback() {

        //Listens to the SDK registration result
        @Override
        public void onRegister(DJIError error) {

            if(error == DJISDKError.REGISTRATION_SUCCESS) {

                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Validation de l'api Key", Toast.LENGTH_LONG).show();

                    }
                });

                DJISDKManager.getInstance().startConnectionToProduct(); // Initialisation de la entre l'application et le drone.

            } else {

                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Echec de la validation de l'api, veuillez verifier votre réseau cellulaire", Toast.LENGTH_LONG).show();
                    }
                });

            }
            Log.e("TAG", error.toString());
        }

        // Verification du changement de la connection du drone ou changement du drone
        @Override
        public void onProductChange(BaseProduct oldProduct, BaseProduct newProduct) {

            mProduct = newProduct;
            if(mProduct != null) {
                mProduct.setBaseProductListener(mDJIBaseProductListener);
            }
            notifyStatusChange(); // On notifie le changement en appelant la fonction
        }
    };

    private BaseProduct.BaseProductListener mDJIBaseProductListener = new BaseProduct.BaseProductListener() {

        @Override
        public void onComponentChange(BaseProduct.ComponentKey key, BaseComponent oldComponent, BaseComponent newComponent) {

            if(newComponent != null) {
                newComponent.setComponentListener(mDJIComponentListener);
            }
            notifyStatusChange(); // On notifie le changement en appelant la fonction
        }

        @Override
        public void onConnectivityChange(boolean isConnected) {

            notifyStatusChange();// On notifie le changement en appelant la fonction
        }

    };

    private BaseComponent.ComponentListener mDJIComponentListener = new BaseComponent.ComponentListener() {

        @Override
        public void onConnectivityChange(boolean isConnected) {
            notifyStatusChange();
        }

    };

    private void notifyStatusChange() {
        mHandler.removeCallbacks(updateRunnable);
        mHandler.postDelayed(updateRunnable, 500);
    }

    private Runnable updateRunnable = new Runnable() {

        @Override
        public void run() {
            Intent intent = new Intent(FLAG_CONNECTION_CHANGE);
            sendBroadcast(intent);
        }
    };

}


text:
@extends('layouts.app')

@section('content')

				<form method="post">
					<input type="hidden" name="_token" value="{{ csrf_token() }}">

						<input type="text" name="city" placeholder="Arusha, Tanzania" class="form-control">

							<button type="submit" class="btn btn-primary">Display output</button>

				</form>

Text message 1

						<?= nl2br($one) ?>

Text message 2

						<?= nl2br($two); ?>

@endsection


text:
package org.ppwcode.vernacular.persistence.IV;

import javax.persistence.Column;
import javax.persistence.Version;
import java.io.Serializable;

import static org.ppwcode.vernacular.semantics.VII.util.CloneHelpers.safeReference;

/**
 * A partial implementation of the interface {@link VersionedPersistentBean}.
 *
 * @author    Ruben Vandeginste
 * @author    Jan Dockx
 * @author    PeopleWare n.v.
 */
@SuppressWarnings("WeakerAccess")
public abstract class AbstractVersionedPersistentBean<_Id_ extends Serializable, _Version_ extends Serializable>
    extends AbstractPersistentBean<_Id_>
    implements VersionedPersistentBean<_Id_, _Version_> {

  /*<property name="version">*/
  //------------------------------------------------------------------

  /*
    @Basic(init = @Expression("null"))
  */
  public final _Version_ getPersistenceVersion() {
    return safeReference($persistenceVersion);
  }

  /**
   * Provided to make testing possible.
   */
  protected void setPersistenceVersion(_Version_ persistenceVersion) {
    $persistenceVersion = persistenceVersion;
  }

  @Version
  @Column(name="persistenceVersion")
  private _Version_ $persistenceVersion;

  /*</property>*/

}


text:
package parquet.filter;

import parquet.column.ColumnReader;
import java.util.Arrays;
import static parquet.Preconditions.checkNotNull;

/**
 * Record filter which applies the supplied predicate to the specified column.
 */
public final class ColumnRecordFilter implements RecordFilter {

  private final ColumnReader filterOnColumn;
  private final ColumnPredicates.Predicate filterPredicate;

  /**
   * Factory method for record filter which applies the supplied predicate to the specified column.
   * Note that if searching for a repeated sub-attribute it will only ever match against the
   * first instance of it in the object.
   *
   * @param columnPath Dot separated path specifier, e.g. "engine.capacity"
   * @param predicate Should call getBinary etc. and check the value
   */
  public static final UnboundRecordFilter column(final String columnPath,
                                                 final ColumnPredicates.Predicate predicate) {
    checkNotNull(columnPath, "columnPath");
    checkNotNull(predicate,  "predicate");
    return new UnboundRecordFilter() {
      final String[] filterPath = columnPath.split("\\.");
      @Override
      public RecordFilter bind(Iterable<ColumnReader> readers) {
        for (ColumnReader reader : readers) {
          if ( Arrays.equals( reader.getDescriptor().getPath(), filterPath)) {
            return new ColumnRecordFilter(reader, predicate);
          }
        }
        throw new IllegalArgumentException( "Column " + columnPath + " does not exist.");
      }
    };
  }

  /**
   * Private constructor. Use column() instead.
   */
  private ColumnRecordFilter(ColumnReader filterOnColumn, ColumnPredicates.Predicate filterPredicate) {
    this.filterOnColumn  = filterOnColumn;
    this.filterPredicate = filterPredicate;
  }

  /**
   * @return true if the current value for the column reader matches the predicate.
   */
  @Override
  public boolean isMatch() {
    return filterPredicate.apply(filterOnColumn);
  }

}


text:
(function (root) {
    "use strict";

    var buster = root.buster || require("buster");
    var sinon = root.sinon || require("../../lib/sinon");
    var assert = buster.assert;
    var refute = buster.refute;

    buster.testCase("issues", {
        setUp: function () {
            this.sandbox = sinon.sandbox.create();
        },

        tearDown: function () {
            this.sandbox.restore();
        },

        "// #283": function () {
            function testSinonFakeTimersWith(interval, ticks) {
                var clock = sinon.useFakeTimers();

                var spy = sinon.spy();
                var id = setInterval(spy, interval);
                assert(!spy.calledOnce);
                clock.tick(ticks);
                assert(spy.calledOnce);

                clearInterval(id);
                clock.restore();
            }

            // FAILS
            testSinonFakeTimersWith(10, 101);

            // PASS
            testSinonFakeTimersWith(99, 101);

            // FAILS
            testSinonFakeTimersWith(100, 200);

            // PASS
            testSinonFakeTimersWith(199, 200);

            // FAILS
            testSinonFakeTimersWith(500, 1001);

            // PASS
            testSinonFakeTimersWith(1000, 1001);
        },

        "// #397": function () {
            var clock = sinon.useFakeTimers();

            var cb2 = sinon.spy();
            var cb1 = sinon.spy(function () {
                setTimeout(cb2, 0);
            });

            setTimeout(cb1, 0);

            clock.tick(10);
            assert(cb1.called);
            assert(!cb2.called);

            clock.tick(10);
            assert(cb2.called);

            clock.restore();
        },

        "#458": {
            "on node": {
                requiresSupportFor: {
                    process: typeof process !== "undefined"
                },

                "stub out fs.readFileSync": function () {
                    var fs = require("fs");
                    var testCase = this;

                    refute.exception(function () {
                        testCase.sandbox.stub(fs, "readFileSync");
                    });
                }
            }
        },

        "#624": {
            "//useFakeTimers should be idempotent": function () {
                // Issue #624 shows that useFakeTimers is not idempotent when it comes to
                // using Date.now
                // This test verifies that it's working, at least for Date.now
                var clock;

                clock = sinon.useFakeTimers(new Date("2014-12-29").getTime());
                assert.equals(clock.now, Date.now());

                clock = sinon.useFakeTimers(new Date("2015-12-15").getTime());
                assert.equals(clock.now, Date.now());

                clock = sinon.useFakeTimers(new Date("2015-1-5").getTime());
                assert.equals(clock.now, Date.now());
            }
        },

        "#852 - createStubInstance on intherited constructors": {
            "must not throw error": function () {
                var A = function () {};
                var B = function () {};

                B.prototype = Object.create(A.prototype);
                B.prototype.constructor = A;

                refute.exception(function () {
                    sinon.createStubInstance(B);
                });
            }
        },

        "#852(2) - createStubInstance should on same constructor": {
            "must be idempotent": function () {
                var A = function () {};
                refute.exception(function () {
                    sinon.createStubInstance(A);
                    sinon.createStubInstance(A);
                });
            }
        }
    });
}(this));


text:
A jquery plugin to change colors of a svg file

##UNDER CONSTRUCTION


text:
import { Component, AfterViewInit, ElementRef, Input, Output, EventEmitter, Renderer2, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
/* tslint:disable-next-line */
let hljs: any = require('highlight.js/lib');

@Component({
  selector: 'td-highlight',
  styleUrls: ['./highlight.component.scss'],
  templateUrl: './highlight.component.html',
})
export class TdHighlightComponent implements AfterViewInit {

  private _content: string;

  /**
   * content?: string
   *
   * Code content to be parsed as highlighted html.
   * Used to load data dynamically.
   *
   * e.g. `.html`, `.ts` , etc.
   */
  @Input('content')
  set content(content: string) {
    this._content = content;
    this._loadContent(this._content);
  }

  /**
   * lang?: string
   *
   * Language of the code content to be parsed as highlighted html.
   * Defaults to `typescript`
   *
   * e.g. `typescript`, `html` , etc.
   */
  @Input('lang') language: string = 'typescript';

  /**
   * contentReady?: function
   * Event emitted after the highlight content rendering is finished.
   */
  @Output('contentReady') onContentReady: EventEmitter<undefined> = new EventEmitter<undefined>();

  constructor(private _renderer: Renderer2,
              private _elementRef: ElementRef,
              private _domSanitizer: DomSanitizer) {}

  ngAfterViewInit(): void {
    if (!this.language) {
      throw new Error('Error: language attribute must be defined in TdHighlightComponent.');
    }
    if (!this._content) {
      this._loadContent((<HTMLElement>this._elementRef.nativeElement).textContent);
    }
  }
  /**
   * General method to parse a string of code into HTML Elements and load them into the container
   */
  private _loadContent(code: string): void {
    if (code && code.trim().length > 0) {
      // Clean container
      this._renderer.setProperty(this._elementRef.nativeElement, 'innerHTML', '');
      // Parse html string into actual HTML elements.
      let preElement: HTMLPreElement = this._elementFromString(this._render(code));
    }
    this.onContentReady.emit();
  }

  private _elementFromString(codeStr: string): HTMLPreElement {
    // Renderer2 doesnt have a parsing method, so we have to sanitize and use [innerHTML]
    // to parse the string into DOM element for now.
    const preElement: HTMLPreElement = this._renderer.createElement('pre');
    this._renderer.appendChild(this._elementRef.nativeElement, preElement);
    const codeElement: HTMLElement = this._renderer.createElement('code');
    this._renderer.appendChild(preElement, codeElement);
    // Set .highlight class into <code> element
    this._renderer.addClass(codeElement, 'highlight');
    codeElement.innerHTML = this._domSanitizer.sanitize(SecurityContext.HTML, codeStr);
    return preElement;
  }

  private _render(contents: string): string {
    // Trim leading and trailing newlines
    contents = contents.replace(/^(\s|\t)*\n+/g, '')
                       .replace(/(\s|\t)*\n+(\s|\t)*$/g, '');
    // Split markup by line characters
    let lines: string[] = contents.split('\n');

    // check how much indentation is used by the first actual code line
    let firstLineWhitespace: string = lines[0].match(/^(\s|\t)*/)[0];

    // Remove all indentation spaces so code can be parsed correctly
    let startingWhitespaceRegex: RegExp = new RegExp('^' + firstLineWhitespace);
    lines = lines.map(function(line: string): string {
      return line
        .replace('=""', '') // remove empty values
        .replace(startingWhitespaceRegex, '')
        .replace(/\s+$/, ''); // remove trailing white spaces
    });

    let codeToParse: string =  lines.join('\n')
    .replace(/\{ \{/gi, '{{').replace(/\} \}/gi, '}}')
    .replace(/</gi, '<').replace(/>/gi, '>');  // replace with < and > to render HTML in angular

    // Parse code with highlight.js depending on language
    let highlightedCode: any = hljs.highlight(this.language, codeToParse, true);
    highlightedCode.value = highlightedCode.value
      .replace(/=<span class="hljs-value">""<\/span>/gi, '')
      .replace('<head>', '')
      .replace('<head/>', '');
    return highlightedCode.value;
  }
}


text:
<?php

namespace Ivory\GoogleMapBundle\Templating;

use Ivory\GoogleMap\Helper\StaticMapHelper as BaseStaticMapHelper;
use Ivory\GoogleMap\Map;
use Symfony\Component\Templating\Helper\Helper;

/**
 * @author GeLo <geloen.eric@gmail.com>
 */
class StaticMapHelper extends Helper
{
    /**
     * @var BaseStaticMapHelper
     */
    private $staticMapHelper;

    /**
     * @param BaseStaticMapHelper $staticMapHelper
     */
    public function __construct(BaseStaticMapHelper $staticMapHelper)
    {
        $this->staticMapHelper = $staticMapHelper;
    }

    /**
     * @param Map $map
     *
     * @return string
     */
    public function render(Map $map)
    {
        return $this->staticMapHelper->render($map);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'ivory_google_map_static';
    }
}


text:
namespace RIAPP.MOD.binding {
    import elviewMOD = RIAPP.MOD.baseElView;
    import errMOD = RIAPP.MOD.errors;
    import utilsMOD = RIAPP.MOD.utils;
    import parserMOD = RIAPP.MOD.parser;

    binding._isBinding = (obj: any) => {
        return !!obj && obj instanceof Binding;
    };

    export const enum BINDING_MODE {
        OneTime = 0,
        OneWay = 1,
        TwoWay = 2,
        BackWay = 3
    }
    export var bindModeMap: { [name: string]: BINDING_MODE } = {};
    bindModeMap["OneTime"] = BINDING_MODE.OneTime;
    bindModeMap["OneWay"] = BINDING_MODE.OneWay;
    bindModeMap["TwoWay"] = BINDING_MODE.TwoWay;
    bindModeMap["BackWay"] = BINDING_MODE.BackWay;

    var global = RIAPP.global, base_utils = RIAPP.baseUtils, utils: utilsMOD.Utils, parser: parserMOD.Parser;
    global.addOnInitialize((s, args) => {
        utils = s.utils;
        parser = s.parser;
    });

    export interface IBindingOptions {
        mode?: BINDING_MODE;
        converterParam?: any;
        converter?: RIAPP.IConverter;
        targetPath: string;
        sourcePath?: string;
        target?: RIAPP.BaseObject;
        source?: any;
        isSourceFixed?: boolean;
    }

    interface IBindingState {
        source: any;
        target: any;
    }

    export function getBindingOptions(app: RIAPP.Application, bindInfo: IBindingInfo, defaultTarget: RIAPP.BaseObject, defaultSource: any) {
        var bindingOpts: IBindingOptions = {
            mode: BINDING_MODE.OneWay,
            converterParam: null,
            converter: null,
            targetPath: null,
            sourcePath: null,
            target: null,
            source: null,
            isSourceFixed: false
        };

        var fixedSource = bindInfo.source, fixedTarget = bindInfo.target;

        if (!bindInfo.sourcePath && !!bindInfo.to)
            bindingOpts.sourcePath = bindInfo.to;
        else if (!!bindInfo.sourcePath)
            bindingOpts.sourcePath = bindInfo.sourcePath;
        if (!!bindInfo.targetPath)
            bindingOpts.targetPath = bindInfo.targetPath;
        if (!!bindInfo.converterParam)
            bindingOpts.converterParam = bindInfo.converterParam;
        if (!!bindInfo.mode)
            bindingOpts.mode = bindModeMap[bindInfo.mode];

        if (!!bindInfo.converter) {
            if (utils.check.isString(bindInfo.converter))
                bindingOpts.converter = app.getConverter(bindInfo.converter);
            else
                bindingOpts.converter = bindInfo.converter;
        }

        if (!fixedTarget)
            bindingOpts.target = defaultTarget;
        else {
            if (utils.check.isString(fixedTarget)) {
                if (fixedTarget == 'this')
                    bindingOpts.target = defaultTarget;
                else {
                    //if no fixed target, then target evaluation starts from this app
                    bindingOpts.target = parser.resolveBindingSource(app, parser.getPathParts(fixedTarget));
                }
            }
            else
                bindingOpts.target = fixedTarget;
        }

        if (!fixedSource) {
            //if source is not supplied use defaultSource parameter as source
            bindingOpts.source = defaultSource;
        }
        else {
            bindingOpts.isSourceFixed = true;
            if (utils.check.isString(fixedSource)) {
                if (fixedSource == 'this') {
                    bindingOpts.source = defaultTarget;
                }
                else {
                    //source evaluation starts from this app
                    bindingOpts.source = parser.resolveBindingSource(app, parser.getPathParts(fixedSource));
                }
            }
            else
                bindingOpts.source = fixedSource;
        }

        return bindingOpts;
    }

    export class Binding extends RIAPP.BaseObject {
        private _state: IBindingState;
        private _mode: BINDING_MODE;
        private _converter: RIAPP.IConverter;
        private _converterParam: any;
        private _srcPath: string[];
        private _tgtPath: string[];
        private _isSourceFixed: boolean;
        private _pathItems: { [key: string]: BaseObject; };
        private _objId: string;
        private _ignoreSrcChange: boolean;
        private _ignoreTgtChange: boolean;
        private _sourceObj: any;
        private _targetObj: any;
        private _source: any;
        private _target: RIAPP.BaseObject;
        private _appName: string;

        constructor(options: IBindingOptions, appName?: string) {
            super();
            var opts: IBindingOptions = utils.extend(false, {
                target: null, source: null,
                targetPath: null, sourcePath: null, mode: BINDING_MODE.OneWay,
                converter: null, converterParam: null, isSourceFixed: false
            }, options);

            if (utils.check.isString(opts.mode)) {
                opts.mode = bindModeMap[opts.mode];
            }

            if (!utils.check.isString(opts.targetPath)) {
                if (RIAPP.DebugLevel == RIAPP.DEBUG_LEVEL.HIGH) {
                    RIAPP.startDebugger();
                }
                throw new Error(base_utils.format(RIAPP.ERRS.ERR_BIND_TGTPATH_INVALID, opts.targetPath));
            }

            if (utils.check.isUndefined(opts.mode)) {
                if (RIAPP.DebugLevel == RIAPP.DEBUG_LEVEL.HIGH) {
                    RIAPP.startDebugger();
                }
                throw new Error(base_utils.format(RIAPP.ERRS.ERR_BIND_MODE_INVALID, opts.mode));
            }

            if (!opts.target) {
                throw new Error(RIAPP.ERRS.ERR_BIND_TARGET_EMPTY);
            }

            if (!utils.check.isBaseObj(opts.target)) {
                throw new Error(RIAPP.ERRS.ERR_BIND_TARGET_INVALID);
            }

            this._appName = appName;
            this._state = null; //save state - source and target when binding is disabled
            this._mode = opts.mode;
            this._converter = opts.converter || global._getInternal().getConverter('BaseConverter');
            this._converterParam = opts.converterParam;
            this._srcPath = parser.getPathParts(opts.sourcePath);
            this._tgtPath = parser.getPathParts(opts.targetPath);
            if (this._tgtPath.length < 1)
                throw new Error(utils.format(RIAPP.ERRS.ERR_BIND_TGTPATH_INVALID, opts.targetPath));
            this._isSourceFixed = (!!opts.isSourceFixed);
            this._pathItems = {};
            this._objId = 'bnd' + baseUtils.getNewID();
            this._ignoreSrcChange = false;
            this._ignoreTgtChange = false;
            this._sourceObj = null;
            this._targetObj = null;
            this._source = null;
            this._target = null;
            this.target = opts.target;
            this.source = opts.source;
            var err_notif = utils.getErrorNotification(this._sourceObj);
            if (!!err_notif && err_notif.getIsHasErrors())
                this._onSrcErrorsChanged(err_notif);
        }
        private static _isDestroyed(obj: any): boolean {
            var res = false;
            if (utils.check.isBaseObj(obj)) {
                res = (<BaseObject>obj).getIsDestroyCalled();
            }
            return res;
        }
        private _onSrcErrorsChanged(err_notif: IErrorNotification, args?: any) {
            var errors: IValidationInfo[] = [], tgt = this._targetObj, src = this._sourceObj, srcPath = this._srcPath;
            if (!!tgt && elviewMOD._isElView(tgt)) {
                if (!!src && srcPath.length > 0) {
                    var prop = srcPath[srcPath.length - 1];
                    errors = err_notif.getFieldErrors(prop);
                }
                (<elviewMOD.BaseElView>tgt).validationErrors = errors;
            }
        }
        private _getTgtChangedFn(self: Binding, obj: any, prop: string, restPath: string[], lvl: number) {
            var fn = function (sender: any, data: any) {
                var val = parser.resolveProp(obj, prop);
                if (restPath.length > 0) {
                    self._setPathItem(null, BindTo.Target, lvl, restPath);
                }
                //bind and trigger target update
                self._parseTgtPath(val, restPath, lvl);
            };
            return fn;
        }
        private _getSrcChangedFn(self: Binding, obj: any, prop: string, restPath: string[], lvl: number) {
            var fn = function (sender: any, data: any) {
                var val = parser.resolveProp(obj, prop);
                if (restPath.length > 0) {
                    self._setPathItem(null, BindTo.Source, lvl, restPath);
                }
                self._parseSrcPath(val, restPath, lvl);
            };
            return fn;
        }
        private _parseSrcPath(obj: any, path: string[], lvl: number) {
            var self = this;
            self._sourceObj = null;
            if (path.length === 0) {
                self._sourceObj = obj;
            }
            else
                self._parseSrcPath2(obj, path, lvl);

            if (self._mode === BINDING_MODE.BackWay) {
                if (!!self._sourceObj)
                    self._updateSource();
            }
            else {
                if (!!self._targetObj)
                    self._updateTarget();
            }
        }
        private _parseSrcPath2(obj: any, path: string[], lvl: number) {
            var self = this, nextObj: any, isBaseObj = (!!obj && utils.check.isBaseObj(obj)), isValidProp: boolean;

            if (isBaseObj) {
                (<BaseObject>obj).addOnDestroyed(self._onSrcDestroyed, self._objId, self);
                self._setPathItem(obj, BindTo.Source, lvl, path);
            }

            if (path.length > 1) {
                if (isBaseObj) {
                    (<BaseObject>obj).addOnPropertyChange(path[0], self._getSrcChangedFn(self, obj, path[0], path.slice(1), lvl + 1), self._objId);
                }

                if (!!obj) {
                    nextObj = global.parser.resolveProp(obj, path[0]);
                    if (!!nextObj) {
                        self._parseSrcPath2(nextObj, path.slice(1), lvl + 1);
                    }
                    else if (base_utils.isUndefined(nextObj)) {
                        if (DebugLevel == DEBUG_LEVEL.HIGH) {
                            RIAPP.startDebugger();
                        }
                        if (DebugLevel > DEBUG_LEVEL.NONE) {
                            global._getInternal().onUnResolvedBinding(BindTo.Source, self.source, self._srcPath.join('.'), path[0]);
                        }
                    }
                }
                return;
            }

            if (!!obj && path.length == 1) {
                isValidProp = true;
                if (DebugLevel != DEBUG_LEVEL.NONE)
                    isValidProp = isBaseObj ? obj._isHasProp(path[0]) : base_utils.hasProp(obj, path[0]);

                if (isValidProp) {
                    var updateOnChange = isBaseObj && (self._mode === BINDING_MODE.OneWay || self._mode === BINDING_MODE.TwoWay);
                    if (updateOnChange) {
                        (<BaseObject>obj).addOnPropertyChange(path[0], self._updateTarget, self._objId, self);
                    }
                    var err_notif = utils.getErrorNotification(obj);
                    if (!!err_notif) {
                        err_notif.addOnErrorsChanged(self._onSrcErrorsChanged, self._objId, self);
                    }
                    self._sourceObj = obj;
                }
                else {
                    if (DebugLevel == DEBUG_LEVEL.HIGH) {
                        RIAPP.startDebugger();
                    }
                    global._getInternal().onUnResolvedBinding(BindTo.Source, self.source, self._srcPath.join('.'), path[0]);
                }
            }
        }
        private _parseTgtPath(obj: any, path: string[], lvl: number) {
            var self = this;
            self._targetObj = null;
            if (path.length === 0) {
                self._targetObj = obj;
            }
            else
                self._parseTgtPath2(obj, path, lvl);

            if (self._mode === BINDING_MODE.BackWay) {
                if (!!self._sourceObj)
                    self._updateSource();
            }
            else {
                //if new target then update target (not source!)
                if (!!self._targetObj)
                    self._updateTarget();
            }
        }
        private _parseTgtPath2(obj: any, path: string[], lvl: number) {
            var self = this, nextObj: any, isBaseObj = (!!obj && utils.check.isBaseObj(obj)), isValidProp: boolean;

            if (isBaseObj) {
                (<BaseObject>obj).addOnDestroyed(self._onTgtDestroyed, self._objId, self);
                self._setPathItem(obj, BindTo.Target, lvl, path);
            }

            if (path.length > 1) {
                if (isBaseObj) {
                    (<BaseObject>obj).addOnPropertyChange(path[0], self._getTgtChangedFn(self, obj, path[0], path.slice(1), lvl + 1), self._objId, self);
                }
                if (!!obj) {
                    nextObj = global.parser.resolveProp(obj, path[0]);
                    if (!!nextObj) {
                        self._parseTgtPath2(nextObj, path.slice(1), lvl + 1);
                    }
                    else if (base_utils.isUndefined(nextObj)) {
                        if (DebugLevel == DEBUG_LEVEL.HIGH) {
                            RIAPP.startDebugger();
                        }
                        if (DebugLevel > DEBUG_LEVEL.NONE) {
                            global._getInternal().onUnResolvedBinding(BindTo.Target, self.target, self._tgtPath.join('.'), path[0]);
                        }
                    }
                }
                return;
            }

            if (!!obj && path.length === 1) {
                isValidProp = true;
                if (DebugLevel != DEBUG_LEVEL.NONE)
                    isValidProp = isBaseObj ? obj._isHasProp(path[0]) : base_utils.hasProp(obj, path[0]);

                if (isValidProp) {
                    var updateOnChange = isBaseObj && (self._mode === BINDING_MODE.TwoWay || self._mode === BINDING_MODE.BackWay);
                    if (updateOnChange) {
                        (<BaseObject>obj).addOnPropertyChange(path[0], self._updateSource, self._objId, self);
                    }
                    self._targetObj = obj;
                }
                else {
                    if (DebugLevel == DEBUG_LEVEL.HIGH) {
                        RIAPP.startDebugger();
                    }
                    global._getInternal().onUnResolvedBinding(BindTo.Target, self.target, self._tgtPath.join('.'), path[0]);
                }
            }
        }
        private _setPathItem(newObj: BaseObject, bindingTo: BindTo, lvl: number, path: string[]) {
            var oldObj: RIAPP.BaseObject, key: string, len: number = lvl + path.length;
            for (var i = lvl; i < len; i += 1) {
                switch (bindingTo) {
                    case BindTo.Source:
                        key = 's' + i;
                        break;
                    case BindTo.Target:
                        key = 't' + i;
                        break;
                    default:
                        throw new Error(RIAPP.baseUtils.format(RIAPP.ERRS.ERR_PARAM_INVALID, 'bindingTo', bindingTo));
                }

                oldObj = this._pathItems[key];
                if (!!oldObj) {
                    this._cleanUpObj(oldObj);
                    delete this._pathItems[key];
                }

                if (!!newObj && i == lvl) {
                    this._pathItems[key] = newObj;
                }
            }
        }
        private _cleanUpObj(oldObj: RIAPP.BaseObject) {
            if (!!oldObj) {
                oldObj.removeNSHandlers(this._objId);
                var err_notif = utils.getErrorNotification(oldObj);
                if (!!err_notif) {
                    err_notif.removeOnErrorsChanged(this._objId);
                }
            }
        }
        private _onTgtDestroyed(sender: any, args: any) {
            if (this._isDestroyCalled)
                return;
            this._setTarget(null);
        }
        private _onSrcDestroyed(sender: any, args: any) {
            var self = this;
            if (self._isDestroyCalled)
                return;
            if (sender === self.source)
                self._setSource(null);
            else {
                self._setPathItem(null, BindTo.Source, 0, self._srcPath);
                setTimeout(function () {
                    if (self._isDestroyCalled)
                        return;
                    //rebind after the source destroy is fully completed
                    self._bindToSource();
                }, 0);
            }
        }
        private _bindToSource() {
            this._parseSrcPath(this.source, this._srcPath, 0);
        }
        private _bindToTarget() {
            this._parseTgtPath(this.target, this._tgtPath, 0);
        }
        private _updateTarget(sender?: any, args?: any) {
            if (this._ignoreSrcChange || this._isDestroyCalled)
                return;
            this._ignoreTgtChange = true;
            try {
                var res = this._converter.convertToTarget(this.sourceValue, this._converterParam, this._sourceObj);
                if (res !== undefined)
                    this.targetValue = res;
            }
            catch (ex) {
                if (this._mode === BINDING_MODE.BackWay) {
                    //resync
                    this._updateSource();
                }
                RIAPP.reThrow(ex, this.handleError(ex, this));
            }
            finally {
                this._ignoreTgtChange = false;
            }
        }
        private _updateSource(sender?: any, args?: any) {
            if (this._ignoreTgtChange || this._isDestroyCalled)
                return;
            this._ignoreSrcChange = true;
            try {
                var res = this._converter.convertToSource(this.targetValue, this._converterParam, this._sourceObj);
                if (res !== undefined)
                    this.sourceValue = res;
            }
            catch (ex) {
                if (!(ex instanceof errMOD.ValidationError) || !elviewMOD._isElView(this._targetObj)) {
                    //BaseElView is notified about errors in _onSrcErrorsChanged event handler
                    //we only need to invoke _onError in other cases
                    //1) when target is not BaseElView
                    //2) when error is not ValidationError
                    this._ignoreSrcChange = false;
                    if (this._mode != BINDING_MODE.BackWay) {
                        //resync
                        this._updateTarget();
                    }
                    if (!this.handleError(ex, this))
                        throw ex;
                }
            }
            finally {
                this._ignoreSrcChange = false;
            }
        }
        protected _setTarget(value: any) {
            if (!!this._state) {
                this._state.target = value;
                return;
            }
            if (this._target !== value) {
                if (!!this._targetObj) {
                    this._ignoreTgtChange = true;
                    try {
                        this.targetValue = null;
                    }
                    finally {
                        this._ignoreTgtChange = false;
                    }
                }
                this._setPathItem(null, BindTo.Target, 0, this._tgtPath);
                if (!!value && !utils.check.isBaseObj(value))
                    throw new Error(RIAPP.ERRS.ERR_BIND_TARGET_INVALID);
                this._target = value;
                this._bindToTarget();
                if (!!this._target && !this._targetObj)
                    throw new Error(utils.format(RIAPP.ERRS.ERR_BIND_TGTPATH_INVALID, this._tgtPath.join('.')));
            }
        }
        protected _setSource(value: any) {
            if (!!this._state) {
                this._state.source = value;
                return;
            }
            if (this._source !== value) {
                this._setPathItem(null, BindTo.Source, 0, this._srcPath);
                this._source = value;
                this._bindToSource();
            }
        }
        handleError(error: any, source: any): boolean {
            var isHandled = super.handleError(error, source);
            if (!isHandled) {
                if (!!this._appName) {
                    return global.findApp(this._appName).handleError(error, source);
                }
                else
                    return global.handleError(error, source);
            }
            return isHandled;
        }
        destroy() {
            if (this._isDestroyed)
                return;
            this._isDestroyCalled = true;
            var self = this;
            utils.forEachProp(this._pathItems, function (key) {
                var old = self._pathItems[key];
                self._cleanUpObj(old);
            });
            this._pathItems = {};
            this._setSource(null);
            this._setTarget(null);
            this._state = null;
            this._converter = null;
            this._converterParam = null;
            this._srcPath = null;
            this._tgtPath = null;
            this._sourceObj = null;
            this._targetObj = null;
            this._source = null;
            this._target = null;
            super.destroy();
        }
        toString() {
            return 'Binding';
        }

        get bindingID() {
            return this._objId;
        }
        get target() { return this._target; }
        set target(v: BaseObject) {
            this._setTarget(v);
        }
        get source() { return this._source; }
        set source(v) {
            this._setSource(v);
        }
        get targetPath() { return this._tgtPath; }
        get sourcePath() { return this._srcPath; }
        get sourceValue() {
            if (this._srcPath.length === 0)
                return this._sourceObj;
            if (!this._sourceObj)
                return undefined;
            var prop = this._srcPath[this._srcPath.length - 1];
            var res = global.parser.resolveProp(this._sourceObj, prop);
            return res;
        }
        set sourceValue(v) {
            if (this._srcPath.length === 0 || !this._sourceObj)
                return;
            if (Binding._isDestroyed(this._sourceObj))
                return;
            var prop = this._srcPath[this._srcPath.length - 1];
            global.parser.setPropertyValue(this._sourceObj, prop, v);
        }
        get targetValue() {
            if (!this._targetObj)
                return undefined;
            var prop = this._tgtPath[this._tgtPath.length - 1];
            return global.parser.resolveProp(this._targetObj, prop);
        }
        set targetValue(v) {
            if (this._tgtPath.length == 0 || !this._targetObj)
                return;
            if (Binding._isDestroyed(this._targetObj))
                return;
            var prop = this._tgtPath[this._tgtPath.length - 1];
            global.parser.setPropertyValue(this._targetObj, prop, v);
        }
        get mode() { return this._mode; }
        get converter() { return this._converter; }
        set converter(v: RIAPP.IConverter) { this._converter = v; }
        get converterParam() { return this._converterParam; }
        set converterParam(v) { this._converterParam = v; }
        get isSourceFixed() { return this._isSourceFixed; }
        get isDisabled() { return !!this._state; }
        set isDisabled(v) {
            var s: IBindingState;
            v = !!v;
            if (this.isDisabled != v) {
                if (v) {
                    //going to disabled state
                    s = { source: this._source, target: this._target };
                    try {
                        this.target = null;
                        this.source = null;
                    }
                    finally {
                        this._state = s;
                    }
                }
                else {
                    //restoring from disabled state
                    s = this._state;
                    this._state = null;
                    this._setTarget(s.target);
                    this._setSource(s.source);
                }
            }
        }
        get appName() { return this._appName; }
    }

    _isModuleLoaded = true;
}


text:
/** @namespace Verifier */

var $ = require('preconditions').singleton();
var _ = require('lodash');

var WalletUtils = require('bitcore-wallet-utils');
var Bitcore = WalletUtils.Bitcore;

var log = require('./log');

/**
 * @desc Verifier constructor. Checks data given by the server
 *
 * @constructor
 */
function Verifier(opts) {};

/**
 * Check address
 *
 * @param {Function} credentials
 * @param {String} address
 * @returns {Boolean} true or false
 */
Verifier.checkAddress = function(credentials, address) {
  $.checkState(credentials.isComplete());
  var local = WalletUtils.deriveAddress(credentials.publicKeyRing, address.path, credentials.m, credentials.network);
  return (local.address == address.address && JSON.stringify(local.publicKeys) == JSON.stringify(address.publicKeys));
};

/**
 * Check copayers
 *
 * @param {Function} credentials
 * @param {Array} copayers
 * @returns {Boolean} true or false
 */
Verifier.checkCopayers = function(credentials, copayers) {
  $.checkState(credentials.walletPrivKey);
  var walletPubKey = Bitcore.PrivateKey.fromString(credentials.walletPrivKey).toPublicKey().toString();

  if (copayers.length != credentials.n) {
    log.error('Missing public keys in server response');
    return false;
  }

  // Repeated xpub kes?
  var uniq = [];
  var error;
  _.each(copayers, function(copayer) {
    if (uniq[copayers.xPubKey]++) {
      log.error('Repeated public keys in server response');
      error = true;
    }

    // Not signed pub keys
    if (!copayer.name || !copayer.xPubKey || !copayer.requestPubKey || !copayer.signature) {
      log.error('Missing copayer fields in server response');
      error = true;
    } else {
      var hash = WalletUtils.getCopayerHash(copayer.name, copayer.xPubKey, copayer.requestPubKey);
      if (!WalletUtils.verifyMessage(hash, copayer.signature, walletPubKey)) {
        log.error('Invalid signatures in server response');
        error = true;
      }
    }
  });

  if (error) return false;

  if (!_.contains(_.pluck(copayers, 'xPubKey'), credentials.xPubKey)) {
    log.error('Server response does not contains our public keys')
    return false;
  }
  return true;
};

/**
 * Check transaction proposal
 *
 * @param {Function} credentials
 * @param {Object} txp
 * @returns {Boolean} true or false
 */
Verifier.checkTxProposal = function(credentials, txp) {
  $.checkArgument(txp.creatorId);
  $.checkState(credentials.isComplete());

  var creatorKeys = _.find(credentials.publicKeyRing, function(item) {
    if (WalletUtils.xPubToCopayerId(item.xPubKey) === txp.creatorId) return true;
  });

  if (!creatorKeys) return false;

  // TODO: this should be an independent key
  var creatorSigningPubKey = creatorKeys.requestPubKey;

  var hash = WalletUtils.getProposalHash(txp.toAddress, txp.amount, txp.encryptedMessage || txp.message);
  log.debug('Regenerating & verifying tx proposal hash -> Hash: ', hash, ' Signature: ', txp.proposalSignature);

  if (!WalletUtils.verifyMessage(hash, txp.proposalSignature, creatorSigningPubKey))
    return false;

  return Verifier.checkAddress(credentials, txp.changeAddress);
};

module.exports = Verifier;


text:
package org.apache.commons.lang3.exception;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.AbstractLangTest;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 * Abstract test of an ExceptionContext implementation.
 */
public abstract class AbstractExceptionContextTest<T extends ExceptionContext & Serializable> extends AbstractLangTest {

    protected static final String TEST_MESSAGE_2 = "This is monotonous";
    protected static final String TEST_MESSAGE = "Test Message";
    protected T exceptionContext;

    protected static class ObjectWithFaultyToString {
        @Override
        public String toString() {
            throw new RuntimeException("Crap");
        }
    }

    @BeforeEach
    public void setUp() throws Exception {
        exceptionContext
            .addContextValue("test1", null)
            .addContextValue("test2", "some value")
            .addContextValue("test Date", new Date())
            .addContextValue("test Nbr", Integer.valueOf(5))
            .addContextValue("test Poorly written obj", new ObjectWithFaultyToString());
    }

    @Test
    public void testAddContextValue() {
        final String message = exceptionContext.getFormattedExceptionMessage(TEST_MESSAGE);
        assertTrue(message.contains(TEST_MESSAGE));
        assertTrue(message.contains("test1"));
        assertTrue(message.contains("test2"));
        assertTrue(message.contains("test Date"));
        assertTrue(message.contains("test Nbr"));
        assertTrue(message.contains("some value"));
        assertTrue(message.contains("5"));

        assertNull(exceptionContext.getFirstContextValue("test1"));
        assertEquals("some value", exceptionContext.getFirstContextValue("test2"));

        assertEquals(5, exceptionContext.getContextLabels().size());
        assertTrue(exceptionContext.getContextLabels().contains("test1"));
        assertTrue(exceptionContext.getContextLabels().contains("test2"));
        assertTrue(exceptionContext.getContextLabels().contains("test Date"));
        assertTrue(exceptionContext.getContextLabels().contains("test Nbr"));

        exceptionContext.addContextValue("test2", "different value");
        assertEquals(5, exceptionContext.getContextLabels().size());
        assertTrue(exceptionContext.getContextLabels().contains("test2"));

        final String contextMessage = exceptionContext.getFormattedExceptionMessage(null);
        assertFalse(contextMessage.contains(TEST_MESSAGE));
    }

    @Test
    public void testSetContextValue() {
        exceptionContext.addContextValue("test2", "different value");
        exceptionContext.setContextValue("test3", "3");

        final String message = exceptionContext.getFormattedExceptionMessage(TEST_MESSAGE);
        assertTrue(message.contains(TEST_MESSAGE));
        assertTrue(message.contains("test Poorly written obj"));
        assertTrue(message.contains("Crap"));

        assertNull(exceptionContext.getFirstContextValue("crap"));
        assertTrue(exceptionContext.getFirstContextValue("test Poorly written obj") instanceof ObjectWithFaultyToString);

        assertEquals(7, exceptionContext.getContextEntries().size());
        assertEquals(6, exceptionContext.getContextLabels().size());

        assertTrue(exceptionContext.getContextLabels().contains("test Poorly written obj"));
        assertFalse(exceptionContext.getContextLabels().contains("crap"));

        exceptionContext.setContextValue("test Poorly written obj", "replacement");

        assertEquals(7, exceptionContext.getContextEntries().size());
        assertEquals(6, exceptionContext.getContextLabels().size());

        exceptionContext.setContextValue("test2", "another");

        assertEquals(6, exceptionContext.getContextEntries().size());
        assertEquals(6, exceptionContext.getContextLabels().size());

        final String contextMessage = exceptionContext.getFormattedExceptionMessage(null);
        assertFalse(contextMessage.contains(TEST_MESSAGE));
    }

    @Test
    public void testGetFirstContextValue() {
        exceptionContext.addContextValue("test2", "different value");

        assertNull(exceptionContext.getFirstContextValue("test1"));
        assertEquals("some value", exceptionContext.getFirstContextValue("test2"));
        assertNull(exceptionContext.getFirstContextValue("crap"));

        exceptionContext.setContextValue("test2", "another");

        assertEquals("another", exceptionContext.getFirstContextValue("test2"));
    }

    @Test
    public void testGetContextValues() {
        exceptionContext.addContextValue("test2", "different value");

        assertEquals(exceptionContext.getContextValues("test1"), Collections.singletonList(null));
        assertEquals(exceptionContext.getContextValues("test2"), Arrays.asList("some value", "different value"));

        exceptionContext.setContextValue("test2", "another");

        assertEquals("another", exceptionContext.getFirstContextValue("test2"));
    }

    @Test
    public void testGetContextLabels() {
        assertEquals(5, exceptionContext.getContextEntries().size());

        exceptionContext.addContextValue("test2", "different value");

        final Set<String> labels = exceptionContext.getContextLabels();
        assertEquals(6, exceptionContext.getContextEntries().size());
        assertEquals(5, labels.size());
        assertTrue(labels.contains("test1"));
        assertTrue(labels.contains("test2"));
        assertTrue(labels.contains("test Date"));
        assertTrue(labels.contains("test Nbr"));
    }

    @Test
    public void testGetContextEntries() {
        assertEquals(5, exceptionContext.getContextEntries().size());

        exceptionContext.addContextValue("test2", "different value");

        final List<Pair<String, Object>> entries = exceptionContext.getContextEntries();
        assertEquals(6, entries.size());
        assertEquals("test1", entries.get(0).getKey());
        assertEquals("test2", entries.get(1).getKey());
        assertEquals("test Date", entries.get(2).getKey());
        assertEquals("test Nbr", entries.get(3).getKey());
        assertEquals("test Poorly written obj", entries.get(4).getKey());
        assertEquals("test2", entries.get(5).getKey());
    }

    @Test
    public void testJavaSerialization() {
        exceptionContext.setContextValue("test Poorly written obj", "serializable replacement");

        final T clone = SerializationUtils.deserialize(SerializationUtils.serialize(exceptionContext));

        assertEquals(exceptionContext.getFormattedExceptionMessage(null), clone.getFormattedExceptionMessage(null));
    }
}


text:
using UnityEngine;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Debug = UnityEngine.Debug;

namespace CoreEditor.Drawing
{
	public static class Compare
	{
		public class CompareParams
		{
			public string FileA;
			public string FileB;

			public override string ToString()
			{
				return string.Format(@"-metric RMSE ""{0}"" ""{1}"" NULL:",  FileA, FileB );
			}
		}

		public static string Path
		{
			get
			{
				switch ( Application.platform )
				{
					case RuntimePlatform.OSXEditor:
						return "/usr/local/bin/compare";
					case RuntimePlatform.WindowsEditor:
						return Directory.GetCurrentDirectory() + @"\ExternalTools\Windows\compare.exe";
					default:
						throw new System.PlatformNotSupportedException();
				}
			}
		}

		public static bool IsInstalled
		{
			get
			{
				return File.Exists( Path );
			}
		}

		public static bool IsIdentical( string imageA, string imageB, bool verbose = false )
		{
			return IsIdentical( new CompareParams(){FileA = imageA, FileB = imageB }, verbose );
		}

		public static bool IsIdentical( CompareParams paramObj, bool verbose = false )
		{
			return RunCommand( paramObj.ToString(), verbose );
		}

		public static bool RunCommand( string command, bool verbose = false )
		{
			if ( IsInstalled == false )
			{
				Debug.LogError( "Cannot find " + Path );
				return false;
			}

			var proc = new Process();
			proc.StartInfo.FileName = Path;
			proc.StartInfo.Arguments = command;
			proc.StartInfo.CreateNoWindow = true;
			proc.StartInfo.WorkingDirectory =  Directory.GetCurrentDirectory();
			proc.StartInfo.RedirectStandardOutput = true;
			proc.StartInfo.RedirectStandardError = true;
			proc.StartInfo.UseShellExecute = false;
			proc.StartInfo.EnvironmentVariables["PATH"] = System.Environment.GetEnvironmentVariable("PATH");
			proc.Start();

			var output = new List<string>();
			string line;
			while ( ( line = proc.StandardOutput.ReadLine() ) != null )
			{
				output.Add( line );
			}

			var error = new List<string>();
			while ( ( line = proc.StandardError.ReadLine() ) != null )
			{
				error.Add( line );
			}

			proc.WaitForExit();

			if ( verbose && error.Count > 0 )
				Debug.LogWarning( string.Join( "\n", error.ToArray() ) );

			return proc.ExitCode == 0;
		}
	}
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**content** | [**List<AchievementDefinitionResource>**](AchievementDefinitionResource.md) |  |  [optional]
**first** | **Boolean** |  |  [optional]
**last** | **Boolean** |  |  [optional]
**number** | **Integer** |  |  [optional]
**numberOfElements** | **Integer** |  |  [optional]
**size** | **Integer** |  |  [optional]
**sort** | [**List<Order>**](Order.md) |  |  [optional]
**totalElements** | **Long** |  |  [optional]
**totalPages** | **Integer** |  |  [optional]


text:
using Xunit;
using Nicomputer.PokerBot.PokerGame;

namespace Nicomputer.PokerBot.UnitTests.PokerGame
{

    public class PlayerUnitTests
    {
        [Fact]
        public void Player_Constructor()
        {
            var player = new Player
            {
                Name = "John Doe",
                DisplayName = "Johnny",
                NickName = "Connor"
            };
            Assert.Equal("John Doe", player.Name);
            Assert.Equal("Johnny", player.DisplayName);
            Assert.Equal("Connor", player.NickName);
            Assert.Equal(player.Name, player.ToString());
        }
    }
}


text:
require 'spec_helper'

describe Puppet::Type.type(:dsc_xiishandler) do

  let :dsc_xiishandler do
    Puppet::Type.type(:dsc_xiishandler).new(
      :name     => 'foo',
      :dsc_name => 'foo',
    )
  end

  it "should stringify normally" do
    expect(dsc_xiishandler.to_s).to eq("Dsc_xiishandler[foo]")
  end

  it 'should default to ensure => present' do
    expect(dsc_xiishandler[:ensure]).to eq :present
  end

  it 'should require that dsc_name is specified' do
    #dsc_xiishandler[:dsc_name]
    expect { Puppet::Type.type(:dsc_xiishandler).new(
      :name     => 'foo',
      :dsc_ensure => 'Present',
    )}.to raise_error(Puppet::Error, /dsc_name is a required attribute/)
  end

  it 'should not accept array for dsc_name' do
    expect{dsc_xiishandler[:dsc_name] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_name' do
    expect{dsc_xiishandler[:dsc_name] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_name' do
    expect{dsc_xiishandler[:dsc_name] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_name' do
    expect{dsc_xiishandler[:dsc_name] = 16}.to raise_error(Puppet::ResourceError)
  end

  it 'should accept dsc_ensure predefined value Present' do
    dsc_xiishandler[:dsc_ensure] = 'Present'
    expect(dsc_xiishandler[:dsc_ensure]).to eq('Present')
  end

  it 'should accept dsc_ensure predefined value present' do
    dsc_xiishandler[:dsc_ensure] = 'present'
    expect(dsc_xiishandler[:dsc_ensure]).to eq('present')
  end

  it 'should accept dsc_ensure predefined value present and update ensure with this value (ensure end value should be a symbol)' do
    dsc_xiishandler[:dsc_ensure] = 'present'
    expect(dsc_xiishandler[:ensure]).to eq(dsc_xiishandler[:dsc_ensure].downcase.to_sym)
  end

  it 'should accept dsc_ensure predefined value Absent' do
    dsc_xiishandler[:dsc_ensure] = 'Absent'
    expect(dsc_xiishandler[:dsc_ensure]).to eq('Absent')
  end

  it 'should accept dsc_ensure predefined value absent' do
    dsc_xiishandler[:dsc_ensure] = 'absent'
    expect(dsc_xiishandler[:dsc_ensure]).to eq('absent')
  end

  it 'should accept dsc_ensure predefined value absent and update ensure with this value (ensure end value should be a symbol)' do
    dsc_xiishandler[:dsc_ensure] = 'absent'
    expect(dsc_xiishandler[:ensure]).to eq(dsc_xiishandler[:dsc_ensure].downcase.to_sym)
  end

  it 'should not accept values not equal to predefined values' do
    expect{dsc_xiishandler[:dsc_ensure] = 'invalid value'}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept array for dsc_ensure' do
    expect{dsc_xiishandler[:dsc_ensure] = ["foo", "bar", "spec"]}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept boolean for dsc_ensure' do
    expect{dsc_xiishandler[:dsc_ensure] = true}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept int for dsc_ensure' do
    expect{dsc_xiishandler[:dsc_ensure] = -16}.to raise_error(Puppet::ResourceError)
  end

  it 'should not accept uint for dsc_ensure' do
    expect{dsc_xiishandler[:dsc_ensure] = 16}.to raise_error(Puppet::ResourceError)
  end

  # Configuration PROVIDER TESTS

  describe "powershell provider tests" do

    it "should successfully instanciate the provider" do
      described_class.provider(:powershell).new(dsc_xiishandler)
    end

    before(:each) do
      @provider = described_class.provider(:powershell).new(dsc_xiishandler)
    end

    describe "when dscmeta_import_resource is true (default) and dscmeta_module_name existing/is defined " do

      it "should compute powershell dsc test script with Invoke-DscResource" do
        expect(@provider.ps_script_content('test')).to match(/Invoke-DscResource/)
      end

      it "should compute powershell dsc test script with method Test" do
        expect(@provider.ps_script_content('test')).to match(/Method\s+=\s*'test'/)
      end

      it "should compute powershell dsc set script with Invoke-DscResource" do
        expect(@provider.ps_script_content('set')).to match(/Invoke-DscResource/)
      end

      it "should compute powershell dsc test script with method Set" do
        expect(@provider.ps_script_content('set')).to match(/Method\s+=\s*'set'/)
      end

    end

    describe "when dsc_ensure is 'present'" do

      before(:each) do
        dsc_xiishandler.original_parameters[:dsc_ensure] = 'present'
        dsc_xiishandler[:dsc_ensure] = 'present'
        @provider = described_class.provider(:powershell).new(dsc_xiishandler)
      end

      it "should update :ensure to :present" do
        expect(dsc_xiishandler[:ensure]).to eq(:present)
      end

      it "should compute powershell dsc test script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/)
      end

      it "should compute powershell dsc set script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('set')).to match(/ensure = 'present'/)
      end

    end

    describe "when dsc_ensure is 'absent'" do

      before(:each) do
        dsc_xiishandler.original_parameters[:dsc_ensure] = 'absent'
        dsc_xiishandler[:dsc_ensure] = 'absent'
        @provider = described_class.provider(:powershell).new(dsc_xiishandler)
      end

      it "should update :ensure to :absent" do
        expect(dsc_xiishandler[:ensure]).to eq(:absent)
      end

      it "should compute powershell dsc test script in which ensure value is 'present'" do
        expect(@provider.ps_script_content('test')).to match(/ensure = 'present'/)
      end

      it "should compute powershell dsc set script in which ensure value is 'absent'" do
        expect(@provider.ps_script_content('set')).to match(/ensure = 'absent'/)
      end

    end

  end
end


text:
"""Support for RESTful API sensors."""
import logging
import json

import voluptuous as vol
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth

from homeassistant.components.sensor import PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA
from homeassistant.const import (
    CONF_AUTHENTICATION,
    CONF_FORCE_UPDATE,
    CONF_HEADERS,
    CONF_NAME,
    CONF_METHOD,
    CONF_PASSWORD,
    CONF_PAYLOAD,
    CONF_RESOURCE,
    CONF_RESOURCE_TEMPLATE,
    CONF_UNIT_OF_MEASUREMENT,
    CONF_USERNAME,
    CONF_TIMEOUT,
    CONF_VALUE_TEMPLATE,
    CONF_VERIFY_SSL,
    CONF_DEVICE_CLASS,
    HTTP_BASIC_AUTHENTICATION,
    HTTP_DIGEST_AUTHENTICATION,
)
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

DEFAULT_METHOD = "GET"
DEFAULT_NAME = "REST Sensor"
DEFAULT_VERIFY_SSL = True
DEFAULT_FORCE_UPDATE = False
DEFAULT_TIMEOUT = 10

CONF_JSON_ATTRS = "json_attributes"
METHODS = ["POST", "GET"]

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Exclusive(CONF_RESOURCE, CONF_RESOURCE): cv.url,
        vol.Exclusive(CONF_RESOURCE_TEMPLATE, CONF_RESOURCE): cv.template,
        vol.Optional(CONF_AUTHENTICATION): vol.In(
            [HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION]
        ),
        vol.Optional(CONF_HEADERS): vol.Schema({cv.string: cv.string}),
        vol.Optional(CONF_JSON_ATTRS, default=[]): cv.ensure_list_csv,
        vol.Optional(CONF_METHOD, default=DEFAULT_METHOD): vol.In(METHODS),
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(CONF_PASSWORD): cv.string,
        vol.Optional(CONF_PAYLOAD): cv.string,
        vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
        vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
        vol.Optional(CONF_USERNAME): cv.string,
        vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
        vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,
        vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
        vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
    }
)

PLATFORM_SCHEMA = vol.All(
    cv.has_at_least_one_key(CONF_RESOURCE, CONF_RESOURCE_TEMPLATE), PLATFORM_SCHEMA
)

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the RESTful sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    resource_template = config.get(CONF_RESOURCE_TEMPLATE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    headers = config.get(CONF_HEADERS)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    device_class = config.get(CONF_DEVICE_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    json_attrs = config.get(CONF_JSON_ATTRS)
    force_update = config.get(CONF_FORCE_UPDATE)
    timeout = config.get(CONF_TIMEOUT)

    if value_template is not None:
        value_template.hass = hass

    if resource_template is not None:
        resource_template.hass = hass
        resource = resource_template.render()

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = HTTPDigestAuth(username, password)
        else:
            auth = HTTPBasicAuth(username, password)
    else:
        auth = None
    rest = RestData(method, resource, auth, headers, payload, verify_ssl, timeout)
    rest.update()
    if rest.data is None:
        raise PlatformNotReady

    # Must update the sensor now (including fetching the rest resource) to
    # ensure it's updating its state.
    add_entities(
        [
            RestSensor(
                hass,
                rest,
                name,
                unit,
                device_class,
                value_template,
                json_attrs,
                force_update,
                resource_template,
            )
        ],
        True,
    )

class RestSensor(Entity):
    """Implementation of a REST sensor."""

    def __init__(
        self,
        hass,
        rest,
        name,
        unit_of_measurement,
        device_class,
        value_template,
        json_attrs,
        force_update,
        resource_template,
    ):
        """Initialize the REST sensor."""
        self._hass = hass
        self.rest = rest
        self._name = name
        self._state = None
        self._unit_of_measurement = unit_of_measurement
        self._device_class = device_class
        self._value_template = value_template
        self._json_attrs = json_attrs
        self._attributes = None
        self._force_update = force_update
        self._resource_template = resource_template

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def unit_of_measurement(self):
        """Return the unit the value is expressed in."""
        return self._unit_of_measurement

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return self._device_class

    @property
    def available(self):
        """Return if the sensor data are available."""
        return self.rest.data is not None

    @property
    def state(self):
        """Return the state of the device."""
        return self._state

    @property
    def force_update(self):
        """Force update."""
        return self._force_update

    def update(self):
        """Get the latest data from REST API and update the state."""
        if self._resource_template is not None:
            self.rest.set_url(self._resource_template.render())

        self.rest.update()
        value = self.rest.data

        if self._json_attrs:
            self._attributes = {}
            if value:
                try:
                    json_dict = json.loads(value)
                    if isinstance(json_dict, list):
                        json_dict = json_dict[0]
                    if isinstance(json_dict, dict):
                        attrs = {
                            k: json_dict[k] for k in self._json_attrs if k in json_dict
                        }
                        self._attributes = attrs
                    else:
                        _LOGGER.warning(
                            "JSON result was not a dictionary"
                            " or list with 0th element a dictionary"
                        )
                except ValueError:
                    _LOGGER.warning("REST result could not be parsed as JSON")
                    _LOGGER.debug("Erroneous JSON: %s", value)
            else:
                _LOGGER.warning("Empty reply found when expecting JSON data")
        if value is not None and self._value_template is not None:
            value = self._value_template.render_with_possible_json_value(value, None)

        self._state = value

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return self._attributes

class RestData:
    """Class for handling the data retrieval."""

    def __init__(
        self, method, resource, auth, headers, data, verify_ssl, timeout=DEFAULT_TIMEOUT
    ):
        """Initialize the data object."""
        self._method = method
        self._resource = resource
        self._auth = auth
        self._headers = headers
        self._request_data = data
        self._verify_ssl = verify_ssl
        self._timeout = timeout
        self.data = None

    def set_url(self, url):
        """Set url."""
        self._resource = url

    def update(self):
        """Get the latest data from REST service with provided method."""
        _LOGGER.debug("Updating from %s", self._resource)
        try:
            response = requests.request(
                self._method,
                self._resource,
                headers=self._headers,
                auth=self._auth,
                data=self._request_data,
                timeout=self._timeout,
                verify=self._verify_ssl,
            )
            self.data = response.text
        except requests.exceptions.RequestException as ex:
            _LOGGER.error("Error fetching data: %s failed with %s", self._resource, ex)
            self.data = None