text:
{-# language GADTs                      #-}
{-# language DataKinds                  #-}
{-# language TypeOperators              #-}
{-# language TypeFamilies               #-}
{-# language MultiParamTypeClasses      #-}
{-# language FlexibleContexts           #-}
{-# language FlexibleInstances          #-}
{-# language GeneralizedNewtypeDeriving #-}

module Feldspar.Hardware.Representation where

import Feldspar.Sugar
import Feldspar.Representation
import Feldspar.Frontend
import Feldspar.Storable
import Feldspar.Array.Buffered (ArraysEq(..))
import Feldspar.Hardware.Primitive
import Feldspar.Hardware.Expression
import Data.Struct

import Data.Int
import Data.Word
import Data.List (genericTake)
import Data.Typeable (Typeable)
import Data.Constraint

import Control.Monad.Identity (Identity)
import Control.Monad.Trans

-- syntactic.
import Language.Syntactic hiding (Signature, Args)
import Language.Syntactic.Functional hiding (Lam)
import Language.Syntactic.Functional.Tuple

import qualified Language.Syntactic as Syn

-- operational-higher.
import Control.Monad.Operational.Higher as Oper hiding ((:<:))

-- hardware-edsl.
import qualified Language.Embedded.Hardware.Command   as Imp
import qualified Language.Embedded.Hardware.Interface as Imp

import Prelude hiding ((==))
import qualified Prelude as P

--------------------------------------------------------------------------------
-- * Programs.
--------------------------------------------------------------------------------

-- | Hardware instruction set.
type HardwareCMD =
    -- ^ Computatonal instructions.
           Imp.VariableCMD
  Oper.:+: Imp.VArrayCMD
  Oper.:+: Imp.LoopCMD
  Oper.:+: Imp.ConditionalCMD
    -- ^ Hardware specific instructions.
  Oper.:+: Imp.SignalCMD
  Oper.:+: Imp.ArrayCMD
  Oper.:+: Imp.ProcessCMD
  Oper.:+: Imp.ComponentCMD

-- | Monad for building hardware programs in Co-Feldspar.
newtype Hardware a = Hardware { unHardware :: Program HardwareCMD (Param2 HExp HardwarePrimType) a}
  deriving (Functor, Applicative, Monad)

--------------------------------------------------------------------------------

-- | Hardware references.
newtype Ref a = Ref { unRef :: Struct HardwarePrimType Imp.Variable (Internal a) }

-- | Hardware arrays.
data Arr a = Arr
  { arrOffset :: HExp Index
  , arrLength :: HExp Length
  , unArr     :: Struct HardwarePrimType Imp.VArray (Internal a)
  }

-- | Immutable hardware arrays.
data IArr a = IArr
  { iarrOffset :: HExp Index
  , iarrLength :: HExp Length
  , unIArr     :: Struct HardwarePrimType Imp.IArray (Internal a)
  }

--------------------------------------------------------------------------------
-- ** ...
--------------------------------------------------------------------------------

instance ArraysEq Arr IArr
  where
    unsafeArrEq (Arr _ _ arr) (IArr _ _ brr) =
        and (zipListStruct sameId arr brr)
      where
        sameId :: Imp.VArray a -> Imp.IArray a -> Bool
        sameId (Imp.VArrayC a) (Imp.IArrayC b) = a P.== b
        sameId _ _ = False

--------------------------------------------------------------------------------

type instance Expr     Hardware = HExp
type instance DomainOf Hardware = HardwareDomain

--------------------------------------------------------------------------------

instance (Reference Hardware ~ Ref, Type HardwarePrimType a) =>
    Storable Hardware (HExp a)
  where
    type StoreRep Hardware (HExp a) = Ref (HExp a)
    type StoreSize Hardware (HExp a) = ()
    newStoreRep _ _      = newRef
    initStoreRep         = initRef
    readStoreRep         = getRef
    unsafeFreezeStoreRep = unsafeFreezeRef
    writeStoreRep        = setRef

--------------------------------------------------------------------------------

redpajama_set_name: RedPajamaGithub


text:
<link rel="import" href="../bower/polymer/polymer.html">

<dom-module id="s3-file-saver">
    <template>

{{identityPoolId}}

{{googleIdToken}}

{{filePath}}

{{contentType}}

{{fileData}}

    </template>
</dom-module>


text:
using System;
using System.Linq;
using Ploeh.Samples.Commerce.Domain;
using Xunit;

namespace Ploeh.Samples.Commerce.DomainUnitTest
{
    public class Conventions
    {
        [Fact]
        public void SutShouldNotReferenceSqlDataAccess()
        {
            // Fixture setup
            Type sutRepresentative = typeof(Basket);
            var unwanted = "Ploeh.Samples.Commerce.Data.Sql";
            // Exercise system
            var references =
                sutRepresentative.Assembly
                .GetReferencedAssemblies();
            // Verify outcome
            Assert.False(references.Any(a => a.Name == unwanted),
                string.Format(
                "{0} should not be referenced by SUT", unwanted));
            // Teardown
        }
    }
}


text:
{% extends "admin/base.html" %}

{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}

{% block branding %}

Regional Work Finder

{% endblock %}

{% block nav-global %}{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Duality
{
	/// <summary>
	/// Manages a set of <see cref="GameObject">GameObject</see> and exposes suitable object enumerations as well as un/registeration events.
	/// If a registered object has been disposed, it will be automatically unregistered.
	/// </summary>
	public class GameObjectManager
	{
		private	HashSet<GameObject>	allObj	= new HashSet<GameObject>();

		/// <summary>
		/// [GET] The number of registered objects.
		/// </summary>
		public int Count
		{
			get { return this.allObj.Count; }
		}
		/// <summary>
		/// [GET] Enumerates all registered GameObjects.
		/// </summary>
		public IEnumerable<GameObject> AllObjects
		{
			get
			{
				return this.allObj.Where(o => !o.Disposed);
			}
		}
		/// <summary>
		/// [GET] Enumerates all registered GameObjects that are currently active.
		/// </summary>
		public IEnumerable<GameObject> ActiveObjects
		{
			get
			{
				return this.allObj.Where(o => o.Active);
			}
		}
		/// <summary>
		/// [GET] Enumerates all root GameObjects, i.e. all GameObjects without a parent object.
		/// </summary>
		public IEnumerable<GameObject> RootObjects
		{
			get
			{
				return this.allObj.Where(o => !o.Disposed && o.Parent == null);
			}
		}
		/// <summary>
		/// [GET] Enumerates all <see cref="RootObjects"/> that are currently active.
		/// </summary>
		public IEnumerable<GameObject> ActiveRootObjects
		{
			get
			{
				return this.allObj.Where(o => o.Parent == null && o.Active);
			}
		}

		/// <summary>
		/// Fired when a GameObject is registered
		/// </summary>
		public event EventHandler<GameObjectEventArgs>	GameObjectAdded;
		/// <summary>
		/// Fired when a GameObject is unregistered
		/// </summary>
		public event EventHandler<GameObjectEventArgs>	GameObjectRemoved;
		/// <summary>
		/// Fired when a registered GameObjects parent has changed
		/// </summary>
		public event EventHandler<GameObjectParentChangedEventArgs>	ParentChanged;
		/// <summary>
		/// Fired when a <see cref="Duality.Component"/> is added to an already registered GameObject.
		/// </summary>
		public event EventHandler<ComponentEventArgs> ComponentAdded;
		/// <summary>
		/// Fired when a <see cref="Duality.Component"/> is removed from an already registered GameObject.
		/// </summary>
		public event EventHandler<ComponentEventArgs> ComponentRemoving;

		/// <summary>
		/// Registers a GameObject and all of its children.
		/// </summary>
		/// <param name="obj"></param>
		public bool AddObject(GameObject obj)
		{
			return this.AddObjectDeep(obj);
		}
		/// <summary>
		/// Registers a set of GameObjects
		/// </summary>
		/// <param name="objEnum"></param>
		public void AddObject(IEnumerable<GameObject> objEnum)
		{
			foreach (GameObject obj in objEnum.ToArray())
				this.AddObjectDeep(obj);
		}
		/// <summary>
		/// Unregisters a GameObject and all of its children
		/// </summary>
		/// <param name="obj"></param>
		public bool RemoveObject(GameObject obj)
		{
			bool removed = this.RemoveObjectDeep(obj);
			this.Flush();
			return removed;
		}
		/// <summary>
		/// Unregisters a set of GameObjects
		/// </summary>
		/// <param name="objEnum"></param>
		public void RemoveObject(IEnumerable<GameObject> objEnum)
		{
			foreach (GameObject obj in objEnum.ToArray())
			{
				this.RemoveObjectDeep(obj);
			}
			this.Flush();
		}
		/// <summary>
		/// Unregisters all GameObjects.
		/// </summary>
		public void Clear()
		{
			foreach (GameObject obj in this.allObj)
				this.OnObjectRemoved(obj);
			this.allObj.Clear();
		}
		/// <summary>
		/// Unregisters all dead / disposed GameObjects
		/// </summary>
		public void Flush()
		{
			// Determine which objects will be removed due to being disposed
			List<GameObject> removed = new List<GameObject>();
			foreach (GameObject obj in this.allObj)
			{
				if (obj.Disposed)
					removed.Add(obj);
			}

			// Remove disposed objects
			this.allObj.RemoveWhere(obj => obj.Disposed);

			// Notify removed objects
			foreach (GameObject obj in removed)
				this.OnObjectRemoved(obj);
		}

		private bool AddObjectDeep(GameObject obj)
		{
			bool added = false;
			if (!this.allObj.Contains(obj))
			{
				this.allObj.Add(obj);
				this.OnObjectAdded(obj);
				added = true;
			}
			foreach (GameObject child in obj.Children)
			{
				this.AddObjectDeep(child);
			}
			return added;
		}
		private bool RemoveObjectDeep(GameObject obj)
		{
			foreach (GameObject child in obj.Children)
			{
				this.RemoveObjectDeep(child);
			}
			bool removed = this.allObj.Remove(obj);
			if (removed) this.OnObjectRemoved(obj);
			return removed;
		}

		private void RegisterEvents(GameObject obj)
		{
			obj.EventParentChanged		+= this.OnParentChanged;
			obj.EventComponentAdded		+= this.OnComponentAdded;
			obj.EventComponentRemoving	+= this.OnComponentRemoving;
		}
		private void UnregisterEvents(GameObject obj)
		{
			obj.EventParentChanged		-= this.OnParentChanged;
			obj.EventComponentAdded		-= this.OnComponentAdded;
			obj.EventComponentRemoving	-= this.OnComponentRemoving;
		}

		private void OnObjectAdded(GameObject obj)
		{
			this.RegisterEvents(obj);
			if (this.GameObjectAdded != null)
				this.GameObjectAdded(this, new GameObjectEventArgs(obj));
		}
		private void OnObjectRemoved(GameObject obj)
		{
			this.UnregisterEvents(obj);
			if (this.GameObjectRemoved != null)
				this.GameObjectRemoved(this, new GameObjectEventArgs(obj));
		}
		private void OnParentChanged(object sender, GameObjectParentChangedEventArgs e)
		{
			if (this.ParentChanged != null)
				this.ParentChanged(sender, e);
		}
		private void OnComponentAdded(object sender, ComponentEventArgs e)
		{
			if (this.ComponentAdded != null)
				this.ComponentAdded(sender, e);
		}
		private void OnComponentRemoving(object sender, ComponentEventArgs e)
		{
			if (this.ComponentRemoving != null)
				this.ComponentRemoving(sender, e);
		}
	}
}


text:
package org.labkey.webutils.api;

import org.labkey.api.view.JspView;

public enum KnockoutTemplate
{
    Table()
    {
        @Override
        String getJspPath()
        {
            return "/org/labkey/webutils/view/knockout_components/lk-table.jsp";
        }
    },
    QueryTable()
    {
        @Override
        String getJspPath()
        {
            return "/org/labkey/webutils/view/knockout_components/lk-querytable.jsp";
        }
    },
    InputTextArea()
    {
        @Override
        String getJspPath()
        {
            return "/org/labkey/webutils/view/knockout_components/lk-input-textarea.jsp";
        }
    };

    JspView<?> getJspView()
    {
        return new JspView<>(getJspPath());
    }

    abstract String getJspPath();
}


text:
@page can-core Core
@parent canjs
@description The best, most hardened and generally useful libraries in CanJS.
@outline 0

@body

## Use

CanJS's core libraries are the modules most commonly used to build web
applications.  Each module is part of an independent package, so you
should install the ones you use directly:

```
npm install can-define can-set can-connect can-component can-stache can-route --save
```

Lets explore each one a bit more.

## can-compute

[can-compute]s represent an observable value.  A compute can contain its
own value and notify listeners of changes like:

```js
var compute = require("can-compute");

var name = compute("Justin");

// read the value
name() //-> "Justin"

name.on("change", function(ev, newVal, oldVal){
	newVal //-> "Matthew"
	oldVal //-> "Justin"
});

name("Matthew");
```

More commonly, a compute derives its value from other observables.  The following
`info` compute derives its value from a `person` map, `hobbies` list, and `age`
compute:

```js
var DefineMap = require("can-define/map/map"),
	DefineList = require("can-define/list/list"),
	compute = require("can-compute");

var person = new DefineMap({first: "Justin", last: "Meyer"}),
	hobbies = new DefineList(["js","bball"]),
	age = compute(33);

var info = compute(function(){
	return person.first +" "+ person.last+ " is "+age()+
		"and like "+hobbies.join(", ")+".";
});

info() //-> "Justin Meyer is 33 and likes js, bball."

info.on("change", function(ev, newVal){
	newVal //-> "Justin Meyer is 33 and likes js."
});

hobbies.pop();
```

## can-define

[can-define/map/map] and [can-define/list/list] allow you to create observable
maps and lists with well defined properties.  You can
[can-define.types.propDefinition define a property's type initial value, enumerability, getter-setters and much more].
For example, you can define the behavior of a `Todo` type and a `TodoList` type as follows:

```js
var DefineMap = require("can-define/map/map");
var DefineList = require("can-define/list/list");

var Todo = DefineMap.extend({           // A todo has a:
  name: "string",                       // .name that's a string
  complete: {                           // .complete that's
	type: "boolean",                    //        a boolean
	value: false                        //        initialized to false
  },
  dueDate: "date",                      // .dueDate that's a date
  get isPastDue(){                      // .pastDue that returns if the
	return new Date() > this.dueDate;   //        dueDate is before now
  },
  toggleComplete: function(){           // .toggleComplete method that
    this.complete = !this.complete;     //        changes .complete
  }
});

var TodoList = DefineList.extend({      // A list of todos:
  "#": Todo,                            // has numeric properties
                                        //         as todos

  get completeCount(){                  // has .completeCount that
    return this.filter("complete")      //         returns # of
	           .length;                 //         complete todos
  }
});
```

This allows you to create a Todo, read its properties, and
call back its methods like:

```js
var dishes = new Todo({
	name: "do dishes",
	// due yesterday
	dueDate: new Date() - 1000 * 60 * 60 * 24
});
dishes.name      //-> "do dishes"
dishes.isPastDue //-> true
dishes.complete  //-> false
dishes.toggleComplete()
dishes.complete  //-> true
```

And it allows you to create a `TodoList`, access its items and properties
like:

```js
var todos = new TodoList( dishes, {name: "mow lawn", dueDate: new Date()});
todos.length         //-> 2
todos[0].complete    //-> true
todos.completeCount //-> 1
```

These observables provide the foundation
for data connection (models), view-models and even routing in your application.

## can-set

[can-set] models a service layer's behavior as a [can-set.Algebra set.Algebra]. Once modeled, other libraries such as [can-connect] or [can-fixture] can
add a host of functionality like: real-time behavior, performance optimizations, and
simulated service layers.

A `todosAlgebra` set algebra for a `GET /api/todos` service might look like:

```js
var set = require("can-set");
var todosAlgebra = new set.Algebra(
    // specify the unique identifier property on data
    set.prop.id("_id"),
    // specify that completed can be true, false or undefined
    set.prop.boolean("complete"),
    // specify the property that controls sorting
    set.prop.sort("orderBy")
)
```

This assumes that the service:

 - Returns data where the unique property name is `_id`:
   ```js
   GET /api/todos
   -> [{_id: 1, name: "mow lawn", complete: true},
       {_id: 2, name: "do dishes", complete: false}, ...]
   ```
 - Can filter by a `complete` property:
   ```js
   GET /api/todos?complete=false
   -> [{_id: 2, name: "do dishes", complete: false}, ...]
   ```
 - Sorts by an `orderBy` property:
   ```js
   GET /api/todos?orderBy=name
   -> [{_id: 2, name: "do dishes", complete: false},
       {_id: 1, name: "mow lawn", complete: true}]
   ```

In the next section will use `todoAlgebra` to build a model with [can-connect].

## can-connect

[can-connect] connects a data type, typically a `DefineMap` and its `DefineList`,
to a service layer. This is often done via the
[can-connect/can/base-map/base-map] module which bundles many common behaviors
into a single api:

```js
var baseMap = require("can-connect/can/base-map/base-map"),
    DefineMap = require("can-define/map/map"),
    DefineList = require("can-define/list/list"),
	set = require("can-set");

var Todo = DefineMap.extend({
	...
});
var TodosList = DefineMap.extend({
	"#": Todo,
	...
});
var todosAlgebra = new set.Algebra({
	...
});

var connection = baseMap({
	url: "/api/todos",
	Map: Todo,
	List: TodoList,
	algebra: todosAlgebra,
	name: "todo"
});
```

`baseMap` extends the `Map` type, in this case, `Todo`, with
the ability to make requests to the service layer.

 - [can-connect/can/map/map.getList Get a list] of Todos
   ```js
   Todo.getList({complete: true}).then(function(todos){})
   ```
 - [can-connect/can/map/map.get Get] a single Todo
   ```js
   Todo.get({_id: 6}).then(function(todo){})
   ```
 - [can-connect/can/map/map.prototype.save Create] a Todo
   ```js
   var todo = new Todo({name: "do dishes", complete: false})
   todo.save().then(function(todo){})
   ```
 - [can-connect/can/map/map.prototype.save Update] an [can-connect/can/map/map.prototype.isNew already created] Todo
   ```js
   todo.complete = true;
   todo.save().then(function(todo){})
   ```
 - [can-connect/can/map/map.prototype.destroy Delete] a Todo
   ```js
   todo.destroy().then(function(todo){})
   ```

[can-connect] is also middleware, so custom connections can
be assembled too:

```js
var base = require("can-connect/base/base");
var dataUrl = require("can-connect/data-url/data-url");
var constructor = require("can-connect/constructor/constructor");
var map = require("can-connect/can/map/map");

var options = {
	url: "/api/todos",
	Map: Todo,
	List: TodoList,
	algebra: todosAlgebra,
	name: "todo"
}
var connection = map(constructor(dataUrl(base(options))));
```

## can-stache

[can-stache] provides live binding mustache and handlebars syntax. While
templates should typically be loaded with a module loader like [steal-stache],
you can create a template programmatically that lists out todos within a
promise loaded from `Todo.getList` like:

```js
var stache = require("can-stache");

// Creates a template
var template = stache(
	"<ul>"+
		"{{#if todos.isPending}}<li>Loading...</li>{{/if}}"+
		"{{#if todos.isResolved}}"+
			"{{#each todos.value}}"+
				"<li class='{{#complete}}complete{{/complete}}'>{{name}}</li>"+
			"{{else}}"+
				"<li>No todos</li>"+
			"{{/each}}"+
		"{{/if}}"+
	"</ul>");

// Calls the template with some data
var frag = template({
	todos: Todo.getList({})
});

// Inserts the result into the page
document.body.appendChild(frag);
```

[can-stache] templates use magic tags like `{{}}` to control what
content is rendered. The most common forms of those magic tags are:

 - [can-stache.tags.escaped {{key}}] - Insert the value at `key` in the page. If `key` is a function or helper, run it and insert the result.
 - [can-stache.tags.section {{#key}}...{{/key}}] - Render the content between magic tags based on some criteria.

[can-stache] templates return document fragments that update whenever
their source data changes.

## can-component

[can-component] creates custom elements with unit-testable view models. It
combines a view model created by [can-define/map/map] with a template
created by [can-stache].

```js
var Component = require("can-component");
var DefineMap = require("can-define/map/map");
var stache = require("can-stache");

// Defines the todos-list view model
var TodosListVM = DefineMap.extend({
	// An initial value that is a promise containing the
	// list of all todos.
	todos: {
		value: function(){
			return Todo.getList({});
		}
	},
	// A method that toggles a todo's complete property
	// and updates the todo on the server.
	toggleComplete: function(todo){
		todo.complete = !todo.complete;
		todo.save();
	}
});

Component.extend({
	tag: "todos-list",
	ViewModel: TodosVM,
	view: stache(
		"<ul>"+
			"{{#if todos.isPending}}<li>Loading...</li>{{/if}}"+
			"{{#if todos.isResolved}}"+
				"{{#each todos.value}}"+
					"<li ($click)='toggleComplete(.)'"+
					     "class='{{#complete}}complete{{/complete}}'>{{name}}</li>"+
				"{{else}}"+
					"<li>No todos</li>"+
				"{{/each}}"+
			"{{/if}}"+
		"</ul>");
});
```

## can-stache-bindings

[can-stache-bindings] provides [can-view-callbacks.attr custom attributes] for
[can-stache] event and data bindings.

Bindings look like:

 - `(event)="key()"` for [can-stache-bindings.event event binding].
 - `{prop}="key"` for [can-stache-bindings.toChild one-way binding to a child].
 - `{^prop}="key"` for [can-stache-bindings.toParent one-way binding to a parent].
 - `{(prop)}="key"` for [can-stache-bindings.twoWay two-way binding].

Adding `$` to a binding like `($event)="key()"` changes the binding from the viewModel to the element's attributes or properties.

[can-stache-bindings.event Event] binding examples:

```html
<!-- calls `toggleComplete` when the li is clicked -->
<li ($click)="toggleComplete(.)"/>

<!-- calls `resetData` when cancel is dispatched on `my-modal`'s view model -->
<my-modal (cancel)="resetData()"/>
```

[can-stache-bindings.toChild One-way to child] examples:

```html
<!-- updates input's `checked` property with the value of complete -->
<input type="checkbox" {$checked}="complete"/>

<!-- updates `todo-lists`'s  `todos` property with the result of `getTodos`-->
<todos-list {todos}="getTodos(complete=true)"/>
```

[can-stache-bindings.toChild One-way to parent] examples:

```html
<!-- updates `complete` with input's `checked` property -->
<input type="checkbox" {^$checked}="complete"/>

<!-- updates `todosList` with `todo-lists`'s `todos` property -->
<todos-list {^todos}="todosList"/>
```

[can-stache-bindings.twoWay Two-way] examples:

```html
<!-- Updates the input's `value` with `name` and vice versa -->
<input type="text" {($value)}="name"/>

<!-- Updates `date-picker`'s `date` with `dueDate` and vice versa -->
<date-picker {(date)}="dueDate"/>
```

## can-route and can-route-pushstate

[can-route] connects a `DefineMap`'s properties to values in the
url. Create a map type, [canjs/doc/can-route.map connect it to the url], and [can-route.ready begin routing] like:

```js
var route = require("can-route");
var DefineMap = require("can-define/map/map");

var AppViewModel = DefineMap.extend({
	seal: false
},{
	// Sets the default type to string
	"#": "string",
	todoId: "string",
	todo: {
		get: function(){
			if(this.todoId) {
				return Todo.get({_id: this.todoId})
			}
		}
	}
});

var appViewModel = new AppViewModel();
route.map(appViewModel);

route.ready();
```

When the url changes, to something like `#!&todoId=5`, so will the
`appViewModel`'s `todoId` and `todo` property:

```js
appViewModel.todoId //-> "5"
appViewModel.todo   //-> Promise<Todo>
```

Similarly, if `appViewModel`'s `todoId` is set like:

```js
appViewModel.todoId = 6;
```

The hash will be updated:

```js
window.location.hash //-> "#!&todoId=6"
```

The `route` function can be used to specify pretty routing rules that
translate property changes to a url and a url to property changes. For example,

```js
// a route like:
route("todo/{todoId}");

// and a hash like:
window.location.hash = "#!todo/7";

// produces an appViewModel like:
appViewModel.serialize() //-> {route: "todo/{todoId}", todoId: "7"}
```

[can-route-pushstate] adds [pushstate](https://developer.mozilla.org/en-US/docs/Web/API/History_API) support. It
mixes in this behavior so you just need to import the module:

```js
var route = require("can-route");
require("can-route-pushstate");
```

## Want to learn more?

If you haven't already, checkout the [guides] page on how to learn CanJS.  Specifically, you'll
want to checkout the [guides/chat] and [guides/todomvc] to learn the basics of using CanJS's
core libraries.  After that, checkout the [guides/api] on how to use and learn from these API docs.


text:
using JetBrains.ReSharper.Feature.Services.Daemon;

namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Daemon.Errors
{
    [RegisterStaticHighlightingsGroup("AsmDef Errors", true)]
    public class AsmDefErrors
    {
    }

    [RegisterStaticHighlightingsGroup("AsmDef Warnings", true)]
    public class AsmDefWarnings
    {
    }
}


text:
module Taxi
  class Vehicle
    include Adamantium, DataMapper::Resource
    # Vehicle[:mot :insurance :address :road_tax :tx_plate :owner :type=>[:wchair, :limo, :minibus, :MPV, :Saloon] :make :make_model driver: {}]

    property :id,               Serial
    property :nickname,         String #,  required: true
    property :registration,     String,  required: true
    property :make,             String,  required: true
    property :modeli,           String #,  required: true
    property :type,             Enum[:wchair, :limo, :minibus, :MPV, :saloon], default: :saloon
    property :year,             Date,    required: true
    property :vin,              String,  required: true
    property :taxi_plate,       String,  required: true
    property :number_of_seats,  Integer, required: true
    property :driver_1,         Integer, required: true
    property :driver_2,         Integer
    property :colour,           String,  required: true
    property :fuel_type,        String
    property :owner_id,         Integer
    property :owner_type,       Enum[:person, :organisation], default: :person

    # Purchase Information
    property :purchase_date,    Date
    property :purchase_price,   Integer
    property :purchase_meter,   Integer
    property :purchase_comment, String

    # Warranty Information
    property :warranty_exp_date,   Date
    property :warranty_exp_meter,  Integer

    property :created_at, DateTime
    property :updated_at, DateTime

    has n, :licenses
    has n, :mileages

    def driver
      Taxi::Person.get(driver_1)
    end

    def drivers
      # pr = Taxi::Person.properties[:id]
      d = Taxi::Person.all(id: [driver_1, driver_2].compact)
      # .select{|id| pr.valid?(id)})
      # return driver unless d.size > 1
      d
    end

    def registered_keeper
      type = owner_type
      raise  Taxi::OwnerTypeError, 'The owner_id or owner_type are not available' unless type

      case type
      when :organisation
        Taxi::Organisation.get(owner_id)
      when :person
        Taxi::Person.get(owner_id)
      end
    end

  end #Vehicle

  class Mileage
    include DataMapper::Resource

    property :id,       Serial
    property :on,       DateTime, required: true
    property :odometer, Integer, required: true
    property :at,       Flag[:start_of_shift, :end_of_shift, :last_service, :fueling]
    property :comment,  Text

    property :created_at, DateTime
    property :updated_at, DateTime

    belongs_to :vehicle
  end #Mileage

  class Fuel
    include DataMapper::Resource

    property :id,       Serial
    property :on,       DateTime, required: true
    property :odometer, Integer, required: true
    property :gallons,  Integer, required: true
    property :price,    Integer, required: true
    property :comment,  Text

    property :created_at, DateTime
    property :updated_at, DateTime

    belongs_to :vehicle
  end #Fuel

  class OwnerTypeError < StandardError
  end #OwnerTypeError

end


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

namespace HomeCinema.Entities
{
    public class User : EntityBase
    {
        public User()
        {
            Roles = new List<Role>();
        }

        public string Username { get; set; }
        public string Email { get; set; }
        public string HashedPassword { get; set; }
        public string Salt { get; set; }
        public bool IsLocked { get; set; }
        public DateTime DateCreated { get; set; }

        public virtual ICollection<Role> Roles { get; set; }
    }
}


text:
#include "talk/app/webrtc/mediastreamproxy.h"
#include "talk/base/refcount.h"
#include "talk/base/scoped_ref_ptr.h"

namespace {

enum {
  MSG_SET_TRACKLIST_IMPLEMENTATION = 1,
  MSG_REGISTER_OBSERVER,
  MSG_UNREGISTER_OBSERVER,
  MSG_LABEL,
  MSG_ADD_AUDIO_TRACK,
  MSG_ADD_VIDEO_TRACK,
  MSG_READY_STATE,
  MSG_COUNT,
  MSG_AT
};

typedef talk_base::TypedMessageData<std::string*> LabelMessageData;
typedef talk_base::TypedMessageData<size_t> SizeTMessageData;
typedef talk_base::TypedMessageData<webrtc::ObserverInterface*>
    ObserverMessageData;
typedef talk_base::TypedMessageData<webrtc::MediaStreamInterface::ReadyState>
    ReadyStateMessageData;

template<typename T>
class MediaStreamTrackMessageData : public talk_base::MessageData {
 public:
  explicit MediaStreamTrackMessageData(T* track)
      : track_(track),
        result_(false) {
  }

  talk_base::scoped_refptr<T> track_;
  bool result_;
};

typedef MediaStreamTrackMessageData<webrtc::AudioTrackInterface>
    AudioTrackMsgData;
typedef MediaStreamTrackMessageData<webrtc::VideoTrackInterface>
    VideoTrackMsgData;

template <class TrackType>
class MediaStreamTrackAtMessageData : public talk_base::MessageData {
 public:
  explicit MediaStreamTrackAtMessageData(size_t index)
      : index_(index) {
  }

  size_t index_;
  talk_base::scoped_refptr<TrackType> track_;
};

class MediaStreamTrackListsMessageData : public talk_base::MessageData {
 public:
  talk_base::scoped_refptr<webrtc::AudioTracks> audio_tracks_;
  talk_base::scoped_refptr<webrtc::VideoTracks> video_tracks_;
};

}  // namespace anonymous

namespace webrtc {

talk_base::scoped_refptr<MediaStreamProxy> MediaStreamProxy::Create(
    const std::string& label,
    talk_base::Thread* signaling_thread) {
  ASSERT(signaling_thread != NULL);
  talk_base::RefCountedObject<MediaStreamProxy>* stream =
      new talk_base::RefCountedObject<MediaStreamProxy>(
          label, signaling_thread,
          reinterpret_cast<LocalMediaStreamInterface*>(NULL));
  return stream;
}

talk_base::scoped_refptr<MediaStreamProxy> MediaStreamProxy::Create(
    const std::string& label,
    talk_base::Thread* signaling_thread,
    LocalMediaStreamInterface* media_stream_impl) {
  ASSERT(signaling_thread != NULL);
  ASSERT(media_stream_impl != NULL);
  talk_base::RefCountedObject<MediaStreamProxy>* stream =
      new talk_base::RefCountedObject<MediaStreamProxy>(label, signaling_thread,
                                                media_stream_impl);
  return stream;
}

MediaStreamProxy::MediaStreamProxy(const std::string& label,
                                   talk_base::Thread* signaling_thread,
                                   LocalMediaStreamInterface* media_stream_impl)
    : signaling_thread_(signaling_thread),
      media_stream_impl_(media_stream_impl),
      audio_tracks_(new talk_base::RefCountedObject<
                        MediaStreamTrackListProxy<AudioTrackInterface> >(
                              signaling_thread_)),
      video_tracks_(new talk_base::RefCountedObject<
                        MediaStreamTrackListProxy<VideoTrackInterface> >(
                            signaling_thread_)) {
  if (media_stream_impl_ == NULL) {
    media_stream_impl_ = MediaStream::Create(label);
  }

  MediaStreamTrackListsMessageData tracklists;
  Send(MSG_SET_TRACKLIST_IMPLEMENTATION, &tracklists);
  audio_tracks_->SetImplementation(tracklists.audio_tracks_);
  video_tracks_->SetImplementation(tracklists.video_tracks_);
}

std::string MediaStreamProxy::label() const {
  if (!signaling_thread_->IsCurrent()) {
    std::string label;
    LabelMessageData msg(&label);
    Send(MSG_LABEL, &msg);
    return label;
  }
  return media_stream_impl_->label();
}

MediaStreamInterface::ReadyState MediaStreamProxy::ready_state() const {
  if (!signaling_thread_->IsCurrent()) {
    ReadyStateMessageData msg(MediaStreamInterface::kInitializing);
    Send(MSG_READY_STATE, &msg);
    return msg.data();
  }
  return media_stream_impl_->ready_state();
}

void MediaStreamProxy::set_ready_state(
    MediaStreamInterface::ReadyState new_state) {
  if (!signaling_thread_->IsCurrent()) {
    // State should only be allowed to be changed from the signaling thread.
    ASSERT(!"Not Allowed!");
    return;
  }
  media_stream_impl_->set_ready_state(new_state);
}

bool MediaStreamProxy::AddTrack(AudioTrackInterface* track) {
  if (!signaling_thread_->IsCurrent()) {
    AudioTrackMsgData msg(track);
    Send(MSG_ADD_AUDIO_TRACK, &msg);
    return msg.result_;
  }
  return media_stream_impl_->AddTrack(track);
}

bool MediaStreamProxy::AddTrack(VideoTrackInterface* track) {
  if (!signaling_thread_->IsCurrent()) {
    VideoTrackMsgData msg(track);
    Send(MSG_ADD_VIDEO_TRACK, &msg);
    return msg.result_;
  }
  return media_stream_impl_->AddTrack(track);
}

void MediaStreamProxy::RegisterObserver(ObserverInterface* observer) {
  if (!signaling_thread_->IsCurrent()) {
    ObserverMessageData msg(observer);
    Send(MSG_REGISTER_OBSERVER, &msg);
    return;
  }
  media_stream_impl_->RegisterObserver(observer);
}

void MediaStreamProxy::UnregisterObserver(ObserverInterface* observer) {
  if (!signaling_thread_->IsCurrent()) {
    ObserverMessageData msg(observer);
    Send(MSG_UNREGISTER_OBSERVER, &msg);
    return;
  }
  media_stream_impl_->UnregisterObserver(observer);
}

void MediaStreamProxy::Send(uint32 id, talk_base::MessageData* data) const {
  signaling_thread_->Send(const_cast<MediaStreamProxy*>(this), id,
                          data);
}

// Implement MessageHandler
void MediaStreamProxy::OnMessage(talk_base::Message* msg) {
  talk_base::MessageData* data = msg->pdata;
  switch (msg->message_id) {
    case MSG_SET_TRACKLIST_IMPLEMENTATION: {
      MediaStreamTrackListsMessageData* lists =
          static_cast<MediaStreamTrackListsMessageData*>(data);
      lists->audio_tracks_ = media_stream_impl_->audio_tracks();
      lists->video_tracks_ = media_stream_impl_->video_tracks();
      break;
    }
    case MSG_REGISTER_OBSERVER: {
      ObserverMessageData* observer = static_cast<ObserverMessageData*>(data);
      media_stream_impl_->RegisterObserver(observer->data());
      break;
    }
    case MSG_UNREGISTER_OBSERVER: {
      ObserverMessageData* observer = static_cast<ObserverMessageData*>(data);
      media_stream_impl_->UnregisterObserver(observer->data());
      break;
    }
    case MSG_LABEL: {
      LabelMessageData * label = static_cast<LabelMessageData*>(data);
      *(label->data()) = media_stream_impl_->label();
      break;
    }
    case MSG_ADD_AUDIO_TRACK: {
      AudioTrackMsgData * track =
          static_cast<AudioTrackMsgData *>(data);
      track->result_ = media_stream_impl_->AddTrack(track->track_.get());
      break;
    }
    case MSG_ADD_VIDEO_TRACK: {
      VideoTrackMsgData * track =
          static_cast<VideoTrackMsgData *>(data);
      track->result_ = media_stream_impl_->AddTrack(track->track_.get());
      break;
    }
    case MSG_READY_STATE: {
      ReadyStateMessageData* state = static_cast<ReadyStateMessageData*>(data);
      state->data() = media_stream_impl_->ready_state();
      break;
    }
    default:
      ASSERT(!"Not Implemented!");
      break;
  }
}

template <class T>
MediaStreamProxy::MediaStreamTrackListProxy<T>::MediaStreamTrackListProxy(
    talk_base::Thread* signaling_thread)
    : signaling_thread_(signaling_thread) {
}

template <class T>
void MediaStreamProxy::MediaStreamTrackListProxy<T>::SetImplementation(
    MediaStreamTrackListInterface<T>* track_list) {
  track_list_ = track_list;
}

template <class T>
size_t MediaStreamProxy::MediaStreamTrackListProxy<T>::count() const {
  if (!signaling_thread_->IsCurrent()) {
    SizeTMessageData msg(0u);
    Send(MSG_COUNT, &msg);
    return msg.data();
  }
  return track_list_->count();
}

template <class T>
T* MediaStreamProxy::MediaStreamTrackListProxy<T>::at(
    size_t index) {
  if (!signaling_thread_->IsCurrent()) {
    MediaStreamTrackAtMessageData<T> msg(index);
    Send(MSG_AT, &msg);
    return msg.track_;
  }
  return track_list_->at(index);
}

template <class T>
void MediaStreamProxy::MediaStreamTrackListProxy<T>::Send(
    uint32 id, talk_base::MessageData* data) const {
  signaling_thread_->Send(
      const_cast<MediaStreamProxy::MediaStreamTrackListProxy<T>*>(
          this), id, data);
}

// Implement MessageHandler
template <class T>
void MediaStreamProxy::MediaStreamTrackListProxy<T>::OnMessage(
    talk_base::Message* msg) {
  talk_base::MessageData* data = msg->pdata;
  switch (msg->message_id) {
    case MSG_COUNT: {
      SizeTMessageData* count = static_cast<SizeTMessageData*>(data);
      count->data() = track_list_->count();
      break;
    }
    case MSG_AT: {
      MediaStreamTrackAtMessageData<T>* track =
          static_cast<MediaStreamTrackAtMessageData<T>*>(data);
      track->track_ = track_list_->at(track->index_);
      break;
    }
    default:
      ASSERT(!"Not Implemented!");
      break;
  }
}

}  // namespace webrtc


text:
(function(){
    var d = document,
    $ = function(selector){
        return d.querySelector(selector);
    }

    var selectButton = $('.js-select-toggle'),
        selectDropdown = $('.js-select-dropdown'),
        selectChildren = selectDropdown.children,
        selectOptions = [],
        currentlySelectedOption = 1;

    var init = function(){
        //save all the inputs to memory
        for (var i = 0, len = selectDropdown.children.length; i < len; i++){
            if(selectDropdown.children[i].nodeName == "INPUT"){
                selectOptions.push(selectDropdown.children[i]);
            }
        }
    }
    var checkSelected = function(){
        for (var i = 0, len = selectOptions.length; i < len; i++){
            if(selectOptions[i].checked){
                console.log(selectOptions[i].dataset.name + " was selected");
                currentlySelectedOption = (i + 1);
            }
        }
    }

    var selectToggle = function(){
        checkSelected();
        selectDropdown.classList.toggle('is-active');
        selectButton.classList.toggle('is-active');
        selectDropdown.children[currentlySelectedOption].focus();
    }

    var closeDropdown = function(){
        selectDropdown.classList.remove('is-active');
    }
    var handleKeys = function(e){
        switch(e.keyCode){
            case 13:
            case 32:
            case 9:
                closeDropdown();
                selectButton.focus();

            break;
            case 40:
            case 37: // Down, Left

                //focus the next one
                break;
            case 38:
            case 39:

                //focus the previous one
                 // Top, Right
            break;
        }

        //e.preventDefault();
    }
    var handleClick = function(e){
        console.log(e);
        //e.preventDefault();
        //updateButtonText(e.target.dataset.name);
       // closeDropdown();
        //selectButton.focus();
    }
    var handleChange = function(e){
        updateButtonText(e.target.dataset.name);

        //when a change occurs update which is currently selected
    }
    var updateButtonText = function(selectTitle){
        selectButton.textContent = selectTitle;
    }

    init();
     for (var i = 0, len = selectOptions.length; i < len; i++){
           selectOptions[i].addEventListener('keydown', handleKeys, false);
           // selectOptions[i].addEventListener('click', handleClick, false);
           selectOptions[i].addEventListener('change', handleChange, false);

    }
    selectButton.addEventListener('click', selectToggle, false);

   //1. spacebar on the button ( works )
   //2. tab should close it
   //
   //3. not having JS should mean the dropdown is always open /
   //potentially JS is inserting the component
   //4. clicking clicking off the select should automatically close it
   //

})();


text:
package edu.neu.nutrons.ultimateascent.commands;

/**
 *
 * @author NUTRONs
 * SPITS INTAKE
 * Reverses intake in case of Frisbee jam.
 */
public class IntakeSpitCmd extends CommandBase {

    public IntakeSpitCmd() {
        requires(intake);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        intake.spit();
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
/*
 * $Id: AbstractConfiguration.java,v 1.3 2004/05/20 22:36:38 gmartone Exp $
 *
 */

/*
 * This class is based on sources in org.apache.avalon.
 * The authors of those sources are Federico Barbieri,
 * Stefano Mazzocchi, and Pierpaolo Fumagalli.
 *
 */

package org.jdbf.engine.configuration;
/**
 * AbstractConfiguration is a abstract configuration that represents
 * a node in a XML file.

 *
 * This class is based on sources in org.apache.avalon.
 * The authors of those sources are Federico Barbieri,
 * Stefano Mazzocchi, and Pierpaolo Fumagalli.
 *
 * @version $Revision: 1.3 $

 * last changed by $Author: gmartone $

 * @see Configuration
 */
public abstract class AbstractConfiguration implements Configuration {
    /** value of this configuration */
    protected String value;

    /** name of this configuration */
    protected String name;

    /**
     * Creates the AbstractConfiguration object.
     *
     * @param name
     */
    protected AbstractConfiguration(String name){
        this.name = name;
    }

    /**
     * Return the value of this configuraion as a float.
     *
     * @return a float for this configuration value
     */
    public float getFloatValue() throws NumberFormatException {
        try {
            return(Float.parseFloat(value.trim()));
        }
        catch (NumberFormatException except) {
            throw new NumberFormatException(except.getMessage());
        }
    }

    /**
     * Return the value of this configuraion as a int
     *
     * @return a int for this configuration value
     * @throws NumberFormatException
     */
    public int getIntValue() throws NumberFormatException{
        try {
            return(Integer.parseInt(value.trim()));
        }
        catch (NumberFormatException except) {
            throw new NumberFormatException(except.getMessage());
        }
    }

    /**
     * Return the name of this configuration
     *
     * @return name of this configuration
     */
    public String getName(){
        return name;
    }

    /**
     * Return the value of this configuration
     *
     * @return value of this configuration
     */
    public String getValue(){
        return value;
    }

    /**
     * Return the value of this configuration. Return the defaultValue is value
     * is null
     *
     * @param defaultValue default value of node
     * @return value of node,if value is null return the defaultValue specified
     * in defaultValue
     */
    public String getValue(String defaultValue){
        if (value == null)
            return defaultValue;
        return value;
    }

    /**
     * Return a iterator of configuration specified in name
     *
     * @return iterator of configuration specified in name
     */
    public abstract java.util.Iterator getConfigurations(String name);

    /**
     * Return a  configuration specified in name
     *
     * @return Configuration configuration specified in name
     */
    public abstract Configuration getConfiguration(String name);
}

/*
 *
 * $Log: AbstractConfiguration.java,v $
 * Revision 1.3  2004/05/20 22:36:38  gmartone
 * Changed for task 99073 (Coverage Javadocs)
 *
 *
 */


text:
module Api
  module V1
    class ApiController < ActionController::API
      before_action :authenticate

      def logged_in?
        !!current_user
      end

      def current_user
        if auth_present? && token_present?
          user = User.find(auth["user"])
          session[:user_id] = user.id
          @current_user ||= user if user
        end
      end

      def authenticate
        render json: { errors: "unauthorized" }, status: 401 unless logged_in?
      end

      def as_nested_hash(klass)
        klass.constantize.all.each_with_object({}) do |object, hash|
          hash[object.id] = "#{klass}Serializer".constantize.new(object).attributes
        end
      end

     private

      def token
        request.env["HTTP_AUTHORIZATION"].scan(/Bearer(.*)$/).flatten.last.strip
      end

      def token_present?
        token != "undefined"
      end

      def auth
        Auth.decode(token)
      end

      def auth_present?
        !!request.env.fetch("HTTP_AUTHORIZATION", "").scan(/Bearer/).flatten.first
      end
    end
  end
end


text:
import { commands, env, ProgressLocation, Uri, window } from 'vscode';
import * as nls from 'vscode-nls';
import { getOctokit } from './auth';
import { GitErrorCodes, PushErrorHandler, Remote, Repository } from './typings/git';

const localize = nls.loadMessageBundle();

type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T;

export function isInCodespaces(): boolean {
	return env.remoteName === 'codespaces';
}

async function handlePushError(repository: Repository, remote: Remote, refspec: string, owner: string, repo: string): Promise<void> {
	const yes = localize('create a fork', "Create Fork");
	const no = localize('no', "No");

	const answer = await window.showInformationMessage(localize('fork', "You don't have permissions to push to '{0}/{1}' on GitHub. Would you like to create a fork and push to it instead?", owner, repo), yes, no);
	if (answer === no) {
		return;
	}

	const match = /^([^:]*):([^:]*)$/.exec(refspec);
	const localName = match ? match[1] : refspec;
	let remoteName = match ? match[2] : refspec;

	const [octokit, ghRepository] = await window.withProgress({ location: ProgressLocation.Notification, cancellable: false, title: localize('create fork', 'Create GitHub fork') }, async progress => {
		progress.report({ message: localize('forking', "Forking '{0}/{1}'...", owner, repo), increment: 33 });

		const octokit = await getOctokit();

		type CreateForkResponseData = Awaited<ReturnType<typeof octokit.repos.createFork>>['data'];

		// Issue: what if the repo already exists?
		let ghRepository: CreateForkResponseData;
		try {
			if (isInCodespaces()) {
				// Call into the codespaces extension to fork the repository
				const resp = await commands.executeCommand<{ repository: CreateForkResponseData, ref: string }>('github.codespaces.forkRepository');
				if (!resp) {
					throw new Error('Unable to fork respository');
				}

				ghRepository = resp.repository;

				if (resp.ref) {
					let ref = resp.ref;
					if (ref.startsWith('refs/heads/')) {
						ref = ref.substr(11);
					}

					remoteName = ref;
				}
			} else {
				const resp = await octokit.repos.createFork({ owner, repo });
				ghRepository = resp.data;
			}
		} catch (ex) {
			console.error(ex);
			throw ex;
		}

		progress.report({ message: localize('forking_pushing', "Pushing changes..."), increment: 33 });

		// Issue: what if there's already an `upstream` repo?
		await repository.renameRemote(remote.name, 'upstream');

		// Issue: what if there's already another `origin` repo?
		await repository.addRemote('origin', ghRepository.clone_url);

		try {
			await repository.fetch('origin', remoteName);
			await repository.setBranchUpstream(localName, `origin/${remoteName}`);
		} catch {
			// noop
		}

		await repository.push('origin', localName, true);

		return [octokit, ghRepository];
	});

	// yield
	(async () => {
		const openOnGitHub = localize('openingithub', "Open on GitHub");
		const createPR = localize('createpr', "Create PR");
		const action = await window.showInformationMessage(localize('forking_done', "The fork '{0}' was successfully created on GitHub.", ghRepository.full_name), openOnGitHub, createPR);

		if (action === openOnGitHub) {
			await commands.executeCommand('vscode.open', Uri.parse(ghRepository.html_url));
		} else if (action === createPR) {
			const pr = await window.withProgress({ location: ProgressLocation.Notification, cancellable: false, title: localize('createghpr', "Creating GitHub Pull Request...") }, async _ => {
				let title = `Update ${remoteName}`;
				const head = repository.state.HEAD?.name;

				if (head) {
					const commit = await repository.getCommit(head);
					title = commit.message.replace(/\n.*$/m, '');
				}

				const res = await octokit.pulls.create({
					owner,
					repo,
					title,
					head: `${ghRepository.owner.login}:${remoteName}`,
					base: remoteName
				});

				await repository.setConfig(`branch.${localName}.remote`, 'upstream');
				await repository.setConfig(`branch.${localName}.merge`, `refs/heads/${remoteName}`);
				await repository.setConfig(`branch.${localName}.github-pr-owner-number`, `${owner}#${repo}#${pr.number}`);

				return res.data;
			});

			const openPR = localize('openpr', "Open PR");
			const action = await window.showInformationMessage(localize('donepr', "The PR '{0}/{1}#{2}' was successfully created on GitHub.", owner, repo, pr.number), openPR);

			if (action === openPR) {
				await commands.executeCommand('vscode.open', Uri.parse(pr.html_url));
			}
		}
	})();
}

export class GithubPushErrorHandler implements PushErrorHandler {

	async handlePushError(repository: Repository, remote: Remote, refspec: string, error: Error & { gitErrorCode: GitErrorCodes }): Promise<boolean> {
		if (error.gitErrorCode !== GitErrorCodes.PermissionDenied) {
			return false;
		}

		const remoteUrl = remote.pushUrl || (isInCodespaces() ? remote.fetchUrl : undefined);
		if (!remoteUrl) {
			return false;
		}

		const match = /^(?:https:\/\/github\.com\/|git@github\.com:)([^/]+)\/([^/.]+)(?:\.git)?$/i.exec(remoteUrl);
		if (!match) {
			return false;
		}

		if (/^:/.test(refspec)) {
			return false;
		}

		const [, owner, repo] = match;
		await handlePushError(repository, remote, refspec, owner, repo);

		return true;
	}
}


text:
import Component from 'react-pure-render/component';
import DocumentTitle from 'react-document-title';
import React, {PropTypes} from 'react';
import fetch from '../components/fetch';
import {fetchMonster} from '../../common/monsters/actions';

// This decorator (higher order component) fetches todos both in browser and
// on server side. It's true isomorphic data fetching and rendering.
@fetch(fetchMonster)
export default class Page extends Component {

  static propTypes = {
    actions: PropTypes.object,
    msg: PropTypes.object,
    monster: PropTypes.object
  }

  render() {
    const {actions, msg: {monster: msg}, monsters: {monster}} = this.props;
    console.log("My Props", this.props.monsters);

    return (
      <DocumentTitle title={msg.title}>

{monster.name}

National Dex: {monster.dex}

Classification: {monster.classification} Pokémon

      </DocumentTitle>
    );
  }

}