text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>f1</title>
    <link rel="stylesheet" href="css/animate.css">

helloxway**

redpajama_set_name: RedPajamaGithub


text:
#include <Corrade/TestSuite/Tester.h>

#include "Magnum/Audio/Extensions.h"
#include "Magnum/Audio/Context.h"

namespace Magnum { namespace Audio { namespace Test {

struct ContextALTest: TestSuite::Tester {
    explicit ContextALTest();

    void extensionsString();
    void isExtensionEnabled();

    Context _context;
};

ContextALTest::ContextALTest() {
    addTests({&ContextALTest::extensionsString,
              &ContextALTest::isExtensionEnabled});
}

void ContextALTest::extensionsString() {
    std::vector<std::string> extensions = _context.extensionStrings();

    CORRADE_VERIFY(!extensions.empty());
}

void ContextALTest::isExtensionEnabled() {
    CORRADE_VERIFY(Context::current().isExtensionSupported<Extensions::ALC::EXT::ENUMERATION>());
}

}}}

CORRADE_TEST_MAIN(Magnum::Audio::Test::ContextALTest)


text:
@interface SmokeView : UIView
-(void)changeColour:(float)red green:(float)green blue:(float)blue;
-(void)setEmitterPositionFromTouch: (UITouch*)t;
-(void)setIsEmitting:(BOOL)isEmitting;
@end


text:
#ifndef itkAdaptiveHistogramEqualizationImageFilter_h
#define itkAdaptiveHistogramEqualizationImageFilter_h

#include "itkMovingHistogramImageFilter.h"
#include "itkAdaptiveEqualizationHistogram.h"
#include "itkImage.h"

namespace itk
{
/**
 * \class AdaptiveHistogramEqualizationImageFilter
 * \brief Power Law Adaptive Histogram Equalization
 *
 * Histogram equalization modifies the contrast in an image. The
 * AdaptiveHistogramEqualizationImageFilter is a superset of many
 * contrast enhancing filters. By modifying its parameters (alpha,
 * beta, and window), the AdaptiveHistogramEqualizationImageFilter can
 * produce an adaptively equalized histogram or a version of unsharp
 * mask (local mean subtraction). Instead of applying a strict
 * histogram equalization in a window about a pixel, this filter
 * prescribes a mapping function (power law) controlled by the
 * parameters alpha and beta.
 *
 * The parameter alpha controls how much the filter acts like the
 * classical histogram equalization method (alpha=0) to how
 * much the filter acts like an unsharp mask (alpha=1).
 *
 * The parameter beta controls how much the filter acts like an
 * unsharp mask (beta=0) to much the filter acts like pass through
 * (beta=1, with alpha=1).
 *
 * The parameter window controls the size of the region over which
 * local statistics are calculated.
 *
 * By altering alpha, beta and window, a host of equalization and unsharp
 * masking filters is available.
 *
 * The boundary condition ignores the part of the neighborhood
 * outside the image, and over-weights the valid part of the
 * neighborhood.
 *
 * For detail description, reference "Adaptive Image Contrast
 * Enhancement using Generalizations of Histogram Equalization."
 * J.Alex Stark. IEEE Transactions on Image Processing, May 2000.
 *
 * \ingroup ImageEnhancement
 * \ingroup ITKImageStatistics
 *
 * \wiki
 * \wikiexample{NeedDemo/ImageProcessing/AdaptiveHistogramEqualizationImageFilter,Adaptive histogram equalization}
 * \endwiki
 */
template< typename TImageType , typename TKernel = Neighborhood<bool, TImageType::ImageDimension> >
class AdaptiveHistogramEqualizationImageFilter:
  public MovingHistogramImageFilter< TImageType,
                                     TImageType,
                                     TKernel,
                                     typename Function::AdaptiveEqualizationHistogram< typename TImageType::PixelType,
                                                                                typename TImageType::PixelType > >

{
public:
  /**
   * Standard class typedefs
   */
  typedef AdaptiveHistogramEqualizationImageFilter     Self;
  typedef MovingHistogramImageFilter< TImageType,
                                     TImageType,
                                     TKernel,
                                     typename Function::AdaptiveEqualizationHistogram< typename TImageType::PixelType,
                                                                                typename TImageType::PixelType > >
                                                       Superclass;
  typedef SmartPointer< Self >                         Pointer;
  typedef SmartPointer< const Self >                   ConstPointer;

  itkStaticConstMacro(ImageDimension, unsigned int,
                      TImageType::ImageDimension);

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(AdaptiveHistogramEqualizationImageFilter, ImageToImageFilter);

  /** Image type typedef support. */
  typedef TImageType                    ImageType;
  typedef typename ImageType::PixelType InputPixelType;
  typedef typename ImageType::SizeType  ImageSizeType;

  /** Set/Get the value of alpha.  Alpha=0 produces the adaptive
   * histogram equalization (provided beta=0).  Alpha=1 produces an
   * unsharp mask. Default is 0.3. */
  itkSetMacro(Alpha, float);
  itkGetConstMacro(Alpha, float);

  /** Set/Get the value of beta.  If beta=1 (and alpha=1),
   * then the output image matches the input image.  As beta
   * approaches 0, the filter behaves as an unsharp mask. Default is
   * 0.3. */
  itkSetMacro(Beta, float);
  itkGetConstMacro(Beta, float);

#ifndef ITK_FUTURE_LEGACY_REMOVE
  /** Set/Get whether an optimized lookup table for the intensity
   * mapping function is used.  Default is off.
   * \deprecated
   */
  virtual void SetUseLookupTable( const bool _arg )
    {
  itkDebugMacro("setting UseLookupTable to " << _arg );
  itkGenericLegacyReplaceBodyMacro( "UseLookupTable", "", "nothing" );
  if (this->m_UseLookupTable != _arg)
    {
    this->m_UseLookupTable = _arg;
  this->Modified();
    }
  }
  itkGetConstMacro(UseLookupTable, bool);
  itkBooleanMacro(UseLookupTable);
#endif

  virtual void ConfigureHistogram( typename Superclass::HistogramType &h) ITK_OVERRIDE
    {
      h.SetAlpha( this->m_Alpha );
      h.SetBeta( this->m_Beta );
      h.SetMinimum( this->m_InputMinimum );
      h.SetMaximum( this->m_InputMaximum );

      typename Superclass::HistogramType::RealType kernelSize = 1;
      for ( unsigned int i = 0; i < ImageDimension; i++ )
        {
        kernelSize *= ( 2 * this->GetRadius()[i] + 1 );
        }
      h.SetKernelSize(kernelSize);
    }

protected:
  AdaptiveHistogramEqualizationImageFilter()
  {
    m_Alpha = .3;
    m_Beta = .3;
    this->SetRadius(5);
    m_UseLookupTable = false;
  }

  virtual ~AdaptiveHistogramEqualizationImageFilter(){}
  void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;

  /**
   * Standard pipeline method
   */
  void BeforeThreadedGenerateData() ITK_OVERRIDE;

private:
  AdaptiveHistogramEqualizationImageFilter(const Self &) ITK_DELETE_FUNCTION;
  void operator=(const Self &) ITK_DELETE_FUNCTION;

  /** The beta parameter of the AdaptiveHistogramEqualization. */
  float m_Alpha;

  /** The alpha parameter of the AdaptiveHistogramEqualization. */
  float m_Beta;

  InputPixelType m_InputMinimum;
  InputPixelType m_InputMaximum;

  /** Should we use a lookup table to optimize the use of the
   * intensity mapping function? */
  bool m_UseLookupTable;

};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkAdaptiveHistogramEqualizationImageFilter.hxx"
#endif

#endif


text:
require_relative '../../spec_helper'

describe Lot::Sidekiq::Worker do

  let(:worker) { Lot::Sidekiq::Worker.new }

  it "should be a sidekiq worker" do
    worker.is_a?(::Sidekiq::Worker).must_equal true
  end

  describe "perform" do

    let(:subscriber) { Lot::EventSubscriber.new }

    let(:the_key)   { random_string }
    let(:the_value) { random_string }

    let(:the_event_subscriber) { random_string }
    let(:the_event)            { random_string }
    let(:the_data)             { { the_key => the_value } }

    before do
      the_event_subscriber
        .stubs(:constantize)
        .returns Struct.new(:new).new(subscriber)
    end

    describe "no instigator" do

      let(:the_instigator)       { nil }

      it "should instantiate the worker with the right values and then run it" do

        subscriber.expects(:execute).with do |e, d, i|
          subscriber.event.must_equal the_event
          subscriber.data[the_key].must_equal the_value
          subscriber.instigator.nil?.must_equal true
        end

        worker.perform the_event_subscriber, the_event, the_data, the_instigator

      end

      it "should convert the hash to a case insenstiive hash" do
        subscriber.expects(:execute).with do |e, d, i|
          subscriber.data[the_key.to_sym].must_equal the_value
        end

        worker.perform the_event_subscriber, the_event, the_data, the_instigator
      end

      describe "but the data is nil" do

        let(:the_data) { nil }

        it "should still get an indifferent hash" do

          subscriber.expects(:execute).with do |e, d, i|
            subscriber.data.count.must_equal 0

            key,value = random_string, random_string
            subscriber.data[key] = value
            subscriber.data[key].must_equal value
            subscriber.data[key.to_sym].must_equal value
          end

          worker.perform the_event_subscriber, the_event, the_data, the_instigator

        end

      end

    end
    j
    describe "an instigator" do

      let(:the_record_type) { random_string }
      let(:the_record_id)   { random_string }
      let(:the_instigator)  { "#{the_record_type}:#{the_record_id}" }

      let(:the_real_instigator) { Object.new }

      before do
        constantized_record = Object.new
        constantized_record.stubs(:find).with(the_record_id).returns the_real_instigator
        Lot.stubs(:class_from_record_type).with(the_record_type).returns constantized_record
      end

      it "should instantiate the worker with the instgator" do

        subscriber.expects(:execute).with do |e, d, i|
          subscriber.instigator.must_be_same_as the_real_instigator
        end

        worker.perform the_event_subscriber, the_event, the_data, the_instigator

      end

      it "should convert the hash to a case insenstiive hash" do
        subscriber.expects(:execute).with do |e, d, i|
          subscriber.data[the_key.to_sym].must_equal the_value
        end

        worker.perform the_event_subscriber, the_event, the_data, the_instigator
      end

    end

  end

end


text:
#pragma once

#include "Utils/Span.h"

#include "Math/Math.h"

#include "WaveTable.h"
#include "WaveTableSampler.h"

namespace Intra { namespace Audio { namespace Synth {

#if INTRA_DISABLED
inline void AddSineHarmonic(Span<float> wavetableAmplitudes, float freqSampleRateRatio, float amplitude, float bandwidthCents)
{
	const size_t N = wavetableAmplitudes.Length()*2;
	float bwi = (Math::Pow2(bandwidthCents/1200 - 1) - 0.5f)*freqSampleRateRatio;
	float rw = -freqSampleRateRatio, rdw = 1.0f/N;
	while(!wavetableAmplitudes.Empty())
	{
		wavetableAmplitudes.Next() += amplitude * GaussianProfile(rw, bwi);
		rw += rdw;
	}
}
#endif

void AddSineHarmonicGaussianProfile(Span<float> wavetableAmplitudes, float freqSampleRateRatio,
	float harmFreqMultiplier, float harmBandwidthScale, float amplitude, float bandwidthCents);

//! Получает на вход массив inAmplitudesX2OutSamples, первая половина которого содержит амплитуды частот.
//! Присваивает каждой из них случайные фазы и заполняет весь inAmplitudesX2OutSamples семплами.
//! @param tempBuffer - временный буфер размера не меньше inAmplitudesX2OutSamples.Length(), в который будет производиться запись алгоримом.
void ConvertAmplutudesToSamples(Span<float> inAmplitudesX2OutSamples, Span<float> tempBuffer, float volume=1);

//! Принимает table, у которого Data содержит table.BaseLevelLength / 2 частот.
//! После работы этой функции table содержит table.BaseLevelLength семплов, соответствующих этим частотам со случайными фазами.
//! Кроме того генерирует все уровни детализации для полученного сигнала.
void ConvertAmplitudesToSamples(WaveTable& table, float volume=1, bool genMipmaps=false);

struct SineHarmonicWithBandwidthDesc
{
	float Amplitude;
	float FreqMultiplier;
	float Bandwidth;
};

WaveTableCache CreateWaveTablesFromHarmonics(CSpan<SineHarmonicWithBandwidthDesc> harmonics,
	float bandwidthScale, size_t tableSize, bool allowMipmaps);

//Первые numHarmonics слагаемых ряда гармоник с коэффициентами sin(alpha*n) / n^harmonicAttenuationPower и частотами freqMult+freqMultStep*(n-1)
Array<SineHarmonicWithBandwidthDesc> CreateHarmonicArray(float bandwidth, float bandwidthStep,
	float harmonicAttenuationPower, float freqMult, float freqMultStep, size_t numHarmonics, float scale, float alpha=0, float omega=0);

//Гармоники обобщённой пилообразной волны c указанным соотношением времени нарастания к времени спада updownRatio
Array<SineHarmonicWithBandwidthDesc> CreateUpdownHarmonicArray(float bandwidth, float bandwidthStep,
	float updownRatio, size_t numHarmonics=16, float scale=1, float freqMult=1, float harmonicAttenuationPower=2);

struct FormantDesc
{
	float Frequency;
	float Coeff;
	float Scale;
};

WaveTableCache CreateWaveTablesFromFormants(CSpan<FormantDesc> formants, uint numHarmonics,
	float harmonicAttenuationPower, float bandwidth, float bandwidthScale, size_t tableSize);

}}}


text:
USACO Online Judge Practice
=====
A considerable small portion of the practice set is done.
:worried:


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Orlova & Golodnaya, Lichenoth. Veneta 94 (1959)

#### Original name
Cephalosporium euonymi Orlova

### Remarks
null


text:
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
(function(widget) {
  return widget.Widget = (function() {
    Widget.prototype.name = "widget";
    Widget.prototype.defaultElement = "

";
    Widget.prototype.options = {};
    function Widget(options, element) {
      var name, _options;
      _options = {};
      for (name in this.options) {
        _options[name] = this.options[name];
      }
      for (name in options) {
        _options[name] = options[name];
      }
      this.options = _options;
      this.el = this.element = $(element || this.options.el || this.defaultElement);
      this.el.data(this.name, this);
      this.create();
      this.el.trigger('create', this);
      this.el.bind('remove', __bind(function(event) {
        if (event.target === this.el) {
          return this.destroy();
        }
      }, this));
      this.init();
    }
    Widget.prototype.$ = function(selector) {
      return $(selector, this.el);
    };
    Widget.prototype.create = function() {};
    Widget.prototype.init = function() {};
    Widget.prototype.destroy = function() {
      return this.el.data(this.name, void 0);
    };
    Widget.prototype.option = function(key, value) {
      var options;
      if (typeof key === 'string') {
        if (!(value != null)) {
          return this.options[key];
        }
        options = {
          key: value
        };
      } else {
        options = key;
      }
      for (key in options) {
        value = options[key];
        this.options[key] = value;
      }
      return this;
    };
    Widget.prototype.widgetName = Widget.prototype.name;
    Widget.prototype._create = Widget.prototype.create;
    Widget.prototype._init = Widget.prototype.init;
    Widget.prototype._destroy = Widget.prototype.destroy;
    Widget.prototype._bind = Widget.prototype.bind;
    Widget.prototype._trigger = Widget.prototype.trigger;
    return Widget;
  })();
})(typeof exports !== "undefined" && exports !== null ? exports : (this['widget'] = {}));


text:
Weibull
===
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![Dependencies][dependencies-image]][dependencies-url]

> Weibull distribution.

## Installation

``` bash
$ npm install distributions-weibull
```

For use in the browser, use [browserify](https://github.com/substack/node-browserify).

## Usage

``` javascript
var createDist = require( 'distributions-weibull' );
```

To create a Weibull distribution,

``` javascript
var dist = createDist();
```

The constructor function takes two input arguments, `lambda` and `k`, the shape and scale parameters of the Weibull distribution. By default, a distribution with `lambda = 1` and `k = 1` is created.

The distribution is configurable and has the following methods...

#### dist.support()

Returns the distribution support, which is all numbers in the interval `(0,∞)`.

``` javascript
var support = dist.support();
// returns [ 0,+Infinity ]
```

#### dist.lambda( [value] )

This method is a setter/getter. If no `value` is provided, returns the shape parameter `lambda`. To set `lambda`,

``` javascript
dist.lambda( 10 );
```

The default shape parameter is 1.

#### dist.k( [value] )

This method is a setter/getter. If no `value` is provided, returns the scale parameter `k`. To set `k`,

``` javascript
dist.k( 100 );
```

The default scale parameter is 1.

#### dist.mean()

Returns the distribution `mean`.

``` javascript
var mean = dist.mean();
```

#### dist.variance()

Returns the distribution `variance`.

``` javascript
var variance = dist.variance();
```

#### dist.median()

Returns the distribution `median`.

``` javascript
var median = dist.median();
```

#### dist.skewness()

Returns the distribution `skewness`.

``` javascript
var skewness = dist.skewness();
```

#### dist.ekurtosis()

Returns the distribution `excess kurtosis`.

``` javascript
var excess = dist.ekurtosis();
```

#### dist.entropy()

Returns the distribution's [differential entropy](http://en.wikipedia.org/wiki/Differential_entropy).

``` javascript
var entropy = dist.entropy();
```

#### dist.pdf( [x] )

If no argument is provided, returns the probability density function (PDF). If a [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), an [`array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), a [`typed array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), or a [`matrix`](https://github.com/dstructs/matrix) is provided, evaluates the PDF for each element.

``` javascript
var data = [ 0, 0.2, 0.5, 0.8 ];

var pdf = dist.pdf( data );
// returns [...]
```

#### dist.cdf( [x] )

If no argument is provided, returns the cumulative distribution function (CDF). If a [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), an [`array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), a [`typed array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), or a [`matrix`](https://github.com/dstructs/matrix) is provided, evaluates the CDF for each element.

``` javascript
var data = [ 0, 0.2, 0.5, 0.8 ];

var cdf = dist.cdf( data );
// returns [...]
```

#### dist.quantile( [p] )

If no argument is provided, returns the inverse cumulative distribution (quantile) function. If a [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), an [`array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), a [`typed array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), or a [`matrix`](https://github.com/dstructs/matrix) of probabilities is provided, evaluates the quantile function for each element.

``` javascript
var probs = [ 0.025, 0.5, 0.975 ];

var quantiles = dist.quantile( probs );
// returns [...]
```

Note: all values must exist on the interval `[0, 1]`. The function returns `NaN` for a value not satisfying this condition.

#### dist.mgf( [t] )

If no argument is provided, returns the moment generating function (MGF) of the distribution. If a [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), an [`array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), a [`typed array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), or a [`matrix`](https://github.com/dstructs/matrix) is provided, evaluates the MGF for each input element.

## Examples

``` javascript
var createDist = require( 'distributions-weibull' );

// Define the distribution parameters...
var lambda = 10,
	k = 20;

// Create a vector...
var vec = new Array( 1000 ),
	len = vec.length;

for ( var i = 0; i < len; i++ ) {
	vec[ i ] = lambda * Math.pow( -Math.log( 1 - Math.random() ) , 1/k );
}

// Create a Weibull distribution and configure...
var dist = createDist( lambda, k );

// Evaluate the probability density function over the vector...
var pdf = dist.pdf( vec );

var arr = new Array( 100 );
for ( var j = 0; j < arr.length; j++ ) {
	arr[ j ] = [ vec[j], pdf[j] ];
}
console.log( arr );

// Evaluate the quantile function for canonical cumulative probability values...
var quantiles = dist.quantile( [ 0.025, 0.5, 0.975 ] );

console.log( quantiles );
```

To run the example code from the top-level application directory,

``` bash
$ node ./examples/index.js
```

## Tests

### Unit

Unit tests use the [Mocha](http://mochajs.org) test framework with [Chai](http://chaijs.com) assertions. To run the tests, execute the following command in the top-level application directory:

``` bash
$ make test
```

All new feature development should have corresponding unit tests to validate correct functionality.

### Test Coverage

This repository uses [Istanbul](https://github.com/gotwarlost/istanbul) as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:

``` bash
$ make test-cov
```

Istanbul creates a `./reports/coverage` directory. To access an HTML version of the report,

``` bash
$ open reports/coverage/lcov-report/index.html
```

---
## License

[MIT license](http://opensource.org/licenses/MIT).

## Copyright

Copyright © 2015. The [Distributions.io](https://github.com/distributions-io) Authors.

[npm-image]: http://img.shields.io/npm/v/distributions-weibull.svg
[npm-url]: https://npmjs.org/package/distributions-weibull

[travis-image]: http://img.shields.io/travis/distributions-io/weibull/master.svg
[travis-url]: https://travis-ci.org/distributions-io/weibull

[coveralls-image]: https://img.shields.io/coveralls/distributions-io/weibull/master.svg
[coveralls-url]: https://coveralls.io/r/distributions-io/weibull?branch=master

[dependencies-image]: http://img.shields.io/david/distributions-io/weibull.svg
[dependencies-url]: https://david-dm.org/distributions-io/weibull

[dev-dependencies-image]: http://img.shields.io/david/dev/distributions-io/weibull.svg
[dev-dependencies-url]: https://david-dm.org/dev/distributions-io/weibull

[github-issues-image]: http://img.shields.io/github/issues/distributions-io/weibull.svg
[github-issues-url]: https://github.com/distributions-io/weibull/issues


text:
<?php
namespace Concrete\Package\VividStore\Src\VividStore\Utilities;

use Controller;
use Core;

class States extends Controller
{
    public function getStateList()
    {
        $countryCode = $_POST['country'];
        $selectedState = $_POST['selectedState'];
        $type = $_POST['type'];
        $list = Core::make('helper/lists/states_provinces')->getStateProvinceArray($countryCode);
        if ($list) {
            if ($type=="tax") {
                echo "<select name='taxState' id='taxState' class='form-control'>";
            } else {
                echo "<select name='checkout-{$type}-state' id='checkout-{$type}-state' ccm-passed-value='' class='form-control'>";
            }
            foreach ($list as $code=>$country) {
                if ($code == $selectedState) {
                    echo "<option selected value='{$code}'>{$country}</option>";
                } else {
                    echo "<option value='{$code}'>{$country}</option>";
                }
            }
            echo "<select>";
        } else {
            if ($type=="tax") {
                echo "<input name='taxState' id='taxState' class='form-control'>";
            } else {
                echo "<input name='checkout-{$type}-state' id='checkout-{$type}-state' value='{$selectedState}' class='form-control'>";
            }
        }
    }
}


text:
namespace ui {
class ImageCursors;
}

namespace ash {

namespace test {
class CursorManagerTestApi;
}

// This does the ash-specific setting of cursor details like cursor
// visibility. It communicates back with the CursorManager through the
// NativeCursorManagerDelegate interface, which receives messages about what
// changes were acted on.
class ASH_EXPORT AshNativeCursorManager
    : public ::wm::NativeCursorManager {
 public:
  AshNativeCursorManager();
  ~AshNativeCursorManager() override;

  // Toggle native cursor enabled/disabled.
  // The native cursor is enabled by default. When disabled, we hide the native
  // cursor regardless of visibility state, and let CursorWindowManager draw
  // the cursor.
  void SetNativeCursorEnabled(bool enabled);

 private:
  friend class test::CursorManagerTestApi;

  // Overridden from ::wm::NativeCursorManager:
  void SetDisplay(const gfx::Display& display,
                  ::wm::NativeCursorManagerDelegate* delegate) override;
  void SetCursor(gfx::NativeCursor cursor,
                 ::wm::NativeCursorManagerDelegate* delegate) override;
  void SetVisibility(bool visible,
                     ::wm::NativeCursorManagerDelegate* delegate) override;
  void SetCursorSet(ui::CursorSetType cursor_set,
                    ::wm::NativeCursorManagerDelegate* delegate) override;
  void SetMouseEventsEnabled(
      bool enabled,
      ::wm::NativeCursorManagerDelegate* delegate) override;

  // The cursor location where the cursor was disabled.
  gfx::Point disabled_cursor_location_;

  bool native_cursor_enabled_;

  std::unique_ptr<ui::ImageCursors> image_cursors_;

  DISALLOW_COPY_AND_ASSIGN(AshNativeCursorManager);
};

}  // namespace ash

#endif  // ASH_WM_ASH_NATIVE_CURSOR_MANAGER_H_


text:
<html>
<head>
<script type="text/javascript" src="../../http/tests/inspector-protocol/inspector-protocol-test.js"></script>
<script>

function logActiveElement() {
    var el = document.activeElement;
    log(el ? (el.id || el.tagName) : "(none)");
}

function test()
{
    InspectorTest.sendCommand("Runtime.evaluate", { "expression": "logActiveElement()" });

    InspectorTest.sendCommand("DOM.getDocument", {}, onGotDocument);

    function onGotDocument(msg) {
        if (msg.error) {
            InspectorTest.log(msg.error.message);
            InspectorTest.completeTest();
            return;
        }
        var node = msg.result.root;
        InspectorTest.sendCommand("DOM.querySelector", { "nodeId": node.nodeId, "selector": "#second" }, onQuerySelector);
    }

    function onQuerySelector(msg) {
        if (msg.error) {
            InspectorTest.log(msg.error.message);
            InspectorTest.completeTest();
            return;
        }
        var node = msg.result;
        InspectorTest.sendCommand("DOM.focus", { "nodeId": node.nodeId }, onFocus);
    }

    function onFocus(msg) {
        if (msg.error)
            InspectorTest.log(msg.error);

        InspectorTest.sendCommand("Runtime.evaluate", { expression: 'logActiveElement()' });
        InspectorTest.completeTest();
    }
}

</script>
</head>
<body onload="runTest()">
<input></input>
<input id="second"></input>
</body>
</html>


text:
package org.apache.deltaspike.example.tests.persistence;

import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Query;
import org.apache.deltaspike.data.api.QueryParam;
import org.apache.deltaspike.data.api.Repository;
import org.apache.deltaspike.example.jpa.Employees;

import java.util.List;

@Repository(forEntity = Employees.class)
public interface EmployeeRepository extends EntityRepository<Employees,Integer> {

    @Query("select e from Employees e where lastName like :name")
    public List<Employees> findByname(@QueryParam("name") String name);

}


text:
package org.apache.carbondata.hadoop.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.apache.hadoop.io.Writable;

/**
 * A String sequence that is usable as a key or value.
 */
public class StringArrayWritable implements Writable {
  private String[] values;

  public String[] toStrings() {
    return values;
  }

  public void set(String[] values) {
    this.values = values;
  }

  public String[] get() {
    return values;
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    int length = in.readInt();
    values = new String[length];
    for (int i = 0; i < length; i++) {
      byte[] b = new byte[in.readInt()];
      in.readFully(b);
      values[i] = new String(b, Charset.defaultCharset());
    }
  }

  @Override
  public void write(DataOutput out) throws IOException {
    out.writeInt(values.length);                 // write values
    for (int i = 0; i < values.length; i++) {
      byte[] b = values[i].getBytes(Charset.defaultCharset());
      out.writeInt(b.length);
      out.write(b);
    }
  }

  @Override
  public String toString() {
    return Arrays.toString(values);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="pl.bclogic.pulsator4droid.demo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <activity android:name="pl.bclogic.pulsator4droid.demo.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
package com.example.android.directshare;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toolbar;

/**
 * Provides the landing screen of this sample. There is nothing particularly interesting here. All
 * the codes related to the Direct Share feature are in {@link SampleChooserTargetService}.
 */
public class MainActivity extends Activity {

    private EditText mEditBody;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setActionBar((Toolbar) findViewById(R.id.toolbar));
        mEditBody = (EditText) findViewById(R.id.body);
        findViewById(R.id.share).setOnClickListener(mOnClickListener);
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.share:
                    share();
                    break;
            }
        }
    };

    /**
     * Emits a sample share {@link Intent}.
     */
    private void share() {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, mEditBody.getText().toString());
        startActivity(Intent.createChooser(sharingIntent, getString(R.string.send_intent_title)));
    }

}


text:
<?php

/**
 * Woorule_Logging trait.
 *
 * @package WooRule
 * @SuppressWarnings(PHPMD.CamelCaseClassName)
 * @SuppressWarnings(PHPMD.CamelCaseMethodName)
 * @SuppressWarnings(PHPMD.CamelCaseParameterName)
 * @SuppressWarnings(PHPMD.CamelCasePropertyName)
 * @SuppressWarnings(PHPMD.CamelCaseVariableName)
 * @SuppressWarnings(PHPMD.MissingImport)
 */
trait Woorule_Logging {

	/**
	 * Log.
	 *
	 * @param mixed $msg Message.
	 *
	 * @return void
	 * @SuppressWarnings(PHPMD.MissingImport)
	 * @SuppressWarnings(PHPMD.ElseExpression)
	 */
	private static function log( $msg ) {
		if ( WP_DEBUG === true ) {
			$logger = new WC_Logger();

			if ( is_array( $msg ) || is_object( $msg ) ) {
				$logger->add( 'woorule', wc_print_r( $msg, true ) );
			} else {
				$logger->add( 'woorule', $msg );
			}
		}
	}

	/**
	 * Activate API logging.
	 *
	 * @return void
	 * @codeCoverageIgnore
	 */
	private static function activate_api_logging() {
		add_action( 'http_api_debug', __CLASS__ . '::http_api_debug', 20, 5 );
	}

	/**
	 * Deactivate API logging.
	 *
	 * @return void
	 * @codeCoverageIgnore
	 */
	private static function deactivate_api_logging() {
		remove_action( 'http_api_debug', __CLASS__ . '::http_api_debug', 20 );
	}

	/**
	 * Debug HTTP api request.
	 *
	 * @param array|WP_Error $response
	 * @param string $arg2
	 * @param string $arg3
	 * @param array $parsed_args
	 * @param string $url
	 * @return void
	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
	 * @codeCoverageIgnore
	 */
	public static function http_api_debug( $response, $arg2, $arg3, $parsed_args, $url ) {
		$method          = $parsed_args['method'];
		$request_body    = isset( $parsed_args['body'] ) ? $parsed_args['body'] : '';
		$request_headers = isset( $parsed_args['headers'] ) ?
			implode( "\n", $parsed_args['headers'] ) : array();

		if ( is_wp_error( $response ) ) {
			/** @var WP_Error $response */

			$debug = "\n>>>>>>>> BEGIN CLIENT REQUEST DEBUG INFO >>>>>>>>\n\n" .
				"Request Method: $method\n" .
				"Request URL: $url\n" .
				"Request Headers: $request_headers\n" .
				"Request Body:\n$request_body\n\n" .
				"Error: {$response->get_error_message()}\n" .
				"<<<<<<<< END CLIENT REQUEST DEBUG INFO <<<<<<<<\n\n";

			self::log( $debug );

			return;
		}

		$body = wp_remote_retrieve_body( $response );
		$code = wp_remote_retrieve_response_code( $response );

		$debug = "\n>>>>>>>> BEGIN CLIENT REQUEST DEBUG INFO >>>>>>>>\n\n" .
			"Request Method: $method\n" .
			"Request URL: $url\n" .
			"Request Headers: $request_headers\n" .
			"Request Body:\n$request_body\n\n" .
			"Response Code: $code\n" .
			"Response Body:\n$body\n\n" .
			"<<<<<<<< END CLIENT REQUEST DEBUG INFO <<<<<<<<\n\n";

		self::log( $debug );
	}
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.bluemoon.jeesite.modules.activity.dao.MallPromotionActivityMjsDao">

	<sql id="mallPromotionActivityMjsColumns">
		a.activity_mjs_id AS "activityMjsId",
		a.activity_id AS "activityId",
		a.condition_type AS "conditionType"
	</sql>

	<sql id="mallPromotionActivityMjsJoins">
	</sql>

	<select id="get" resultType="MallPromotionActivityMjs">
		SELECT
			<include refid="mallPromotionActivityMjsColumns"/>
		FROM mall_promotion_activity_mjs a
		<include refid="mallPromotionActivityMjsJoins"/>
		WHERE a.id = #{id}
	</select>

	<select id="findList" resultType="MallPromotionActivityMjs">
		SELECT
			<include refid="mallPromotionActivityMjsColumns"/>
		FROM mall_promotion_activity_mjs a
		<include refid="mallPromotionActivityMjsJoins"/>
		<where>

		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
			</otherwise>
		</choose>
	</select>

	<select id="findAllList" resultType="MallPromotionActivityMjs">
		SELECT
			<include refid="mallPromotionActivityMjsColumns"/>
		FROM mall_promotion_activity_mjs a
		<include refid="mallPromotionActivityMjsJoins"/>
		<where>

		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
			</otherwise>
		</choose>
	</select>

	<insert id="insert">
		INSERT INTO mall_promotion_activity_mjs(
			activity_mjs_id,
			activity_id,
			condition_type
		) VALUES (
			#{activityMjsId},
			#{activityId},
			#{conditionType}
		)
	</insert>

	<update id="update">
		UPDATE mall_promotion_activity_mjs SET
			activity_mjs_id = #{activityMjsId},
			activity_id = #{activityId},
			condition_type = #{conditionType}
		WHERE id = #{id}
	</update>

	<update id="delete">
		DELETE FROM mall_promotion_activity_mjs
		WHERE id = #{id}
	</update>

</mapper>


text:
package org.apache.spark.api.java.function;

import java.io.Serializable;

/**
 * A function that takes two inputs and returns zero or more output records.
 */
public interface FlatMapFunction2<T1, T2, R> extends Serializable {
  Iterable<R> call(T1 t1, T2 t2) throws Exception;
}


text:
'use strict';

import veritoneApi from './apis/helper/ApiClient';
import apis from './apis';

export default function ApiClient(options) {
	return veritoneApi(options, apis);
}


text:
<?php

/**
 *
 * @package Core_Model
 * @author Christian Gijtenbeek
 */
class Core_Model_User extends TA_Model_Acl_Abstract
{

	public function getAuthSources()
	{
		return array(
			'test' => 'test',
			'default-sp' => 'TERENA'
		);
	}

	/**
	 * Get user by id
	 * @param		integer		$id		User id
	 * @return		Core_Resource_User_Item
	 */
	public function getUserById($id)
	{
		$row = $this->getResource('users')->getUserById( (int) $id );
    	if ($row === null) {
    		throw new TA_Model_Exception('id not found');
    	}
    	return $row;
	}

	/**
	 * Get user by email address
	 * @param		string		$email	Email address
	 * @return		Core_Resource_User_Item
	 */
	public function getUserByEmail($email)
	{
		return $this->getResource('users')->getUserByEmail( $email );
	}

	/**
	 * Get user by Smart ID
	 * @param		string		$smartid SmartID from SimpleSAML authproc
	 * @return		Core_Resource_User_Item
	 */
	public function getUserBySmartId($smartid)
	{
		return $this->getResource('users')->getUserBySmartId( $smartid );
	}

	/**
	 * Gets array of users for use in select box.
	 *
	 * @param 	boolean	$addEmpty Add empty value to array?
	 * @param 	string	$role role
	 * @return	array
	 */
	public function getUsersForSelect($addEmpty = null, $role = null)
	{
		$users = $this->getUsersWithRole(null, null, $role);

		$userArray = array();
		if ($addEmpty) {
			$userArray[0] = '---';
		}
		foreach ($users['rows'] as $user) {
			$userArray[$user->user_id] = $user->getOneliner();
		}

		return $userArray;
	}

	/**
	 * Search for string within user table
	 * @param	string		$search		String to search for in user table
	 * @return	array		Array of user_id
	 */
	public function searchUser($search)
	{
		if (!$this->checkAcl('searchUser')) {
            throw new TA_Model_Acl_Exception("Insufficient rights");
        }
        return $this->getResource('users')->searchUser($search);
	}

	/**
	 * Get a list of users
	 * @param		integer		$page	Page number to show
	 * @param		array		$order	Array with keys 'field' and 'direction'
	 * @param		boolean		$bypassAcl
	 * @return		array		Grid array with keys 'cols', 'primary', 'rows'
	 */
	public function getUsers($paged, $order, $filter=null, $bypassAcl = false)
	{
		if (!$bypassAcl) {
			if (!$this->checkAcl('list')) {
        	    throw new TA_Model_Acl_Exception("Insufficient rights");
        	}
        }

		return $this->getResource('users')->getUsers($paged, $order, $filter);
	}

	/**
	 * Get a list of users with certain role
	 * @param		string		$role	Name of role that user should have
	 */
	public function getUsersWithRole($paged, $order, $role)
	{
		if (!$role) {
			throw new TA_Model_Exception('Please provide a role');
		}
		if ( $this->getResource('roles')->getRoleIdByName($role) ) {
			$filter = new stdClass();
			$filter->filters = new stdClass();
			$filter->filters->role_name = $role;
			return $this->getResource('usersview')->getUsers($paged, $order, $filter);
		}
		return false;
	}

	/**
	 * Get role of user
	 * @param		integer		$id		User id
	 * @return		array		Array of roles
	 */
	public function getRolesOfUser($id)
	{
		if (!$this->checkAcl('showRoles')) {
            throw new TA_Model_Acl_Exception("Insufficient rights");
        }

        return $this->getResource('users')->getRolesOfUser($id);
	}

	public function getRolesForSelect($addEmpty = null)
	{
		if (!$this->checkAcl('showRoles')) {
            throw new TA_Model_Acl_Exception("Insufficient rights");
        }

        return $this->getResource('roles')->getRolesForSelect($addEmpty);
	}

	/**
	 * Remove user from resource
	 * @param		integer		$id		Id of record to delete
	 * @return		boolean
	 */
	public function delete($id = null)
	{
		if (!$this->checkAcl('delete')) {
            throw new TA_Model_Acl_Exception("Insufficient rights");
        }

		if (!$id) {
			return false;
		}
		$id = (int) $id;

		return $this->getUserById($id)->delete();
	}

	/**
	 * Save user to resource
	 *
	 * @param		array	$post	Post request
	 * @param		string	$action	The subform part to validate against
	 * @return		mixed	The primary key of the inserted/updated record or resource error message
	 */
	public function saveUser(array $post, $action = null)
	{
		if (!$this->checkAcl('save')) {
            throw new TA_Model_Acl_Exception("Insufficient rights");
        }

        // get different form (needed to validate values against) based on action parameter
		$formName = ($action) ? 'user' . ucfirst($action) : 'userInvite';
		$form = $this->getForm($formName);

		// perform validation
		if (!$form->isValid($post)) {
			return false;
		}

		if ( $form->file->isUploaded() ) {

			// save file to filesystem
			try {
				$fileInfo = array();
				$adapter = $form->file->getTransferAdapter();
			    $hash = $adapter->getHash('sha1');

			    $form->file->addFilter('rename', array(
			        'target' => Zend_Registry::get('config')->directories->uploads.$hash,
			        'overwrite' => true // @todo: set to FALSE when debugging is over!
			    ));

			    $origName = $adapter->getFileName();
			    $adapter->receive();
				$fileInfo = $adapter->getFileInfo();
				$fileInfo['file']['_filename_original'] = $origName;
				$fileInfo['file']['_filehash'] = $hash;
				$fileInfo['file']['_filetype'] = 2;
			} catch (Zend_File_Transfer_Exception $e) {
				$e->getMessage();
			}

		}

		$db = $this->getResource('files')->getAdapter();
		$db->beginTransaction();

		try {
			// get filtered values
			$values = $form->getValues();

			if ( $form->file->isUploaded() ) {
				// persist file
				$fileId = $this->getResource('files')->saveRow($fileInfo);
				$values['file_id'] = $fileId;
			}

			// if user_id is set, then get user object and pass it as parameter to the saveRow method
			$user = array_key_exists('user_id', $values) ?
				$this->getResource('users')
					 ->getUserById($values['user_id']) : null;

			$userId = $this->getResource('users')->saveRow($values, $user);

			// Give user a role
			if ($this->checkAcl('roleSave')) {
				if ( array_key_exists('role_id', $values) ) {
					$data = array('user_id' => $userId, 'role_id' => $values['role_id']);
					if (!$this->getResource('userroles')->getItemByValues($data)) {
					    $this->getResource('userroles')->saveRow($data);
					}
				}
        	}

        	// store invitee data in audit table
        	if (!$user) {
        		$values['user_id'] = $userId;
        		$this->saveUseraudit($values);
        	}

			$db->commit();
			if ($user) {
				$user->reloadSession();
			}
			return $userId;

		} catch (Exception $e) {
			$db->rollBack();
			throw new TA_Model_Exception($e->getMessage());
		}
	}

	/**
	 * Save user audit data
	 *
	 */
	public function saveUseraudit($values)
	{
		if (!$this->checkAcl('audit')) {
			throw new TA_Model_Acl_Exception("Insufficient rights");
        }
        $this->getResource('useraudit')->saveRow($values);
	}

	/**
     * Save user/role link
     *
     * @param	array	$post	Post variable
     * @return	mixed	The primary key of the inserted record if insert went OK
     *					false if user already belongs to this session
     */
	public function saveRoles(array $post)
	{
		if (!$this->checkAcl('roleSave')) {
			throw new TA_Model_Acl_Exception("Insufficient rights");
        }

		$form = $this->getForm('userRole');
		// perform validation
		if (!$form->isValid($post)) {
			return false;
		}

		$values = $form->getValues();

		$resource = $this->getResource('userroles');

		// if user role link does not already exist, save link
		if (!$resource->getItemByValues($values)) {
			return $resource->saveRow($values);
		} else {
			return false;
		}
	}

	/**
	 * Delete a role from this user
	 *
	 * @param	integer		$id		session_user_id
	 * @return	The number of rows deleted
	 */
	public function deleteRole($id = null)
	{
		if (!$this->checkAcl('roleDelete')) {
            throw new TA_Model_Acl_Exception("Insufficient rights");
        }

		if (!$id) {
			return false;
		}
		$id = (int) $id;

		return $this->getResource('userroles')->getItemById($id)->delete();
	}

	/**
	 * Save a user with federated attributes
	 *
	 * @param	array	$federatedAttributes	Federated attribute array
	 * @param	string	$uuid					Invite uuid
	 *
	 * @return mixed The primary key of the inserted/updated record
	 */
	public function saveUserFromFederatedIdentity(array $federatedAttributes, $uuid = null)
	{
		$users = $this->getResource('users');

		$user = ($uuid) ? $users->getUserByInvite($uuid) : null;

		$values = $users->mapFederatedToUser($federatedAttributes);
		// see https://tracker.terena.org/browse/CORE-245
		if ($uuid) {
			$values['invite'] = null;
		}

		return $users->getUserById(
			$users->saveRow(
				$values,
				$user
			)
		);
	}

}


text:
package org.postgresql.benchmark.statement;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.profile.GCProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.postgresql.benchmark.profilers.FlightRecorderProfiler;
import org.postgresql.util.ConnectionUtil;

import java.sql.*;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

@Fork(value = 1, jvmArgsPrepend = "-Xmx128m")
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class InsertBatch {
    private Connection connection;
    private PreparedStatement ps;
    String[] strings;

    @Param({"100"})
    int nrows;

    @Setup(Level.Trial)
    public void setUp() throws SQLException {
        Properties props = ConnectionUtil.getProperties();

        connection = DriverManager.getConnection(ConnectionUtil.getURL(), props);
        Statement s = connection.createStatement();;
        try {
            s.execute("drop table batch_perf_test");
        } catch(SQLException e) {
            /* ignore */
        }
        s.execute("create table batch_perf_test(a int4, b varchar(100), c int4)");
        s.close();
        ps = connection.prepareStatement("insert into batch_perf_test(a, b, c) values(?, ?, ?)");
        strings = new String[nrows];
        for (int i = 0; i < nrows; i++) {
            strings[i] = "s" + i;
        }
    }

    @TearDown(Level.Trial)
    public void tearDown() throws SQLException {
        ps.close();
        Statement s = connection.createStatement();
        s.execute("drop table batch_perf_test");
        s.close();
        connection.close();
    }

    @Benchmark
    public int[] insertBatch() throws SQLException {
        for (int i = 0; i < nrows; i++) {
            ps.setInt(1, i);
            ps.setString(2, strings[i]);
            ps.setInt(3, i);
            ps.addBatch();
        }
        return ps.executeBatch();
    }

    @Benchmark
    public void insertExecute(Blackhole b) throws SQLException {
        for (int i = 0; i < nrows; i++) {
            ps.setInt(1, i);
            ps.setString(2, strings[i]);
            ps.setInt(3, i);
            b.consume(ps.execute());
        }
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(InsertBatch.class.getSimpleName())
                .addProfiler(GCProfiler.class)
//                .addProfiler(FlightRecorderProfiler.class)
                .detectJvmArgs()
                .build();

        new Runner(opt).run();
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!-- Labelling_USER_Config: LB.[LocationPrint]GetAllLocationSites.xml -->
<Settings format="2">
 <CAT name="USER">
  <MOD name="Labelling">
   <LEV1 name="Config" nodekind="scheme">
    <LEV2 name="[LocationPrint]GetAllLocationSites">
     <LEV3 name="Data" nodekind="block">
      <LEV4 name="Article">
       <Setting name="DissectAssemblies" type="bool">
        <Val/>
       </Setting>
       <Setting name="DissectAssembliesLevel" type="int">
        <Val>1</Val>
       </Setting>
       <Setting name="DissectModules" type="bool">
        <Val/>
       </Setting>
       <Setting name="IncludeBusbarConnectorParts" type="bool">
        <Val>1</Val>
       </Setting>
       <Setting name="IncludeBusbarParts" type="bool">
        <Val>1</Val>
       </Setting>
       <Setting name="IncludeCableConnectionParts" type="bool">
        <Val/>
       </Setting>
       <Setting name="IncludeCableParts" type="bool">
        <Val>1</Val>
       </Setting>
       <Setting name="IncludeCableProjectParts" type="bool">
        <Val/>
       </Setting>
       <Setting name="IncludeClampParts" type="bool">
        <Val>1</Val>
       </Setting>
       <Setting name="IncludeConnectionParts" type="bool">
        <Val/>
       </Setting>
       <Setting name="IncludeDeviceTagsWithoutPartNumber" type="bool">
        <Val>1</Val>
       </Setting>
       <Setting name="IncludeHarnessAssemblyParts" type="bool">
        <Val/>
       </Setting>
       <Setting name="IncludeHarnessMainPart" type="bool">
        <Val/>
       </Setting>
       <Setting name="IncludePinAndJackParts" type="bool">
        <Val>1</Val>
       </Setting>
       <Setting name="IncludePlanningParts" type="bool">
        <Val/>
       </Setting>
       <Setting name="IncludePlugStripParts" type="bool">
        <Val>1</Val>
       </Setting>
       <Setting name="IncludePpeHookUpParts" type="bool">
        <Val>0</Val>
       </Setting>
       <Setting name="IncludePpeSpecificationParts" type="bool">
        <Val>0</Val>
       </Setting>
       <Setting name="IncludeTerminalStripParts" type="bool">
        <Val>1</Val>
       </Setting>
       <Setting name="SummarizePartsOfSameDT" type="bool">
        <Val>1</Val>
       </Setting>
      </LEV4>
      <Setting name="DocumentTypeID" type="int">
       <Val>13</Val>
      </Setting>
      <LEV4 name="Export">
       <Setting name="CharCode" type="int">
        <Val>2</Val>
       </Setting>
       <Setting name="CharacterCount" type="int">
        <Val>1</Val>
       </Setting>
       <Setting name="CharacterType" type="int">
        <Val>0</Val>
       </Setting>
       <Setting name="ColumnDescription" type="int">
        <Val>1</Val>
       </Setting>
       <Setting name="Editor" type="string">
        <Val/>
       </Setting>
       <Setting name="Separator" type="string">
        <Val/>
       </Setting>
       <Setting name="UmlautIf" type="int">
        <Val>0</Val>
       </Setting>
      </LEV4>
      <LEV4 name="File">
       <Setting name="Destination" type="string">
        <Val/>
       </Setting>
       <Setting name="Format" type="string">
        <Val>XmlLblTextExportConverterImpl</Val>
       </Setting>
       <Setting name="Template" type="string">
        <Val/>
       </Setting>
      </LEV4>
      <LEV4 name="Footer">
       <Setting name="OnEachPage" type="bool">
        <Val>0</Val>
       </Setting>
      </LEV4>
      <LEV4 name="Header">
       <Setting name="OnEachPage" type="bool">
        <Val>1</Val>
       </Setting>
      </LEV4>
      <LEV4 name="Record">
       <LEV5 name="FormatElements">
        <Setting name="Element" type="int">
         <Val>1</Val>
        </Setting>
        <Setting name="ID" type="int">
         <Val>0</Val>
        </Setting>
        <LEV6 name="PropertyPack0">
         <Setting name="Length" type="int">
          <Val>32</Val>
         </Setting>
         <Setting name="LengthType" type="int">
          <Val>0</Val>
         </Setting>
         <Setting name="PHGroupType" type="int">
          <Val>-1</Val>
         </Setting>
         <Setting name="PHType" type="int">
          <Val>0</Val>
         </Setting>
         <Setting name="PrecisionId" type="int">
          <Val>2</Val>
         </Setting>
         <Setting name="PrecisionVariable" type="bool">
          <Val>0</Val>
         </Setting>
         <Setting name="RelationId" type="int">
          <Val>17</Val>
         </Setting>
         <Setting name="RelationIndex" type="int">
          <Val>0</Val>
         </Setting>
         <Setting name="RelationName" type="string">
          <Val>Funktion</Val>
         </Setting>
         <Setting name="RelationSeparator" type="string">
          <Val/>
         </Setting>
         <Setting name="RightAlign" type="bool">
          <Val>1</Val>
         </Setting>
         <Setting name="SelectedPropertyId" type="int">
          <Val>19023</Val>
         </Setting>
         <Setting name="SelectedPropertyIndex" type="int">
          <Val>0</Val>
         </Setting>
         <Setting name="Settings" type="string">
          <Val>[19023<...>]</Val>
         </Setting>
         <Setting name="SumInLine" type="bool">
          <Val>0</Val>
         </Setting>
         <Setting name="Symbol" type="string">
          <Val>P19023</Val>
         </Setting>
         <Setting name="Unit" type="int">
          <Val>0</Val>
         </Setting>
         <Setting name="UnitFormatFlags" type="int">
          <Val>0</Val>
         </Setting>
         <Setting name="WithLineFeeds" type="bool">
          <Val>0</Val>
         </Setting>
        </LEV6>
       </LEV5>
       <Setting name="NrLinePerPage" type="int">
        <Val>10000</Val>
       </Setting>
       <Setting name="NrRecPerLine" type="int">
        <Val>1</Val>
       </Setting>
       <Setting name="RecSeparator" type="string">
        <Val>;</Val>
       </Setting>
      </LEV4>
      <Setting name="SameBlockOppress" type="int">
       <Val>0</Val>
      </Setting>
      <LEV4 name="SortFilter">
       <Setting name="FilterSchemeData" type="string">
        <Val>FilterLocation</Val>
       </Setting>
       <Setting name="FilterSchemeName" type="string">
        <Val>[LocationPrint]GetAllLocationSitesFilter</Val>
       </Setting>
       <Setting name="SortSchemeData" type="string">
        <Val/>
       </Setting>
       <Setting name="SortSchemeName" type="string">
        <Val/>
       </Setting>
       <Setting name="SubFilterSchemeData" type="string">
        <Val/>
       </Setting>
       <Setting name="SubFilterSchemeName" type="string">
        <Val/>
       </Setting>
       <Setting name="SubSortSchemeData" type="string">
        <Val/>
       </Setting>
       <Setting name="SubSortSchemeName" type="string">
        <Val/>
       </Setting>
      </LEV4>
      <Setting name="TemplateAction" type="string">
       <Val/>
      </Setting>
     </LEV3>
     <Setting name="Description" type="mlstring">
      <Val>??_??@[LocationPrint]GetAllLocationSites;</Val>
     </Setting>
     <Setting name="Name" type="mlstring">
      <Val>??_??@[LocationPrint]GetAllLocationSites;</Val>
     </Setting>
     <Setting name="ReadOnly" type="bool">
      <Val>0</Val>
     </Setting>
    </LEV2>
   </LEV1>
  </MOD>
 </CAT>
</Settings>


text:
import {default as applyUpdaters} from '../../src/utils/applyUpdaters';
import {default as equals} from 'equals';
import {assign} from 'es6-object-assign';

describe('applyUpdaters: ', function () {

  var prevOpts;

  beforeEach(() => {
    prevOpts = {
      option_one: 'one',
      option_two: 2,
      option_three: ['three']
    };
  });

  it('should call the updater if the option has been updated', () => {
    const opts = assign({}, prevOpts, {option_one: 'three'});
    const updaters = {option_one: sinon.stub()};
    const tag = 'tag';

    applyUpdaters(opts, prevOpts, updaters, tag);

    expect(updaters.option_one.calledWith(opts.option_one, tag)).to.be(true);
  });

  it('should not call the update if the option have not changed', () => {
    const opts = assign({}, prevOpts);
    const updaters = {option_one: sinon.stub()};
    const tag = 'tag';

    applyUpdaters(opts, prevOpts, updaters, tag);

    expect(updaters.option_one.calledWith(opts.option_one, tag)).not.to.be(true);
    expect(equals(opts, prevOpts)).to.be(true);
  });

  it('should deep compare objects', () => {
    prevOpts.option_three = { a : [ 2, 'three' ], b : [ 4 ] };
    const updaters = {option_three: sinon.stub()};
    const tag = 'tag';
    const opts = assign({}, prevOpts, {
      option_three: { a : [ 2, 3 ], b : [ 4 ] }
    });

    applyUpdaters(opts, prevOpts, updaters, tag);

    expect(updaters.option_three.calledWith(opts.option_three, tag)).to.be(true);
  });

  it('should deep compare functional objects', () => {
    function myValue(value) {
      this.value = value;
    }

    prevOpts.option_three = new myValue({ a : [ 2, 'three' ], b : [ 4 ] });
    const updaters = {option_three: sinon.stub()};
    const tag = 'tag';
    const opts = assign({}, prevOpts, {
      option_three: new myValue({ a : [ 2, 3 ], b : [ 4 ] })
    });

    applyUpdaters(opts, prevOpts, updaters, tag);

    expect(updaters.option_three.calledWith(opts.option_three, tag)).to.be(true);
  });

});


text:
package org.llama.llama.settings;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.preference.RingtonePreference;
import android.preference.SwitchPreference;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.common.base.Joiner;

import org.jdeferred.DoneCallback;
import org.jdeferred.Promise;
import org.llama.llama.MyApp;
import org.llama.llama.R;
import org.llama.llama.model.Country;
import org.llama.llama.model.Language;
import org.llama.llama.model.User;
import org.llama.llama.services.CountryService;
import org.llama.llama.services.ICountryService;
import org.llama.llama.services.ILanguageService;
import org.llama.llama.services.IUserService;
import org.llama.llama.services.LanguageService;
import org.llama.llama.services.UserService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * A {@link PreferenceActivity} that presents a set of application settings. On
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 *

 * See
 * Android Design: Settings for design guidelines and the Settings
 * API Guide for more information on developing a Settings UI.
 */
public class SettingsActivity extends AppCompatPreferenceActivity {

    /**
     * A preference value change listener that updates the preference's summary
     * to reflect its new value.
     */
    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        private ListPreference langPref;

        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            final String stringValue = value.toString();

            IUserService userService = new UserService();

            switch (preference.getKey()) {
                case "pref_user_name":
                    final EditTextPreference pref = (EditTextPreference) preference;
                    final String oldUsername = pref.getText();

                    if (!stringValue.equals(pref.getText())) {
                        userService.updateCurrentUserName(stringValue, new Runnable() {
                            @Override
                            public void run() {
                                pref.setText(oldUsername);
                                pref.setSummary(oldUsername);

                                Context context = MyApp.getAppContext();
                                CharSequence text = "Username '" + stringValue + "' is already taken.";
                                int duration = Toast.LENGTH_SHORT;

                                Toast toast = Toast.makeText(context, text, duration);
                                toast.show();
                            }
                        });
                    }
                    break;
                case "pref_display_name":
                    if (!stringValue.equals(((EditTextPreference) preference).getText())) {
                        userService.updateCurrentUserDisplayName(stringValue);
                    }
                    break;
                case "pref_mood":
                    if (!stringValue.equals(((EditTextPreference) preference).getText())) {
                        userService.updateCurrentUserMood(stringValue);
                    }
                    break;
                case "pref_email":
                    if (!stringValue.equals(((EditTextPreference) preference).getText())) {
                        userService.updateCurrentUserEmail(stringValue);
                    }
                    break;
                case "pref_country":
                    if (!stringValue.equals(((ListPreference) preference).getValue())) {
                        userService.updateCurrentUserCountry(stringValue);
                    }
                    break;
                case "pref_default_language":
                    langPref = (ListPreference) preference;
                    if (!stringValue.equals(langPref.getValue())) {
                        userService.updateCurrentUserDefaultLanguage(stringValue);
                    }
                    break;
                case "pref_languages":
                    Set<String> values = (Set<String>) value;
                    MultiSelectListPreference msPref = (MultiSelectListPreference) preference;

                    // there needs to be at least one language
                    if (values.isEmpty()) {
                        values.add("ll");
                    }

                    if (!values.equals(msPref.getValues())) {
                        userService.updateCurrentUserLanguages(values);

                        // update pref_default_language
                        if (langPref != null) {
                            List<String> entries = new ArrayList<>();
                            CharSequence[] entryValues = values.toArray(new CharSequence[entries.size()]);

                            CharSequence[] allEntries = msPref.getEntries();

                            for (String v : values) {
                                entries.add((String) allEntries[msPref.findIndexOfValue(v)]);
                            }

                            langPref.setEntries(entries.toArray(new CharSequence[entries.size()]));
                            langPref.setEntryValues(entryValues);
                            langPref.setDefaultValue(entryValues[0]);

                            // update default language if it's not in available languages any more
                            if (!values.contains(langPref.getValue())) {
                                langPref.setValue(values.iterator().next());
                            }

                            bindPreferenceSummaryToValue(langPref);
                        }
                    }
                    break;
                case "notifications_new_message":
                    Boolean boolValue = (Boolean) value;
                    if (boolValue == !((SwitchPreference) preference).isChecked()) {
                        userService.updateCurrentUserNotifications(boolValue);
                    }
                    break;
            }

            if (preference instanceof ListPreference) {
                // For list preferences, look up the correct display value in
                // the preference's 'entries' list.
                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(stringValue);

                // Set the summary to reflect the new value.
                preference.setSummary(
                        index >= 0
                                ? listPreference.getEntries()[index]
                                : null);

            } else if (preference instanceof MultiSelectListPreference) {
                MultiSelectListPreference listPreference = (MultiSelectListPreference) preference;
                CharSequence[] entries = listPreference.getEntries();
                Set<String> selectedValues = (Set<String>) value;
                SortedSet<String> selectedEntries = new TreeSet<>();

                for (String v : selectedValues) {
                    selectedEntries.add((String) entries[listPreference.findIndexOfValue(v)]);
                }

                preference.setSummary(Joiner.on(", ").join(selectedEntries));
            } else if (preference instanceof RingtonePreference) {
                // For ringtone preferences, look up the correct display value
                // using RingtoneManager.
                if (TextUtils.isEmpty(stringValue)) {
                    // Empty values correspond to 'silent' (no ringtone).
                    preference.setSummary(R.string.pref_ringtone_silent);
                } else {
                    Ringtone ringtone = RingtoneManager.getRingtone(
                            preference.getContext(), Uri.parse(stringValue));

                    if (ringtone == null) {
                        // Clear the summary if there was a lookup error.
                        preference.setSummary(null);
                    } else {
                        // Set the summary to reflect the new ringtone display
                        // name.
                        String name = ringtone.getTitle(preference.getContext());
                        preference.setSummary(name);
                    }
                }
            } else if (preference instanceof SwitchPreference) {
                // nothing to do
            } else {
                // For all other preferences, set the summary to the value's
                // simple string representation.
                preference.setSummary(stringValue);
            }
            return true;
        }
    };

    /**
     * Helper method to determine if the device has an extra-large screen. For
     * example, 10" tablets are extra-large.
     */
    private static boolean isXLargeTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
    }

    /**
     * Binds a preference's summary to its value. More specifically, when the
     * preference's value is changed, its summary (line of text below the
     * preference title) is updated to reflect the value. The summary is also
     * immediately updated upon calling this method. The exact display format is
     * dependent on the type of preference.
     *
     * @see #sBindPreferenceSummaryToValueListener
     */
    private static void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        // Trigger the listener immediately with the preference's
        // current value.
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    private static void bindPreferenceSummaryToValue(MultiSelectListPreference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        // Trigger the listener immediately with the preference's
        // current value.
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getStringSet(preference.getKey(), null));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    private void setupActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onIsMultiPane() {
        return isXLargeTablet(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void onBuildHeaders(List target) {
        loadHeadersFromResource(R.xml.pref_headers, target);
    }

    /**
     * This method stops fragment injection in malicious applications.
     * Make sure to deny any unknown fragments here.
     */
    protected boolean isValidFragment(String fragmentName) {
        return PreferenceFragment.class.getName().equals(fragmentName)
                || GeneralPreferenceFragment.class.getName().equals(fragmentName)
                /*|| DataSyncPreferenceFragment.class.getName().equals(fragmentName)*/
                || NotificationPreferenceFragment.class.getName().equals(fragmentName);
    }

    /**
     * This fragment shows general preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class GeneralPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_general);
            setHasOptionsMenu(true);

            IUserService userService = new UserService();
            Promise pu = userService.getUserInfo(userService.getCurrentUserId());
            ILanguageService langService = new LanguageService();
            final Promise pl = langService.getLanguages();
            ICountryService countryService = new CountryService();
            final Promise pc = countryService.getCountries();

            final EditTextPreference namePref = (EditTextPreference) findPreference("pref_display_name");
            final EditTextPreference usernamePref = (EditTextPreference) findPreference("pref_user_name");
            final EditTextPreference moodPref = (EditTextPreference) findPreference("pref_mood");
            final EditTextPreference emailPref = (EditTextPreference) findPreference("pref_email");
            final ListPreference countryPref = (ListPreference) findPreference("pref_country");
            final MultiSelectListPreference langsPref = (MultiSelectListPreference) findPreference("pref_languages");
            final ListPreference langPref = (ListPreference) findPreference("pref_default_language");

            pu.done(new DoneCallback() {
                @Override
                public void onDone(Object result) {
                    final User user = (User) result;

                    namePref.setText(user.getName());
                    namePref.setSummary(user.getName());
                    bindPreferenceSummaryToValue(namePref);

                    usernamePref.setText(user.getUsername());
                    usernamePref.setSummary(user.getUsername());
                    bindPreferenceSummaryToValue(usernamePref);

                    moodPref.setText(user.getMood());
                    moodPref.setSummary(user.getMood());
                    bindPreferenceSummaryToValue(moodPref);

                    emailPref.setText(user.getEmail());
                    emailPref.setSummary(user.getEmail());
                    bindPreferenceSummaryToValue(emailPref);

                    countryPref.setValue(user.getCountry());
                    setListPreferenceData(countryPref, pc);
                    countryPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                        @Override
                        public boolean onPreferenceClick(Preference preference) {
                            setListPreferenceData(countryPref, pc);
                            return false;
                        }
                    });

                    langsPref.setValues(user.getLanguages().keySet());
                    setListPreferenceData(langPref, langsPref, pl);
                    langsPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                        @Override
                        public boolean onPreferenceClick(Preference preference) {
                            setListPreferenceData(langPref, langsPref, pl);
                            return false;
                        }
                    });

                    // TODO: update entries/values for pref_default_language when pref_languages is changed
                    langPref.setValue(user.getDefaultLanguage());
                    langPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                        @Override
                        public boolean onPreferenceClick(Preference preference) {
                            setListPreferenceData(langPref, langsPref, PreferenceManager
                                    .getDefaultSharedPreferences(langsPref.getContext())
                                    .getStringSet(langsPref.getKey(), null));
                            return false;
                        }
                    });
                }
            });
        }

        protected static void setListPreferenceData(final ListPreference lp, Promise p) {
            p.done(new DoneCallback() {
                @Override
                public void onDone(Object result) {
                    Map<String, Country> countries = (Map<String, Country>) result;

                    List<String> entries = new ArrayList<>();
                    for (Country c : countries.values()) {
                        if (c.getNativeName().equals(c.getName())) {
                            entries.add(c.getNativeName());
                        } else {
                            entries.add(c.getNativeName() + " (" + c.getName() + ")");
                        }
                    }

                    lp.setEntries(entries.toArray(new CharSequence[entries.size()]));
                    lp.setEntryValues(countries.keySet().toArray(new CharSequence[entries.size()]));
                    lp.setDefaultValue("AT");
                    bindPreferenceSummaryToValue(lp);
                }
            });
        }

        public static void setListPreferenceData(ListPreference lp, MultiSelectListPreference langsp, Set<String> values) {
            List<String> entries = new ArrayList<>();
            CharSequence[] entryValues = values.toArray(new CharSequence[entries.size()]);

            CharSequence[] allEntries = langsp.getEntries();

            for (String v : values) {
                entries.add((String) allEntries[langsp.findIndexOfValue(v)]);
            }

            lp.setEntries(entries.toArray(new CharSequence[entries.size()]));
            lp.setEntryValues(entryValues);
            lp.setDefaultValue(entryValues[0]);
            bindPreferenceSummaryToValue(lp);
        }

        protected static void setListPreferenceData(final ListPreference lp, final MultiSelectListPreference langsp, Promise p) {
            p.done(new DoneCallback() {
                @Override
                public void onDone(Object result) {
                    Map<String, Language> langs = (Map<String, Language>) result;

                    List<String> entries = new ArrayList<>();
                    for (Language l : langs.values()) {
                        if (l.getNativeName().equals(l.getName())) {
                            entries.add(l.getNativeName());
                        } else {
                            entries.add(l.getNativeName() + " (" + l.getName() + ")");
                        }
                    }

                    langsp.setEntries(entries.toArray(new CharSequence[entries.size()]));
                    langsp.setEntryValues(langs.keySet().toArray(new CharSequence[entries.size()]));
                    langsp.setDefaultValue("en");
                    bindPreferenceSummaryToValue(langsp);

                    setListPreferenceData(lp, langsp, langsp.getValues());
                }
            });
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * This fragment shows notification preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class NotificationPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_notification);
            setHasOptionsMenu(true);

            IUserService userService = new UserService();
            Promise pu = userService.getUserInfo(userService.getCurrentUserId());

            final SwitchPreference notificationsPref = (SwitchPreference) findPreference("notifications_new_message");

            pu.done(new DoneCallback() {
                @Override
                public void onDone(Object result) {
                    final User user = (User) result;

                    notificationsPref.setChecked(user.getNotifications());
                    notificationsPref.setDefaultValue(user.getNotifications());
                    bindPreferenceSummaryToValue(notificationsPref);
                }
            });

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.
            //bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));

            PreferenceScreen screen = getPreferenceScreen();
            screen.removePreference(findPreference("notifications_new_message_ringtone"));
            screen.removePreference(findPreference("notifications_new_message_vibrate"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * This fragment shows data and sync preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class DataSyncPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //addPreferencesFromResource(R.xml.pref_data_sync);
            setHasOptionsMenu(true);

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.
            bindPreferenceSummaryToValue(findPreference("sync_frequency"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace blink\eventbus;

use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\EventDispatcher\ListenerProviderInterface;
use Psr\EventDispatcher\StoppableEventInterface;

/**
 * Class EventBus
 *
 * @package blink\eventbus
 */
class EventBus implements EventDispatcherInterface, ListenerProviderInterface
{
    protected array $listeners = [];

    /**
     * Attach a handler to the given eventClass.
     *
     * @param string $eventClass
     * @param callable $handler
     */
    public function attach(string $eventClass, callable $handler)
    {
        $this->listeners[$eventClass][] = $handler;
    }

    /**
     * Dispatch a event.
     *
     * @param object $event
     * @return object
     */
    public function dispatch(object $event)
    {
        $listeners = $this->getListenersForEvent($event);

        foreach ($listeners as $listener) {
            if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
                return $event;
            }
            $listener($event);
        }

        return $event;
    }

    /**
     * Starts a new transaction.
     *
     * @return Transaction
     */
    public function beginTransaction(): Transaction
    {
        return new Transaction($this);
    }

    public function getListenersForEvent(object $event): iterable
    {
        yield from $this->listenersFor(get_class($event));
        yield from $this->listenersFor(...class_parents($event));
        yield from $this->listenersFor(...class_implements($event));
    }

    protected function listenersFor(string ...$classNames): iterable
    {
        foreach ($classNames as $className) {
            if (isset($this->listeners[$className])) {
                yield from $this->listeners[$className];
            }
        }
    }
}


text:
///<reference path="..\typings\globals\node\index.d.ts" />
"use strict";
var ContractsModule = require("../Library/Contracts");
var Util = require("../Library/Util");
var AutoCollectExceptions = (function () {
    function AutoCollectExceptions(client) {
        if (!!AutoCollectExceptions.INSTANCE) {
            throw new Error("Exception tracking should be configured from the applicationInsights object");
        }
        AutoCollectExceptions.INSTANCE = this;
        this._client = client;
    }
    AutoCollectExceptions.prototype.isInitialized = function () {
        return this._isInitialized;
    };
    AutoCollectExceptions.prototype.enable = function (isEnabled) {
        var _this = this;
        if (isEnabled) {
            this._isInitialized = true;
            var self = this;
            if (!this._exceptionListenerHandle) {
                var handle = function (reThrow, error) {
                    var data = AutoCollectExceptions.getExceptionData(error, false);
                    var envelope = _this._client.getEnvelope(data);
                    _this._client.channel.handleCrash(envelope);
                    if (reThrow) {
                        throw error;
                    }
                };
                this._exceptionListenerHandle = handle.bind(this, true);
                this._rejectionListenerHandle = handle.bind(this, false);
                process.on("uncaughtException", this._exceptionListenerHandle);
                process.on("unhandledRejection", this._rejectionListenerHandle);
            }
        }
        else {
            if (this._exceptionListenerHandle) {
                process.removeListener("uncaughtException", this._exceptionListenerHandle);
                process.removeListener("unhandledRejection", this._rejectionListenerHandle);
                this._exceptionListenerHandle = undefined;
                this._rejectionListenerHandle = undefined;
                delete this._exceptionListenerHandle;
                delete this._rejectionListenerHandle;
            }
        }
    };
    /**
     * Track an exception
     * @param error the exception to track
     * @param handledAt where this exception was handled (leave null for unhandled)
     * @param properties additional properties
     * @param measurements metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
     */
    AutoCollectExceptions.getExceptionData = function (error, isHandled, properties, measurements) {
        var exception = new ContractsModule.Contracts.ExceptionData();
        exception.properties = properties;
        exception.severityLevel = ContractsModule.Contracts.SeverityLevel.Error;
        exception.measurements = measurements;
        exception.exceptions = [];
        var stack = error["stack"];
        var exceptionDetails = new ContractsModule.Contracts.ExceptionDetails();
        exceptionDetails.message = error.message;
        exceptionDetails.typeName = error.name;
        exceptionDetails.parsedStack = this.parseStack(stack);
        exceptionDetails.hasFullStack = Util.isArray(exceptionDetails.parsedStack) && exceptionDetails.parsedStack.length > 0;
        exception.exceptions.push(exceptionDetails);
        var data = new ContractsModule.Contracts.Data();
        data.baseType = "Microsoft.ApplicationInsights.ExceptionData";
        data.baseData = exception;
        return data;
    };
    AutoCollectExceptions.parseStack = function (stack) {
        var parsedStack = undefined;
        if (typeof stack === "string") {
            var frames = stack.split("\n");
            parsedStack = [];
            var level = 0;
            var totalSizeInBytes = 0;
            for (var i = 0; i <= frames.length; i++) {
                var frame = frames[i];
                if (_StackFrame.regex.test(frame)) {
                    var parsedFrame = new _StackFrame(frames[i], level++);
                    totalSizeInBytes += parsedFrame.sizeInBytes;
                    parsedStack.push(parsedFrame);
                }
            }
            // DP Constraint - exception parsed stack must be < 32KB
            // remove frames from the middle to meet the threshold
            var exceptionParsedStackThreshold = 32 * 1024;
            if (totalSizeInBytes > exceptionParsedStackThreshold) {
                var left = 0;
                var right = parsedStack.length - 1;
                var size = 0;
                var acceptedLeft = left;
                var acceptedRight = right;
                while (left < right) {
                    // check size
                    var lSize = parsedStack[left].sizeInBytes;
                    var rSize = parsedStack[right].sizeInBytes;
                    size += lSize + rSize;
                    if (size > exceptionParsedStackThreshold) {
                        // remove extra frames from the middle
                        var howMany = acceptedRight - acceptedLeft + 1;
                        parsedStack.splice(acceptedLeft, howMany);
                        break;
                    }
                    // update pointers
                    acceptedLeft = left;
                    acceptedRight = right;
                    left++;
                    right--;
                }
            }
        }
        return parsedStack;
    };
    AutoCollectExceptions.prototype.dispose = function () {
        AutoCollectExceptions.INSTANCE = null;
        this._isInitialized = false;
    };
    return AutoCollectExceptions;
}());
AutoCollectExceptions.INSTANCE = null;
var _StackFrame = (function () {
    function _StackFrame(frame, level) {
        this.sizeInBytes = 0;
        this.level = level;
        this.method = "<no_method>";
        this.assembly = Util.trim(frame);
        var matches = frame.match(_StackFrame.regex);
        if (matches && matches.length >= 5) {
            this.method = Util.trim(matches[2]) || this.method;
            this.fileName = Util.trim(matches[4]) || "<no_filename>";
            this.line = parseInt(matches[5]) || 0;
        }
        this.sizeInBytes += this.method.length;
        this.sizeInBytes += this.fileName.length;
        this.sizeInBytes += this.assembly.length;
        // todo: these might need to be removed depending on how the back-end settles on their size calculation
        this.sizeInBytes += _StackFrame.baseSize;
        this.sizeInBytes += this.level.toString().length;
        this.sizeInBytes += this.line.toString().length;
    }
    return _StackFrame;
}());
// regex to match stack frames from ie/chrome/ff
// methodName=$2, fileName=$4, lineNo=$5, column=$6
_StackFrame.regex = /^([\s]+at)?(.*?)(\@|\s\(|\s)([^\(\@\n]+):([0-9]+):([0-9]+)(\)?)$/;
_StackFrame.baseSize = 58; //'{"method":"","level":,"assembly":"","fileName":"","line":}'.length
module.exports = AutoCollectExceptions;


text:
package basi.CoronaLauncher;

import java.util.prefs.Preferences;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;

public class Configuration {

	private static final String KEY_PROJECT_PATH = "projectPath";
	private static final String KEY_CORONA_PATH = "coronaPath";
	private static final String KEY_PROVISIONING_PATH = "provisioningPath";

	private String projectPath;
	private String coronaPath;
	private String provisioningPath;

	private static Configuration instance;

	public static synchronized Configuration getInstance() {
	    if (instance == null) {
	        instance = new Configuration();
	    }
	    return instance;
	}

	private Configuration() {

	}

	public boolean load() {
		JFileChooser fr = new JFileChooser();
		FileSystemView fw = fr.getFileSystemView();
		String defaultPathValue = fw.getDefaultDirectory().getAbsolutePath();

		Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
		projectPath = prefs.get(KEY_PROJECT_PATH, defaultPathValue);
		coronaPath = prefs.get(KEY_CORONA_PATH, defaultPathValue);
		provisioningPath = prefs.get(KEY_PROVISIONING_PATH, defaultPathValue);

		return true;
	}

	public boolean save() {
		Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
		prefs.put(KEY_PROJECT_PATH, projectPath);
		prefs.put(KEY_CORONA_PATH, coronaPath);
		prefs.put(KEY_PROVISIONING_PATH, provisioningPath);

		return true;
	}

	public String getCoronaPath() {
		return coronaPath;
	}

	public String getProjectsPath() {
		return projectPath;
	}

	public String getProvisioningPath() {
		return provisioningPath;
	}

	public void setCoronaPath(String newPath) {
		coronaPath = newPath;

	}

	public void setProjectsPath(String newPath) {
		projectPath = newPath;
	}

	public void setProvisioningPath(String newPath) {
		provisioningPath = newPath;
	}
}