text:
package unaggregated

import (
	"testing"
	"time"

	"github.com/m3db/m3metrics/aggregation"
	"github.com/m3db/m3metrics/generated/proto/aggregationpb"
	"github.com/m3db/m3metrics/generated/proto/metricpb"
	"github.com/m3db/m3metrics/generated/proto/pipelinepb"
	"github.com/m3db/m3metrics/generated/proto/policypb"
	"github.com/m3db/m3metrics/generated/proto/transformationpb"
	"github.com/m3db/m3metrics/metadata"
	"github.com/m3db/m3metrics/metric"
	"github.com/m3db/m3metrics/pipeline"
	"github.com/m3db/m3metrics/pipeline/applied"
	"github.com/m3db/m3metrics/policy"
	"github.com/m3db/m3metrics/transformation"
	xtime "github.com/m3db/m3x/time"

	"github.com/stretchr/testify/require"
)

var (
	testCounter = Counter{
		ID:    []byte("testCounter"),
		Value: 1234,
	}
	testCounterUnion = MetricUnion{
		Type:       metric.CounterType,
		ID:         []byte("testCounter"),
		CounterVal: 1234,
	}
	testBatchTimer = BatchTimer{
		ID:     []byte("testBatchTimer"),
		Values: []float64{4.78, -2384, 0.0, 3145, 9999},
	}
	testBatchTimerUnion = MetricUnion{
		Type:          metric.TimerType,
		ID:            []byte("testBatchTimer"),
		BatchTimerVal: []float64{4.78, -2384, 0.0, 3145, 9999},
	}
	testGauge = Gauge{
		ID:    []byte("testGauge"),
		Value: 45.28,
	}
	testGaugeUnion = MetricUnion{
		Type:     metric.GaugeType,
		ID:       []byte("testGauge"),
		GaugeVal: 45.28,
	}
	testMetadatas = metadata.StagedMetadatas{
		{
			CutoverNanos: 1234,
			Tombstoned:   false,
		},
		{
			CutoverNanos: 4567,
			Tombstoned:   true,
			Metadata: metadata.Metadata{
				Pipelines: []metadata.PipelineMetadata{
					{
						AggregationID: aggregation.MustCompressTypes(aggregation.Count),
						StoragePolicies: []policy.StoragePolicy{
							policy.NewStoragePolicy(time.Second, xtime.Second, time.Hour),
						},
					},
					{
						AggregationID: aggregation.DefaultID,
						StoragePolicies: []policy.StoragePolicy{
							policy.NewStoragePolicy(time.Minute, xtime.Minute, 6*time.Hour),
							policy.NewStoragePolicy(time.Hour, xtime.Hour, 30*24*time.Hour),
						},
						Pipeline: applied.NewPipeline([]applied.OpUnion{
							{
								Type: pipeline.TransformationOpType,
								Transformation: pipeline.TransformationOp{
									Type: transformation.Absolute,
								},
							},
							{
								Type: pipeline.RollupOpType,
								Rollup: applied.RollupOp{
									ID:            []byte("foo"),
									AggregationID: aggregation.MustCompressTypes(aggregation.Last, aggregation.Sum),
								},
							},
						}),
					},
				},
			},
		},
		{
			CutoverNanos: 32768,
			Tombstoned:   false,
			Metadata: metadata.Metadata{
				Pipelines: []metadata.PipelineMetadata{
					{
						AggregationID: aggregation.DefaultID,
						Pipeline: applied.NewPipeline([]applied.OpUnion{
							{
								Type: pipeline.TransformationOpType,
								Transformation: pipeline.TransformationOp{
									Type: transformation.PerSecond,
								},
							},
							{
								Type: pipeline.RollupOpType,
								Rollup: applied.RollupOp{
									ID:            []byte("bar"),
									AggregationID: aggregation.MustCompressTypes(aggregation.P99),
								},
							},
						}),
					},
				},
			},
		},
	}
	testBadMetadatas = metadata.StagedMetadatas{
		{
			Metadata: metadata.Metadata{
				Pipelines: []metadata.PipelineMetadata{
					{
						AggregationID: aggregation.DefaultID,
						StoragePolicies: []policy.StoragePolicy{
							policy.NewStoragePolicy(time.Minute, xtime.Unit(100), 6*time.Hour),
						},
					},
				},
			},
		},
	}
	testCounterWithMetadatas = CounterWithMetadatas{
		Counter:         testCounter,
		StagedMetadatas: testMetadatas,
	}
	testBatchTimerWithMetadatas = BatchTimerWithMetadatas{
		BatchTimer:      testBatchTimer,
		StagedMetadatas: testMetadatas,
	}
	testGaugeWithMetadatas = GaugeWithMetadatas{
		Gauge:           testGauge,
		StagedMetadatas: testMetadatas,
	}
	testCounterProto = metricpb.Counter{
		Id:    []byte("testCounter"),
		Value: 1234,
	}
	testBatchTimerProto = metricpb.BatchTimer{
		Id:     []byte("testBatchTimer"),
		Values: []float64{4.78, -2384, 0.0, 3145, 9999},
	}
	testGaugeProto = metricpb.Gauge{
		Id:    []byte("testGauge"),
		Value: 45.28,
	}
	testMetadatasProto = metricpb.StagedMetadatas{
		Metadatas: []metricpb.StagedMetadata{
			{
				CutoverNanos: 1234,
				Tombstoned:   false,
			},
			{
				CutoverNanos: 4567,
				Tombstoned:   true,
				Metadata: metricpb.Metadata{
					Pipelines: []metricpb.PipelineMetadata{
						{
							AggregationId: aggregationpb.AggregationID{Id: aggregation.MustCompressTypes(aggregation.Count)[0]},
							StoragePolicies: []policypb.StoragePolicy{
								{
									Resolution: &policypb.Resolution{
										WindowSize: time.Second.Nanoseconds(),
										Precision:  time.Second.Nanoseconds(),
									},
									Retention: &policypb.Retention{
										Period: time.Hour.Nanoseconds(),
									},
								},
							},
						},
						{
							AggregationId: aggregationpb.AggregationID{Id: 0},
							StoragePolicies: []policypb.StoragePolicy{
								{
									Resolution: &policypb.Resolution{
										WindowSize: time.Minute.Nanoseconds(),
										Precision:  time.Minute.Nanoseconds(),
									},
									Retention: &policypb.Retention{
										Period: (6 * time.Hour).Nanoseconds(),
									},
								},
								{
									Resolution: &policypb.Resolution{
										WindowSize: time.Hour.Nanoseconds(),
										Precision:  time.Hour.Nanoseconds(),
									},
									Retention: &policypb.Retention{
										Period: (30 * 24 * time.Hour).Nanoseconds(),
									},
								},
							},
							Pipeline: pipelinepb.AppliedPipeline{
								Ops: []pipelinepb.AppliedPipelineOp{
									{
										Type: pipelinepb.AppliedPipelineOp_TRANSFORMATION,
										Transformation: &pipelinepb.TransformationOp{
											Type: transformationpb.TransformationType_ABSOLUTE,
										},
									},
									{
										Type: pipelinepb.AppliedPipelineOp_ROLLUP,
										Rollup: &pipelinepb.AppliedRollupOp{
											Id:            []byte("foo"),
											AggregationId: aggregationpb.AggregationID{Id: aggregation.MustCompressTypes(aggregation.Last, aggregation.Sum)[0]},
										},
									},
								},
							},
						},
					},
				},
			},
			{
				CutoverNanos: 32768,
				Tombstoned:   false,
				Metadata: metricpb.Metadata{
					Pipelines: []metricpb.PipelineMetadata{
						{
							AggregationId: aggregationpb.AggregationID{Id: 0},
							Pipeline: pipelinepb.AppliedPipeline{
								Ops: []pipelinepb.AppliedPipelineOp{
									{
										Type: pipelinepb.AppliedPipelineOp_TRANSFORMATION,
										Transformation: &pipelinepb.TransformationOp{
											Type: transformationpb.TransformationType_PERSECOND,
										},
									},
									{
										Type: pipelinepb.AppliedPipelineOp_ROLLUP,
										Rollup: &pipelinepb.AppliedRollupOp{
											Id:            []byte("bar"),
											AggregationId: aggregationpb.AggregationID{Id: aggregation.MustCompressTypes(aggregation.P99)[0]},
										},
									},
								},
							},
						},
					},
				},
			},
		},
	}
	testBadMetadatasProto = metricpb.StagedMetadatas{
		Metadatas: []metricpb.StagedMetadata{
			{
				Metadata: metricpb.Metadata{
					Pipelines: []metricpb.PipelineMetadata{
						{
							StoragePolicies: []policypb.StoragePolicy{
								{},
							},
						},
					},
				},
			},
		},
	}
	testCounterWithMetadatasProto = metricpb.CounterWithMetadatas{
		Counter:   testCounterProto,
		Metadatas: testMetadatasProto,
	}
	testBatchTimerWithMetadatasProto = metricpb.BatchTimerWithMetadatas{
		BatchTimer: testBatchTimerProto,
		Metadatas:  testMetadatasProto,
	}
	testGaugeWithMetadatasProto = metricpb.GaugeWithMetadatas{
		Gauge:     testGaugeProto,
		Metadatas: testMetadatasProto,
	}
)

func TestCounterToUnion(t *testing.T) {
	require.Equal(t, testCounterUnion, testCounter.ToUnion())
}

func TestCounterToProto(t *testing.T) {
	var pb metricpb.Counter
	testCounter.ToProto(&pb)
	require.Equal(t, testCounterProto, pb)
}

func TestCounterFromProto(t *testing.T) {
	var c Counter
	c.FromProto(testCounterProto)
	require.Equal(t, testCounter, c)
}

func TestCounterRoundTrip(t *testing.T) {
	var (
		pb metricpb.Counter
		c  Counter
	)
	testCounter.ToProto(&pb)
	c.FromProto(pb)
	require.Equal(t, testCounter, c)
}

func TestBatchTimerToUnion(t *testing.T) {
	require.Equal(t, testBatchTimerUnion, testBatchTimer.ToUnion())
}

func TestBatchTimerToProto(t *testing.T) {
	var pb metricpb.BatchTimer
	testBatchTimer.ToProto(&pb)
	require.Equal(t, testBatchTimerProto, pb)
}

func TestBatchTimerFromProto(t *testing.T) {
	var c BatchTimer
	c.FromProto(testBatchTimerProto)
	require.Equal(t, testBatchTimer, c)
}

func TestBatchTimerRoundTrip(t *testing.T) {
	var (
		pb metricpb.BatchTimer
		c  BatchTimer
	)
	testBatchTimer.ToProto(&pb)
	c.FromProto(pb)
	require.Equal(t, testBatchTimer, c)
}

func TestGaugeToUnion(t *testing.T) {
	require.Equal(t, testGaugeUnion, testGauge.ToUnion())
}

func TestGaugeToProto(t *testing.T) {
	var pb metricpb.Gauge
	testGauge.ToProto(&pb)
	require.Equal(t, testGaugeProto, pb)
}

func TestGaugeFromProto(t *testing.T) {
	var c Gauge
	c.FromProto(testGaugeProto)
	require.Equal(t, testGauge, c)
}

func TestGaugeRoundTrip(t *testing.T) {
	var (
		pb metricpb.Gauge
		c  Gauge
	)
	testGauge.ToProto(&pb)
	c.FromProto(pb)
	require.Equal(t, testGauge, c)
}

func TestCounterWithMetadatasToProto(t *testing.T) {
	var pb metricpb.CounterWithMetadatas
	require.NoError(t, testCounterWithMetadatas.ToProto(&pb))
	require.Equal(t, testCounterWithMetadatasProto, pb)
}

func TestCounterWithMetadatasToProtoBadMetadatas(t *testing.T) {
	var pb metricpb.CounterWithMetadatas
	badCounterWithMetadatas := CounterWithMetadatas{
		Counter:         testCounter,
		StagedMetadatas: testBadMetadatas,
	}
	require.Error(t, badCounterWithMetadatas.ToProto(&pb))
}

func TestCounterWithMetadatasFromProto(t *testing.T) {
	var c CounterWithMetadatas
	require.NoError(t, c.FromProto(&testCounterWithMetadatasProto))
	require.Equal(t, testCounterWithMetadatas, c)
}

func TestCounterWithMetadatasFromProtoNilProto(t *testing.T) {
	var c CounterWithMetadatas
	require.Equal(t, errNilCounterWithMetadatasProto, c.FromProto(nil))
}

func TestCounterWithMetadatasFromProtoBadProto(t *testing.T) {
	var c CounterWithMetadatas
	badCounterWithMetadatasProto := metricpb.CounterWithMetadatas{
		Counter:   testCounterProto,
		Metadatas: testBadMetadatasProto,
	}
	require.Error(t, c.FromProto(&badCounterWithMetadatasProto))
}

func TestCounterWithMetadatasRoundTrip(t *testing.T) {
	var (
		pb metricpb.CounterWithMetadatas
		c  CounterWithMetadatas
	)
	require.NoError(t, testCounterWithMetadatas.ToProto(&pb))
	require.NoError(t, c.FromProto(&pb))
	require.Equal(t, testCounterWithMetadatas, c)
}

func TestBatchTimerWithMetadatasToProto(t *testing.T) {
	var pb metricpb.BatchTimerWithMetadatas
	require.NoError(t, testBatchTimerWithMetadatas.ToProto(&pb))
	require.Equal(t, testBatchTimerWithMetadatasProto, pb)
}

func TestBatchTimerWithMetadatasToProtoBadMetadatas(t *testing.T) {
	var pb metricpb.BatchTimerWithMetadatas
	badBatchTimerWithMetadatas := BatchTimerWithMetadatas{
		BatchTimer:      testBatchTimer,
		StagedMetadatas: testBadMetadatas,
	}
	require.Error(t, badBatchTimerWithMetadatas.ToProto(&pb))
}

func TestBatchTimerWithMetadatasFromProto(t *testing.T) {
	var b BatchTimerWithMetadatas
	require.NoError(t, b.FromProto(&testBatchTimerWithMetadatasProto))
	require.Equal(t, testBatchTimerWithMetadatas, b)
}

func TestBatchTimerWithMetadatasFromProtoNilProto(t *testing.T) {
	var b BatchTimerWithMetadatas
	require.Equal(t, errNilBatchTimerWithMetadatasProto, b.FromProto(nil))
}

func TestBatchTimerWithMetadatasFromProtoBadProto(t *testing.T) {
	var b BatchTimerWithMetadatas
	badBatchTimerWithMetadatasProto := metricpb.BatchTimerWithMetadatas{
		BatchTimer: testBatchTimerProto,
		Metadatas:  testBadMetadatasProto,
	}
	require.Error(t, b.FromProto(&badBatchTimerWithMetadatasProto))
}

func TestBatchTimerWithMetadatasRoundTrip(t *testing.T) {
	var (
		pb metricpb.BatchTimerWithMetadatas
		b  BatchTimerWithMetadatas
	)
	require.NoError(t, testBatchTimerWithMetadatas.ToProto(&pb))
	require.NoError(t, b.FromProto(&pb))
	require.Equal(t, testBatchTimerWithMetadatas, b)
}

func TestGaugeWithMetadatasToProto(t *testing.T) {
	var pb metricpb.GaugeWithMetadatas
	require.NoError(t, testGaugeWithMetadatas.ToProto(&pb))
	require.Equal(t, testGaugeWithMetadatasProto, pb)
}

func TestGaugeWithMetadatasToProtoBadMetadatas(t *testing.T) {
	var pb metricpb.GaugeWithMetadatas
	badGaugeWithMetadatas := GaugeWithMetadatas{
		Gauge:           testGauge,
		StagedMetadatas: testBadMetadatas,
	}
	require.Error(t, badGaugeWithMetadatas.ToProto(&pb))
}

func TestGaugeWithMetadatasFromProto(t *testing.T) {
	var g GaugeWithMetadatas
	require.NoError(t, g.FromProto(&testGaugeWithMetadatasProto))
	require.Equal(t, testGaugeWithMetadatas, g)
}

func TestGaugeWithMetadatasFromProtoNilProto(t *testing.T) {
	var g GaugeWithMetadatas
	require.Equal(t, errNilGaugeWithMetadatasProto, g.FromProto(nil))
}

func TestGaugeWithMetadatasFromProtoBadProto(t *testing.T) {
	var g GaugeWithMetadatas
	badGaugeWithMetadatasProto := metricpb.GaugeWithMetadatas{
		Gauge:     testGaugeProto,
		Metadatas: testBadMetadatasProto,
	}
	require.Error(t, g.FromProto(&badGaugeWithMetadatasProto))
}

func TestGaugeWithMetadatasRoundTrip(t *testing.T) {
	var (
		pb metricpb.GaugeWithMetadatas
		g  GaugeWithMetadatas
	)
	require.NoError(t, testGaugeWithMetadatas.ToProto(&pb))
	require.NoError(t, g.FromProto(&pb))
	require.Equal(t, testGaugeWithMetadatas, g)
}


text:
@interface SNAlertView : UIAlertView {
	NSMutableArray		*fieldArray;
	NSMutableDictionary	*fieldTable;
	BOOL				isLayouted;
	CGSize				keyboardSize;
}
- (void)registerForKeyboardNotifications;
- (void)keyboardWillShow:(NSNotification*)aNotification ;
#pragma mark Access to TextFields
- (NSArray*)textFieldTags;
- (NSInteger)textFieldCount;
- (UITextField*)textFieldWithTag:(NSString*)tag ;
- (UITextField*)textFieldAtIndex:(NSInteger)index;
- (BOOL)addTextFieldDefaultValue:(NSString*)value placeholder:(NSString*)placeholder tag:(NSString*)tag;
#pragma mark Layout helper
- (float)heightOfLabelArea;
- (float)heightOfFields;
@end

redpajama_set_name: RedPajamaGithub


text:
This is my [advent of code](https://adventofcode.com/) repo.

## Leader Board
Have a Slack channel and want daily scores posted to you? Check out the [Advent Of Code Leaderboard Slack Bot](https://github.com/tomswartz07/AdventOfCodeLeaderboard).


text:
import Ivory.BSP.STM32.Peripheral.DMA
import Ivory.BSP.STM32F427.DMA

main :: IO ()
main = do
  putStr (showDMA dma1)


text:
#include "harfbuzz-impl.h"
#include "harfbuzz-stream-private.h"
#include <stdlib.h>

#if 0
#include <stdio.h>
#define  LOG(x)  _hb_log x

static void
_hb_log( const char*   format, ... )
{
  va_list  ap;

  va_start( ap, format );
  vfprintf( stderr, format, ap );
  va_end( ap );
}

#else
#define  LOG(x)  do {} while (0)
#endif

HB_INTERNAL void
_hb_close_stream( HB_Stream stream )
{
  if (!stream)
      return;
  free(stream->base);
  free(stream);
}

HB_INTERNAL HB_Int
_hb_stream_pos( HB_Stream stream )
{
  LOG(( "_hb_stream_pos() -> %ld\n", stream->pos ));
  return stream->pos;
}

HB_INTERNAL HB_Error
_hb_stream_seek( HB_Stream stream,
		 HB_UInt pos )
{
  HB_Error  error = 0;

  stream->pos = pos;
  if (pos > stream->size)
      error = ERR(HB_Err_Read_Error);

  LOG(( "_hb_stream_seek(%ld) -> 0x%04X\n", pos, error ));
  return error;
}

HB_INTERNAL HB_Error
_hb_stream_frame_enter( HB_Stream stream,
			HB_UInt count )
{
  HB_Error  error = HB_Err_Ok;

  /* check new position, watch for overflow */
  if (HB_UNLIKELY (stream->pos + count > stream->size ||
		   stream->pos + count < stream->pos))
  {
    error = ERR(HB_Err_Read_Error);
    goto Exit;
  }

  /* set cursor */
  stream->cursor = stream->base + stream->pos;
  stream->pos   += count;

Exit:
  LOG(( "_hb_stream_frame_enter(%ld) -> 0x%04X\n", count, error ));
  return error;
}

HB_INTERNAL void
_hb_stream_frame_exit( HB_Stream stream )
{
  stream->cursor = NULL;

  LOG(( "_hb_stream_frame_exit()\n" ));
}


text:
namespace CSTest
{
    namespace TextEntry
    {
        //------------------------------------------------------------------------------
        void State::CreateSystems()
        {
            CreateSystem<Common::TestNavigator>("Text Entry");
            CreateSystem<TextEntryPresenter>();
            CreateSystem<Common::BackButtonSystem>();
        }

        //------------------------------------------------------------------------------
        void State::OnInit()
        {
            GetMainScene()->SetClearColour(CS::Colour(0.9f, 0.9f, 0.9f, 1.0f));
        }
    }
}


text:
Phingy is a small collection of build scripts which you can mix together differently
depending on your project. To use these scripts, you include the required ones in
your build script starting with your own project.xml.

###Installation & dependencies

Phingy is installed via [Composer](http://getcomposer.org/). Add the following to
your project's `composer.json` and run `composer install`:

```json
{
    "require": {
        "3ev/phingy": "~4.0"
    },
    "scripts": {
        "post-install-cmd": [
            "Tev\\Phingy\\ComposerScripts::postInstall"
        ]
    },
    "config": {
        "bin-dir": "bin"
    }
}
```

You'll then be able to run Phing using

```
$ bin/phing
```

###'Skel' files

Phingy will automatically generate files from `.skel` files anywhere in your project.
These files can include Phing properties which will be replaced with their actual
values at compile time.

You may for example want to create an Apache vhost config file for your project,
which you'll be able to commit to source control without having to including any
environment specific config. Like so:

```
# In config/httpd.conf.skel

<VirtualHost *:80>
    ServerName ${build.url}
    DocumentRoot ${build.public_dir}
</VirtualHost>
```

###Database tasks & S3

If you'd like to make use of the database tasks that push/pull database dumps
from Amazon S3, you will need to install the
[Pear Amazon S3 package](http://pear.php.net/package/Services_Amazon_S3/):

```sh
$ pear install Services_Amazon_S3
```

This will allow you to backup and download your full database to/from S3 using:

```
$ bin/phing db:commit
$ bin/phing db:update
```

There are numerous other database tasks that make it easy to configure a MySQL
database for your project.

###Setting up a webserver

Phingy includes a `build:server` task which will by default configure and install
Apache configuration for your project.

Config will be symlinked from `config/httpd.conf` to `/etc/apache2/sites-enabled`,
so you can commit a file to version control (or use a `.skel` extension) and simply
run

```
$ sudo bin/phing build:server
```

to start your project running on Apache.

###Platform specific tasks

Phingy includes a few 'platform' specifc task sets, as followss:

- [typo3](https://github.com/3ev/phingy/blob/master/scripts/platform/typo3.xml)
Typo3 specific tasks (includes [db](https://github.com/3ev/phingy/blob/master/scripts/core/database.xml)). Will set up TYPO3 on build, and provides some utility methods.
- [sphinx](https://github.com/3ev/phingy/blob/master/scripts/platform/sphinx.xml)
Sphinx specific tasks. Provides tasks to index Sphinx data for the project.
- [laravel](https://github.com/3ev/phingy/blob/master/scripts/platform/laravel.xml)
Laravel specific tasks. Provides tasks to work with the Laravel framework

###Setting up your project with Platforms

When you run `composer install`, you will be prompted to pick a template to use
for your project. Selecting a template will create a file called `project.xml` in
your project's `config/` directory.

The `project.xml` file includes a number of hooks you can add to for project-specific
tasks. Currently, These are:

```
project:config                Configure extra properties to use in your build
project:build:before          Run some tasks before `build`
project:build:after           Run some tasks after `build`
project:build:housekeeping    Cleanup any uneeded files or data
```

Each platform includes each of these hooks as well, of the form `[platform]:build:before` etc.
If you'd like to make use of a platform, simply include it with:

```xml
<import file="${phingy.path}/scripts/platform/[platform].xml" />
```

and then call each of its hooks in your project-specific hooks:

```xml
<target name="project:build:before">
    <phingcall target="[platform]:build:before" />
</target>
```

**Note:** If you pick a non-default template (like 'typo3'), all of this will be
handled for you.

###Adding your own project specific tasks and config

You can add any of your own tasks in `config/project.xml`. These should be namespaced
with `project:` for convention. You can either add standalone tasks, or call them
in any of the available hooks.

###Overriding existing tasks

If you need to, you can override built in tasks by creating a new task with the
same name in your `project.xml`. You shouldn't have to do this though, as the
built in hooks provide enough flexibility for you to customise tasks.

###Adding extra config

You add should any project specific config to `config/project.properties` if possible.
If you need to prompt the user for it during build, you can do so in the
`project:config` hook.

###About ./build.xml

`build.xml` sits in the root of your project, and is symlinked from `vendor/`.
You should add this file to your `.gitignore`.


text:
using System.Diagnostics;

namespace ForexFramework.Indicators
{
    public class RelativeStrengthIndicator
    {
        private double? _previousValue = null;
        private readonly ExponentialMovingAverage _downAverage;
        private readonly ExponentialMovingAverage _upAverage;

        public RelativeStrengthIndicator(int periods)
        {
            _upAverage = new ExponentialMovingAverage(periods);
            _downAverage = new ExponentialMovingAverage(periods);
        }

        public void Push(double value)
        {
            if (value < _previousValue)
            {
                Debug.Assert(_previousValue != null, "_previousValue != null");
                _downAverage.Push(_previousValue.Value - value);
                _upAverage.Push(0);
            }
            if (value > _previousValue)
            {
                Debug.Assert(_previousValue != null, "_previousValue != null");
                _upAverage.Push(value - _previousValue.Value);
                _downAverage.Push(0);
            }

            _previousValue = value;
        }

        public double? Value
        {
            get
            {
                if (!_downAverage.Value.HasValue)
                {
                    return null;
                }
                Debug.Assert(_upAverage.Value.HasValue);
                if (_downAverage.Value.Value < 1e-30)
                {
                    return 100;
                }
                var rs = _upAverage.Value.Value / _downAverage.Value.Value;
                return 100 - 100 / (1 + rs);
            }
        }
    }
}


text:
package de.dominicscheurer.fsautils {
	import Conversions._

	object Types {
		type Letter = Symbol
		type Word = List[Letter]
		type NFADeltaResult = Set[State]
        type States = Set[State]

		abstract sealed class State

		case class q(i: Int) extends State {
		  override def toString = i toString
		}

		case class set(s: Set[State]) extends State {
		  override def toString = {
		    var sb = new StringBuilder

		    sb ++= s.foldLeft("{")((result, state) => result + state.toString + ",")
		    sb = sb.dropRight(1 - s.isEmpty)
		    sb ++= "}"

		    sb toString
		  }
		}

		case class pair(s1: State, s2: State) extends State
	}
}


text:
describe('Service: $cordovaSerial', function() {

  var $cordovaSerial, $rootScope;

  beforeEach(module('ngCordova.plugins.serial'));

  beforeEach(inject(function (_$cordovaSerial_, _$q_, _$rootScope_) {
    $cordovaSerial = _$cordovaSerial_;
    $rootScope = _$rootScope_;

    serial = {
      requestPermission: angular.noop,
      open: angular.noop,
      write: angular.noop,
      writeHex: angular.noop,
      read: angular.noop,
      registerReadCallback: angular.noop,
      close: angular.noop
    };
  }));

  describe('when requestPermission is called', function() {
    var options = {
      vid: '1000',
      pid: '1200',
      driver: 'FtdiSerialDriver'
    };

    it('should call serial.requestPermission with the provided options', function() {
      spyOn(serial, 'requestPermission');
      $cordovaSerial.requestPermission(options);
      expect(serial.requestPermission).toHaveBeenCalledWith(options, jasmine.any(Function), jasmine.any(Function));
    });

    it('should resolve the promise when serial.requestPermission is successful', function() {
      var result;

      spyOn(serial, 'requestPermission').and.callFake(function(options, successCallback, errorCallback) {
        successCallback();
      });
      $cordovaSerial.requestPermission(options).then(function() {
        result = 'success';
      }).catch(function(err) {
        fail(err);
      });
      $rootScope.$digest();
      expect(result).toEqual('success');
    });

    it('should reject the promise when serial.requestPermission has an error', function() {
      var expectedError = 'Some error';
      var error;

      spyOn(serial, 'requestPermission').and.callFake(function(options, successCallback, errorCallback) {
        errorCallback(expectedError);
      });
      $cordovaSerial.requestPermission(options).then(function() {
        fail('Expected requestPermission to reject promise');
      }).catch(function(err) {
        error = err;
      });
      $rootScope.$digest();
      expect(error).toEqual(expectedError);
    });
  });

  describe('when open is called', function() {
    var options = {
      baudRate: 115200
    };

    it('should call serial.open with the provided options', function() {
      spyOn(serial, 'open');
      $cordovaSerial.open(options);
      expect(serial.open).toHaveBeenCalledWith(options, jasmine.any(Function), jasmine.any(Function));
    });

    it('should resolve the promise when serial.open is successful', function() {
      var result;

      spyOn(serial, 'open').and.callFake(function(options, successCallback, errorCallback) {
        successCallback();
      });
      $cordovaSerial.open(options).then(function() {
        result = 'success';
      }).catch(function(err) {
        fail(err);
      });
      $rootScope.$digest();
      expect(result).toEqual('success');
    });

    it('should reject the promise when serial.open has an error', function() {
      var expectedError = 'Some error';
      var error;

      spyOn(serial, 'open').and.callFake(function(options, successCallback, errorCallback) {
        errorCallback(expectedError);
      });
      $cordovaSerial.open(options).then(function() {
        fail('Expected open to reject promise');
      }).catch(function(err) {
        error = err;
      });
      $rootScope.$digest();
      expect(error).toEqual(expectedError);
    });
  });

  describe('when write is called', function() {
    var data = 'ff';

    it('should call serial.write with the provided options', function() {
      spyOn(serial, 'write');
      $cordovaSerial.write(data);
      expect(serial.write).toHaveBeenCalledWith(data, jasmine.any(Function), jasmine.any(Function));
    });

    it('should resolve the promise when serial.write is successful', function() {
      var result;

      spyOn(serial, 'write').and.callFake(function(data, successCallback, errorCallback) {
        successCallback();
      });
      $cordovaSerial.write(data).then(function() {
        result = 'success';
      }).catch(function(err) {
        fail(err);
      });
      $rootScope.$digest();
      expect(result).toEqual('success');
    });

    it('should reject the promise when serial.write has an error', function() {
      var expectedError = 'Some error';
      var error;

      spyOn(serial, 'write').and.callFake(function(data, successCallback, errorCallback) {
        errorCallback(expectedError);
      });
      $cordovaSerial.write(data).then(function() {
        fail('Expected write to reject promise');
      }).catch(function(err) {
        error = err;
      });
      $rootScope.$digest();
      expect(error).toEqual(expectedError);
    });
  });

  describe('when writeHex is called', function() {
    var data = 'ff';

    it('should call serial.writeHex with the provided options', function() {
      spyOn(serial, 'writeHex');
      $cordovaSerial.writeHex(data);
      expect(serial.writeHex).toHaveBeenCalledWith(data, jasmine.any(Function), jasmine.any(Function));
    });

    it('should resolve the promise when serial.writeHex is successful', function() {
      var result;

      spyOn(serial, 'writeHex').and.callFake(function(data, successCallback, errorCallback) {
        successCallback();
      });
      $cordovaSerial.writeHex(data).then(function() {
        result = 'success';
      }).catch(function(err) {
        fail(err);
      });
      $rootScope.$digest();
      expect(result).toEqual('success');
    });

    it('should reject the promise when serial.writeHex has an error', function() {
      var expectedError = 'Some error';
      var error;

      spyOn(serial, 'writeHex').and.callFake(function(data, successCallback, errorCallback) {
        errorCallback(expectedError);
      });
      $cordovaSerial.writeHex(data).then(function() {
        fail('Expected writeHex to reject promise');
      }).catch(function(err) {
        error = err;
      });
      $rootScope.$digest();
      expect(error).toEqual(expectedError);
    });
  });

  describe('when read is called', function() {
    var data = [0,1];

    it('should resolve the promise when serial.read is successful', function() {
      var result;

      spyOn(serial, 'read').and.callFake(function(successCallback, errorCallback) {
        successCallback(data);
      });
      $cordovaSerial.read().then(function() {
        result = 'success';
      }).catch(function(err) {
        fail(err);
      });
      $rootScope.$digest();
      expect(result).toEqual('success');
    });

    it('should parse the successful response data as a Uint8Array', function() {
      var response;

      spyOn(serial, 'read').and.callFake(function(successCallback, errorCallback) {
        successCallback(data);
      });
      $cordovaSerial.read().then(function(result) {
         response = result;
      }).catch(function(err) {
        fail(err);
      });
      $rootScope.$digest();
      expect(response instanceof Uint8Array).toEqual(true);
    });

    it('should reject the promise when serial.read has an error', function() {
      var expectedError = 'Some error';
      var error;

      spyOn(serial, 'read').and.callFake(function(successCallback, errorCallback) {
        errorCallback(expectedError);
      });
      $cordovaSerial.read().then(function() {
        fail('Expected read to reject promise');
      }).catch(function(err) {
        error = err;
      });
      $rootScope.$digest();
      expect(error).toEqual(expectedError);
    });
  });

  describe('when registerReadCallback is called', function() {
    var data = [0,1];

    it('should call serial.registerReadCallback with a success and failure callback', function() {
      var successCallback = angular.noop;
      var errorCallback = angular.noop;
      spyOn(serial, 'registerReadCallback');
      $cordovaSerial.registerReadCallback(successCallback, errorCallback);
      expect(serial.registerReadCallback).toHaveBeenCalledWith(jasmine.any(Function), errorCallback);
    });

    it('should call the provided success callback', function() {
      var successCallback = jasmine.createSpy('successCallback');
      var errorCallback = jasmine.createSpy('errorCallback');

      spyOn(serial, 'registerReadCallback').and.callFake(function(successCallback, errorCallback) {
        successCallback(data);
      });

      $cordovaSerial.registerReadCallback(successCallback, errorCallback);

      expect(successCallback).toHaveBeenCalled();
      expect(errorCallback).not.toHaveBeenCalled();
    });

    it('should parse the successful response data as a Uint8Array', function() {
      var response;

      var successCallback = jasmine.createSpy('successCallback').and.callFake(function(data) {
        response = data;
      });
      var errorCallback = jasmine.createSpy('errorCallback');

      spyOn(serial, 'registerReadCallback').and.callFake(function(successCallback, errorCallback) {
        successCallback(data);
      });

      $cordovaSerial.registerReadCallback(successCallback, errorCallback);

      expect(response instanceof Uint8Array).toEqual(true);
    });

    it('should call the provided failure callback', function() {
      var error = 'Some error';
      var successCallback = jasmine.createSpy('successCallback');
      var errorCallback = jasmine.createSpy('errorCallback');

      spyOn(serial, 'registerReadCallback').and.callFake(function(successCallback, errorCallback) {
        errorCallback(error);
      });

      $cordovaSerial.registerReadCallback(successCallback, errorCallback);

      expect(successCallback).not.toHaveBeenCalled();
      expect(errorCallback).toHaveBeenCalledWith(error);
    });
  });

  describe('when close is called', function() {
    it('should resolve the promise when serial.close is successful', function() {
      var result;

      spyOn(serial, 'close').and.callFake(function(successCallback, errorCallback) {
        successCallback();
      });
      $cordovaSerial.close().then(function() {
        result = 'success';
      }).catch(function(err) {
        fail(err);
      });
      $rootScope.$digest();
      expect(result).toEqual('success');
    });

    it('should reject the promise when serial.close has an error', function() {
      var expectedError = 'Some error';
      var error;

      spyOn(serial, 'close').and.callFake(function(successCallback, errorCallback) {
        errorCallback(expectedError);
      });
      $cordovaSerial.close().then(function() {
        fail('Expected close to reject promise');
      }).catch(function(err) {
        error = err;
      });
      $rootScope.$digest();
      expect(error).toEqual(expectedError);
    });
  });

});


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">
    <meta name="description" content="Good choice Limo offers a huge range of transportation needs in the city of Toronto, Mississauga, Oakville, Burlington, Milton and the Province of Ontario.">
    <meta name="author" content="Good Choice Limo">

    <title>Good Choice Limo - The ultimate Limo experience</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/thankyou.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

Thank you!

                            Your submission is recieved and we will contact you soon.

                         BACK TO HOME


text:
module ActiveRecord
  module QueryCounter
    IGNORE = [/^PRAGMA (?!(table_info))/, /^SELECT attr.attname/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/]

    attr_reader :active, :count

    def run(&block)
      @active, @count = true, 0
      block.call
      @active = false
      @count
    end

    def call(name, start, finish, message_id, values)
      if active && !ignore?(values)
        # puts values[:sql]
        @count += 1
      end
    end

    def ignore?(values)
      'CACHE' == values[:name] || IGNORE.any? { |r| values[:sql].strip =~ r }
    end

    extend self
    ActiveSupport::Notifications.subscribe('sql.active_record', self)
  end
end

module ActiveRecord
  class Base
    def self.count_queries(&block)
      QueryCounter.run(&block)
    end
  end
end


text:
package org.instantlogic.designer.flow;

import org.instantlogic.designer.DesignerApplicationGenerator;
import org.instantlogic.designer.FlowDesign;
import org.instantlogic.designer.FlowNodeBaseDesignEntityGenerator;
import org.instantlogic.designer.SubFlowDesign;
import org.instantlogic.designer.event.FlowNodeDetailsEventGenerator;
import org.instantlogic.designer.event.PlaceTemplateDetailsEventGenerator;

public class FlowNodeFlowGenerator extends FlowDesign {

	public static final FlowNodeFlowGenerator FLOW = new FlowNodeFlowGenerator();

	private FlowNodeFlowGenerator() {
		DesignerApplicationGenerator.APPLICATION.addToFlows(this);
		setName("FlowNode");
	}

	@Override
	public void init() {
		addToParameters(FlowNodeBaseDesignEntityGenerator.ENTITY);

		SubFlowDesign flowNodeChoiceSubFlow = addSubFlow(FlowNodeChoiceFlowGenerator.FLOW);

		newEdge()
			.setEvent(FlowNodeDetailsEventGenerator.EVENT)
			.setEndNode(flowNodeChoiceSubFlow);

		super.init();
	}
}


text:
<?php

$db_dir = getcwd();
$dbname = 'comments.txt';
$mytable ="posts";

// Check for filedb support
//if (!file_exists($dbname)) die("File $dbname not extant.");

function xdb_write($title,$author,$timestamp,$content) {
	global $dbname;
	// Get write handle (not needed for read)
	@$fp = fopen($dbname, 'a');
    if (!$fp) {
        //The file could not be opened
        $opstatus = "The comment data file could not be opened.";
    } else {
        //The file was successfully opened, lets write the comment to it.
        $outputstring = "

" .$title. "

Posted:" .$timestamp. " by " .$author. "

" .$content. "
\r\n";
        //Write to the file
        fwrite($fp, $outputstring, strlen($outputstring));
        //We are finished writing, close the file for security / memory management purposes
        fclose($fp);
        //Post the success message
        $opstatus = "Your post was successfully entered.";
    }
    return $opstatus;
}

function db_readmany($id='*') {
	global $dbname, $mytable, $collectionType, $xmlpath;
	//echo "$collectionType($xmlpath)";
	echo hook_action('mytopiclist',array());
}

function db_readone($id='*') {
	global $dbname, $mytable, $collectionType, $xmlpath;
	//echo "$collectionType($xmlpath)";

	if ($id == '*') {
		return;
	} else {
		$querystring = " WHERE (post_id=$id)";
	}

	$queryType = 'topic';
	$dx[15] = 'any2dita.dita';
	$dx[28] = 'migrate.dita';
	$xmlpath = $dx[$id];

	//$outstream = hook_action('xform_stream',$srcstream);
	$outstream = hook_filter('trydita2html',array($xmlpath));//tiny implementation now in plugin_ditaxform.php
	$row['post_id'] = $id;
	$row['post_title'] = '';
	$row['post_content'] = $outstream;
	$row['post_author'] = '';
	$row['post_date'] = '';
	$row['guid'] = $id;

	return $row;
}

function xdb_read($id) {
	global $dbname;
	ob_start();
	include $dbname;
	$output = ob_get_contents();
	ob_end_clean();
	return $output;
}

$ccmd = 'read';
if ($ccmd == 'create') {
}

// Read
if ($ccmd == 'read') {
	//include("comments.txt");
}

// Insert
if ($ccmd == 'insert') {
        //The file was successfully opened, lets write the comment to it.
        $outputstring = "

" .$title. "

Posted:" .$timestamp. " by " .$name. "

" .$message. "
\r\n";
        //Write to the file
        fwrite($fp, $outputstring, strlen($outputstring));
        //We are finished writing, close the file for security / memory management purposes
        fclose($fp);
        //Post the success message
        $output = "Your post was successfully entered.";
}

// Delete
if ($ccmd == 'delete') {
}
?>


text:
import pygame
import pygame.freetype

from . import (
    gamestate,
    )

def main(args=None):
    """The main routine."""
    # if args is None:
    #     args = sys.argv[1:]
    # XXX - arg parsing

    pygame.init()
    pygame.freetype.init()

    WHITE = (255, 255, 255)

    size = (800, 480)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Yendor Defender")

    gs = gamestate.GameState()

    while gs.active():
        gs.handle_events()
        gs.update()

        screen.fill(WHITE)

        gs.draw(screen)
        pygame.display.flip()

    pygame.quit()

if __name__ == "__main__":
    main()


text:
> **Tags:**
> - [New Feature]
> - [Bug Fix]
> - [Spec Compliancy]
> - [Breaking Change]
> - [Documentation]
> - [Internal]
> - [Polish]

**Note**: Gaps between patch versions are faulty/broken releases.

## v0.2.0

- **Breaking Change**
  + upgrade to tcomb v2.2

## v0.1.4

- **Internal**
  + Optimized `integer` type (@chriskjaer idea)

## v0.1.3

- **New Feature**
  + Support format property for string types #6 (@oliger idea)
  + Support integer type #5 (@chriskjaer idea)
- **Bug Fix**
  + Removed `t.util.format`
- **Internal**
  + Optimized `Null` type
- **Polish**
  + Formatted CHANGELOG

## v0.1.2

- **Internal**
  + Upgrade to latest `tcomb`
  + Move `tcomb` to `peerDependencies`

## v0.1.1

- **Internal**
  + Upgrade to latest `tcomb`


text:
<resources>
  <string name='choose_account_label'>"Wybierz konto"</string>
  <string name='add_account_button_label'>"Dodaj konto"</string>
</resources>


text:
Write a robot simulator.

A robot factory's test facility needs a program to verify robot movements.

The robots have three possible movements:

- turn right
- turn left
- advance

Robots are placed on a hypothetical infinite grid, facing a particular
direction (north, east, south, or west) at a set of {x,y} coordinates,
e.g., {3,8}, with coordinates increasing to the north and east.

The robot then receives a number of instructions, at which point the
testing facility verifies the robot's new position, and in which
direction it is pointing.

- The letter-string "RAALAL" means:
  - Turn right
  - Advance twice
  - Turn left
  - Advance once
  - Turn left yet again
- Say a robot starts at {7, 3} facing north. Then running this stream
  of instructions should leave it at {9, 4} facing west.

## Setup

Go through the setup instructions for JavaScript to
install the necessary dependencies:

http://exercism.io/languages/javascript

## Making the Test Suite Pass

Execute the tests with:

    jasmine-node .

In many test suites all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by
changing `xit` to `it`.

## Source

Inspired by an interview question at a famous company.


text:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef MODULE_NAME
#define MODULE_NAME "log"
#endif

#include <px4_log.h>
#if defined(__PX4_POSIX)
#include <px4_daemon/server_io.h>
#endif

#include <uORB/uORB.h>
#include <uORB/topics/log_message.h>
#include <drivers/drv_hrt.h>

static orb_advert_t orb_log_message_pub = NULL;

__EXPORT const char *__px4_log_level_str[_PX4_LOG_LEVEL_PANIC + 1] = { "DEBUG", "INFO", "WARN", "ERROR", "PANIC" };
__EXPORT const char *__px4_log_level_color[_PX4_LOG_LEVEL_PANIC + 1] =
{ PX4_ANSI_COLOR_GREEN, PX4_ANSI_COLOR_RESET, PX4_ANSI_COLOR_YELLOW, PX4_ANSI_COLOR_RED, PX4_ANSI_COLOR_RED };

void px4_log_initialize(void)
{
	assert(orb_log_message_pub == NULL);

	/* we need to advertise with a valid message */
	struct log_message_s log_message;
	log_message.timestamp = hrt_absolute_time();
	log_message.severity = 6; //info
	strcpy((char *)log_message.text, "initialized uORB logging");

#if !defined(PARAM_NO_ORB)
	orb_log_message_pub = orb_advertise_queue(ORB_ID(log_message), &log_message, 2);
#endif /* !PARAM_NO_ORB */

	if (!orb_log_message_pub) {
		PX4_ERR("failed to advertise log_message");
	}
}

__EXPORT void px4_log_modulename(int level, const char *moduleName, const char *fmt, ...)
{
	FILE *out = stdout;
	bool use_color = true;

#ifdef __PX4_POSIX
	out = get_stdout(&use_color);
#endif

#ifndef PX4_LOG_COLORIZED_OUTPUT
	use_color = false;
#endif

	if (level >= _PX4_LOG_LEVEL_INFO) {
		if (use_color) { fputs(__px4_log_level_color[level], out); }

		fprintf(out, __px4__log_level_fmt __px4__log_level_arg(level));

		if (use_color) { fputs(PX4_ANSI_COLOR_GRAY, out); }

		fprintf(out, __px4__log_modulename_pfmt, moduleName);

		if (use_color) { fputs(__px4_log_level_color[level], out); }

		va_list argptr;
		va_start(argptr, fmt);
		vfprintf(out, fmt, argptr);
		va_end(argptr);

		if (use_color) { fputs(PX4_ANSI_COLOR_RESET, out); }

		fputc('\n', out);
	}

	/* publish an orb log message */
	if (level >= _PX4_LOG_LEVEL_WARN && orb_log_message_pub) { //only publish important messages

		struct log_message_s log_message;
		const unsigned max_length_pub = sizeof(log_message.text);
		log_message.timestamp = hrt_absolute_time();

		const uint8_t log_level_table[] = {
			7, /* _PX4_LOG_LEVEL_DEBUG */
			6, /* _PX4_LOG_LEVEL_INFO */
			4, /* _PX4_LOG_LEVEL_WARN */
			3, /* _PX4_LOG_LEVEL_ERROR */
			0  /* _PX4_LOG_LEVEL_PANIC */
		};
		log_message.severity = log_level_table[level];

		unsigned pos = 0;

		va_list argptr;

		pos += snprintf((char *)log_message.text + pos, max_length_pub - pos, __px4__log_modulename_pfmt, moduleName);
		va_start(argptr, fmt);
		pos += vsnprintf((char *)log_message.text + pos, max_length_pub - pos, fmt, argptr);
		va_end(argptr);
		log_message.text[max_length_pub - 1] = 0; //ensure 0-termination

#if !defined(PARAM_NO_ORB)
		orb_publish(ORB_ID(log_message), orb_log_message_pub, &log_message);
#endif /* !PARAM_NO_ORB */
	}
}

__EXPORT void px4_log_raw(int level, const char *fmt, ...)
{
	FILE *out = stdout;
	bool use_color = true;

#ifdef __PX4_POSIX
	out = get_stdout(&use_color);
#endif

#ifndef PX4_LOG_COLORIZED_OUTPUT
	use_color = false;
#endif

	if (level >= _PX4_LOG_LEVEL_INFO) {
		if (use_color) { fputs(__px4_log_level_color[level], out); }

		va_list argptr;
		va_start(argptr, fmt);
		vfprintf(out, fmt, argptr);
		va_end(argptr);

		if (use_color) { fputs(PX4_ANSI_COLOR_RESET, out); }
	}
}


text:
package de.cronn.demo.react.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import de.cronn.demo.react.model.LogMessage;

/**
 * Service providing a simple POJO
 *
 * @author Hanno Fellmann, cronn GmbH
 */
@Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class StatusService {
	private final AtomicInteger lowestComponent = new AtomicInteger(0);

	public StatusService() {
		new Timer().schedule(new TimerTask() {
			public void run() {
				lowestComponent.addAndGet(1);
			}
		}, 2000, 2000);
	}

	public List<LogMessage> listNewestLogs() {
		final ArrayList<LogMessage> ret = new ArrayList<LogMessage>();
		final int start = lowestComponent.get();
		IntStream
			.range(0, 5)
			.map(i -> ((5-i) + start))
			.mapToObj(id -> new LogMessage(id, "Log entry " + id, "Some really bad error occured. Please read this log carefully."))
			.forEach(ret::add);
		return ret;
	}
}


text:
// Copyright 2017 The Promagent Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package io.promagent.internal.jmx;

import io.prometheus.client.Collector;

import java.util.HashMap;
import java.util.Map;

public class Metric implements MetricMBean {

    private final Collector metric;

    Metric(Collector metric) {
        this.metric = metric;
    }

    /**
     * @see MetricMBean#getValues()
     */
    @Override
    public Map<Map<String, String>, Double> getValues() {
        Map<Map<String, String>, Double> result = new HashMap<>();
        for (Collector.MetricFamilySamples samples : metric.collect()) {
            for (Collector.MetricFamilySamples.Sample sample : samples.samples) {
                Map<String, String> labels = new HashMap<>();
                for (int i = 0; i < sample.labelNames.size(); i++) {
                    labels.put(sample.labelNames.get(i), sample.labelValues.get(i));
                }
                result.put(labels, sample.value);
            }
        }
        return result;
    }
}


text:
<?php

namespace BetterReflectionTest\Fixture;

function myFunction() {
}


text:
layout: page
title: Reyes 15th Anniversary
date: 2016-05-24
author: Carl Mckenzie
tags: weekly links, java
status: published
summary: Nullam vel egestas nunc. Proin nec sem mattis, posuere lectus.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 05/08/2019
  endDate: 05/09/2019
  ctyhocn: TYSHSHX
  groupCode: R1A
published: true
---
In pellentesque, lectus vitae elementum cursus, magna leo porta ligula, ut lacinia lorem ipsum nec turpis. Curabitur erat nunc, finibus ut erat a, laoreet placerat sapien. Nullam felis mauris, semper in risus at, congue volutpat purus. Aenean ultricies lorem at nibh pharetra gravida. Nam vitae mi vestibulum nisi tempor ultrices. Quisque vehicula imperdiet quam et vehicula. Etiam bibendum dignissim risus, ac ullamcorper sapien mollis eu. Nunc gravida facilisis mi, a pulvinar nulla pellentesque non. Suspendisse potenti. Nullam suscipit mollis neque. Nunc porta dictum nulla eu molestie. Fusce laoreet diam in lectus tempus, ut pretium leo scelerisque.

1 Pellentesque hendrerit felis non nisi mollis interdum
1 Donec at tortor et nibh porta vulputate
1 Donec eleifend mi in augue scelerisque efficitur.

Nam convallis purus erat, ut mattis lorem iaculis ac. Mauris nec felis mattis, venenatis urna sit amet, maximus augue. Praesent vestibulum nunc sed leo porttitor tincidunt. Aliquam faucibus blandit massa, vel commodo velit elementum vitae. Maecenas lorem justo, varius quis nibh ac, gravida rutrum ipsum. Nam vehicula arcu urna, eu lacinia enim dictum cursus. Donec tempus condimentum mi, id hendrerit leo aliquet eu. Ut fermentum ultricies nibh ac accumsan. Maecenas suscipit lacus eu ornare consequat. Curabitur consectetur elit non sapien facilisis tempus. Aliquam ultricies tellus ut massa euismod facilisis. Quisque molestie diam sed aliquet fermentum. Donec ut odio ante. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Maecenas ac lectus ut purus tristique bibendum. Curabitur vitae pulvinar ante. In mollis quam sem, id fermentum sapien efficitur sodales. Proin nec facilisis lectus. Integer a viverra massa. Ut ac mollis justo, sed elementum elit. Pellentesque at mauris ante. In dictum libero id urna dictum, vel varius est interdum. Quisque pulvinar in nunc a vestibulum. Etiam sed congue erat.


text:
rkt-runner
=========

An Ansible role for creating a systemd service unit that runs an ACI using rkt.

Requirements
------------

Assumes that [rkt](https://github.com/coreos/rkt) is already installed on the target system and is available at `/usr/bin/rkt`.

Requires [systemd](http://freedesktop.org/wiki/Software/systemd/). [The Wikipedia article for systemd](http://en.wikipedia.org/wiki/Systemd) lists the Linux distributions and corresponding versions that come with systemd out of the box.

Role Variables
--------------

This role has two required variables:

* `image_path`: the path to the ACI (eg. `/images/cool-thing.aci` or `http://www.example.com/cool-thing.aci` or `example.com/cool-thing:v1.2.3`)
* `service_name`: the name of the service (eg. `cool-thing`)

There are also two optional variables:

* `extra_args`: arguments to pass through to the container's executable
  (eg. setting `extra_args` to `--do-stuff` will result in the `rkt run` command being `/usr/bin/rkt run /path/to/image.aci -- --do-stuff`)
* `rkt_opts`: rkt options (eg. https://coreos.com/rkt/docs/latest/subcommands/run.html)

Dependencies
------------

This role does not have any dependencies.

Example Playbook
----------------

    - hosts: servers
      roles:
         - { role: rkt-runner, image_path: "/images/cool-thing.aci", service_name: "cool-thing" }

License
-------

MIT

Author Information
------------------

Created by Charles Korn ([me@charleskorn.com](me@charleskorn.com)).

Contributing
------------

Submit issues and pull requests on GitHub at [https://github.com/charleskorn/rkt-runner](https://github.com/charleskorn/rkt-runner).


text:
"""Create an application instance."""
from flask.helpers import get_debug_flag
from orderlc.user.models import User
from orderlc.app import create_app
from orderlc.settings import DevConfig, ProdConfig

# from orderlc.public.models import Script, Job, STATUS_WAITING, STATUS_COMPLETE, STATUS_ERROR, STATUS_RUNNING
from flask_script import Manager

from flask_script import Manager, Shell, Server
from flask_migrate import MigrateCommand
from orderlc.database import db

from orderlc.public.models import Customer, Good, Container

# import logging
# logging.basicConfig(level=logging.DEBUG)

CONFIG = ProdConfig # DevConfig if get_debug_flag() else ProdConfig

app = create_app(CONFIG)

manager = Manager(app)

def _make_context():
    """Return context dict for a shell session so you can access
    app, db, and the User model by default.
    """
    return {'app': app, 'db': db, 'User': User,'Customer':Customer,'Good':Good,'Container':Container}

@manager.command
def test():
    """Run the tests."""
    import pytest
    exit_code = pytest.main([TEST_PATH, '--verbose'])
    return exit_code

manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()


text:
var path = require('path'),
  fs = require('fs'),
  log4js = require('log4js');

var logger = log4js.getLogger();
var helper = {
  osHomePath: process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'],
  isWin: process.platform == 'win32' ? true : false,
  logger: function () {
    return logger;
  },
  run: function(generateFun) {
    var g = generateFun(resume);
    g.next();

    function resume(value) {
      if (value) {
        logger.error(value);
        return;
      }
      g.next();
    }
  },
  mkdir: function(dirpath, root) {
    var dirs = dirpath.split(path.sep),
      dir = dirs.shift(),
      root = path.join(root || '', dir);

    logger.log(dirs.join(path.sep));
    try {
      fs.mkdirSync(root);
    } catch (e) {
      //dir wasn't made, something went wrong
      logger.log(dirpath);
      logger.log(root);
      if (!fs.statSync(root).isDirectory()) throw new Error(e);
    }
    return !dirs.length || helper.mkdir(dirs.join(path.sep), root);
  },
  mkdirSync: function(path) {
    try {
      fs.mkdirSync(root);
    } catch (e) {}
  },
  /**
   *
   * @param src
   * @param dest
   * @param opts { overwrite, basename }
   * @param cb
   */
  copy: function(src, dest, opts, cb) {
    var basename, read, write;
    if (typeof opts === 'function') {
      cb = opts;
      opts = {};
    }
    opts = Object.assign({
      overwrite: true,
      basename: ''
    }, opts);

    try {
      fs.accessSync(dest, fs.F_OK);
    } catch (e) {
      //util.mkdir(dest)
      fs.mkdirSync(dest);
    }
    basename = opts.basename !== '' ? opts.basename : path.basename(src);

    dest = path.join(dest, basename);

    read = fs.createReadStream(src);
    read.on('error', function(err) {});
    read.on('data', function(data) {});
    read.on('end', function() {});

    write = fs.createWriteStream(dest, {
      flags: opts.overwrite ? 'w' : 'wx'
    });
    write.on('error', function(err) {
      cb && cb(err);
    });
    write.on('close', function() {
      cb && cb();
    })

    read.pipe(write);
  }
}
module.exports = helper;


text:
"""
A model to demonstrate the use of soft nearest neighbor loss presented in
Frosst, Nicholas, Nicolas Papernot, and Geoffrey Hinton. "Analyzing and
Improving Representations with the Soft Nearest Neighbor Loss." arXiv preprint
arXiv:1902.01889 (2019).
"""


text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.rules.cpp.proto;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode.TARGET;

import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.rules.cpp.CcSkylarkApiProvider;

/** Part of the implementation of cc_proto_library. */
public class CcProtoLibrary implements RuleConfiguredTargetFactory {
  @Override
  public ConfiguredTarget create(RuleContext ruleContext)
      throws InterruptedException, RuleErrorException {

    if (ruleContext.getPrerequisites("deps", TARGET).size() != 1) {
      ruleContext.throwWithAttributeError(
          "deps",
          "'deps' attribute must contain exactly one label "
              + "(we didn't name it 'dep' for consistency). "
              + "The main use-case for multiple deps is to create a rule that contains several "
              + "other targets. This makes dependency bloat more likely. It also makes it harder"
              + "to remove unused deps.");
    }

    CcProtoLibraryProviders depProviders =
        checkNotNull(ruleContext.getPrerequisite("deps", TARGET))
            .getProvider(CcProtoLibraryProviders.class);

    return new RuleConfiguredTargetBuilder(ruleContext)
        .setFilesToBuild(depProviders.filesBuilder)
        .addProvider(
            RunfilesProvider.class, RunfilesProvider.withData(Runfiles.EMPTY, Runfiles.EMPTY))
        .addProviders(depProviders.providerMap)
        .addSkylarkTransitiveInfo(CcSkylarkApiProvider.NAME, new CcSkylarkApiProvider())
        .build();
  }
}


text:
namespace extensions {

class MockSandboxedUnpackerClient : public SandboxedUnpackerClient {
 public:

  void WaitForUnpack() {
    scoped_refptr<content::MessageLoopRunner> runner =
        new content::MessageLoopRunner;
    quit_closure_ = runner->QuitClosure();
    runner->Run();
  }

  base::FilePath temp_dir() const { return temp_dir_; }

 private:
  virtual ~MockSandboxedUnpackerClient() {}

  virtual void OnUnpackSuccess(const base::FilePath& temp_dir,
                               const base::FilePath& extension_root,
                               const base::DictionaryValue* original_manifest,
                               const Extension* extension,
                               const SkBitmap& install_icon) OVERRIDE {
    temp_dir_ = temp_dir;
    quit_closure_.Run();

  }

  virtual void OnUnpackFailure(const string16& error) OVERRIDE {
    ASSERT_TRUE(false);
  }

  base::Closure quit_closure_;
  base::FilePath temp_dir_;
};

class SandboxedUnpackerTest : public testing::Test {
 public:
  virtual void SetUp() {
   ASSERT_TRUE(extensions_dir_.CreateUniqueTempDir());
    browser_threads_.reset(new content::TestBrowserThreadBundle(
        content::TestBrowserThreadBundle::IO_MAINLOOP));
    // It will delete itself.
    client_ = new MockSandboxedUnpackerClient;
    content::RenderProcessHost::SetRunRendererInProcess(true);
  }

  virtual void TearDown() {
    // Need to destruct SandboxedUnpacker before the message loop since
    // it posts a task to it.
    sandboxed_unpacker_ = NULL;
    base::RunLoop().RunUntilIdle();
    content::RenderProcessHost::SetRunRendererInProcess(false);
  }

  void SetupUnpacker(const std::string& crx_name) {
    base::FilePath original_path;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path));
    original_path = original_path.AppendASCII("extensions")
        .AppendASCII("unpacker")
        .AppendASCII(crx_name);
    ASSERT_TRUE(base::PathExists(original_path)) << original_path.value();

    sandboxed_unpacker_ = new SandboxedUnpacker(
        original_path,
        Manifest::INTERNAL,
        Extension::NO_FLAGS,
        extensions_dir_.path(),
        base::MessageLoopProxy::current(),
        client_);

    base::MessageLoopProxy::current()->PostTask(
        FROM_HERE,
        base::Bind(&SandboxedUnpacker::Start, sandboxed_unpacker_.get()));
    client_->WaitForUnpack();
  }

  base::FilePath GetInstallPath() {
    return client_->temp_dir().AppendASCII(kTempExtensionName);
  }

 protected:
  base::ScopedTempDir extensions_dir_;
  MockSandboxedUnpackerClient* client_;
  scoped_refptr<SandboxedUnpacker> sandboxed_unpacker_;
  scoped_ptr<content::TestBrowserThreadBundle> browser_threads_;
};

TEST_F(SandboxedUnpackerTest, NoCatalogsSuccess) {
  SetupUnpacker("no_l10n.crx");
  // Check that there is no _locales folder.
  base::FilePath install_path =
      GetInstallPath().Append(kLocaleFolder);
  EXPECT_FALSE(base::PathExists(install_path));
}

#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)
// Consistently times out.
// TODO(erg): linux_aura bringup: http://crbug.com/163931
#define MAYBE_WithCatalogsSuccess DISABLED_WithCatalogsSuccess
#else
#define MAYBE_WithCatalogsSuccess WithCatalogsSuccess
#endif

TEST_F(SandboxedUnpackerTest, MAYBE_WithCatalogsSuccess) {
  SetupUnpacker("good_l10n.crx");
  // Check that there is _locales folder.
  base::FilePath install_path =
      GetInstallPath().Append(kLocaleFolder);
  EXPECT_TRUE(base::PathExists(install_path));
}

}  // namespace extensions


text:
from mpi4py import MPI
import numpy

comm = MPI.COMM_WORLD
assert comm.size == 2

rank = comm.rank

# pass explicit MPI datatypes
if rank == 0:
    data = numpy.arange(10, dtype='i')
    comm.Send([data, MPI.INT], dest=1, tag=77)
elif rank == 1:
    data = numpy.empty(10, dtype='i')
    comm.Recv([data, MPI.INT], source=0, tag=77)
    print "[%02d] Received: %s" % (rank, data)
# automatic MPI datatype discovery
if rank == 0:
    data = numpy.arange(10, dtype=numpy.float64)
    comm.Send(data, dest=1, tag=13)
elif rank == 1:
    data = numpy.empty(10, dtype=numpy.float64)
    comm.Recv(data, source=0, tag=13)
    print "[%02d] Received: %s" % (rank, data)


text:
/* $NetBSD: tmureg.h,v 1.4 2000/03/20 20:36:58 msaitoh Exp $ */

/*-
 * Copyright (C) 1999 SAITOH Masanobu.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _SH3_TMUREG_H_
#define _SH3_TMUREG_H_

/*
 * Timer Unit
 */

#if !defined(SH4)

/* SH3 definition */

/* common */
#define SHREG_TOCR	(*(volatile unsigned char *)	0xfffffe90)
#define SHREG_TSTR	(*(volatile unsigned char *)	0xfffffe92)

/* ch. 0 */
#define SHREG_TCOR0	(*(volatile unsigned int *)	0xfffffe94)
#define SHREG_TCNT0	(*(volatile unsigned int *)	0xfffffe98)
#define SHREG_TCR0	(*(volatile unsigned short *)	0xfffffe9c)

/* ch. 1 */
#define SHREG_TCOR1	(*(volatile unsigned int *)	0xfffffea0)
#define SHREG_TCNT1	(*(volatile unsigned int *)	0xfffffea4)
#define SHREG_TCR1	(*(volatile unsigned short *)	0xfffffea8)

/* ch. 2 */
#define SHREG_TCOR2	(*(volatile unsigned int *)	0xfffffeac)
#define SHREG_TCNT2	(*(volatile unsigned int *)	0xfffffeb0)
#define SHREG_TCR2	(*(volatile unsigned short *)	0xfffffeb4)
#define SHREG_TCPR2	(*(volatile unsigned int *)	0xfffffeb8)

#else

/* SH4 address definition */

/* common */
#define SHREG_TOCR	(*(volatile unsigned char *)	0xffd80000)
#define SHREG_TSTR	(*(volatile unsigned char *)	0xffd80004)

/* ch. 0 */
#define SHREG_TCOR0	(*(volatile unsigned int *)	0xffd80008)
#define SHREG_TCNT0	(*(volatile unsigned int *)	0xffd8000c)
#define SHREG_TCR0	(*(volatile unsigned short *)	0xffd80010)

/* ch. 1 */
#define SHREG_TCOR1	(*(volatile unsigned int *)	0xffd80014)
#define SHREG_TCNT1	(*(volatile unsigned int *)	0xffd80018)
#define SHREG_TCR1	(*(volatile unsigned short *)	0xffd8001c)

/* ch. 2 */
#define SHREG_TCOR2	(*(volatile unsigned int *)	0xffd80020)
#define SHREG_TCNT2	(*(volatile unsigned int *)	0xffd80024)
#define SHREG_TCR2	(*(volatile unsigned short *)	0xffd80028)
#define SHREG_TCPR2	(*(volatile unsigned int *)	0xffd8002c)

#endif

#define TOCR_TCOE	0x01

#define TSTR_STR2	0x04
#define TSTR_STR1	0x02
#define TSTR_STR0	0x01

#define TCR_ICPF	0x0200
#define TCR_UNF		0x0100
#define TCR_ICPE1	0x0080
#define TCR_ICPE0	0x0040
#define TCR_UNIE	0x0020
#define TCR_CKEG1	0x0010
#define TCR_CKEG0	0x0008
#define TCR_TPSC2	0x0004
#define TCR_TPSC1	0x0002
#define TCR_TPSC0	0x0001

#define TCR_TPSC_P4	0x0000
#define TCR_TPSC_P16	0x0001
#define TCR_TPSC_P64	0x0002
#define TCR_TPSC_P256	0x0003
#if !defined(SH4)
#define TCR_TPSC_RTC	0x0004
#define TCR_TPSC_TCLK	0x0005
#else
#define TCR_TPSC_P512	0x0004
#define TCR_TPSC_RTC	0x0006
#define TCR_TPSC_TCLK	0x0007
#endif

#endif	/* !_SH3_TMUREG_H_ */


text:
'use strict';
/*
 * options:
 *
 `grunt server` - run developer server
 `--server-port=9000` - set port for `grunt server` cmd, where localhost will be opened `localhost:9000` for example
 `--hostname=0.0.0.0` - set host IP. if value is 0.0.0.0, this server will be accessed from outside

 `grunt build` - compile all src to `www` folder for phonegap build

 `--build-type=dev` - default value. for DEVELOPMENT. used `dev-config.js`
 `--build-type=release` - for PRODUCTION. used `dist-config.js`
 `--build-type=corporate` - for CORPORATE. used `corp-config.js`

 `--build-version=x.x.x` - for define custom version of app. instead `package.json:version` field value
 `--minify=false|general,topStyles,diag,utests,etc...` - `true` by default. minify js, css files. also can be used with list of modules to minify
 `--rev-files=false` - `true` by default. static asset revisioning through file content hash
 `--config-mixin=my-config.js` - for define own my-config.js file for build. keys and values from config-mixin will be used as primary.
 `--web=true` - `false` by default. make web app, NOT cordova version.
 `--config-xml=my-config.xml` - empty by default. for custom config.xml using
 `--copy-static=false` - `true` by default. copy from `www-static/**` to `www/`
 `--cordova-id=just.my.id` - set `id` value to config.xml. instead `package.json:cordova-id` field value

 `--include=module1,module5,etc...` - include modules
 `--exclude=module1,module2,etc...` - exclude modules for build
 `--excludeAll=true` - `false` by default. exclude all defined modules. flag `--exclude` will be dropped.

 *
 *
 * */

module.exports = function (grunt) {
    require('time-grunt')(grunt);
    require('load-grunt-tasks')(grunt);

    // load files from /tasks/* folder
    grunt.loadTasks('tasks');

    var buildTypes = {
        dev: 'dev',
        release: 'release',
        corporate: 'corporate'
    };

    var BT_DEV = buildTypes.dev;
    var BT_CORPORATE = buildTypes.corporate;
    var BT_RELEASE = buildTypes.release;
    var PATH_APP = 'app';

    var buildType = grunt.option("build-type") || BT_DEV;
    if (grunt.option('release')) {
        // old keys support
        buildType = BT_RELEASE;
    }

    var corporateName = grunt.option('corporate');
    var corpPath = '';
    if (corporateName) {
        corpPath = 'corporate/' + corporateName + '/app/';
        grunt.log.write('using corporate "' + corporateName + '"');
        grunt.log.writeln(' ');
    }
    var usingCorp = !!corpPath;

    var ownConfig;
    if (grunt.option('config')) {
        //old keys
        ownConfig = grunt.option('config');
    }

    var copyStatic = (grunt.option("copy-static") !== false); // true by default

    var isWebVersion = grunt.option('web');

    var configMixinFile = grunt.option("config-mixin");
    var hostname = grunt.option("hostname") || '0.0.0.0';

    var configXml = grunt.option("config-xml") || 'config.xml';

    var port = 9000;

    var serverPortOption = grunt.option('server-port');
    if (serverPortOption) {
        port = serverPortOption;
    }

    function getPathForExtendVersion(configApp, corpPath) {
        var extendFilesByBuildType = {};
        extendFilesByBuildType[BT_DEV] = configApp + '/config-xml-extenders/dev/';
        extendFilesByBuildType[BT_RELEASE] = configApp + '/config-xml-extenders/release/';
        if (corpPath) {
            extendFilesByBuildType[BT_CORPORATE] = corpPath + 'config-xml-extenders/';
        } else {
            extendFilesByBuildType[BT_CORPORATE] = extendFilesByBuildType[BT_DEV];
        }
        var ret = extendFilesByBuildType[buildType];
        if (!ret) {
            // use dev by default
            ret = extendFilesByBuildType[BT_DEV];
        }
        return ret;
    }

    grunt.initConfig({
        jrconfig: {
            // configurable paths
            app: PATH_APP,
            corporate: corpPath,
            dist: 'www',
            tmp: '.tmp'
        },
        notify: {
            postcss: {
                options: {
                    message: 'css updated'
                }
            },
            build: {
                options: {
                    message: 'build completed'
                }
            },
            views: {
                options: {
                    message: 'views updated'
                }
            }
        },
        watch: {
            compileScss: {
                files: ['<%= jrconfig.app %>/{,**/}*.scss'],
                tasks: ['compileScss:server', 'postcss', 'notify:postcss']
            },
            styles: {
                files: ['<%= jrconfig.app %>/{,**/}*.css'],
                tasks: ['copy:compiledStyles', 'postcss']
            },
            views: {
                files: ['<%= jrconfig.app %>/{,**/}*.html'],
                tasks: ['updateViews', 'cssInRoot:dev', 'notify:views']
            }
        },
        updateViews: {
            dev: {
                options: {
                    from: '<%= jrconfig.app %>/scripts/core/templater-data.js',
                    to: '<%= jrconfig.tmp %>/scripts/core/templater-data.js',
                    replaceViews: {
                        whereReplace: '<%= jrconfig.tmp %>/scripts/core/templater-data.js',
                        prefix: '<%= jrconfig.app %>/',
                        viewsSrc: '<%= jrconfig.app %>/{,**/}*.html'
                    }
                }
            }
        },
        postcss: {
            options: {
                processors: [
                    require('autoprefixer')({browsers: ['> 2%', 'last 5 versions']}) // add vendor prefixes
                ]
            },
            dist: {
                files: [
                    {
                        expand: true,
                        cwd: '<%= jrconfig.tmp %>/',
                        src: '{,**/}*.css',
                        dest: '<%= jrconfig.tmp %>/'
                    }
                ]
            }
        },
        connect: {
            options: {
                port: port,
                hostname: hostname,
                livereload: false //reloadPort
            },
            livereload: {
                options: {
                    open: true,
                    base: [
                        '<%= jrconfig.tmp %>',
                        '<%= jrconfig.app %>'
                    ]
                }
            }
        },
        clean: {
            defaultConfigs: {
                files: [
                    {
                        src: [
                            '<%= jrconfig.dist %>/dev-config.js',
                            '<%= jrconfig.dist %>/dist-config.js',
                            '<%= jrconfig.dist %>/corp-config.js'
                        ]
                    }
                ]
            },
            cordovaJsFile: {
                files: [
                    {
                        src: [
                            '<%= jrconfig.tmp %>/www/cordova.js'
                        ]
                    }
                ]
            },
            dist: {
                files: [
                    {
                        dot: true,
                        src: [
                            '<%= jrconfig.tmp %>',
                            '<%= jrconfig.dist %>/*',
                            '!<%= jrconfig.dist %>/.git*'
                        ]
                    }
                ]
            },
            server: '<%= jrconfig.tmp %>'
        },
        compileScss: {
            options: {
                sassDir: ['<%= jrconfig.app %>/', corpPath ? corpPath + '/' : ''],
                files: '{,**/}**.scss',
                outDir: '<%= jrconfig.tmp %>/',
                libOptions: {}
            },
            dist: {},
            server: {
                files: '{,**/}**.scss'
            }
        },
        copy: {
            wwwStatic: {
                files: [
                    {
                        expand: true,
                        follow: true,
                        cwd: 'www-static',
                        dest: '<%= jrconfig.dist %>',
                        src: [
                            '**'
                        ]
                    }
                ]
            },
            cordovaJs: {
                src: '<%= jrconfig.app %>/cordova.js',
                dest: '<%= jrconfig.dist %>/cordova.js'
            },

            cordovaConfigXml: {
                src: '<%= jrconfig.app %>/' + configXml,
                dest: 'config.xml'
            },

            configDist: {
                src: '<%= jrconfig.app %>/scripts/' + (ownConfig ? ownConfig : 'dist-config.js'),
                dest: '<%= jrconfig.tmp %>/www/scripts/config.js'
            },
            configDev: {
                src: '<%= jrconfig.app %>/scripts/' + (ownConfig ? ownConfig : 'dev-config.js'),
                dest: '<%= jrconfig.tmp %>/www/scripts/config.js'
            },
            configCorporate: {
                src: '<%= jrconfig.app %>/scripts/' + (ownConfig ? ownConfig : 'corp-config.js'),
                dest: '<%= jrconfig.tmp %>/www/scripts/config.js'
            },
            mixinConfigFile: {
                src: '<%= jrconfig.app %>/scripts/configs/' + configMixinFile,
                dest: '<%= jrconfig.tmp %>/www/scripts/config-mixin.js'
            },
            corporate: {
                files: [
                    {
                        src: '<%= jrconfig.corporate %>/configs/config-mixin.js',
                        dest: '<%= jrconfig.tmp %>/www/scripts/config-mixin.js'
                    },
                    {
                        expand: true,
                        follow: true,
                        cwd: '<%= jrconfig.corporate %>',
                        dest: '<%= jrconfig.dist %>',
                        src: [
                            'images/**'
                        ]
                    },
                    {
                        expand: true,
                        follow: true,
                        cwd: '<%= jrconfig.corporate %>',
                        dest: '<%= jrconfig.tmp %>/www',
                        src: [
                            'scripts/**'
                        ]
                    },
                    {
                        expand: true,
                        follow: true,
                        cwd: '<%= jrconfig.corporate %>',
                        dest: '<%= jrconfig.tmp %>/www',
                        src: [
                            'scripts/{,**/}**.css',
                            'styles/{,**/}**.css'
                        ]
                    }
                ]
            },
            minifiedModules: {
                //filled in minify task
                files: []
            },
            withoutMinify: {
                // called from minify task
                files: [
                    {
                        expand: true,
                        follow: true,
                        cwd: '<%= jrconfig.app %>',
                        dest: '<%= jrconfig.dist %>',
                        src: [
                            'fonts/**',
                            'images/**'
                        ]

                    },
                    {
                        expand: true,
                        follow: true,
                        cwd: '<%= jrconfig.tmp %>/www',
                        dest: '<%= jrconfig.dist %>',
                        src: [
                            'scripts/**',
                            'styles/**'
                        ]

                    }
                ]
            },
            js: {
                expand: true,
                follow: true,
                cwd: '<%= jrconfig.app %>',
                dest: '<%= jrconfig.tmp %>/www/',
                src: [
                    '{,**/}**.js'
                ]
            },
            stylesOnlyCSS: {
                expand: true,
                follow: true,
                cwd: '<%= jrconfig.app %>/',
                dest: '<%= jrconfig.tmp %>/',
                src: '{,**/}**.css'
            },
            compiledStyles: {
                expand: true,
                follow: true,
                cwd: '<%= jrconfig.tmp %>/',
                dest: '<%= jrconfig.tmp %>/www/',
                src: '{,**/}**.css'
            },
            images: {
                expand: true,
                follow: true,
                cwd: '<%= jrconfig.app %>/images',
                dest: '<%= jrconfig.dist %>/images',
                src: '{,**/}**.{png,jpg,jpeg,gif,webp,svg}'
            },
            fonts: {
                expand: true,
                follow: true,
                cwd: '<%= jrconfig.app %>/fonts',
                dest: '<%= jrconfig.dist %>/fonts',
                src: '**'
            },
            views: {
                expand: true,
                follow: true,
                cwd: '<%= jrconfig.app %>/',
                dest: '<%= jrconfig.tmp %>/www/',
                src: [
                    'scripts/{,**/}*.html',
                    'views/{,**/}*.html',
                    'styles/{,**/}*.html'
                ]
            },
            rootFilesFromTmp: {
                expand: true,
                follow: true,
                dot: false,
                cwd: '<%= jrconfig.tmp %>/www',
                dest: '<%= jrconfig.dist %>',
                src: [
                    '*'
                ]
            },
            otherFiles: {
                expand: true,
                follow: true,
                dot: true,
                cwd: '<%= jrconfig.app %>',
                dest: '<%= jrconfig.tmp %>/www',
                src: [
                    '*.{ico,png,txt}',
                    '.htaccess'
                ]
            }
        },
        cssInRoot: {
            dev: {
                options: {
                    from: '<%= jrconfig.app %>/index.html',
                    to: '<%= jrconfig.tmp %>/index.html',
                    processor: function (data) {
                        var ret = data.split('.scss').join('.css');
                        return ret;
                    }
                }
            },
            dist: {
                options: {
                    from: '<%= jrconfig.app %>/index.html',
                    to: '<%= jrconfig.tmp %>/www/index.html',
                    processor: function (data) {
                        var ret = data.split('.scss').join('.css');
                        return ret;
                    }
                }
            }
        },
        concat: {
            dist: {
                files: {} // will be redefined in minify task
            }
        },
        replaceAfterRev: {
            dist: {
                options: {
                    method: 'md5',
                    length: 8
                },
                folder: '<%= jrconfig.dist %>',
                files: [
                    {
                        where: '{,**/}**.css',
                        list: ['fonts/**', 'images/**']
                    },
                    {
                        where: ['index.html', 'robots.txt'],
                        list: ['{,**/}**.css', '{,**/}**.js']
                    }
                ]
            }
        },
        cssmin: {
            dist: {
                files: {} // will be redefined in minify task
            }
        },
        uglify: {
            dist: {
                files: {} // will be redefined in minify task
            }
        },
        minify: {
            dist: {
                src: '<%= jrconfig.tmp %>/www',
                dest: '<%= jrconfig.dist %>',
                buildType: buildType,
                replaceViews: {
                    cleanSrc: true,
                    whereReplace: '<%= jrconfig.tmp %>/www/scripts/core/templater-data.js',
                    prefix: '<%= jrconfig.tmp %>/www/',
                    viewsSrc: '<%= jrconfig.tmp %>/www/{,**/}*.html'
                }
            }
        },
        insertVersion: {
            dist: {
                src: '<%= jrconfig.tmp %>/www/scripts/core-plugins/build-version.js',
                inputXmlPath: 'config.xml',
                extendFilesPath: getPathForExtendVersion(PATH_APP, corpPath)
            }
        },
        iconsSplashes: {
            dist: {}
        },
        htmlmin: {                                     // Task
            dist: {                                      // Target
                options: {                                 // Target options
                    removeComments: true,
                    collapseWhitespace: true
                },
                files: {                                   // Dictionary of files
                    '<%= jrconfig.dist %>/index.html': '<%= jrconfig.dist %>/index.html'     // 'destination': 'source'
                }
            }
        }
    });

    var serverTasks = [
        'compileScss:server',
        'copy:compiledStyles',
        'cssInRoot:dev',
        'updateViews:dev',
        'postcss'
    ];

    grunt.registerTask('purify', function () {
        grunt.task.run(['purifycss']);
    });

    grunt.registerTask('server', function (target) {
        var tasks = ['clean:server'];
        tasks.push.apply(tasks, serverTasks);
        tasks.push.apply(tasks, [
            'connect:livereload',
            'watch']);

        grunt.task.run(tasks);
    });

    var defaultTasksForBuild = [
        // drop all
        'clean:dist',

        // prepare css
        'compileScss:dist',
        'copy:stylesOnlyCSS',
        'postcss', // compiled to <%= jrconfig.tmp %>/styles
        'copy:compiledStyles',
        'cssInRoot:dist',

        // prepare others
        'copy:images',
        'copy:js',
        'copy:fonts',
        'copy:views',
        'copy:otherFiles',
        'copy:cordovaConfigXml',
        usingCorp ? 'copy:corporate' : null,
        'clean:defaultConfigs',
        'insertVersion'
    ];

    grunt.registerTask('build', 'Default build', function () {
        runTasks.call(this, defaultTasksForBuild);
    });

    grunt.registerTask('default', [
        'build'
    ]);

    function defineCopyConfigs(tasks) {
        // copy config.js to config.tmp
        var beforeTasks = [];

        var mainConfigTitle = 'DEV';
        // prepare config.js as defined flags
        if (buildType == BT_RELEASE) {
            beforeTasks.push('copy:configDist');
            mainConfigTitle = 'PROD';
        } else if (buildType == BT_CORPORATE) {
            beforeTasks.push('copy:configCorporate');
            mainConfigTitle = 'CORPORATE';
        } else {
            beforeTasks.push('copy:configDev');
        }

        grunt.log.write('using ');
        grunt.log.write(mainConfigTitle['yellow'].bold);
        grunt.log.writeln(' config');

        configMixinFile && beforeTasks.push('copy:mixinConfigFile');

        // put them
        tasks.push.apply(tasks, beforeTasks);
    }

    function runTasks(tasks) {

        defineCopyConfigs(tasks);

        copyStatic && tasks.push('copy:wwwStatic');

        // cleanup code for mobile version
        !isWebVersion && tasks.push('clean:cordovaJsFile');

        tasks.push('minify');

        //last task
        tasks.push('updateViews:dev');
        !isWebVersion && tasks.push('iconsSplashes');

        tasks.push('htmlmin');
        tasks.push('notify:build');

        tasks.push.apply(tasks, serverTasks); // when server started, need update all views, css, code, etc...

        for (var i = tasks.length - 1; i >= 0; i--) {
            if (!tasks[i]) {
                tasks.splice(i, 1);
            }
        }

        var outStr = 'tasks for run: \n';
        outStr += tasks.join('\n ');
        grunt.log.writeln(outStr['yellow']);

        var done = this.async();

        // run all prepared tasks
        setTimeout(function () {
            done();
            grunt.task.run(tasks);
        }, 10);
    }
};


text:
import React from 'react'

class Expander extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            expanded: false,
            overflowing: false,
        }
        this.ref = React.createRef()
    }

    componentDidMount() {
        if(this.ref.current.scrollHeight > this.ref.current.clientHeight) {
            this.setState({overflowing: true})
        }
    }

    toggleExpanded(e) {
        e.preventDefault()
        this.setState({
            expanded: !this.state.expanded
        })
    }

    render() {
        return

                {this.props.children}

            {this.state.overflowing &&

                 this.toggleExpanded(e)}>{(this.state.expanded)?'Show Less':'Show More'}

            }

    }
}

export default Expander


text:
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="WebSite",indexes={@ORM\Index(name="canonicalUrl_idx", columns={"canonicalUrl"})})
 */
class WebSite
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(type="text")
     */
    protected $canonicalUrl;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $canonicalUrl
     *
     * @return WebSite
     */
    public function setCanonicalUrl($canonicalUrl)
    {
        $this->canonicalUrl = $canonicalUrl;
        return $this;
    }

    /**
     * @return string
     */
    public function getCanonicalUrl()
    {
        return $this->canonicalUrl;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->getCanonicalUrl();
    }

    /**
     * @param Website $website
     *
     * @return bool
     */
    public function equals(Website $website)
    {
        return $this->getCanonicalUrl() == $website->getCanonicalUrl();
    }
}


text:
"""load_map contains several shortcut functions to quickly load maps.
Custom map-loading routines will probably be desired, but load_map
can be useful for testing new heuristics, pathfinding algorithms, etc."""
import nodes
import algorithms
import metrics

START = '0'
BLANK = ' '
WALL = '#'
TARGET = '@'

def read_tiles(f):
    """Read file `f` and yield (position, char) tuples"""
    # currently outputs in cartesian coordinates-- bad idea?
    lines = f.read().splitlines()
    for y, line in enumerate(reversed(lines)):
        for x, char in enumerate(line):
            yield (x, y), char

def file_to_tile(f,
        start=START, blank=BLANK, wall=WALL, target=TARGET,
        heuristic=metrics.manhattan):
    """Take an input file `f` and return RectNodes start_node, target_node
    (if a target is not found, start_node, None will be returned instead """
    walkable = {}
    start_pos = target_pos = None
    for pos, char in read_tiles(f):
        if char == wall:
            walkable[pos] = False
        elif char == target:
            target_pos = pos
        elif char == start:
            start_pos = pos
        elif char == blank:
            pass
        else:
            raise ValueError("Unknown tile type: '%s'" % char)
    if start_pos is None:
        raise ValueError("No starting position in map")
    start_node = nodes.RectNode(start_pos,
        walkable=walkable, heuristic=heuristic)
    if target_pos is None:
        # target position is optional
        target_node = None
    else:
        target_node = nodes.RectNode(target_pos,
            walkable=walkable, heuristic=heuristic)
    return start_node, target_node


text:
package eu.qualimaster.common.hardware;
/**
 * Creates the handler interface.
 * @author Cui Qin
 *
 */
public interface IHardwareHandlerCreator {
    /**
     * Create a handler.
     * @param host the host
     * @param port the port
     * @return the handler
     */
    public Runnable createHandler(String host, int port);
}


text: Enable this option to allow Jenkins to connect to instances with self-signed certificates.


text:
package net.peterkuterna.android.apps.devoxxfrsched.ui;

import android.support.v4.app.Fragment;

public class BulletinActivity extends BaseSinglePaneActivity {

	@Override
	public Fragment onCreatePane() {
		return new BulletinFragment();
	}

}


text:
int usage(char *prog);
double gettimevalue();
void mutexThread(int nThreads, int nIterations, boost::random::mt19937 rnd, boost::random::uniform_int_distribution<> dist, std::vector<boost::mutex*>* mutexes);
void sharedMutexThread(int nThreads, int nIterations, boost::random::mt19937, boost::random::uniform_int_distribution<>, std::vector<boost::shared_mutex*>* mutexes);
#endif


text:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.jar.Pack200;
/*
 * @test
 * @bug 7007157
 * @summary make sure the strip command works on an attribute
 * @compile -XDignore.symbol.file Utils.java T7007157.java
 * @run main T7007157
 * @author ksrini
 */
public class T7007157 {

    public static void main(String... args) throws IOException {
        File sdkHome = Utils.JavaSDK;
        File testJar = new File(new File(sdkHome, "lib"), "tools.jar");
        JarFile jarFile = new JarFile(testJar);
        File packFile = new File("foo.pack");
        Pack200.Packer packer = Pack200.newPacker();
        Map<String, String> p = packer.properties();
        // Take the time optimization vs. space
        p.put(packer.EFFORT, "1");  // CAUTION: do not use 0.
        // Make the memory consumption as effective as possible
        p.put(packer.SEGMENT_LIMIT, "10000");
        // ignore all JAR deflation requests to save time
        p.put(packer.DEFLATE_HINT, packer.FALSE);
        // save the file ordering of the original JAR
        p.put(packer.KEEP_FILE_ORDER, packer.TRUE);
        // strip the StackMapTables
        p.put(packer.CODE_ATTRIBUTE_PFX + "StackMapTable", packer.STRIP);
        FileOutputStream fos = null;
        try {
            // Write out to a jtreg scratch area
            fos = new FileOutputStream(packFile);
            // Call the packer
            packer.pack(jarFile, fos);
        } finally {
            Utils.close(fos);
            Utils.close(jarFile);
        }
        Utils.cleanup();
    }
}


text:
'use strict';

var path = require('path'),
    assert = require('assert'),
    request = require('supertest'),
    server = require('../server/app.js'),
    generate = require('./data/generate.js')('amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-0000000betty');

var LOCAL_CERT = 'file://' + path.resolve('test/data/echo-api.pem'),
    SIGNATURE = 'foobar';

function assertEchoResponseFormat(data) {
    assert.equal(data.version, '2.0');
    assert.ok(data.sessionAttributes);
    assert.ok(data.response);
    assert.equal(data.response.outputSpeech.type, 'PlainText');
    assert.equal(typeof data.response.shouldEndSession, 'boolean');
}

describe('launch and end betty', function(){
    it('should launch with question', function(done) {
        request(server)
            .post('/voice/betty')
            .send(generate.getLaunchRequest())
            .set('SignatureCertChainUrl', LOCAL_CERT)
            .set('Signature', SIGNATURE)
            .expect('Content-Type', /json/)
            .expect(function(res) {
                assertEchoResponseFormat(res.body);
                assert.ok(res.body.response.outputSpeech.text.length > 1);
                assert.equal(res.body.response.shouldEndSession, false);
            })
            .expect(200, done);
    });

    it('should end with buh bye', function(done) {
        request(server)
            .post('/voice/betty')
            .send(generate.getEndRequest())
            .set('SignatureCertChainUrl', LOCAL_CERT)
            .set('Signature', SIGNATURE)
            .expect('Content-Type', /json/)
            .expect(function(res) {
                assertEchoResponseFormat(res.body);
                assert.ok(res.body.response.outputSpeech.text.length > 1);
                assert.equal(res.body.response.shouldEndSession, true);
            })
            .expect(200, done);
    });
});


text:
namespace switches {

GLES2_IMPL_EXPORT extern const char kEnableGpuClientTracing[];
GLES2_IMPL_EXPORT extern const char kEnableGPUClientLogging[];

}  // namespace switches

#endif  // GPU_COMMAND_BUFFER_CLIENT_GPU_SWITCHES_H_


text:
{% load i18n %}
<form action="{% url "search_query" %}" class="SearchBar SearchBar--isolated">
    <input class="SearchBar-input" type="text" name="q" id="search-query" value="{{ search_query }}"
           placeholder="{% trans "Search..." %}">
    <button type="submit" class="SearchBar-submit" value="{% trans "SEARCH" %}">{% trans "Search" %}</button>
</form>


text:
DRAGON quick start

Dragon library is possible to install as npm package and use it as ES6 module or as ES5 UMD module, or even it can be loaded as <script> into the simple page.

Installation

                    ES6 module

                    ES5 module

                    No module

npm install dragon

                    or

yarn dragon

                    then in your project just import dragon and start using

import dragon from 'dragon'

let dragonInstance = dragon(element, options)

npm install dragon

                    or

yarn dragon

                    then in your project just import dragon and start using

var dragon require('dragon')

let dragonInstance = dragon(element, options)

download dragon.js (dragon.min.js) from dist folder.
 Where dragon.min.js version is minified one.

                    in your html

<script type="text/javascript" src="./path/to/dragon.js"></script>

                    then in your code

let dragonInstance = dragon(element, options)

Where to go now?

Dragon overview