text:
package com.spectralogic.ds3autogen.utils;

import com.google.common.collect.ImmutableList;
import com.spectralogic.ds3autogen.api.models.apispec.Ds3ResponseCode;
import com.spectralogic.ds3autogen.api.models.apispec.Ds3ResponseType;
import org.junit.Test;

import static com.spectralogic.ds3autogen.testutil.Ds3ModelFixtures.getGetBlobPersistence;
import static com.spectralogic.ds3autogen.testutil.Ds3ModelFixtures.getRequestGetJob;
import static com.spectralogic.ds3autogen.testutil.Ds3ResponseCodeFixture.createTestResponseCodes;
import static com.spectralogic.ds3autogen.utils.ResponsePayloadUtil.*;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class ResponsePayloadUtil_Test {

    @Test
    public void isErrorCode_Test() {
        assertFalse(isErrorCode(100));
        assertFalse(isErrorCode(200));
        assertFalse(isErrorCode(299));
        assertTrue(isErrorCode(300));
        assertTrue(isErrorCode(400));
    }

    @Test
    public void isNonErrorCode_Test() {
        assertTrue(isNonErrorCode(100));
        assertTrue(isNonErrorCode(200));
        assertTrue(isNonErrorCode(299));
        assertFalse(isNonErrorCode(300));
        assertFalse(isNonErrorCode(400));
    }

    @Test (expected = IllegalArgumentException.class)
    public void getResponseType_NullList_Test() {
        getResponseType(null);
    }

    @Test (expected = IllegalArgumentException.class)
    public void getResponseType_EmptyList_Test() {
        getResponseType(ImmutableList.of());
    }

    @Test
    public void getResponseType_ListSizeOne_Test() {
        final String result = getResponseType(ImmutableList.of(
                new Ds3ResponseType("com.spectralogic.s3.server.domain.HttpErrorResultApiBean", null)));
        assertThat(result, is("com.spectralogic.s3.server.domain.HttpErrorResultApiBean"));
    }

    @Test (expected = IllegalArgumentException.class)
    public void getResponseType_ListSizeTwo_Test() {
        final ImmutableList<Ds3ResponseType> responseTypes = ImmutableList.of(
                new Ds3ResponseType("null", null),
                new Ds3ResponseType("com.spectralogic.s3.server.domain.HttpErrorResultApiBean", null));

        getResponseType(responseTypes);
    }

    @Test
    public void getAllResponseTypes_NullList_Test() {
        final ImmutableList<String> result = getAllResponseTypes(null);
        assertThat(result.size(), is(0));
    }

    @Test
    public void getAllResponseTypes_EmptyList_Test() {
        final ImmutableList<String> result = getAllResponseTypes(ImmutableList.of());
        assertThat(result.size(), is(0));
    }

    @Test
    public void getAllResponseTypes_FullList_Test() {
        final ImmutableList<String> result = getAllResponseTypes(createTestResponseCodes(true));
        assertThat(result.size(), is(2));
        assertTrue(result.contains("com.spectralogic.s3.server.domain.JobWithChunksApiBean"));
        assertTrue(result.contains("null"));
    }

    @Test
    public void hasResponsePayload_NullResponses_Test() {
        assertFalse(hasResponsePayload(createTestResponseCodes(false)));
    }

    @Test
    public void hasResponsePayload_PayloadResponse_Test() {
        assertTrue(hasResponsePayload(createTestResponseCodes(true)));
    }

    @Test
    public void getResponsePayload_NullList_Test() {
        assertThat(getResponsePayload(null), is(nullValue()));
    }

    @Test
    public void getResponsePayload_EmptyList_Test() {
        assertThat(getResponsePayload(ImmutableList.of()), is(nullValue()));
    }

    @Test
    public void getResponsePayload_NoResponsePayload_Test() {
        final ImmutableList<Ds3ResponseCode> codes = ImmutableList.of(
                new Ds3ResponseCode(204, ImmutableList.of(new Ds3ResponseType("null", null))));
        assertThat(getResponsePayload(codes), is(nullValue()));
    }

    @Test
    public void getResponsePayload_FullList_Test() {
        final ImmutableList<Ds3ResponseCode> codes = ImmutableList.of(
                new Ds3ResponseCode(200, ImmutableList.of(new Ds3ResponseType("ResponseType", null))),
                new Ds3ResponseCode(204, ImmutableList.of(new Ds3ResponseType("null", null))));
        assertThat(getResponsePayload(codes), is("ResponseType"));
    }

    @Test (expected = IllegalArgumentException.class)
    public void getResponsePayload_Exception_Test() {
        final ImmutableList<Ds3ResponseCode> codes = ImmutableList.of(
                new Ds3ResponseCode(200, ImmutableList.of(new Ds3ResponseType("ResponseType", null))),
                new Ds3ResponseCode(204, ImmutableList.of(new Ds3ResponseType("ResponseType2", null))));
        getResponsePayload(codes);
    }

    @Test
    public void getAllNonErrorResponseCodes_NullList_Test() {
        final ImmutableList<Integer> result = getAllNonErrorResponseCodes(null);
        assertThat(result.size(), is(0));
    }

    @Test
    public void getAllNonErrorResponseCodes_EmptyList_Test() {
        final ImmutableList<Integer> result = getAllNonErrorResponseCodes(ImmutableList.of());
        assertThat(result.size(), is(0));
    }

    @Test
    public void getAllNonErrorResponseCodes_FullList_Test() {
        final ImmutableList<Ds3ResponseCode> codes = ImmutableList.of(
                new Ds3ResponseCode(200, ImmutableList.of(new Ds3ResponseType("com.test.ResponseType", null))),
                new Ds3ResponseCode(204, ImmutableList.of(new Ds3ResponseType("com.test.ResponseType", null))),
                new Ds3ResponseCode(400, ImmutableList.of(new Ds3ResponseType("com.test.ResponseType", null))));

        final ImmutableList<Integer> result = getAllNonErrorResponseCodes(codes);
        assertThat(result.size(), is(2));
        assertThat(result, hasItem(200));
        assertThat(result, hasItem(204));
    }

    @Test
    public void removeNullPayloads_NullList_Test() {
        final ImmutableList<Ds3ResponseCode> result = removeNullPayloads(null);
        assertThat(result.size(), is(0));
    }

    @Test
    public void removeNullPayloads_EmptyList_Test() {
        final ImmutableList<Ds3ResponseCode> result = removeNullPayloads(ImmutableList.of());
        assertThat(result.size(), is(0));
    }

    @Test
    public void removeNullPayloads_FullList_Test() {
        final ImmutableList<Ds3ResponseCode> codes = ImmutableList.of(
                new Ds3ResponseCode(200, ImmutableList.of(new Ds3ResponseType("null", null))),
                new Ds3ResponseCode(207, ImmutableList.of(new Ds3ResponseType("com.test.ResponsePayload", null)))
        );

        final ImmutableList<Ds3ResponseCode> result = removeNullPayloads(codes);
        assertThat(result.size(), is(1));
        assertThat(result.get(0).getCode(), is(207));
    }

    @Test
    public void hasSpecifiedPayload_Test() {
        assertThat(hasSpecifiedPayload(getGetBlobPersistence(), "java.lang.String"), is(true));
        assertThat(hasSpecifiedPayload(getGetBlobPersistence(), "String"), is(true));
        assertThat(hasSpecifiedPayload(getGetBlobPersistence(), "JobWithChunksApiBean"), is(false));

        assertThat(hasSpecifiedPayload(getRequestGetJob(), "com.spectralogic.s3.server.domain.JobWithChunksApiBean"), is(true));
        assertThat(hasSpecifiedPayload(getRequestGetJob(), "JobWithChunksApiBean"), is(true));
        assertThat(hasSpecifiedPayload(getRequestGetJob(), "String"), is(false));
    }
}


text:
These will vary depending on provider.

* [aws](aws-node.md)
* [gke](gke-node.md)

redpajama_set_name: RedPajamaGithub


text:
using System;
using Xamarin.Forms;

namespace GamesWithGravitas.XamarinForms.Sample
{
	public partial class SkiaPage : ContentPage
	{
		public SkiaPage()
		{
			InitializeComponent();
            animatedView.AnimateAsync();
		}

        private void ButtonClicked(object sender, EventArgs e)
        {
            animatedView.AnimateAsync();
        }
	}
}


text:
package io.dropwizard.lifecycle.setup;

import com.codahale.metrics.InstrumentedThreadFactory;
import io.dropwizard.lifecycle.ExecutorServiceManager;
import io.dropwizard.util.Duration;

import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;

public class ScheduledExecutorServiceBuilder {

    private static final AtomicLong COUNT = new AtomicLong(0);
    private final LifecycleEnvironment environment;
    private final String nameFormat;
    private int poolSize;
    private ThreadFactory threadFactory;
    private Duration shutdownTime;
    private RejectedExecutionHandler handler;
    private boolean removeOnCancel;

    public ScheduledExecutorServiceBuilder(LifecycleEnvironment environment, String nameFormat, ThreadFactory factory) {
        this.environment = environment;
        this.nameFormat = nameFormat;
        this.poolSize = 1;
        this.threadFactory = factory;
        this.shutdownTime = Duration.seconds(5);
        this.handler = new ThreadPoolExecutor.AbortPolicy();
        this.removeOnCancel = false;
    }

    public ScheduledExecutorServiceBuilder(LifecycleEnvironment environment, String nameFormat, boolean useDaemonThreads) {
        this(environment, nameFormat, buildThreadFactory(nameFormat, useDaemonThreads));
    }

    private static ThreadFactory buildThreadFactory(String nameFormat, boolean daemon) {
        return r -> {
            final Thread thread = Executors.defaultThreadFactory().newThread(r);
            if (nameFormat != null) {
                thread.setName(String.format(Locale.ROOT, nameFormat, COUNT.incrementAndGet()));
            }
            thread.setDaemon(daemon);
            return thread;
        };
    }

    public ScheduledExecutorServiceBuilder threads(int threads) {
        this.poolSize = threads;
        return this;
    }

    public ScheduledExecutorServiceBuilder shutdownTime(Duration time) {
        this.shutdownTime = time;
        return this;
    }

    public ScheduledExecutorServiceBuilder rejectedExecutionHandler(RejectedExecutionHandler handler) {
        this.handler = handler;
        return this;
    }

    public ScheduledExecutorServiceBuilder threadFactory(ThreadFactory threadFactory) {
        this.threadFactory = threadFactory;
        return this;
    }

    public ScheduledExecutorServiceBuilder removeOnCancelPolicy(boolean removeOnCancel) {
        this.removeOnCancel = removeOnCancel;
        return this;
    }

    public ScheduledExecutorService build() {
        final InstrumentedThreadFactory instrumentedThreadFactory = new InstrumentedThreadFactory(threadFactory,
            environment.getMetricRegistry(), nameFormat);

        final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(poolSize, instrumentedThreadFactory, handler);
        executor.setRemoveOnCancelPolicy(removeOnCancel);

        environment.manage(new ExecutorServiceManager(executor, shutdownTime, nameFormat));
        return executor;
    }
}


text:
using MasterDevs.ChromeDevTools;

namespace MasterDevs.ChromeDevTools.Protocol.Page
{
	/// <summary>
	/// Fired when the page with currently enabled screencast was shown or hidden </code>.
	/// </summary>
	[Event(ProtocolName.Page.ScreencastVisibilityChanged)]
	public class ScreencastVisibilityChangedEvent
	{
		/// <summary>
		/// Gets or sets True if the page is visible.
		/// </summary>
		public bool Visible { get; set; }
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace usbswitch_pccontrol
{
    delegate void AppendLog(string s);

    static class logger
    {
        static AppendLog logDest;

        public static void SetLogDest(AppendLog dest)
        {
            logDest = dest;
        }

        public static void Line(string s)
        {
            logDest(s);
            logDest(Environment.NewLine);
        }
    }
}


text:
Grid extends List to provide tabular display of data items, with different
fields arranged into columns.

```js
require([ 'dgrid/Grid' ], function (Grid) {
    var columns = {
        first: {
            label: "First Name"
        },
        last: {
            label: "Last Name"
        }
    };
    var grid = new Grid({ columns: columns }, 'grid'); // attach to a DOM id
    grid.renderArray(arrayOfData); // render some data
});
```

**Note:** `dgrid/Grid` does not directly support `dstore` stores. `dstore` stores are supported by the following:

* [`dgrid/OnDemandList` and `dgrid/OnDemandGrid`](OnDemandList-and-OnDemandGrid.md)
* [`dgrid/extensions/Pagination`](../extensions/Pagination.md)
* Anything else that extends `dgrid/_StoreMixin`

## APIs

In addition to the methods and properties inherited from [List](List.md), the Grid
component also exposes the following properties and methods.

### Property Summary

Property | Description
-------- | -----------
`formatterScope` | Optional object; if specified, column formatters may be specified as strings instead of functions, in which case they will be searched for as properties within the given `formatterScope` object, and executed in the context of that object.
`hasNeutralSort` | Boolean; controls behavior when clicking the same column heading repeatedly.  `false` (the default) alternates between sorting ascending and descending.  `true` alternates between ascending, descending, and no sort.

### Method Summary

Method | Description
------ | -------------
`cell(target[, columnId])` | Analogous to the `row` method, but at the `cell` level instead.  The `cell` method can look up based on an event or DOM element, or alternatively, a data item (or ID thereof) and the ID of a column. Returns an object containing the following properties: `row` - a Row object (as would be obtained from the `row` method) for the row the cell is within, `column` - the column definition object for the column the cell is within, `element`- the cell's DOM element.
`column(target)` | Returns the column definition object for the given column ID; typically analogous to `cell(...).column`.
`left(cell[, steps])` | Given a cell object (or something that resolves to one via the `cell` method), returns a cell object representing the cell located `steps` cells to the left (where `steps` defaults to `1`), wrapping to previous rows if necessary.
`right(cell[, steps])` | Same as `left()`, but operating towards the right, wrapping to subsequent rows if necessary.
`styleColumn(columnId, css)` | Programmatically adds styles to a column, given its column id, by injecting a rule string into a stylesheet in the document.  Returns a handle with a `remove` function, which can be called to later remove the added style rule.  Styles added via this method will be removed when the instance is destroyed if `cleanAddedRules` is set to `true`.
`updateSortArrow(sort, updateSort)` | Updates the placement of the sort arrow indicator in the appropriate header cell.  Normally called automatically, but can be called manually in the case of custom sort logic where the `dgrid-sort` event is canceled.  `sort` is the new sort order to be reflected by the UI update; `updateSort` is an optional boolean (defaulting to `false`) which, if `true`, will update the internal `_sort` variable to keep it in sync.

By default, the Grid renders a header, containing cells which display the label
of each column. This can be disabled by setting `showHeader: false` in the
arguments object to the Grid; it can also be changed later using
`set("showHeader", ...)`.

## Events

The Grid component emits one custom event, `dgrid-sort`, when a header cell is
clicked to initiate a sort.  This event includes the following properties:

* `grid`: The Grid instance which fired the event
* `parentType`: The original type of event responsible for firing this one
  (`click` or `keydown` within a header cell)
* `sort`: An array of objects with `property` and optionally `descending`
  properties, representing the new sort order to be put into effect

The `dgrid-sort` event bubbles and is cancelable; if canceled, the sort
order will not be set.  This can be useful for instituting custom sort logic
where setting the actual sort on an array or store is undesirable; in this
case, `updateSortArrow` should be called manually if the header is to be
updated.

## Specifying Grid Columns

In the simplest cases, the columns of the grid are defined via the `columns`
property. This property can be a hash (object) or array, containing column
definition objects. When `columns` is an object, each property's key represents
the `id` and `field` of the column, and each value is the column definition object.
When `columns` is an array, the numeric indices become the column IDs; `field`
must be specified within each definition.

Generally, using object notation is slightly more concise and convenient.
However, it's worth noting that doing so relies on the order of enumeration
employed by the JavaScript runtime. Typically this isn't a problem, as it
matches the order in which properties are specified, but one common exception is
in the case of keys coercible to numbers.

### Columns using an object

This is an example of a `Grid` using object column definitions:

```js
require([ 'dgrid/Grid' ], function (Grid) {
    var columns = {
        first: {
            label: 'First Name'
        },
        last: {
            label: 'Last Name'
        },
        age: {
            label: 'Age',
            get: function(object){
                return (new Date() - object.birthDate) / 31536000000;
            }
        }
    };
    var grid = new Grid({ columns: columns }, 'grid'); // attach to a DOM id
    grid.renderArray(arrayOfData); // render some data
    // ...
});
```

### Columns using an array

Alternatively, the same columns as above could be defined in an array, as
follows:

```js
var columns = [
    {
        label: 'First Name',
        field: 'first'
    },
    {
        label: 'Last Name',
        field: 'last'
    },
    {
        label: 'Age',
        field: 'age',
        get: function(object){
            return (new Date() - object.birthDate) / 31536000000;
        }
    }
];
```

### Column shorthand

A column definition may also be specified simply as a string, in which case the
value of the string is interpreted as the label of the column. Thus, the
simplest column structures can be more succinctly written:

```js
var columns = {
    first: 'First Name',
    last: 'Last Name',
    // ...
};
```

### Sub-rows

The Grid component also supports structures with multiple "sub-rows"; that is, it
supports the idea of rendering multiple rows for each data item. Specification
of multiple sub-rows is very much like specifying columns, except that one uses
the `subRows` property instead of `columns`, and it receives an array of columns
objects/arrays. Both the `columns` and `subRows` properties can be later reset
by using the central `set` method.

```js
require([
    'dgrid/Grid'
],function (Grid) {
    var grid = new Grid({
        subRows: [
            [
                { field: 'id', label: 'ID' },
                { field: 'name', label: 'Name' }
            ],
            [
                { field: 'description', label: 'Description', colSpan: 2 }
            ]
        ],
        // ...
    }, 'grid');
});
```

#### Column and row spanning with sub-rows

When defining column structures with multiple sub-rows (via `subRows` or the
[`ColumnSet`](../mixins/ColumnSet.md) mixin), the `colSpan` and `rowSpan` properties (documented below)
can be specified in column definitions.  See the
[`complex_column.html`](../../../test/complex_column.html) test page for examples of these properties in action.

## Column Definition Properties

In any of the above formats, each individual column definition object may have
the following properties (all are optional):

Property | Description
-------- | -------------
`field` | The property from the object in the list to display in the body of the grid (unless otherwise overridden via the `get` function, explained below). In cases where `columns` is passed an object, the key of each property represents the field name, and thus this property is normally omitted.
`id` | The id of the column; normally this is determined automatically from the keys or indices in the `columns` object or array.
`label` | The label to show in the header of the grid. Defaults to the value of `field`.
`className` | CSS class(es) to assign to the cells in the column.  The value of this property may be a string to apply equally to all cells in the column, or a function which is passed the item for each row (or `undefined` for the header row) and should return a string.  In either case, multiple classes may be specified space-delimited.  In addition, a class in the format `field-<field>` is added if the column has a `field` defined.
`colSpan` | A number specifying how many columns the cell should span, when multiple sub-rows are defined.
`rowSpan` | A number specifying how many rows the cell should span, when multiple sub-rows are defined.
`sortable` | Indicates whether or not the grid should allow sorting by values in this field, by clicking on the column's header cell. Defaults to `true`. Note that it is always possible to programmatically sort a Grid by a given field by calling `set("sort", property, descending)` regardless of`sortable` status or even visible presence in the Grid altogether.
`get(item)` | An optional function that, given a data item, will return the value to render in the cell.
`set(item)` | An optional function that, given a modified data item, will return the value to set for the respective field on that item upon a call to `save()`. If no value is returned, the value as set in the passed item will be used.  (Modifying the passed item directly is thus also an option.)
`formatter(value, object)` | An optional function that will return a string of HTML for rendering.  The function is passed the value that would normally be rendered, and the object from the collection.  If `formatterScope` is used, this can be a string instead of a function, in which case a function will be looked up on the `formatterScope` object using the given string. (Note: if a custom `renderCell` is specified, `formatter` will be ignored unless the custom `renderCell` accounts for it.)
`renderCell(object, value, node, options)` | An optional function that will be called to render the value into the target cell. `object` refers to the record from the grid's collection for the row, and `value` refers to the specific value for the current cell (which may have been modified by the column definition's `get` function). `node` refers to the table cell that will be placed in the grid if nothing is returned by `renderCell`; if `renderCell` returns a node, that returned node will be placed inside the table cell. (Note: if a custom `renderCell` is specified, `formatter` will be ignored unless the custom `renderCell` accounts for it.)
`renderHeaderCell(node)` | An optional function that will be called to render the column's header cell. Like `renderCell`, this may either operate on the node directly, or return a new node to be placed within it.


text:
layout: page
title: Menu levels
permalink: /menu-levels/
menu: menu-levels
group: main
---

<p class="lead">
    This is an example for a menu with levels
</p>
{% include edit.html %}


text:
import sbt._
import sbt.Keys._

object BuhtigBuild extends Build {

  lazy val buhtig = Project(
    id = "buhtig",
    base = file("."),
    settings = Project.defaultSettings ++ Seq(
      name := "buhtig",
      organization := "net.caoticode.buhtig",
      version := "0.3.1",
      scalaVersion := "2.11.7",
      crossScalaVersions := Seq("2.10.5", "2.11.7"),
      homepage      := Some(url("https://github.com/mdread/buhtig")),
      description   := "Painless Github client",
      licenses      := Seq("MIT License" -> url("http://www.opensource.org/licenses/mit-license.php")),

      // deps
      libraryDependencies += "net.databinder.dispatch" %% "dispatch-core" % "0.11.2",
      libraryDependencies += "org.json4s" %% "json4s-native" % "3.2.11",

      // testing deps
      libraryDependencies ++= Seq("org.specs2" %% "specs2-core" % "3.6.4" % "test"),
      scalacOptions in Test ++= Seq("-Yrangepos")
    )
  )
}


text:
import shutil
import os

from flask import Flask
from flask import request
from flask import make_response

app = Flask(__name__)

@app.route('/')
def index():
    return app.send_static_file('index.html')

@app.route('/slides.md', methods=['GET'])
def get_slides():
    with open("./slides.md") as fp:
        return fp.read()

@app.route('/slides.md', methods=['PUT'])
def save_slides():
    new_slides = request.get_data()
    with open('./slides.md', 'wb') as fp:
        fp.write(new_slides)
    return make_response("", 200)

if __name__ == '__main__':
    if not os.path.isfile("./slides.md"):
        shutil.copy("initial-slides.md", "./slides.md")
    app.run('0.0.0.0', 8000, debug=True)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. eur. (Erlanga) 1: 261 (1822)

#### Original name
Peziza pulchella var. bicolor Pers.

### Remarks
null


text:
package org.switchyard.quickstarts.demo.txpropagation;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.component.test.mixins.cdi.CDIMixIn;
import org.switchyard.component.test.mixins.transaction.TransactionMixIn;
import org.switchyard.quickstarts.demo.txpropagation.Application;
import org.switchyard.quickstarts.demo.txpropagation.Offer;
import org.switchyard.test.Invoker;
import org.switchyard.test.ServiceOperation;
import org.switchyard.test.SwitchYardRunner;
import org.switchyard.test.SwitchYardTestCaseConfig;

@RunWith(SwitchYardRunner.class)
@SwitchYardTestCaseConfig(mixins = { CDIMixIn.class, TransactionMixIn.class }, config = SwitchYardTestCaseConfig.SWITCHYARD_XML)
public class CreditCheckTest {

    @ServiceOperation("RuleService")
    private Invoker service;

    // Verify that credit scores at or above 600 are approved
    @Test
    public void creditApproved() throws Exception {
        Application app = new Application();
        app.setName("phil garfield");
        app.setCreditScore(600);
        Offer offer = new Offer();
        offer.setApplication(app);

        Application result = service.operation("checkCredit").sendInOut(offer).getContent(Application.class);

        // validate the results
        Assert.assertTrue(result.isApproved());
    }

    // Verify that credit scores below 600 are denied
    @Test
    public void creditDenied() throws Exception {
        Application app = new Application();
        app.setName("bill whatwhatwhat");
        app.setCreditScore(400);
        Offer offer = new Offer();
        offer.setApplication(app);

        Application result = service.operation("checkCredit").sendInOut(offer).getContent(Application.class);

        // validate the results
        Assert.assertFalse(result.isApproved());
    }
}


text:
@interface YTLocateViewController : UIViewController

@end


text:
package kornell.server.web

import javax.servlet._
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import kornell.server.util.{Settings, UserLocale}

class UserLocaleFilter extends Filter {

  override def doFilter(sreq: ServletRequest, sres: ServletResponse, chain: FilterChain): Unit =
    (sreq, sres) match {
      case (hreq: HttpServletRequest, hres: HttpServletResponse) => {
        if (hreq.getRequestURI.startsWith("/api") && !hreq.getRequestURI.equals("/api")) {
          doFilter(hreq, hres, chain)
        } else {
          chain.doFilter(hreq, hres)
        }
      }
    }

  def doFilter(req: HttpServletRequest, resp: HttpServletResponse, chain: FilterChain): Unit = {
    getLocale(req)
    chain.doFilter(req, resp)
    UserLocale.clearLocale()
  }

  def getLocale(req: HttpServletRequest): String = {
    if (req.getCookies != null) {
      val cookie = req.getCookies.find(p => p.getName == "knlLocale")
      if (cookie.isEmpty) {
        //No cookie, set default locale
        UserLocale.setLocale(Settings.DEFAULT_LOCALE)
      } else {
        UserLocale.setLocale(cookie.get.getValue)
      }
    } else {
      //No cookies at all, set default locale
      UserLocale.setLocale(Settings.DEFAULT_LOCALE)
    }
  }

  override def init(cfg: FilterConfig): Unit = {}

  override def destroy(): Unit = {}
}


text:
module InfinityTest
  module Core
    class Base
      # Specify the Ruby Version Manager to run
      cattr_accessor :strategy
      # ==== Options
      # * :rvm
      # * :rbenv
      # * :ruby_normal (Use when don't pass any rubies to run)
      # * :auto_discover(defaults)
      self.strategy = :auto_discover

      # Specify Ruby version(s) to test against
      #
      # ==== Examples
      # rubies = %w(ree jruby)
      #
      cattr_accessor :rubies
      self.rubies = []

      # Options to include in the command.
      #
      cattr_accessor :specific_options
      self.specific_options = ''

      # Test Framework to use Rspec, Bacon, Test::Unit or AutoDiscover(defaults)
      # ==== Options
      # * :rspec
      # * :bacon
      # * :test_unit (Test unit here apply to this two libs: test/unit and minitest)
      # * :auto_discover(defaults)
      #
      # This will load a exactly a class constantize by name.
      #
      cattr_accessor :test_framework
      self.test_framework = :auto_discover

      # Framework to know the folders and files that need to monitoring by the observer.
      #
      # ==== Options
      # * :rails
      # * :rubygems
      # * :auto_discover(defaults)
      #
      # This will load a exactly a class constantize by name.
      #
      cattr_accessor :framework
      self.framework = :auto_discover

      # Framework to observer watch the dirs.
      #
      # ==== Options
      #  * watchr
      #
      cattr_accessor :observer
      self.observer = :watchr

      # Ignore test files.
      #
      # ==== Examples
      #   ignore_test_files = [ 'spec/generators/controller_generator_spec.rb' ]
      #
      cattr_accessor :ignore_test_files
      self.ignore_test_files = []

      # Ignore test folders.
      #
      # ==== Examples
      #   # Imagine that you don't want to run integration specs.
      #   ignore_test_folders = [ 'spec/integration' ]
      #
      cattr_accessor :ignore_test_folders
      self.ignore_test_folders = []

      # Verbose Mode. Print commands before executing them.
      #
      cattr_accessor :verbose
      self.verbose = true

      # Set the notification framework to use with Infinity Test.
      #
      # ==== Options
      # * :growl
      # * :lib_notify
      # * :auto_discover(defaults)
      #
      # This will load a exactly a class constantize by name.
      #
      cattr_writer :notifications
      self.notifications = :auto_discover

      # You can set directory to show images matched by the convention names.
      # => http://github.com/tomas-stefano/infinity_test/tree/master/images/ )
      #
      # Infinity test will work on these names in the notification framework:
      #
      # * success (png, gif, jpeg)
      # * failure (png, gif, jpeg)
      # * pending (png, gif, jpeg)
      #
      cattr_accessor :mode

      #
      # => This will show images in the folder:
      # http://github.com/tomas-stefano/infinity_test/tree/master/images/simpson
      #
      self.mode = :simpson

      # Success Image to show after the tests run.
      #
      cattr_accessor :success_image

      # Pending Image to show after the tests run.
      #
      cattr_accessor :pending_image

      # Failure Image to show after the tests run.
      #
      cattr_accessor :failure_image

      # Use a specific gemset for each ruby.
      # OBS.: This only will work for RVM strategy.
      #
      cattr_accessor :gemset

      # InfinityTest try to use bundler if Gemfile is present.
      # Set to false if you don't want use bundler.
      #
      cattr_accessor :bundler
      self.bundler = true

      # Callbacks accessor to handle before or after all run and for each ruby!
      cattr_accessor :callbacks
      self.callbacks = []

      # Run the observer to monitor files.
      # If set to false will just Run tests and exit.
      # Defaults to true: run tests and monitoring the files.
      #
      cattr_accessor :infinity_and_beyond
      self.infinity_and_beyond = true

      # The extension files that Infinity Test will search.
      # You can observe python, erlang, etc files.
      #
      cattr_accessor :extension
      self.extension = :rb

      # Setup Infinity Test passing the ruby versions and others setting.
      # See the class accessors for more information.
      #
      # ==== Examples
      #
      #  InfinityTest::Base.setup do |config|
      #    config.strategy = :rbenv
      #    config.rubies   = %w(ree jruby rbx 1.9.2)
      #  end
      #
      def self.setup
        yield self
      end

      # Receives a object that quacks like InfinityTest::Options and do the merge with self(Base class).
      #
      def self.merge!(options)
        ConfigurationMerge.new(self, options).merge!
      end

      def self.start_continuous_test_server
        continuous_test_server.start
      end

      def self.continuous_test_server
        @continuous_test_server ||= ContinuousTestServer.new(self)
      end

      # Just a shortcut to bundler class accessor.
      #
      def self.using_bundler?
        bundler
      end

      # Just a shortcut to bundler class accessor.
      #
      def self.verbose?
        verbose
      end

      # Callback method to handle before all run and for each ruby too!
      #
      # ==== Examples
      #
      #   before(:all) do
      #     # ...
      #   end
      #
      #   before(:each_ruby) do |environment|
      #     # ...
      #   end
      #
      #   before do # if you pass not then will use :all option
      #     # ...
      #   end
      #
      def self.before(scope, &block)
        # setting_callback(Callbacks::BeforeCallback, scope, &block)
      end

      # Callback method to handle after all run and for each ruby too!
      #
      # ==== Examples
      #
      #   after(:all) do
      #     # ...
      #   end
      #
      #   after(:each_ruby) do
      #     # ...
      #   end
      #
      #   after do # if you pass not then will use :all option
      #     # ...
      #   end
      #
      def self.after(scope, &block)
        # setting_callback(Callbacks::AfterCallback, scope, &block)
      end

      # Clear the terminal (Useful in the before callback)
      #
      def self.clear_terminal
        system('clear')
      end

      ###### This methods will be removed in the Infinity Test v2.0.1 or 2.0.2 ######

      # DEPRECATED: Please use <tt>.notification=</tt> instead.
      #
      def self.notifications(notification_name = nil, &block)
        if notification_name.blank?
          self.class_variable_get(:@@notifications)
        else
          message = <<-MESSAGE
            .notifications is DEPRECATED.
            Use this instead:
              InfinityTest.setup do |config|
                config.notifications = :growl
              end
          MESSAGE
          ActiveSupport::Deprecation.warn(message)
          self.notifications = notification_name
          self.instance_eval(&block) if block_given?
        end
      end

      # DEPRECATED: Please use:
      # <tt>success_image=</tt> or
      # <tt>pending_image=</tt> or
      # <tt>failure_image=</tt> or
      # <tt>mode=</tt> instead.
      #
      def self.show_images(options)
        message = <<-MESSAGE
          .show_images is DEPRECATED.
          Use this instead:
           InfinityTest.setup do |config|
             config.success_image = 'some_image.png'
             config.pending_image = 'some_image.png'
             config.failure_image = 'some_image.png'
             config.mode          = 'infinity_test_dir_that_contain_images'
           end
        MESSAGE
        ActiveSupport::Deprecation.warn(message)
        self.success_image = options[:success_image] || options[:sucess_image] if options[:success_image].present? || options[:sucess_image].present? # for fail typo in earlier versions.
        self.pending_image = options[:pending_image] if options[:pending_image].present?
        self.failure_image = options[:failure_image] if options[:failure_image].present?
        self.mode = options[:mode] if options[:mode].present?
      end

      # DEPRECATED: Please use:
      # .rubies = or
      # .specific_options = or
      # .test_framework = or
      # .framework = or
      # .verbose = or
      # .gemset = instead
      #
      def self.use(options)
        message = <<-MESSAGE
          .use is DEPRECATED.
          Use this instead:
            InfinityTest.setup do |config|
              config.rubies           = %w(2.0 jruby)
              config.specific_options = '-J'
              config.test_framework   = :rspec
              config.framework        = :padrino
              config.verbose          = true
              config.gemset           = :some_gemset
            end
        MESSAGE
        ActiveSupport::Deprecation.warn(message)
        self.rubies = options[:rubies] if options[:rubies].present?
        self.specific_options = options[:specific_options] if options[:specific_options].present?
        self.test_framework = options[:test_framework] if options[:test_framework].present?
        self.framework = options[:app_framework] if options[:app_framework].present?
        self.verbose = options[:verbose] unless options[:verbose].nil?
        self.gemset = options[:gemset] if options[:gemset].present?
      end

      # DEPRECATED: Please use .clear_terminal instead.
      #
      def self.clear(option)
        message = '.clear(:terminal) is DEPRECATED. Please use .clear_terminal instead.'
        ActiveSupport::Deprecation.warn(message)
        clear_terminal
      end

      def self.heuristics(&block)
        # There is a spec pending.
      end

      def self.replace_patterns(&block)
        # There is a spec pending.
      end

      private

      # def self.setting_callback(callback_class, scope, &block)
      #   callback_instance = callback_class.new(scope, &block)
      #   self.callbacks.push(callback_instance)
      #   callback_instance
      # end
    end
  end
end


text:
- [Mostrando una videogaleria en un carousel partiendo de una ID](demoid.html)

Para utilizar otra id, solo necesitas pasarlo como parámetro en la url.

```
demoid.html?id=3312498
```

### Ejemplos

### /videogalerias - Peticiones Ajax y respuestas esperadas

**Petición Ajax a http://api.rtve.es/api/videogalerias.json**

```javascript
var xmlHttp = new XMLHttpRequest()

xmlHttp.onreadystatechange = function() {
    var datos = {};
    if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
        datos = JSON.parse(xmlHttp.responseText);
        console.info(datos);
    } else if (xmlHttp.readyState === 4 && xmlHttp.status === 400) {
        datos = JSON.parse(xmlHttp.responseText);
        console.error("ERROR! 400 - Solicitud incorrecta!");
    } else if (xmlHttp.readyState === 4 && xmlHttp.status === 404) {
        datos = JSON.parse(xmlHttp.responseText);
        console.error("ERROR! 404 - No encontrado!");
    }
};

xmlHttp.open("GET", "http://api.rtve.es/api/videogalerias.json", true);
xmlHttp.send();
```

**Respuesta esperada**

- page (Object)
	- items (Array)
		- 0 (Object)
		- ...
	- number: Number
	- size: Number
	- offset: Number
	- total: Number
	- totalPages: Number
	- numElements: Number

### /videogalerias/{id} - Peticiones Ajax y respuestas esperadas

**Petición Ajax a http://api.rtve.es/api/videogalerias/147975.json**

```javascript
var xmlHttp = new XMLHttpRequest()

xmlHttp.onreadystatechange = function() {
    var datos = {};
    if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
        datos = JSON.parse(xmlHttp.responseText);
        console.info(datos);
    } else if (xmlHttp.readyState === 4 && xmlHttp.status === 400) {
        datos = JSON.parse(xmlHttp.responseText);
        console.error("ERROR! 400 - Solicitud incorrecta!");
    } else if (xmlHttp.readyState === 4 && xmlHttp.status === 404) {
        datos = JSON.parse(xmlHttp.responseText);
        console.error("ERROR! 404 - No encontrado!");
    }
};

xmlHttp.open("GET", "http://api.rtve.es/api/videogalerias/147975.json", true);
xmlHttp.send();
```

**Respuesta esperada**

- page (Object)
	- items (Array)
		- 0 (Object)
			- uri: String
			- htmlUrl: String
			- htmlShortUrl: String
			- id: String
			- language: String
			- longTitle: String
			- shortTitle: String
			- mainCategoryRef: String
			- popularity: String
			- popHistoric: String
			- numVisits: String
			- publicationDate: String
			- expirationDate: null
			- modificationDate: String
			- pubState (Object)
				- code: String
				- description: String
			- breadCrumbRef: String
			- imageSEO: null
			- publicationDateTimestamp: Number
			- contentType: String
			- statistics (Object)
				- numComentarios: Number
				- numCompartidas: Number
			- image: null
			- description: null
			- links (Object)
				- multimediasRef: String
				- relatedGalleriesRef: String
				- linksRef: String
				- estadisticasRef: String
			- topicsName: null
			- otherTopicsRefs: String
			- mainTopic: null
			- title: String
	- number: Number
	- size: Number
	- offset: Number
	- total: Number
	- totalPages: Number
	- numElements: Number


text:
import * as types from "../constants/ActionTypes";
import * as actions from "./index";

describe("todo actions", () => {
  it("addTodo should create ADD_TODO action", () => {
    expect(actions.addTodo("Use Redux")).toEqual({
      type: types.ADD_TODO,
      text: "Use Redux"
    });
  });

  it("deleteTodo should create DELETE_TODO action", () => {
    expect(actions.deleteTodo(1)).toEqual({
      type: types.DELETE_TODO,
      id: 1
    });
  });

  it("editTodo should create EDIT_TODO action", () => {
    expect(actions.editTodo(1, "Use Redux everywhere")).toEqual({
      type: types.EDIT_TODO,
      id: 1,
      text: "Use Redux everywhere"
    });
  });

  it("completeTodo should create COMPLETE_TODO action", () => {
    expect(actions.completeTodo(1)).toEqual({
      type: types.COMPLETE_TODO,
      id: 1
    });
  });

  it("completeAll should create COMPLETE_ALL action", () => {
    expect(actions.completeAll()).toEqual({
      type: types.COMPLETE_ALL
    });
  });

  it("clearCompleted should create CLEAR_COMPLETED action", () => {
    expect(actions.clearCompleted()).toEqual({
      type: types.CLEAR_COMPLETED
    });
  });
});


text:
package com.google.android.apps.muzei.settings;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.os.UserManagerCompat;

/**
 * Preference constants/helpers.
 */
public class Prefs {
    public static final String PREF_GREY_AMOUNT = "grey_amount";
    public static final String PREF_DIM_AMOUNT = "dim_amount";
    public static final String PREF_BLUR_AMOUNT = "blur_amount";
    public static final String PREF_DISABLE_BLUR_WHEN_LOCKED = "disable_blur_when_screen_locked_enabled";

    private static final String WALLPAPER_PREFERENCES_NAME = "wallpaper_preferences";
    private static final String PREF_MIGRATED = "migrated_from_default";

    public synchronized static SharedPreferences getSharedPreferences(Context context) {
        Context deviceProtectedContext =
                ContextCompat.createDeviceProtectedStorageContext(context);
        if (UserManagerCompat.isUserUnlocked(context)) {
            // First migrate the wallpaper settings to their own file
            SharedPreferences defaultSharedPreferences =
                    PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences wallpaperPreferences = context.getSharedPreferences(
                    WALLPAPER_PREFERENCES_NAME, Context.MODE_PRIVATE);
            migratePreferences(defaultSharedPreferences, wallpaperPreferences);

            // Now migrate the file to device protected storage if available
            if (deviceProtectedContext != null) {
                SharedPreferences deviceProtectedPreferences = deviceProtectedContext.getSharedPreferences(
                        WALLPAPER_PREFERENCES_NAME, Context.MODE_PRIVATE);
                migratePreferences(wallpaperPreferences, deviceProtectedPreferences);
            }
        }
        // Now open the correct SharedPreferences
        Context contextToUse = deviceProtectedContext != null ? deviceProtectedContext : context;
        return contextToUse.getSharedPreferences(WALLPAPER_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }

    private static void migratePreferences(SharedPreferences source, SharedPreferences destination) {
        if (source.getBoolean(PREF_MIGRATED, false)) {
            return;
        }
        SharedPreferences.Editor sourceEditor = source.edit();
        SharedPreferences.Editor destinationEditor = destination.edit();

        if (source.contains(PREF_GREY_AMOUNT)) {
            destinationEditor.putInt(PREF_GREY_AMOUNT, source.getInt(PREF_GREY_AMOUNT, 0));
            sourceEditor.remove(PREF_GREY_AMOUNT);
        }
        if (source.contains(PREF_DIM_AMOUNT)) {
            destinationEditor.putInt(PREF_DIM_AMOUNT, source.getInt(PREF_DIM_AMOUNT, 0));
            sourceEditor.remove(PREF_DIM_AMOUNT);
        }
        if (source.contains(PREF_BLUR_AMOUNT)) {
            destinationEditor.putInt(PREF_BLUR_AMOUNT, source.getInt(PREF_BLUR_AMOUNT, 0));
            sourceEditor.remove(PREF_BLUR_AMOUNT);
        }
        if (source.contains(PREF_DISABLE_BLUR_WHEN_LOCKED)) {
            destinationEditor.putBoolean(PREF_DISABLE_BLUR_WHEN_LOCKED,
                    source.getBoolean(PREF_DISABLE_BLUR_WHEN_LOCKED, false));
            sourceEditor.remove(PREF_DISABLE_BLUR_WHEN_LOCKED);
        }
        sourceEditor.putBoolean(PREF_MIGRATED, true);
        sourceEditor.apply();
        destinationEditor.apply();
    }

    private Prefs() {
    }
}


text:
class ofxGpuLut{

private:
    ofShader lutShader;
    ofTexture lut;
    string vertexShader;
    string fragmentShader;
    ofImage lutImage;
public:
    ofxGpuLut();
    ~ofxGpuLut();

    void load(ofTexture lutTexture);
    void load(ofImage lutImage);
    void load(string path);
    void begin();
    void end();
};


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Task'
        db.create_table(u'tasks_task', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('project', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('item_id', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('url', self.gf('django.db.models.fields.URLField')(max_length=200)),
            ('skills', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('community_tools', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('project_area', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('summary', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('description', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('suggested_for', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('closed', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('suggested_mode', self.gf('django.db.models.fields.CharField')(max_length=25)),
            ('recently_verified', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal(u'tasks', ['Task'])

        # Adding model 'Student'
        db.create_table(u'tasks_student', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('task', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['tasks.Task'])),
        ))
        db.send_create_signal(u'tasks', ['Student'])

    def backwards(self, orm):
        # Deleting model 'Task'
        db.delete_table(u'tasks_task')

        # Deleting model 'Student'
        db.delete_table(u'tasks_student')

    models = {
        u'tasks.student': {
            'Meta': {'object_name': 'Student'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'task': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['tasks.Task']"})
        },
        u'tasks.task': {
            'Meta': {'object_name': 'Task'},
            'closed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'community_tools': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'item_id': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'project': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'project_area': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'recently_verified': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'skills': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'suggested_for': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'suggested_mode': ('django.db.models.fields.CharField', [], {'max_length': '25'}),
            'summary': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'url': ('django.db.models.fields.URLField', [], {'max_length': '200'})
        }
    }

    complete_apps = ['tasks']


text:
using System;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using WitsWay.TempTests.RemainProcessTest.PlanUI.DrawObjects;

namespace WitsWay.TempTests.RemainProcessTest.PlanUI
{
	//[Serializable]
	/// <summary>
	/// Each <see cref="Layer"/> contains a list of Graphic Objects <see cref="GraphicsList"/>.
	/// Each <see cref="Layer"/> is contained in the <see cref="Layers"/> collection.
	/// Properties:
	///	LayerName		User-defined name of the Layer
	///	Graphics			Collection of <see cref="DrawObject"/>s in the Layer
	///	IsVisible			True if the <see cref="Layer"/> is visible
	///	IsActive			True if the <see cref="Layer"/> is the active <see cref="Layer"/> (only one <see cref="Layer"/> may be active at a time)
	///	Dirty				True if any object in the <see cref="Layer"/> is dirty
	/// </summary>
	public class Layer
	{
		//private string _name;
		private bool _isDirty;
		//private bool _visible;
		//private bool _active;
		//private GraphicsList _graphicsList;

		/// <summary>
		/// <see cref="Layer"/> Name (User-defined)
		/// </summary>
		public string LayerName { get; set; }

		/// <summary>
		/// List of Graphic objects (derived from <see cref="DrawObject"/>) contained by this <see cref="Layer"/>
		/// </summary>
		public GraphicsList Graphics { get; set; }

		/// <summary>
		/// Returns True if this <see cref="Layer"/> is visible, else False
		/// </summary>
		public bool IsVisible { get; set; }

		/// <summary>
		/// Returns True if this is the active <see cref="Layer"/>, else False
		/// </summary>
		public bool IsActive { get; set; }

		/// <summary>
		/// Dirty is True if any elements in the contained <see cref="GraphicsList"/> are dirty, else False
		/// </summary>
		public bool Dirty
		{
			get
			{
				if (_isDirty == false)
					_isDirty = Graphics.Dirty;
				return _isDirty;
			}
			set
			{
			    Graphics.Dirty = false;
				_isDirty = false;
			}
		}

		private const string EntryLayerName = "LayerName";
		private const string EntryLayerVisible = "LayerVisible";
		private const string EntryLayerActive = "LayerActive";
		private const string EntryObjectType = "ObjectType";
		private const string EntryGraphicsCount = "GraphicsCount";

		public void SaveToStream(SerializationInfo info, int orderNumber)
		{
			info.AddValue(
				String.Format(CultureInfo.InvariantCulture,
				              "{0}{1}",
				              EntryLayerName, orderNumber),
				LayerName);

			info.AddValue(
				String.Format(CultureInfo.InvariantCulture,
				              "{0}{1}",
				              EntryLayerVisible, orderNumber),
				IsVisible);

			info.AddValue(
				String.Format(CultureInfo.InvariantCulture,
				              "{0}{1}",
				              EntryLayerActive, orderNumber),
				IsActive);

			info.AddValue(
				String.Format(CultureInfo.InvariantCulture,
				              "{0}{1}",
				              EntryGraphicsCount, orderNumber),
				Graphics.Count);

			for (int i = 0; i < Graphics.Count; i++)
			{
				object o = Graphics[i];
				info.AddValue(
					String.Format(CultureInfo.InvariantCulture,
					              "{0}{1}-{2}",
					              EntryObjectType, orderNumber, i),
					o.GetType().FullName);

				((DrawObject)o).SaveToStream(info, orderNumber, i);
			}
		}

		public void LoadFromStream(SerializationInfo info, int orderNumber)
		{
		    Graphics = new GraphicsList();

			LayerName = info.GetString(
				String.Format(CultureInfo.InvariantCulture,
				              "{0}{1}",
				              EntryLayerName, orderNumber));

			IsVisible = info.GetBoolean(
				String.Format(CultureInfo.InvariantCulture,
				              "{0}{1}",
				              EntryLayerVisible, orderNumber));

			IsActive = info.GetBoolean(
				String.Format(CultureInfo.InvariantCulture,
				              "{0}{1}",
				              EntryLayerActive, orderNumber));

			int n = info.GetInt32(
				String.Format(CultureInfo.InvariantCulture,
				              "{0}{1}",
				              EntryGraphicsCount, orderNumber));

			for (int i = 0; i < n; i++)
			{
				string typeName;
				typeName = info.GetString(
					String.Format(CultureInfo.InvariantCulture,
					              "{0}{1}-{2}",
					              EntryObjectType, orderNumber, i));

				object drawObject;
				drawObject = Assembly.GetExecutingAssembly().CreateInstance(typeName);

				((DrawObject)drawObject).LoadFromStream(info, orderNumber, i);

                // Thanks to Member 3272353 for this fix to object ordering problem.
                // _graphicsList.Add((DrawObject)drawObject);
			    Graphics.Append((DrawObject) drawObject);
			}
		}

		internal void Draw(Graphics g)
		{
		    Graphics.Draw(g);
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Automation.Peers;
using System.Windows.Automation;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows;
using System.Xml.Serialization;
using Microsoft.Win32;

namespace DesignScript.Editor.Common
{
    /// <summary>
    /// Interaction logic for CollectInfoDialog.xaml
    /// </summary>
    public partial class CollectInfoDialog : Window
    {
        public CollectInfoDialog()
        {
            InitializeComponent();
            this.CollectFeedback = false;
        }

        private void OnContinueClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        public void OnWindowClose(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void OnWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.CollectFeedback = false;
            if (acceptCheck.IsChecked.HasValue)
                this.CollectFeedback = acceptCheck.IsChecked.Value;
        }

        public bool CollectFeedback { get; private set; }
    }
}


text:
package io.digdag.server.metrics;

import com.google.common.base.Optional;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigElement;
import io.digdag.client.config.ConfigFactory;
import io.digdag.server.metrics.fluency.FluencyMonitorSystemConfig;
import io.digdag.server.metrics.jmx.JmxMonitorSystemConfig;
import io.digdag.spi.metrics.DigdagMetrics;
import static io.digdag.client.DigdagClient.objectMapper;

import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import java.util.HashMap;

public class DigdagMetricsConfigTest
{
    Logger logger = LoggerFactory.getLogger(DigdagMetricsConfigTest.class);

    Config config;

    @Before
    public void setup()
    {
        config = ConfigElement.ofMap(new HashMap<String,String>()).toConfig(new ConfigFactory(objectMapper()));
    }

    public Config fromJson(String json)
    {
        return ConfigElement.fromJson(json).toConfig(new ConfigFactory(objectMapper()));
    }

    @Test
    public void testDefault()
    {
        DigdagMetricsConfig metricsConfig = new DigdagMetricsConfig(config);
        assertFalse("No jmx config", metricsConfig.getMonitorSystemConfig("jmx").isPresent());
    }

    @Test
    public void testJmxEnabled()
    {
        /**
         *  metrics.enable: " jmx "
         */
        config = fromJson("{ \"metrics.enable\": \" jmx \" }");
        DigdagMetricsConfig metricsConfig = new DigdagMetricsConfig(config);

        Optional<JmxMonitorSystemConfig> jmxConfig = metricsConfig.getMonitorSystemConfig("jmx").transform((p) -> (JmxMonitorSystemConfig)p);
        assertTrue("Exist jmx config", jmxConfig.isPresent());
        assertTrue("plugin is enable", jmxConfig.get().getMonitorSystemEnable());
        assertTrue("category 'agent' is enable", jmxConfig.get().enable(DigdagMetrics.Category.AGENT));
        assertTrue("category 'api' is enable", jmxConfig.get().enable(DigdagMetrics.Category.API));
        assertTrue("category 'db' is enable", jmxConfig.get().enable(DigdagMetrics.Category.DB));
        assertTrue("category 'executor' is enable", jmxConfig.get().enable(DigdagMetrics.Category.EXECUTOR));
        assertTrue("category 'default' is enable", jmxConfig.get().enable(DigdagMetrics.Category.DEFAULT));
    }

    @Test
    public void testJmxEnabledWithParams()
    {
        /**
         *  server.metrics.enable: " jmx "
         *  server.metrics.jmx.categories: "agent, executors "
         */
        config = fromJson(
                "{ " +
                        "\"metrics.enable\": \" jmx \", " +
                        "\"metrics.jmx.categories\": \"agent, executor\" " +
                 "}");
        DigdagMetricsConfig metricsConfig = new DigdagMetricsConfig(config);

        Optional<JmxMonitorSystemConfig> jmxConfig = metricsConfig.getMonitorSystemConfig("jmx").transform((p) -> (JmxMonitorSystemConfig)p);
        assertTrue("Exist jmx config", jmxConfig.isPresent());
        assertTrue("plugin is enable", jmxConfig.get().getMonitorSystemEnable());
        assertTrue("category 'agent' is enable", jmxConfig.get().enable(DigdagMetrics.Category.AGENT));
        assertFalse("category 'api' is enable", jmxConfig.get().enable(DigdagMetrics.Category.API));
        assertFalse("category 'db' is enable", jmxConfig.get().enable(DigdagMetrics.Category.DB));
        assertTrue("category 'executor' is enable", jmxConfig.get().enable(DigdagMetrics.Category.EXECUTOR));
        assertFalse("category 'default' is enable", jmxConfig.get().enable(DigdagMetrics.Category.DEFAULT));
    }

    @Test
    public void testFluencyEnabled()
    {
        /**
         *  metrics.enable: " fluency "
         */
        config = fromJson("{ \"metrics.enable\": \" fluency \" }");
        DigdagMetricsConfig metricsConfig = new DigdagMetricsConfig(config);

        Optional<FluencyMonitorSystemConfig> fluencyConfig = metricsConfig.getMonitorSystemConfig("fluency").transform((p) -> (FluencyMonitorSystemConfig)p);
        assertTrue("Exist fluency config", fluencyConfig.isPresent());
        assertTrue("plugin is enable", fluencyConfig.get().getMonitorSystemEnable());
        assertTrue("category 'agent' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.AGENT));
        assertTrue("category 'api' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.API));
        assertTrue("category 'db' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.DB));
        assertTrue("category 'executor' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.EXECUTOR));
        assertTrue("category 'default' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.DEFAULT));
        assertEquals("step is 60 secs as default", 60L,  fluencyConfig.get().getStep());
    }

    @Test
    public void testFluencyEnabledWithParams()
    {
        /**
         *  server.metrics.enable: " fluency "
         *  server.metrics.jmx.categories: "agent, executors "
         */
        config = fromJson(
                "{ " +
                        "\"metrics.enable\": \" fluency \", " +
                        "\"metrics.fluency.categories\": \"agent, executor\", " +
                        "\"metrics.fluency.host\": \"server01:9999\", " +
                        "\"metrics.fluency.tag\": \"tag0001\", " +
                        "\"metrics.fluency.step\": 120" +
                        "}");
        DigdagMetricsConfig metricsConfig = new DigdagMetricsConfig(config);

        Optional<FluencyMonitorSystemConfig> fluencyConfig = metricsConfig.getMonitorSystemConfig("fluency").transform((p) -> (FluencyMonitorSystemConfig)p);
        assertTrue("Exist fluency config", fluencyConfig.isPresent());
        assertTrue("plugin is enable", fluencyConfig.get().getMonitorSystemEnable());
        assertTrue("category 'agent' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.AGENT));
        assertFalse("category 'api' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.API));
        assertFalse("category 'db' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.DB));
        assertTrue("category 'executor' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.EXECUTOR));
        assertFalse("category 'default' is enable", fluencyConfig.get().enable(DigdagMetrics.Category.DEFAULT));
        assertEquals("host", "server01:9999", fluencyConfig.get().getHost());
        assertEquals("tag", "tag0001", fluencyConfig.get().getTag());
        assertEquals("step", 120L, fluencyConfig.get().getStep());
    }
}


text:
using Database.Game.Models;
using Desktop.Models;
using GalaSoft.MvvmLight;
using System;
using System.Linq;

namespace Desktop.ViewModels
{
  public class GameListEntryViewModel : ViewModelBase
  {
    #region Public Constructors

    public GameListEntryViewModel(GameListEntry entry)
    {
      Model = entry;
    }

    #endregion Public Constructors

    #region Public Properties

    /// <summary>
    /// Get the date the game was added to the collection from the model
    /// </summary>
    public DateTime DateAdded
    {
      get => Model.DateAdded;
      set => Model.DateAdded = value;
    }

    /// <summary>
    /// Has this entry previously has metadata downloaded
    /// </summary>
    public bool HasDownloadedData
    {
      get => Model.HasDownloadedData;
      set
      {
        Model.HasDownloadedData = value;
        RaisePropertyChanged("HasDownloadedData");
      }
    }

    /// <summary>
    /// Get if the game is playable on PC from the model
    /// </summary>
    public bool IsOnPC
    {
      get => Model.IsOnPC;
      set => Model.IsOnPC = value;
    }

    /// <summary>
    /// Get if the game is playable on PS3 from the model
    /// </summary>
    public bool IsOnPS3
    {
      get => Model.IsOnPS3;
      set => Model.IsOnPS3 = value;
    }

    /// <summary>
    /// Get if the game is playable on PS4 from the model
    /// </summary>
    public bool IsOnPS4
    {
      get => Model.IsOnPS4;
      set => Model.IsOnPS4 = value;
    }

    /// <summary>
    /// Get if the game is playable on PS Vita from the model
    /// </summary>
    public bool IsOnPSVita
    {
      get => Model.IsOnPSVita;
      set => Model.IsOnPSVita = value;
    }

    /// <summary>
    /// Get the model of the entry
    /// </summary>
    public GameListEntry Model { get; }

    /// <summary>
    /// Get the game name from the model
    /// </summary>
    public string Name
    {
      get => Model.Name;
      set => Model.Name = value;
    }

    /// <summary>
    /// Get if the game is currently owned from the model
    /// </summary>
    public bool Owned
    {
      get => Model.Owned;
      set => Model.Owned = value;
    }

    /// <summary>
    /// Get the current played status from the model
    /// </summary>
    public Status PlayStatus
    {
      get => Model.PlayStatus;
      set => Model.PlayStatus = value;
    }

    #endregion Public Properties

    #region Public Methods

    public void UpdateFromIGDB(IGDB.Models.Game igdbGame) => Model.UpdateFromIGDB(igdbGame);

    #endregion Public Methods
  }
}


text:
import path from "path";
import gulp from "gulp";
import eslint from "gulp-eslint";
import excludeGitignore from "gulp-exclude-gitignore";
import sourceMaps from "gulp-sourcemaps";
import mocha from "gulp-mocha";
import istanbul from "gulp-istanbul";
import nsp from "gulp-nsp";
import plumber from "gulp-plumber";
import coveralls from "gulp-coveralls";
import babel from "gulp-babel";
import del from "del";
import {Instrumenter} from "isparta";

const paths = {
  "es6": ["./lib/**/*.js"],
  "es5": "./dist",
  // Must be absolute or relative to source map
  "sourceRoot": path.join(__dirname, "lib")
};

// Initialize the babel transpiler so ES2015 files gets compiled
// when they"re loaded
require("babel-register");

gulp.task("static", function () {
  return gulp.src(["lib/**/*.js", "test/**/*.js"])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task("nsp", function (cb) {
  nsp({package: path.resolve("package.json")}, cb);
});

gulp.task("pre-test", () => {
  // https://github.com/yeoman/generator-node/issues/209 - index exclusion to allow shebang
  return gulp.src(["lib/**/*.js", "test/**/*.js", "!lib/index.js"])
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true,
      instrumenter: Instrumenter
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task("test", ["pre-test"], (cb) => {
  var mochaErr;

  gulp.src("test/**/*.js")
    .pipe(plumber())
    .pipe(mocha({reporter: "spec"}))
    .on("error", function (err) {
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on("end", function () {
      cb(mochaErr);
    });
});

gulp.task("watch", ["babel"], () => {
  gulp.watch(["lib/**/*.js", "test/**"], ["babel"]);
});

gulp.task("coveralls", ["test"], () => {
  if (!process.env.CI) {
    return;
  }

  return gulp.src(path.join(__dirname, "coverage/lcov.info"))
    .pipe(coveralls());
});

gulp.task("babel", ["clean"], () => {
  return gulp.src("lib/**/*.js")
    .pipe(sourceMaps.init())
    .pipe(babel({
      presets: ["es2015"]
    }))
    .pipe(sourceMaps.write(".", { sourceRoot: paths.sourceRoot }))
    .pipe(gulp.dest("dist"));
});

gulp.task("clean", () => {
  return del("dist");
});

gulp.task("prepublish", ["nsp", "babel"]);
gulp.task("default", ["static", "babel", "coveralls"]);


text:
using EnvCrypt.Core.Key;
using EnvCrypt.Core.Verb.AddEntry.PlainText;
using EnvCrypt.Core.Verb.LoadDat;
using EnvCrypt.Core.Verb.SaveDat;

namespace EnvCrypt.Core.Verb.AddEntry
{
    /// <summary>
    /// Loads the DAT from file and saves it to file.
    /// </summary>
    abstract class AddEntryAndLoadSaveDatToFileWorkflow<TKey, TWorkflowOptions, TKeyLoaderOptions> : AddEntryWorkflow<TKey, TWorkflowOptions, TKeyLoaderOptions, DatFromFileLoaderOptions, DatToFileSaverOptions>
        where TKey : KeyBase
        where TWorkflowOptions : AddPlainTextEntryWorkflowOptions
    {
        protected AddEntryAndLoadSaveDatToFileWorkflow(EncryptWorkflow<TKey, TKeyLoaderOptions> encryptWorkflow, IDatLoader<DatFromFileLoaderOptions> datLoader, IDatSaver<DatToFileSaverOptions> datSaver)
            : base(encryptWorkflow, datLoader, datSaver)
        {}

        protected override DatFromFileLoaderOptions GetDatLoaderOptions(TWorkflowOptions workflowDetails)
        {
            return new DatFromFileLoaderOptions()
            {
                DatFilePath = workflowDetails.DatFilePath
            };
        }

        protected override DatToFileSaverOptions GetDatSaverOptions(TWorkflowOptions workflowDetails)
        {
            return new DatToFileSaverOptions()
            {
                DestinationFilePath = workflowDetails.DatFilePath
            };
        }
    }
}