text:
<?php

namespace Entities;

use Octante\MarvelAPIBundle\Factories\CharacterFactory;
use Octante\MarvelAPIBundle\Model\Lists\ComicList;
use Octante\MarvelAPIBundle\Model\Lists\EventList;
use Octante\MarvelAPIBundle\Model\Lists\SerieList;
use Octante\MarvelAPIBundle\Model\Lists\StoryList;
use Octante\MarvelAPIBundle\Model\ValueObjects\Thumbnail;
use Octante\MarvelAPIBundle\Model\ValueObjects\URI;

class CharacterTest extends \PHPUnit_Framework_TestCase
{
    /**
     * when: characterEntityIsCreated
     * with: AResourceURI
     * should: setResourceURI
     */
    public function test_characterEntityIsCreated_AResourceURI_setResourceURI()
    {
        $sut = $this->getSUT();
        $resourceURI = $sut->getResourceURI();
        $expected = URI::create('http://gateway.marvel.com/v1/public/characters/1009742');
        $this->assertEquals($expected, $resourceURI);
    }

    /**
     * when: characterEntityIsCreated
     * with: thumbnail
     * should: setThumbnail
     */
    public function test_characterEntityIsCreated_thumbnail_setThumbnail()
    {
        $sut = $this->getSUT();
        $thumbnail = $sut->getThumbnail();
        $expected = Thumbnail::create(
                        'http://i.annihil.us/u/prod/marvel/i/mg/c/d0/4ced5ab9078c9',
                        'jpg'
                    );

        $this->assertEquals($expected, $thumbnail);
    }

    /**
     * when: charactersEntityIsCreated
     * with: stories
     * should: setStories
     */
    public function test_charactersEntityIsCreated_stories_setStories()
    {
        $sut = $this->getSUT();
        $stories = $sut->getStories();
        $expected = StoryList::create(
            3,
            3,
            'http://gateway.marvel.com/v1/public/characters/1009742/stories',
            [
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/stories/82130",
                    "name" => "Interior #82130",
                    "type" => "interiorStory",
                ],
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/stories/90817",
                    "name" => "Interior #90817",
                    "type" => "interiorStory",
                ],
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/stories/94784",
                    "name" => "Incredible Hulks (2009) #602, SHS VARIANT",
                    "type" => "cover",
                ],
            ]
        );

        $this->assertEquals($expected, $stories);
    }

    /**
     * when: charactersEntityIsCreated
     * with: events
     * should: setEvents
     */
    public function test_charactersEntityIsCreated_events_setEvents()
    {
        $sut = $this->getSUT();
        $events = $sut->getEvents();
        $expected = EventList::create(
            0,
            0,
            'http://gateway.marvel.com/v1/public/characters/1009742/events',
            [
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/events/94784",
                    "name" => "Incredible Hulks (2009) #602, SHS VARIANT",
                ],
            ]
        );

        $this->assertEquals($expected, $events);
    }

    /**
     * when: charactersEntityIsCreated
     * with: series
     * should: setSeries
     */
    public function test_charactersEntityIsCreated_series_setSeries()
    {
        $sut = $this->getSUT();
        $series = $sut->getSeries();
        $expected = SerieList::create(
            2,
            2,
            'http://gateway.marvel.com/v1/public/characters/1009742/series',
            [
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/series/3374",
                    "name" => "Hulk (2008 - 2012)",
                ],
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/series/8842",
                    "name" => "Incredible Hulks (2009 - 2011)",
                ],
            ]
        );

        $this->assertEquals($expected, $series);
    }

    /**
     * when: charactersEntityIsCreated
     * with: comics
     * should: setComics
     */
    public function test_charactersEntityIsCreated_comics_setComics()
    {
        $sut = $this->getSUT();
        $comics = $sut->getComics();
        $expected = ComicList::create(
            3,
            3,
            'http://gateway.marvel.com/v1/public/characters/1009742/comics',
            [
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/comics/37047",
                    "name" => "Hulk (2008) #36",
                ],
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/comics/40023",
                    "name" => "Hulk (2008) #36 (I Am Captain America Variant)",
                ],
                [
                    "resourceURI" => "http://gateway.marvel.com/v1/public/comics/29541",
                    "name" => "Incredible Hulks (2009) #602 (SHS VARIANT)",
                ],
            ]
        );

        $this->assertEquals($expected, $comics);
    }

    private function getSUT()
    {
        $jsonResponse = file_get_contents(__DIR__ . '/../../Fixtures/getCharactersCollection.json');
        $results = json_decode($jsonResponse, true);

        return (new CharacterFactory())->createCharacter($results['data']['results'][0]);
    }
}


text:
"""The tests for the Alexa component."""
# pylint: disable=protected-access
import datetime

import pytest

from homeassistant.components import alexa
from homeassistant.components.alexa import const
from homeassistant.core import callback
from homeassistant.setup import async_setup_component

SESSION_ID = "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000"
APPLICATION_ID = "amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe"
REQUEST_ID = "amzn1.echo-api.request.0000000-0000-0000-0000-00000000000"

# pylint: disable=invalid-name
calls = []

NPR_NEWS_MP3_URL = "https://pd.npr.org/anon.npr-mp3/npr/news/newscast.mp3"

@pytest.fixture
def alexa_client(loop, hass, hass_client):
    """Initialize a Home Assistant server for testing this module."""

    @callback
    def mock_service(call):
        calls.append(call)

    hass.services.async_register("test", "alexa", mock_service)

    assert loop.run_until_complete(
        async_setup_component(
            hass,
            alexa.DOMAIN,
            {
                # Key is here to verify we allow other keys in config too
                "homeassistant": {},
                "alexa": {
                    "flash_briefings": {
                        "weather": [
                            {
                                "title": "Weekly forecast",
                                "text": "This week it will be sunny.",
                            },
                            {
                                "title": "Current conditions",
                                "text": "Currently it is 80 degrees fahrenheit.",
                            },
                        ],
                        "news_audio": {
                            "title": "NPR",
                            "audio": NPR_NEWS_MP3_URL,
                            "display_url": "https://npr.org",
                            "uid": "uuid",
                        },
                    }
                },
            },
        )
    )
    return loop.run_until_complete(hass_client())

def _flash_briefing_req(client, briefing_id):
    return client.get("/api/alexa/flash_briefings/{}".format(briefing_id))

async def test_flash_briefing_invalid_id(alexa_client):
    """Test an invalid Flash Briefing ID."""
    req = await _flash_briefing_req(alexa_client, 10000)
    assert req.status == 404
    text = await req.text()
    assert text == ""

async def test_flash_briefing_date_from_str(alexa_client):
    """Test the response has a valid date parsed from string."""
    req = await _flash_briefing_req(alexa_client, "weather")
    assert req.status == 200
    data = await req.json()
    assert isinstance(
        datetime.datetime.strptime(
            data[0].get(const.ATTR_UPDATE_DATE), const.DATE_FORMAT
        ),
        datetime.datetime,
    )

async def test_flash_briefing_valid(alexa_client):
    """Test the response is valid."""
    data = [
        {
            "titleText": "NPR",
            "redirectionURL": "https://npr.org",
            "streamUrl": NPR_NEWS_MP3_URL,
            "mainText": "",
            "uid": "uuid",
            "updateDate": "2016-10-10T19:51:42.0Z",
        }
    ]

    req = await _flash_briefing_req(alexa_client, "news_audio")
    assert req.status == 200
    json = await req.json()
    assert isinstance(
        datetime.datetime.strptime(
            json[0].get(const.ATTR_UPDATE_DATE), const.DATE_FORMAT
        ),
        datetime.datetime,
    )
    json[0].pop(const.ATTR_UPDATE_DATE)
    data[0].pop(const.ATTR_UPDATE_DATE)
    assert json == data

redpajama_set_name: RedPajamaGithub


text:
module Polonium
  class Page
    include WaitFor, ValuesMatch
    attr_reader :driver
    PAGE_LOADED_COMMAND = <<-JS
      (function(selenium) {
        BrowserBot.prototype.bodyText = function() {
            if (!this.getDocument().body) {
                return "";
            }
            return getText(this.getDocument().body);
        };
        selenium.browserbot.bodyText = BrowserBot.prototype.bodyText;
        return selenium.browserbot.getDocument().body ? true : false;
      })(this);
    JS

    def initialize(driver)
      @driver = driver
    end

    def open(url)
      driver.open(url)
    end
    alias_method :open_and_wait, :open

    def assert_title(expected_title, params = {})
      wait_for(params) do |configuration|
        actual_title = title
        configuration.message = "Expected title '#{expected_title}' but was '#{actual_title}'"
        values_match?(actual_title, expected_title)
      end
    end
    def title
      driver.get_title
    end

    def assert_text_present(expected_text, options = {})
      options = {
        :message => "Expected '#{expected_text}' to be present, but it wasn't"
      }.merge(options)
      wait_for(options) do
        is_text_present? expected_text
      end
    end
    def is_text_present?(expected_text)
      if expected_text.is_a?(Regexp)
        text_finder = "regexp:#{expected_text.source}"
      else
        text_finder = expected_text
      end
      page_loaded? && driver.is_text_present(text_finder)
    end

    def assert_text_not_present(unexpected_text, options = {})
      options = {
        :message => "Expected '#{unexpected_text}' to be absent, but it wasn't"
      }.merge(options)
      wait_for(options) do
        is_text_not_present? unexpected_text
      end
    end
    def is_text_not_present?(unexpected_text)
      if unexpected_text.is_a?(Regexp)
        text_finder = "regexp:#{unexpected_text.source}"
      else
        text_finder = unexpected_text
      end
      page_loaded? && !driver.is_text_present(text_finder)
    end

    def page_loaded?
      driver.get_eval(PAGE_LOADED_COMMAND) == true.to_s
    end

    def assert_location_ends_with(ends_with, options={})
      driver.assert_location_ends_with(ends_with, options)
    end

    def location_ends_with?(ends_with)
      driver.location_ends_with?(ends_with)
    end

    def ==(other)
      return false unless other.is_a?(Page)
      self.driver == other.driver
    end

    def method_missing(method_name, *args, &blk)
      if driver.respond_to?(method_name)
        driver.__send__(method_name, *args, &blk)
      else
        super
      end
    end
  end
end


text:
using Plugin.Connectivity.Abstractions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace Plugin.Connectivity
{
	/// <summary>
	/// Implementation for Connectivity
	/// </summary>
	public class ConnectivityImplementation : BaseConnectivity
	{
		/// <summary>
		/// Default constructor
		/// </summary>
		public ConnectivityImplementation ()
		{
			UpdateConnected (false);
			Reachability.ReachabilityChanged += ReachabilityChanged;
		}

		void ReachabilityChanged (object sender, EventArgs e)
		{
			UpdateConnected ();
		}

		private bool isConnected;
		private NetworkStatus previousInternetStatus = NetworkStatus.NotReachable;

		private void UpdateConnected (bool triggerChange = true)
		{
			var remoteHostStatus = Reachability.RemoteHostStatus ();
			var internetStatus = Reachability.InternetConnectionStatus ();
			var localWifiStatus = Reachability.LocalWifiConnectionStatus ();

			var previouslyConnected = isConnected;
			isConnected = internetStatus == NetworkStatus.ReachableViaWiFiNetwork ||
			localWifiStatus == NetworkStatus.ReachableViaWiFiNetwork ||
			remoteHostStatus == NetworkStatus.ReachableViaWiFiNetwork;

			if (triggerChange && (previouslyConnected != isConnected || previousInternetStatus != internetStatus))
				OnConnectivityChanged (new ConnectivityChangedEventArgs { IsConnected = isConnected });
			previousInternetStatus = internetStatus;
		}

		/// <summary>
		/// Gets if there is an active internet connection
		/// </summary>
		public override bool IsConnected { get { return isConnected; } }

		/// <summary>
		/// Tests if a host name is pingable
		/// </summary>
		/// <param name="host">The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address (127.0.0.1)</param>
		/// <param name="msTimeout">Timeout in milliseconds</param>
		/// <returns></returns>
		public override async Task<bool> IsReachable (string host, int msTimeout = 5000)
		{
			if (string.IsNullOrEmpty (host))
				throw new ArgumentNullException ("host");

			if (!IsConnected)
				return false;

			return await IsRemoteReachable (host, 80, msTimeout);
		}

		/// <summary>
		/// Tests if a remote host name is reachable
		/// </summary>
		/// <param name="host">Host name can be a remote IP or URL of website</param>
		/// <param name="port">Port to attempt to check is reachable.</param>
		/// <param name="msTimeout">Timeout in milliseconds.</param>
		/// <returns></returns>
		public override async Task<bool> IsRemoteReachable (string host, int port = 80, int msTimeout = 5000)
		{
			if (string.IsNullOrEmpty (host))
				throw new ArgumentNullException ("host");

			if (!IsConnected)
				return false;

			host = host.Replace ("http://www.", string.Empty).
              		Replace ("http://", string.Empty).
              		Replace ("https://www.", string.Empty).
              		Replace ("https://", string.Empty).
              		TrimEnd('/');

			return await Task.Run (() => {
				try {
					var clientDone = new ManualResetEvent (false);
					var reachable = false;
					var hostEntry = new DnsEndPoint (host, port);
					using (var socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
						var socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry };
						socketEventArg.Completed += (s, e) => {
							reachable = e.SocketError == SocketError.Success;

							clientDone.Set ();
						};

						clientDone.Reset ();

						socket.ConnectAsync (socketEventArg);

						clientDone.WaitOne (msTimeout);

						return reachable;
					}
				} catch (Exception ex) {
					Debug.WriteLine ("Unable to reach: " + host + " Error: " + ex);
					return false;
				}
			});
		}

		/// <summary>
		/// Gets the list of all active connection types.
		/// </summary>
		public override IEnumerable<ConnectionType> ConnectionTypes {
			get {
				var status = Reachability.InternetConnectionStatus ();
				switch (status) {
				case NetworkStatus.ReachableViaWiFiNetwork:
					yield return ConnectionType.WiFi;
					break;
				default:
					yield return ConnectionType.Other;
					break;
				}
			}
		}

		/// <summary>
		/// Not supported on iOS
		/// </summary>
		public override IEnumerable<UInt64> Bandwidths {
			get { return new UInt64[] { }; }
		}

		private bool disposed = false;

		/// <summary>
		/// Dispose
		/// </summary>
		/// <param name="disposing"></param>
		public override void Dispose (bool disposing)
		{
			if (!disposed) {
				if (disposing) {
					Reachability.ReachabilityChanged -= ReachabilityChanged;
					Reachability.Dispose ();
				}

				disposed = true;
			}

			base.Dispose (disposing);
		}
	}
}


text:
gh-pages:
	git checkout master
	adocs HSO-Exercises syllabus.html
	git checkout gh-pages
	mv syllabus.html index.html
	git commit index.html -m 'Index updated from master'
	git push origin gh-pages


text:
'use strict';

angular.module('playApp.hdkeys', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/hdkeys', {
    templateUrl: 'hdkeys/hdkeys.html',
    controller: 'HDKeysCtrl'
  });
}])

.controller('HDKeysCtrl', function($scope, bitcore) {

  $scope.bitcoreURL = 'http://bitcore.io/guide/hierarchical.html';
  $scope.bitcoinURL = 'https://bitcoin.org/en/developer-guide#hierarchical-deterministic-key-creation';
  var privateValidPath = function(path) {
    return !!(/^[mM][']?(\/[0-9]+[']?)*[/]?$/.exec(path));
  };
  var publicValidPath = function(path) {
    return !!(/^[mM](\/[0-9]+)*[/]?$/.exec(path));
  };
  $scope.path = "m/44'/0'/0'/0/1337";
  $scope.keys = [];

  $scope.$on('networkUpdate', function() {
    $scope.newKey();
  });

  $scope.newKey = function() {
    $scope.updatePrivate(new bitcore.HDPrivateKey().toString());
  };

  $scope.updatePrivate = function(value) {
    if (!bitcore.HDPrivateKey.isValidSerialized(value)) return; // mark as invalid

    $scope.xpriv = new bitcore.HDPrivateKey(value);
    $scope.xpub = $scope.xpriv.hdPublicKey;
    $scope.keys = $scope.deriveKeys($scope.xpriv, $scope.path);
    setExampleCode($scope.xpriv, $scope.path);
  };

  $scope.updatePublic = function(value) {
    if (!bitcore.HDPublicKey.isValidSerialized(value)) return; // mark as invalid

    $scope.xpriv = '';
    $scope.xpub = new bitcore.HDPublicKey(value);
    $scope.keys = $scope.deriveKeys($scope.xpub, $scope.path);
    setExampleCode($scope.xpub, $scope.path);
  };

  $scope.updatePath = function(value) {
    if ($scope.xpriv) {
      if (!privateValidPath(value)) return;
    } else {
      if (!publicValidPath(value)) return;
    }

    $scope.keys = $scope.deriveKeys($scope.xpriv || $scope.xpub, value);
    setExampleCode($scope.xpriv || $scope.xpub, value);
  };

  $scope.deriveKeys = function(key, path) {
    var xpriv, xpub;
    if (key instanceof bitcore.HDPrivateKey) {
      xpriv = key;
      xpub = key.hdPublicKey;
    } else if (key instanceof bitcore.HDPublicKey) {
      xpriv = null;
      xpub = key;
    } else {
      return;
    }

    if (path[path.length-1] === '/') {
      path = path.substr(0, path.length - 1);
    }

    if (xpriv) {
      if (!privateValidPath(path)) return;
    } else {
      if (!publicValidPath(path)) return;
    }

    var indexes = bitcore.HDPrivateKey._getDerivationIndexes(path);
    var MAX = 2147483647;
    var paths = indexes.map(function(m, i) {
      return 'm/' + indexes.slice(0, i+1).map(function(index) {
        if (index >= MAX) {
          return (index - MAX - 1) + "'";
        }
        return '' + index;
      }).join('/');
    });
    paths = ['m'].concat(paths);

    var nodes = paths.map(function(p) {
      return {
        path: p,
        xpriv: xpriv && key.derive(p),
        xpub: (key instanceof bitcore.HDPublicKey) ? key.derive(p) : key.derive(p).hdPublicKey
      };
    });

    nodes[nodes.length-1].visible = true;
    nodes.reverse();
    return nodes;
  };

  function setExampleCode(hdKey, path, isNew) {
    var template = "";

    if (hdKey instanceof bitcore.HDPublicKey) {
      template += "var hdPublicKey = new bitcore.HDPrivateKey();\n";
      template += "var derivedHdPublicKey = hdPublicKey.derive('" + path + "');\n"

    } else if (hdKey instanceof bitcore.HDPrivateKey) {
      template += "var hdPrivateKey = new bitcore.HDPrivateKey();\n";

      template += "\n// private key derivation\n";
      template += "var derivedHdPrivateKey = hdPrivateKey.derive(\"" + path + "\");\n"
      template += "var derivedPrivateKey = hdPrivateKey.privateKey;\n"

      template += "\n// public key derivation\n";
      template += "var derivedHdPublicKey = derivedHdPrivateKey.hdPublicKey;\n"
    }

    template += "var derivedPublicKey = derivedHdPublicKey.publicKey;\n"
    template += "var address = derivedPublicKey.toAddress();"

    $scope.exampleCode = template;
  };

  $scope.jumpConsole = function() {
    $('#terminaltab').click();
    window.REPL.console.SetPromptText($scope.exampleCode);
    window.REPL.scrollToBottom();
  };

  $scope.newKey();
});


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace DAL.Repository
{
    public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
    {
        private readonly DbSet<TEntity> _context;

        public GenericRepository(DbContext context)
        {
            _context = context.Set<TEntity>();
        }

        public async Task<IEnumerable<TEntity>> GetAsync(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IQueryable<TEntity>> orderBy = null,
        params Expression<Func<TEntity, object>>[] includeProperties)
        {
            IQueryable<TEntity> query = _context;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            query = includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));

            if (orderBy != null)
            {
                return await orderBy(query).AsNoTracking().ToListAsync();
            }

            return await query.AsNoTracking().ToListAsync();
        }

        public async Task<TEntity> GetByIdAsync(int id)
        {
            return await _context.FindAsync(id);
        }

        public async Task AddOrUpdateAsync(TEntity entity)
        {
            await Task.Factory.StartNew(() => _context.AddOrUpdate(entity));
        }

        public async Task DeleteAsync(int id)
        {
            _context.Remove(await GetByIdAsync(id));
        }

        public async Task<int> CountAsync()
        {
            return await _context.CountAsync();
        }
    }
}


text:
module.exports = function(req, res, next){
    next();
};


text:
RED.user = (function() {

    function login(opts,done) {
        if (typeof opts == 'function') {
            done = opts;
            opts = {};
        }

        var dialog = $('
'+
                       '

'+
                       '
'+
                       '<form id="node-dialog-login-fields" class="form-horizontal" style="margin-bottom: 0px;"></form>'+
                       '
'+
                       '
');

        dialog.dialog({
            autoOpen: false,
            dialogClass: "ui-dialog-no-close",
            modal: true,
            closeOnEscape: false,
            width: 600,
            resizable: false,
            draggable: false
        });

        $("#node-dialog-login-fields").empty();
        $.ajax({
            dataType: "json",
            url: "auth/login",
            success: function(data) {
                if (data.type == "credentials") {
                    var i=0;
                    for (;i<data.prompts.length;i++) {
                        var field = data.prompts[i];
                        var row = $("
",{class:"form-row"});
                        $(''+field.label+':
').appendTo(row);
                        $('<input style="width: 100%" id="node-dialog-login-'+field.id+'" type="'+field.type+'" tabIndex="'+(i+1)+'"/>').appendTo(row);
                        row.appendTo("#node-dialog-login-fields");
                    }
                    $('
Login failed'+
                        (opts.cancelable?'Cancel':'')+
                        'Login
').appendTo("#node-dialog-login-fields");
                    $("#node-dialog-login-submit").button().click(function( event ) {
                        $("#node-dialog-login-submit").button("option","disabled",true);
                        $("#node-dialog-login-failed").hide();
                        $(".login-spinner").show();

                        var body = {
                            client_id: "ubicall-admin",
                            grant_type: "password",
                            scope:"*"
                        }
                        for (var i=0;i<data.prompts.length;i++) {
                            var field = data.prompts[i];
                            body[field.id] = $("#node-dialog-login-"+field.id).val();
                        }
                        $.ajax({
                            url:"https://api.ubicall.com/auth/token",
                            type: "POST",
                            data: body
                        }).done(function(data,textStatus,xhr) {
                            RED.settings.set("auth-tokens",data);
                            $("#node-dialog-login").dialog('destroy').remove();
                            done();
                        }).fail(function(jqXHR,textStatus,errorThrown) {
                            RED.settings.remove("auth-tokens");
                            $("#node-dialog-login-failed").show();
                        }).always(function() {
                            $("#node-dialog-login-submit").button("option","disabled",false);
                            $(".login-spinner").hide();
                        });
                        event.preventDefault();
                    });
                    if (opts.cancelable) {
                        $("#node-dialog-login-cancel").button().click(function( event ) {
                            $("#node-dialog-login").dialog('destroy').remove();
                        });
                    }
                }
                dialog.dialog("open");
            }
        });
    }

    function logout() {
        var ats = RED.settings.get("auth-tokens");
        var at = ats ? ats.access_token : undefined;
        if(at){
          $.ajax({
              url: "https://api.ubicall.com/auth/revoke",
              type: "POST",
              data: {token:at},
              success: function() {
                  RED.settings.remove("auth-tokens");
                  document.location.reload(true);
              }
          });
        }else {
          RED.settings.remove("auth-tokens");
          document.location.reload(true);
        }
    }

    function updateUserMenu() {
        $("#btn-usermenu-submenu li").remove();
        if (RED.settings.user.anonymous) {
            RED.menu.addItem("btn-usermenu",{
                id:"btn-login",
                label:"Login",
                onselect: function() {
                    RED.user.login({cancelable:true},function() {
                        RED.settings.load(function() {
                            RED.notify("Logged in as "+RED.settings.user.username,"success");
                            updateUserMenu();
                        });
                    });
                }
            });
        } else {
            RED.menu.addItem("btn-usermenu",{
                id:"btn-username",
                label:""+RED.settings.user.username+""
            });
            RED.menu.addItem("btn-usermenu",{
                id:"btn-logout",
                label:"Logout",
                onselect: function() {
                    RED.user.logout();
                }
            });
        }

    }

    function init() {
        if (RED.settings.user) {
            $('

')
                .prependTo(".header-toolbar");

            RED.menu.init({id:"btn-usermenu",
                options: []
            });
            updateUserMenu();
        }

    }
    return {
        init: init,
        login: login,
        logout: logout
    }

})();


text:
<?php

namespace Angie\AdminBundle\Controller\Comment;

use Admingenerated\AngieAdminBundle\BaseCommentController\ListController as BaseListController;

/**
 * ListController
 */
class ListController extends BaseListController
{
}


text:
/*
   Rewritten by Emil Fresk (1/5 - 2014) for extended input capture
   functionality. And fix for spurious callbacks in the interrupt handler.
*/
/*
   Improved by Uladzimir Pylinsky aka barthess (1/3 - 2015) for support of
   32-bit timers and timers with single capture/compare channels.
*/

#ifndef HAL_EICU_H_
#define HAL_EICU_H_

#if (HAL_USE_EICU == TRUE) || defined(__DOXYGEN__)

/*===========================================================================*/
/* Driver constants.                                                         */
/*===========================================================================*/

/*===========================================================================*/
/* Driver pre-compile time settings.                                         */
/*===========================================================================*/

/*===========================================================================*/
/* Derived constants and error checks.                                       */
/*===========================================================================*/

/*===========================================================================*/
/* Driver data structures and types.                                         */
/*===========================================================================*/

/**
 * @brief   Driver state machine possible states.
 */
typedef enum {
  EICU_UNINIT,                /* Not initialized.                           */
  EICU_STOP,                  /* Stopped.                                   */
  EICU_READY,                 /* Ready.                                     */
  EICU_WAITING,               /* Waiting for first edge.                    */
  EICU_ACTIVE,                /* Active cycle phase.                        */
  EICU_IDLE                   /* Idle cycle phase.                          */
} eicustate_t;

/**
 * @brief   Channel state machine possible states.
 */
typedef enum {
  EICU_CH_IDLE,               /* Idle cycle phase.                          */
  EICU_CH_ACTIVE              /* Active cycle phase.                        */
} eicuchannelstate_t;

/**
 * @brief EICU channel selection definition
 */
typedef enum {
  EICU_CHANNEL_1,
  EICU_CHANNEL_2,
  EICU_CHANNEL_3,
  EICU_CHANNEL_4,
  EICU_CHANNEL_ENUM_END
} eicuchannel_t;

/**
 * @brief   Type of a structure representing an EICU driver.
 */
typedef struct EICUDriver EICUDriver;

/**
 * @brief EICU notification callback type.
 *
 * @param[in] eicup     Pointer to a EICUDriver object
 * @param[in] channel   EICU channel that fired the interrupt
 * @param[in] width     Pulse width
 * @param[in] period    Pulse period
 */
typedef void (*eicucallback_t)(EICUDriver *eicup, eicuchannel_t channel,
                               uint32_t width, uint32_t period);

#include "hal_eicu_lld.h"

/*===========================================================================*/
/* Driver macros.                                                            */
/*===========================================================================*/

/**
 * @name    Macro Functions
 * @{
 */
/**
 * @brief   Enables the extended input capture.
 *
 * @param[in] eicup     Pointer to the @p EICUDriver object
 *
 * @iclass
 */
#define eicuEnableI(eicup) eicu_lld_enable(eicup)

/**
 * @brief   Disables the extended input capture.
 *
 * @param[in] eicup     Pointer to the @p EICUDriver object
 *
 * @iclass
 */
#define eicuDisableI(eicup) eicu_lld_disable(eicup)
/** @} */

/**
 * @name    Low Level driver helper macros
 * @{
 */
/**
 * @brief   Common ISR code, EICU PWM width event.
 *
 * @param[in] eicup     Pointer to the @p EICUDriver object
 * @param[in] channel   The timer channel that fired the interrupt.
 *
 * @notapi
 */
static inline void _eicu_isr_invoke_pwm_width_cb(EICUDriver *eicup,
                                                 eicuchannel_t channel) {
  if (eicup->state != EICU_WAITING) {
    eicup->state = EICU_IDLE;
    eicup->config->iccfgp[channel]->capture_cb(eicup, channel, 0, 0);
  }
}

/**
 * @brief   Common ISR code, EICU PWM period event.
 *
 * @param[in] eicup     Pointer to the @p EICUDriver object
 * @param[in] channel   The timer channel that fired the interrupt.
 *
 * @notapi
 */
static inline void _eicu_isr_invoke_pwm_period_cb(EICUDriver *eicup,
                                                  eicuchannel_t channel) {
  eicustate_t previous_state = eicup->state;
  eicup->state = EICU_ACTIVE;
  if (previous_state != EICU_WAITING)
    eicup->channel[channel].config->capture_cb(eicup, channel, 0, 0);
}

/**
 * @brief   Common ISR code, EICU timer overflow event.
 *
 * @param[in] eicup      Pointer to the @p EICUDriver object
 *
 * @notapi
 */
#define _eicu_isr_invoke_overflow_cb(icup) do {                                \
  (eicup)->config->overflow_cb(eicup, 0, 0, 0);                                \
} while (0)
/** @} */

/*===========================================================================*/
/* External declarations.                                                    */
/*===========================================================================*/

#ifdef __cplusplus
extern "C" {
#endif
  void eicuInit(void);
  void eicuObjectInit(EICUDriver *eicup);
  void eicuStart(EICUDriver *eicup, const EICUConfig *config);
  void eicuStop(EICUDriver *eicup);
  void eicuEnable(EICUDriver *eicup);
  void eicuDisable(EICUDriver *eicup);
#ifdef __cplusplus
}
#endif

#endif /* HAL_USE_EICU */

#endif /* HAL_EICU_H_ */

/** @} */


text:
package org.opensplice.cm.qos;

/**
 * Specifies the behavior of the Service in the case where the value of a sample
 * changes (one or more times) before it can be successfully communicated to one
 * or more existing subscribers.
 *
 * @date Jan 10, 2005
 */
public class HistoryQosKind {
    public static final int _KEEPLAST         = 0;
    public static final int _KEEPALL           = 1;

    /**
     * On the publishing side, the service will only attempt to keep the most
     * recent "depth" samples of each instance of data (identified by its key)
     * managed by the Writer. On the subscribing side, the DataReader will only
     * attempt to keep the most recent "depth" samples received for each
     * instance (identified by its key) until the application "takes" them via
     * the DataReader's take operation. KEEPLAST is the default kind. The
     * default value of depth is 1. If a value other than 1 is specified, it
     * should be consistent with the settings of the ResourcePolicy.
     */
    public static final HistoryQosKind KEEPLAST    = new HistoryQosKind(_KEEPLAST);

    /**
     * On the publishing side, the service will attempt to keep all samples
     * (representing each value written) of each instance of data (identified by
     * its key) managed by the Writer until they can be delivered to all
     * subscribers. On the subscribing side, the service will attempt to keep
     * all samples of each instance of data (identified by its key) managed by
     * the DataReader. These samples are kept until the application "takes" them
     * from the service via the take operation. The setting of depth has no
     * effect. Its implied value is "INFINITE"
     */
    public static final HistoryQosKind KEEPALL      = new HistoryQosKind(_KEEPALL);

    /**
     * Resolves the integer representation of the kind.
     *
     * @return The integer representation of the kind.
     */
    public int value(){
        int result = -1;

        if(this.equals(KEEPLAST)){
            result = _KEEPLAST;
        } else if(this.equals(KEEPALL)){
            result = _KEEPALL;
        }
        return result;
    }

    /**
     * Constructs the kind from its integer representation.
     *
     * @return The created kind.
     */
    public static HistoryQosKind from_int(int value){
        HistoryQosKind result = null;

        if(value == _KEEPLAST){
            result = KEEPLAST;
        } else if(value == _KEEPALL){
            result = KEEPALL;
        }
        return result;
    }

    /**
     * Constructs the kind from its string representation.
     *
     * @return The created kind.
     */
    public static HistoryQosKind from_string(String value){
        HistoryQosKind result = null;

        if("V_HISTORY_KEEPLAST".equals(value)){
            result = KEEPLAST;
        } else if("V_HISTORY_KEEPALL".equals(value)){
            result = KEEPALL;
        } else if("KEEPLAST".equals(value)){
            result = KEEPLAST;
        } else if("KEEPALL".equals(value)){
            result = KEEPALL;
        }
        return result;
    }

    /**
     * Resolves the string representation of the kind.
     *
     * @return The string representation of the kind.
     */
    @Override
    public String toString(){
        String result = "UNKNOWN";

        if(this.equals(KEEPLAST)){
            result = "KEEPLAST";
        } else if(this.equals(KEEPALL)){
            result = "KEEPALL";
        }
        return result;
    }

    public String toKernelString(){
        String result = "UNKNOWN";

        if(this.equals(KEEPLAST)){
            result = "V_HISTORY_KEEPLAST";
        } else if(this.equals(KEEPALL)){
            result = "V_HISTORY_KEEPALL";
        }
        return result;
    }

    protected HistoryQosKind(int value){}
}


text:
package com.eharmony.matching.vw.webservice.messagebodyreader.jsonexamplesmessagebodyreader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.zip.GZIPInputStream;

import junit.framework.Assert;

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

import com.eharmony.matching.vw.webservice.common.example.Example;
import com.google.common.base.Charsets;
import com.google.gson.stream.JsonWriter;

public class GsonJsonExamplesProviderTest {

	private static final Logger LOGGER = LoggerFactory.getLogger(GsonJsonExamplesProviderTest.class);

	/*
	 * Tests that a whole bunch of examples can be written and read in JSON
	 * format.
	 */
	@Test
	public void test() throws IOException, InterruptedException, ExecutionException, TimeoutException {

		//the examples
		GZIPInputStream gzipInputStream = new GZIPInputStream(this.getClass().getClassLoader().getResourceAsStream("ner.train.gz"));
		final BufferedReader testReader = new BufferedReader(new InputStreamReader(gzipInputStream, Charsets.UTF_8));

		final PipedOutputStream pipedOutputStream = new PipedOutputStream();
		PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);

		GsonJsonExamplesProvider toTest = new GsonJsonExamplesProvider();

		final CountDownLatch startWritingExamplesLatch = new CountDownLatch(1);

		final Exchanger<String> exampleExchanger = new Exchanger<String>();

		final JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(pipedOutputStream));

		Future<Void> successFuture = Executors.newCachedThreadPool().submit(new Callable<Void>() {

			@Override
			public Void call() throws Exception {

				startWritingExamplesLatch.await();

				String readExample = null;

				jsonWriter.beginArray();

				while ((readExample = testReader.readLine()) != null) {

					jsonWriter.beginObject();
					jsonWriter.name("example");
					jsonWriter.value(readExample);
					jsonWriter.endObject();

					jsonWriter.flush();
					pipedOutputStream.flush(); //need to flush right after writing, otherwise the reading thread won't get it

					exampleExchanger.exchange(readExample, 1, TimeUnit.SECONDS); //don't care about what's being given to us in exchange
				}

				jsonWriter.endArray();
				jsonWriter.flush();
				jsonWriter.close();
				pipedOutputStream.flush();
				pipedOutputStream.close();

				return null;
			}

		});

		Iterator<Example> examplesIterable = toTest.getExamplesFromStream(pipedInputStream);

		startWritingExamplesLatch.countDown(); //tell the example writing thread to start writing examples

		long numExamplesProcessed = 0;

		while (examplesIterable.hasNext()) { //start reading the examples

			Example theExample = examplesIterable.next();

			Assert.assertEquals(exampleExchanger.exchange("", 1, TimeUnit.SECONDS), theExample.getVWStringRepresentation());

			if (numExamplesProcessed % 20000 == 0) LOGGER.debug("Read example: {}", theExample.getVWStringRepresentation());

			numExamplesProcessed++;
		}

		successFuture.get(); //verify no exceptions were thrown.

		Assert.assertEquals(272274, numExamplesProcessed); //verify all examples in ner.train.gz were processed.

	}

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. nov. -zel. 200 (1855)

#### Original name
Peziza colensoi Berk., 1855

### Remarks
null


text: <manifest package="com.marcohc.architecture.firebase" />


text:
from setuptools import setup, find_packages

setup(
    name='workmate_plugin',
    version='0.0.1',
    description='Workmate Plugin Example',
    long_description=open('README.rst').read(),
    author='Stuart George',
    author_email='stuart.bigmassa@gmail.com',
    url='https://github.com/bigmassa/workmate_plugin',
    download_url='https://pypi.python.org/pypi/',
    license='MIT',
    packages=find_packages(exclude=('example', 'tests')),
    install_requires=[
        'Django>=1.8,<1.10',
        'django-classy-tags>=0.7',
        'django-phonenumber-field>=1.0.0',
        'django-reversion>=1.10.0',
    ],
    dependency_links=['http://github.com/bigmassa/workmate.git#egg=workmate'],
    include_package_data=True,
    keywords=['workmate', 'plugin'],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.8',
        'Framework :: Django :: 1.9',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/PresentationAPI.iml" filepath="$PROJECT_DIR$/PresentationAPI.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text:
package nl.mprog.friendsandfood.Activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

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

import nl.mprog.friendsandfood.R;

/**
 * Created by Tom Verburg on 12-1-2017.
 *
 * In this activity the user is able to write a review of a specific restaurant and give it a rating
 * out of 5 using a RatingBar. After the user clicks the "submit" button, the review is saved to
 * Firebase and the user is returned t
 */

public class WriteReviewActivity extends BaseActivity implements View.OnClickListener {

    private DatabaseReference myRefReviews;
    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private RatingBar ratingBar;
    private String restaurantID;
    private String restaurantName;
    private String reviewID;
    private EditText editText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_review);

        //Intent
        Intent intent = getIntent();
        restaurantID = intent.getStringExtra("restaurantID");
        restaurantName = intent.getStringExtra("restaurantName");

        //Views
        findViewById(R.id.btn_submit_review).setOnClickListener(this);
        ratingBar = (RatingBar)findViewById(R.id.rating_bar);
        editText = (EditText) findViewById(R.id.edit_text_review);
        TextView infoReview = (TextView)findViewById(R.id.write_restaurant_info);

        infoReview.setText(restaurantName);
        generateNewReviewID();
    }

    //* Generates a unique review ID based on the previous amount of reviews written
    // and the id of the user*/
    public void generateNewReviewID(){
        myRefReviews = database.getReference("reviews");
        myRefReviews.addValueEventListener(new ValueEventListener() {
            //Database listener which fires when the database changes and counts reviews.
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                ArrayList<String> oldReviews = new ArrayList<>();
                for (DataSnapshot child: dataSnapshot.getChildren()) {
                    String oldSearchTerm = child.getValue().toString();
                    oldReviews.add(oldSearchTerm);
                }
                WriteReviewActivity.this.reviewID = getProfile() + oldReviews.size();
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
    }

    //* Checks whether the user is entering a valid review. Rating is compulsory, text is not.*/
    public boolean checkReview(float rating){
        if (rating == 0){
            Toast.makeText(getApplicationContext(), R.string.please_enter_rating,
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //*This is an onClick method which saves all the review information to Firebase and then
    // finishes this activity. By doing this, the user is returned to the SelectedRestaurant
    // activity.*/
    @Override
    public void onClick(View v) {
        if (checkReview(ratingBar.getRating())){
            Map<String, Object> reviewInfo = new HashMap<>();
            reviewInfo.put("ReviewID", reviewID);
            reviewInfo.put("RestaurantID", restaurantID);
            reviewInfo.put("RestaurantName", restaurantName);
            reviewInfo.put("Writer", getProfile());
            reviewInfo.put("Rating", ratingBar.getRating());
            reviewInfo.put("Text", String.valueOf(editText.getText()));
            myRefReviews.child(reviewID).updateChildren(reviewInfo);
            Toast.makeText(getApplicationContext(), R.string.review_submitted,
                    Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { Keyup3Component } from './keyup-3.component';

describe('Keyup3Component', () => {
  let component: Keyup3Component;
  let fixture: ComponentFixture<Keyup3Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ Keyup3Component ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Keyup3Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER4(UnaryOp, CPU, "Cos", functor::cos, float, Eigen::half, double,
          complex64);
#if GOOGLE_CUDA
REGISTER3(UnaryOp, GPU, "Cos", functor::cos, float, Eigen::half, double);
#endif
}  // namespace tensorflow


text:
package net.wizardsoflua.lua.nbt;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Map.Entry;

import javax.annotation.Nullable;

import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.sandius.rembulan.Table;
import net.wizardsoflua.lua.table.TableIterable;

/**
 * Merges {@link NBTTagList}s of type Compound by matching the elements via the value of the
 * specified key.
 *
 * @author Adrodoc55
 */
public class ValueBasedNbtListMergeStrategy implements NbtListMergeStrategy {
  private final String key;
  private final NbtConverter converter;

  public ValueBasedNbtListMergeStrategy(String key, NbtConverter converter) {
    this.key = checkNotNull(key, "key == null!");
    this.converter = checkNotNull(converter, "converter == null!");
  }

  @Override
  public NBTTagList merge(NBTTagList nbt, Table data, String path) {
    NBTTagList result = nbt.copy();
    for (Entry<Object, Object> entry : new TableIterable(data)) {
      Table luaValue = (Table) entry.getValue();
      Object keyValue = luaValue.rawget(key);
      checkNotNull(keyValue, "Expected each value to contain the key: '" + key + "'");
      NBTTagCompound oldValue = getCompoundByValueKey(nbt, keyValue);
      String entryPath = path + "[" + keyValue + "]";
      if (oldValue != null) {
        NBTBase newValue = converter.merge(oldValue, luaValue, entryPath);
        result.appendTag(newValue);
      } else {
        NBTBase newValue = converter.toNbtCompound(luaValue, entryPath);
        result.appendTag(newValue);
      }
    }
    return result;
  }

  private @Nullable NBTTagCompound getCompoundByValueKey(NBTTagList compoundList, Object keyValue) {
    checkNotNull(keyValue, "keyValue == null!");
    for (int i = 0; i < compoundList.tagCount(); ++i) {
      NBTTagCompound compound = compoundList.getCompoundTagAt(i);
      NBTBase nbtKeyValue = compound.getTag(key);
      checkNotNull(nbtKeyValue, "Expected each NBT value to contain the key: '" + key + "'");
      if (nbtKeyValue.equals(keyValue)) {
        return compound;
      }
    }
    return null;
  }
}


text:
<md-dialog aria-label="Form" class="md-inline-form">
	<md-content class="md-padding" layout-padding>
		<form name="postForm">

				<md-input-container flex> Title <input ng-model="dc.newPost.title"> </md-input-container>

				<md-input-container flex> Message <textarea ng-model="dc.newPost.message" columns="1" md-maxlength="150"></textarea> </md-input-container>

				<md-input-container flex> Author <input ng-model="dc.newPost.author"> </md-input-container>

				<input filepicker type="filepicker-dragdrop" data-fp-mimetype="image/*" data-fp-services="computer,facebook,instagram,url,box,GOOGLE_DRIVE,picasa,convert,webcam" on-success="dc.setUrl(event.fpfile.url)" data-fp-button-class="md-button md-raised md-ink-ripple" data-fp-drag-class="md-button event-drag-drop" data-fp-button-text="Attach Photo" data-fp-drag-text="Or Drag/Drop File Here" data-fp-image-quality="75" />

		</form>
	</md-content>
	<md-dialog-actions layout="row">

		<md-button ng-click="dc.cancel()" class="md-raised md-ink-ripple"> Cancel </md-button>
		<md-button ng-click="dc.save()" class="md-raised md-ink-ripple md-primary"> Save </md-button>
	</md-dialog-actions>
</md-dialog>


text:
package ejb;

import java.util.ArrayList;
import javax.ejb.Local;
import model.Product;

@Local
public interface Catalogue {

    public Product searchByName(String name);
    public Product searchById(String id);
    public boolean add(Product product);
    public ArrayList<Product> getProducts();

}