text:
static void glfw_error(int error, const char* msg) {
    fprintf(stderr, "error: %d: %s\n", error, msg);
}

int main(int argc, char** argv) {
    glfwSetErrorCallback(glfw_error);

    if (!glfwInit()) {
        return -1;
    }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    GLFWwindow* window = glfwCreateWindow(1280, 720, "TraceView", NULL, NULL);
    glfwMakeContextCurrent(window);
    gl3wInit();

    ImGui_ImplGlfwGL3_Init(window, true);

    if (traceviz_main(argc, argv)) {
        return -1;
    }

    ImVec4 clear = ImColor(144, 144, 154);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        ImGui_ImplGlfwGL3_NewFrame();

    	if (traceviz_render()) {
            break;
        }

        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);
        glClearColor(clear.x, clear.y, clear.z, clear.w);
        glClear(GL_COLOR_BUFFER_BIT);

        ImGui::Render();
        glfwSwapBuffers(window);
    }

    ImGui_ImplGlfwGL3_Shutdown();
    glfwTerminate();
    return 0;
}


text:
package org.apache.jackrabbit.oak.stats;

import java.util.concurrent.TimeUnit;

public final class NoopStats implements TimerStats, MeterStats, CounterStats, HistogramStats {

    public static final NoopStats INSTANCE = new NoopStats();

    private NoopStats(){

    }

    @Override
    public long getCount() {
        return 0;
    }

    @Override
    public void inc() {

    }

    @Override
    public void dec() {

    }

    @Override
    public void inc(long n) {

    }

    @Override
    public void dec(long n) {

    }

    @Override
    public void mark() {

    }

    @Override
    public void mark(long n) {

    }

    @Override
    public void update(long duration, TimeUnit unit) {

    }

    @Override
    public Context time() {
        return NoopContext.INSTANCE;
    }

    @Override
    public void update(long value) {

    }

    private static final class NoopContext implements Context {
        public static final NoopContext INSTANCE = new NoopContext();

        @Override
        public long stop() {
            return 0;
        }

        @Override
        public void close() {

        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
@class MittapLayerView;

@interface MittapLayerLabel : MittapLayerView

- ( id )initWithFrame:(CGRect)frame WithString:( NSString * )pstrText;

@end


text:
using System.IO;
using System.Windows.Media;
using LeaSearch.Core.Notice;
using LeaSearch.Plugin;
using LeaSearch.Plugin.Index;
using LeaSearch.SearchEngine;

namespace LeaSearch.Core.Plugin
{
    internal class PluginApiForCsharpPlugin : IPluginApi
    {
        private readonly Plugin _plugin;
        private readonly LuceneManager _luceneManager;

        public PluginApiForCsharpPlugin(Plugin plugin, LuceneManager luceneManager)
        {
            _plugin = plugin;
            _luceneManager = luceneManager;

            if (plugin != null)
            {
                PluginRootPath = plugin.PluginRootPath;
            }
        }

        public string PluginRootPath { get; }

        public Stream GetPluginEmbedResouceStream(string name)
        {
            return _plugin.GetPluginEmbedResouceStream(name);
        }

        public ImageSource GetPluginEmbedImage(string name)
        {
            var stream = GetPluginEmbedResouceStream(name);
            if (stream == null)
            {
                return null;
            }
            ImageSourceConverter converter = new ImageSourceConverter();
            return (ImageSource)converter.ConvertFrom(stream);
        }

        public void SetIconFromEmbedResource(string imageName)
        {
            _plugin.PluginInitInfo.Icon = GetPluginEmbedImage(imageName);
        }

        public void AddDataItemToIndex(DataItem[] dataItems)
        {
            _luceneManager.AddToIndex(dataItems, _plugin.PluginId);
        }

        public void UpdateDataItemToIndex(DataItem[] dataItems)
        {
            _luceneManager.UpdateToIndex(dataItems, _plugin.PluginId);
        }

        public DataItem[] SearchDataItems(string keyword, int top = 10)
        {
            return _luceneManager.Search(keyword, _plugin.PluginId, top);
        }

        public DataItem[] GetAllDataItems()
        {
            return _luceneManager.SearchByPluginId(_plugin.PluginId);
        }

        public void RemoveIndex()
        {
            _luceneManager.DeleteIndexByPluginId(_plugin.PluginId);
        }

        public string GetTranslation(string key, params object[] paramObjects)
        {
            var translation = _plugin.GetTranslation(key);
            return string.Format(translation, paramObjects);
        }

        public void ShowMessageWithTranslation(string key, params object[] paramObjects)
        {
            var trans = GetTranslation(key, paramObjects);
            UiNoticeHelper.ShowMessage(trans);
        }

    }
}


text:
<?php namespace Raymondidema\UserPackage\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;
use Raymondidema\Commandee\ValidationCommandBus;
use Raymondidema\UserPackage\Users\CreateNewUserCommand;

class RegistrationController extends \BaseController
{
    /**
     * @var \Raymondidema\Commandee\ValidationCommandBus
     */
    protected $commandBus;

    /**
     * @param ValidationCommandBus $commandBus
     */
    function __construct(ValidationCommandBus $commandBus)
    {
        $this->commandBus = $commandBus;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(Auth::check())
            return Redirect::to('/profile');
        return View::make('user-package::registration.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $input = Input::only('first_name', 'last_name', 'email', 'password');
        $command = new CreateNewUserCommand($input['email'], $input['first_name'], $input['last_name'], $input['password']);
        $this->commandBus->execute($command);
        return Redirect::to('/profile');
    }

}


text:
@interface EAIntroPage : NSObject

// title image Y position - from top of the screen
// title and description labels Y position - from bottom of the screen
@property (nonatomic, retain) UIImage *bgImage;
@property (nonatomic, retain) UIImage *titleImage;
@property (nonatomic, assign) CGFloat imgPositionY;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) UIFont *titleFont;
@property (nonatomic, retain) UIColor *titleColor;
@property (nonatomic, assign) CGFloat titlePositionY;
@property (nonatomic, retain) NSString *desc;
@property (nonatomic, retain) UIFont *descFont;
@property (nonatomic, retain) UIColor *descColor;
@property (nonatomic, assign) CGFloat descPositionY;

// if customView is set - all other properties are ignored
@property (nonatomic, retain) UIView *customView;

+ (EAIntroPage *)page;
+ (EAIntroPage *)pageWithCustomView:(UIView *)customV;

@end


text:
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history';
import React from 'react';
import { Router } from 'react-router-dom';

import { createFakeFirestoreRequestEvaluation } from '../../testing/test_utils';
import { RequestDetails } from './index';

const FAKE_EVALUATION_ID = 'first-fake-evaluation';
const FAKE_EVALUATION = createFakeFirestoreRequestEvaluation({
  requestId: FAKE_EVALUATION_ID,
});
const SET_SHOW_COPY_NOTIFICATION = jest.fn();

describe('RequestDetails', () => {
  it('renders header', () => {
    const history = createMemoryHistory({
      initialEntries: [`/firestore/requests/${FAKE_EVALUATION_ID}`],
    });
    const { getByTestId } = render(
      <Router history={history}>
        <RequestDetails
          selectedRequest={FAKE_EVALUATION}
          requestId={FAKE_EVALUATION_ID}
          setShowCopyNotification={SET_SHOW_COPY_NOTIFICATION}
        />
      </Router>
    );
    expect(getByTestId('request-details-header')).not.toBeNull();
  });
  it('renders code viewer section', () => {
    const history = createMemoryHistory({
      initialEntries: [`/firestore/requests/${FAKE_EVALUATION_ID}`],
    });
    const { getByTestId } = render(
      <Router history={history}>
        <RequestDetails
          selectedRequest={FAKE_EVALUATION}
          requestId={FAKE_EVALUATION_ID}
          setShowCopyNotification={SET_SHOW_COPY_NOTIFICATION}
        />
      </Router>
    );
    expect(getByTestId('request-details-code-viewer-section')).not.toBeNull();
  });
  it('renders inspection section', () => {
    const history = createMemoryHistory({
      initialEntries: [`/firestore/requests/${FAKE_EVALUATION_ID}`],
    });
    const { getByTestId } = render(
      <Router history={history}>
        <RequestDetails
          selectedRequest={FAKE_EVALUATION}
          requestId={FAKE_EVALUATION_ID}
          setShowCopyNotification={SET_SHOW_COPY_NOTIFICATION}
        />
      </Router>
    );
    expect(getByTestId('request-details-inspection-section')).not.toBeNull();
  });

  it('redirects back to requests-table when requestId did not match any existing request', async () => {
    const history = createMemoryHistory({
      initialEntries: [`/firestore/requests/${FAKE_EVALUATION_ID}`],
    });
    render(
      <Router history={history}>
        <RequestDetails
          selectedRequest={undefined}
          requestId={FAKE_EVALUATION_ID}
          setShowCopyNotification={SET_SHOW_COPY_NOTIFICATION}
        />
      </Router>
    );
    expect(history.location.pathname).toBe('/firestore/requests');
  });
});


text:
Parker is a stylesheet analysis tool. It runs metrics on your stylesheets and will report on their complexity.

[![Build Status](https://secure.travis-ci.org/katiefenn/parker.png?branch=master)](http://travis-ci.org/katiefenn/parker)

## Installation

Install with npm:

```
npm install -g parker
```

## Usage

### Measuring Local Stylesheets

```
parker a.css b.css c.css
```
```
parker css/
```

### Measuring a Remote Stylesheet Using Curl

```
curl http://www.katiefenn.co.uk/css/shuttle.css -s | parker -s
```

### Output JSON

```
parker example.css --format=json
```

### Programmatic usage

After installing parker as a dependency in your project, you can use it as follows:

```js
var Parker = require('parker/lib/Parker');
var metrics = require('parker/metrics/All'); // Or an array of the metrics you want to measure

var file = fs.readFile('test.css', function (err, data) {
	if (err) throw err;

	var parker = new Parker(metrics);
	var results = parker.run(data.toString());

	// Do something with results
});
```

## Documentation

Documentation can be found in markdown format the [docs folder](https://github.com/katiefenn/parker/tree/master/docs).

## Testing

From the repo root:

```
npm install
npm test
```

## Contributing

Pull requests, issues, new unit tests, code reviews and good advice are all things that would make a difference to Parker. You can even contribute by telling me how useful Parker is to you; please let me know on Twitter at @katie_fenn. Any time generously donated to helping make Parker better is gratefully accepted, and in return I shall do my best to merge contributions.

Please target pull requests at the "develop" branch.

## About

Parker is my first open source project, and your suggestions and feedback are welcome. The project is in a pre-beta phase and is liable to change at any time. Parker is named for the character Parker from Gerry Anderson's Thunderbirds, without which my interest in technology and computers would certainly not be what it is today. Parker is Nosey about your stylesheets.


text:
using namespace std;
using namespace boost;
using namespace graph_tool;

//
// Property map copying
// ====================

template <class IteratorSel, class PropertyMaps>
struct copy_property
{
    template <class GraphTgt, class GraphSrc, class PropertyTgt>
    void operator()(const GraphTgt& tgt, const GraphSrc* src,
                    PropertyTgt dst_map, boost::any prop_src) const
    {
        try
        {
            auto src_map = boost::any_cast<typename PropertyTgt::checked_t>(prop_src);
            dispatch(tgt, src, dst_map, src_map);
        }
        catch (bad_any_cast)
        {
            typedef typename property_traits<PropertyTgt>::value_type val_tgt;
            typedef typename IteratorSel::template get_descriptor<GraphSrc>::type src_d;

            DynamicPropertyMapWrap<val_tgt, src_d> src_map(prop_src, PropertyMaps());

            dispatch(tgt, src, dst_map, src_map);
        }
    }

    template <class GraphTgt, class GraphSrc, class PropertyTgt, class PropertySrc>
    void dispatch(const GraphTgt& tgt, const GraphSrc* src,
                  PropertyTgt dst_map, PropertySrc src_map) const
    {
        try
        {
            typename IteratorSel::template apply<GraphSrc>::type vs, vs_end;
            typename IteratorSel::template apply<GraphTgt>::type vt, vt_end;
            tie(vt, vt_end) = IteratorSel::range(tgt);
            for (tie(vs, vs_end) = IteratorSel::range(*src); vs != vs_end; ++vs)
            {
                if (vt == vt_end)
                    throw ValueException("Error copying properties: "
                                         "graphs not compatible");
                dst_map[*vt] = get(src_map, *vs);
                ++vt;
            }
        }
        catch (bad_lexical_cast&)
        {
            throw ValueException("property values are not convertible");
        }
    }

};

struct edge_selector
{
    template <class Graph>
    struct apply
    {
        typedef typename graph_traits<Graph>::edge_iterator type;
    };

    template <class Graph>
    struct get_descriptor
    {
        typedef typename graph_traits<Graph>::edge_descriptor type;
    };

    template <class Graph>
    static pair<typename apply<Graph>::type,
                typename apply<Graph>::type>
    range(Graph& g)
    {
        return edges(g);
    }
};

struct vertex_selector
{
    template <class Graph>
    struct apply
    {
        typedef typename graph_traits<Graph>::vertex_iterator type;
    };

    template <class Graph>
    struct get_descriptor
    {
        typedef typename graph_traits<Graph>::vertex_descriptor type;
    };

    template <class Graph>
    static pair<typename apply<Graph>::type,
                typename apply<Graph>::type>
    range(Graph& g)
    {
        return vertices(g);
    }
};

struct graph_views:
    boost::mpl::transform<graph_tool::detail::always_directed_never_reversed,
                          boost::mpl::quote1<std::add_pointer> >::type {};

void GraphInterface::CopyVertexProperty(const GraphInterface& src,
                                        boost::any prop_src,
                                        boost::any prop_tgt)
{
    run_action<>()
        (*this, std::bind(copy_property<vertex_selector,vertex_properties>(),
                          std::placeholders::_1, std::placeholders::_2,
                          std::placeholders::_3, prop_src),
         graph_views(), writable_vertex_properties())
        (src.GetGraphView(), prop_tgt);
}

void GraphInterface::CopyEdgeProperty(const GraphInterface& src,
                                      boost::any prop_src,
                                      boost::any prop_tgt)
{
    run_action<>()
        (*this, std::bind(copy_property<edge_selector,edge_properties>(),
                          std::placeholders::_1, std::placeholders::_2,
                          std::placeholders::_3, prop_src),
         graph_views(), writable_edge_properties())
        (src.GetGraphView(), prop_tgt);
}


text:
package com.intellij.psi.impl.java.stubs;

import com.intellij.psi.PsiAnnotationParameterList;
import com.intellij.psi.stubs.StubElement;

/**
 * @author Dmitry Avdeev
 *         Date: 7/27/12
 */
public interface PsiAnnotationParameterListStub extends StubElement<PsiAnnotationParameterList> {
}


text:
cask "nrlquaker-winbox" do
  version "3.27.0"
  sha256 "e38aca871ac88ad1e5646901519ffc9923d445dcb7e50b8c847f1bd874c65326"

  url "https://github.com/nrlquaker/winbox-mac/releases/download/v#{version}/Winbox-mac-#{version}.zip"
  appcast "https://github.com/nrlquaker/winbox-mac/releases.atom"
  name "Winbox-mac"
  desc "MikroTik Winbox"
  homepage "https://github.com/nrlquaker/winbox-mac/"

  app "Winbox-mac.app"

  zap trash: "~/Library/Application Support/com.mikrotik.winbox"
end


text:
namespace gcm {

namespace {

TEST(AccountMappingTest, SerializeAccountMapping) {
  AccountMapping account_mapping;
  account_mapping.account_id = "acc_id";
  account_mapping.email = "test@example.com";
  account_mapping.access_token = "access_token";
  account_mapping.status = AccountMapping::ADDING;
  account_mapping.status_change_timestamp = base::Time();
  account_mapping.last_message_id = "last_message_id_1";
  account_mapping.last_message_type = AccountMapping::MSG_ADD;

  EXPECT_EQ("test@example.com&0&add&last_message_id_1",
            account_mapping.SerializeAsString());

  account_mapping.account_id = "acc_id2";
  account_mapping.email = "test@gmail.com";
  account_mapping.access_token = "access_token";  // should be ignored.
  account_mapping.status = AccountMapping::MAPPED;  // should be ignored.
  account_mapping.status_change_timestamp =
      base::Time::FromInternalValue(1305797421259977LL);
  account_mapping.last_message_id = "last_message_id_2";
  account_mapping.last_message_type = AccountMapping::MSG_REMOVE;

  EXPECT_EQ("test@gmail.com&1305797421259977&remove&last_message_id_2",
            account_mapping.SerializeAsString());

  account_mapping.last_message_type = AccountMapping::MSG_NONE;

  EXPECT_EQ("test@gmail.com&1305797421259977&none",
            account_mapping.SerializeAsString());
}

TEST(AccountMappingTest, DeserializeAccountMapping) {
  AccountMapping account_mapping;
  account_mapping.account_id = "acc_id";
  EXPECT_TRUE(account_mapping.ParseFromString(
      "test@example.com&0&add&last_message_id_1"));
  EXPECT_EQ("acc_id", account_mapping.account_id);
  EXPECT_EQ("test@example.com", account_mapping.email);
  EXPECT_TRUE(account_mapping.access_token.empty());
  EXPECT_EQ(AccountMapping::ADDING, account_mapping.status);
  EXPECT_EQ(base::Time(), account_mapping.status_change_timestamp);
  EXPECT_EQ(AccountMapping::MSG_ADD, account_mapping.last_message_type);
  EXPECT_EQ("last_message_id_1", account_mapping.last_message_id);

  EXPECT_TRUE(account_mapping.ParseFromString(
      "test@gmail.com&1305797421259977&remove&last_message_id_2"));
  EXPECT_EQ("acc_id", account_mapping.account_id);
  EXPECT_EQ("test@gmail.com", account_mapping.email);
  EXPECT_TRUE(account_mapping.access_token.empty());
  EXPECT_EQ(AccountMapping::REMOVING, account_mapping.status);
  EXPECT_EQ(base::Time::FromInternalValue(1305797421259977LL),
            account_mapping.status_change_timestamp);
  EXPECT_EQ(AccountMapping::MSG_REMOVE, account_mapping.last_message_type);
  EXPECT_EQ("last_message_id_2", account_mapping.last_message_id);

  EXPECT_TRUE(account_mapping.ParseFromString(
      "test@gmail.com&1305797421259977&none"));
  EXPECT_EQ("acc_id", account_mapping.account_id);
  EXPECT_EQ("test@gmail.com", account_mapping.email);
  EXPECT_TRUE(account_mapping.access_token.empty());
  EXPECT_EQ(AccountMapping::MAPPED, account_mapping.status);
  EXPECT_EQ(base::Time::FromInternalValue(1305797421259977LL),
            account_mapping.status_change_timestamp);
  EXPECT_EQ(AccountMapping::MSG_NONE, account_mapping.last_message_type);
  EXPECT_EQ("", account_mapping.last_message_id);
}

TEST(AccountMappingTest, DeserializeAccountMappingInvalidInput) {
  AccountMapping account_mapping;
  account_mapping.account_id = "acc_id";
  // Too many agruments.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@example.com&1305797421259935"
      "&add&last_message_id_1&stuff_here"));
  // Too few arguments.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@example.com&1305797421259935&remove"));
  // Too few arguments.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@example.com&1305797421259935"));
  // Missing email.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "&1305797421259935&remove&last_message_id_2"));
  // Missing mapping status change timestamp.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@gmail.com&&remove&last_message_id_2"));
  // Last mapping status change timestamp not parseable.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@gmail.com&remove&asdfjkl&last_message_id_2"));
  // Missing message type.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@example.com&1305797421259935&&last_message_id_2"));
  // Unkown message type.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@example.com&1305797421259935&random&last_message_id_2"));
  // Message type is none when message details specified.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@example.com&1305797421259935&none&last_message_id_2"));
  // Message type is messed up.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@example.com&1305797421259935&random"));
  // Missing last message ID.
  EXPECT_FALSE(account_mapping.ParseFromString(
      "test@example.com&1305797421259935&remove&"));
}

}  // namespace
}  // namespace gcm


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using NUnit.Framework;
using MonoTouch.UIKit;
using FrozenHeadersGrid.UnitTests.Mocks;

namespace FrozenHeadersGrid.UnitTests
{
	[TestFixture]
	public partial class FrozenHeadersGridViewTest
	{
		[Test]
		public void MinimumColumnWidth_HasADefaultValue()
		{
			Assert.AreEqual(120, CreateFrozenHeadersGridView().MinimumColumnWidth);
		}

		[Test]
		public void RowHeight_HasADefaultValue()
		{
			Assert.AreEqual(55, CreateFrozenHeadersGridView().RowHeight);
		}

		[Test]
		public void HeaderColumnWith_HasADefaultValue()
		{
			Assert.AreEqual(60, CreateFrozenHeadersGridView().HeaderColumnWidth);
		}

		[Test]
		public void HeaderRowHeight_HasADefaultValue()
		{
			Assert.AreEqual(55, CreateFrozenHeadersGridView().HeaderRowHeight);
		}

		[Test]
		public void SetDelegate_UpdatesContent()
		{
			var updateCalled = false;
			var gridView = CreateFrozenHeadersGridViewMock();
			gridView.UpdateContentCalled += (sender, e) => updateCalled = true;

			gridView.Delegate = new FrozenHeadersGridViewDelegateMock();

			Assert.True(updateCalled);
		}

        #region TintColor
        [Test]
        public void TintColor_SetsHeaderRowTintColor()
        {
            var gridView = CreateFrozenHeadersGridView();

            gridView.TintColor = UIColor.Blue;

            Assert.AreEqual(UIColor.Blue, gridView.HeaderRowView.TintColor);
        }

        [Test]
        public void TintColor_SetsHeaderRowGridlinesColor()
        {
            var gridView = CreateFrozenHeadersGridView();

            gridView.TintColor = UIColor.Blue;

            Assert.AreEqual(UIColor.Blue, gridView.HeaderRowView.Gridlines.Color);
        }

        [Test]
        public void TintColor_SetsHeaderColumnTintColor()
        {
            var gridView = CreateFrozenHeadersGridView();

            gridView.TintColor = UIColor.Blue;

            Assert.AreEqual(UIColor.Blue, gridView.HeaderColumnView.TintColor);
        }

        [Test]
        public void TintColor_SetsHeaderColumnGridlinesColor()
        {
            var gridView = CreateFrozenHeadersGridView();

            gridView.TintColor = UIColor.Blue;

            Assert.AreEqual(UIColor.Blue, gridView.HeaderColumnView.Gridlines.Color);
        }
        #endregion

		[Test]
		public void UpdateContent_WhenDelegateReturnsItemView_AddsTheViewToTheGridContentView()
		{
			var gridView = CreateFrozenHeadersGridView();
			var itemView = new UIView();
			var mockDelegate = new FrozenHeadersGridViewDelegateMock { ColumnCount = 1, RowCount = 1};
			mockDelegate.ViewForCellDelegate = (view, cell) => {
				return itemView; };

			gridView.Delegate = mockDelegate;

			Assert.AreSame(itemView, gridView.ContentView[new Point(0, 0)]);
		}

		[Test]
		public void UpdateContent_AddsHeaderRowItemsForEachColumn()
		{
			var gridView = CreateFrozenHeadersGridViewWithDelegate();

			gridView.UpdateContent();

			Assert.AreEqual(3, gridView.HeaderRowView.Subviews.Length);
		}

		[Test]
		public void UpdateContent_SetsHeaderRowItemTextFromDelegate()
		{
			string[] titles = {"First title", "Second title"};
			var gridView = CreateFrozenHeadersGridViewWithDelegate(columns: 2);
            ((FrozenHeadersGridViewDelegateMock)gridView.Delegate)
                .TitleForColumnDelegate = (grid, column) => { return titles[column]; };

			gridView.UpdateContent();

			Assert.AreEqual("First title", ((UILabel)gridView.HeaderRowView[0]).Text);
			Assert.AreEqual("Second title", ((UILabel)gridView.HeaderRowView[1]).Text);
		}

		[Test]
		public void UpdateContent_AddsHeaderColumnItemsForEachRow()
		{
			var gridView = CreateFrozenHeadersGridViewMock();

			gridView.UpdateContent();

			Assert.AreEqual(4, gridView.HeaderColumnView.Subviews.Length);
		}

		[Test]
		public void UpdateContent_SetsHeaderColumnItemTextFromDelegate()
		{
			string[] titles = {"First title", "Second title"};
			var gridView = CreateFrozenHeadersGridViewWithDelegate(rows: 2);
            ((FrozenHeadersGridViewDelegateMock)gridView.Delegate)
                .TitleForRowDelegate = (grid, row) => { return titles[row]; };

			gridView.UpdateContent();

			Assert.AreEqual("First title", ((UILabel)gridView.HeaderColumnView[0]).Text);
			Assert.AreEqual("Second title", ((UILabel)gridView.HeaderColumnView[1]).Text);
		}

		FrozenHeadersGridView CreateFrozenHeadersGridView(float width = 100, float height = 100)
		{
			return new FrozenHeadersGridView(new RectangleF(0, 0, width, height));
		}

		FrozenHeadersGridView CreateFrozenHeadersGridViewWithDelegate(float width = 100, float height = 100, int columns = 3, int rows = 4)
		{
			var gridView = new FrozenHeadersGridView(new RectangleF(0, 0, width, height));
			var mockDelegate = new FrozenHeadersGridViewDelegateMock { ColumnCount = columns, RowCount = rows };
			gridView.Delegate = mockDelegate;
			return gridView;
		}

		FrozenHeadersGridViewMock CreateFrozenHeadersGridViewMock(int columns = 3, int rows = 4)
		{
			var mockDelegate = new FrozenHeadersGridViewDelegateMock { ColumnCount = columns, RowCount = rows };
			var gridView = new FrozenHeadersGridViewMock(new RectangleF(0, 0, 100, 100));
			gridView.Delegate = mockDelegate;

			return gridView;
		}
	}
}


text:
package org.encog.util.normalize.output.nominal;

import java.util.ArrayList;
import java.util.List;

import org.encog.util.normalize.input.InputField;
import org.encog.util.normalize.output.BasicOutputField;

/**
 * An output field that uses the "on of" technique to represent input data. For
 * example, if there were five nominal items, or classes, given then each one
 * would be represented by a single output neuron that would be on or off.
 *

 * Often the OutputEquilateral class is a better choice to represent nominal
 * items.
 *

 */
public class OutputOneOf extends BasicOutputField {

    /**
     * The nominal items to represent.
     */
    private final List<NominalItem> items = new ArrayList<NominalItem>();
    /**
     * What is the true value, often just "1".
     */
    private double trueValue;
    /**
     * What is the true value, often just "0" or "-1".
     */
    private double falseValue;

    /**
     * Default constructor for reflection.
     */
    public OutputOneOf() {
        this(1, -1);
    }

    /**
     * Construct a one-of field and specify the true and false value.
     *

     * @param trueValue
     *                   The true value.
     * @param falseValue
     *                   The false value.
     */
    public OutputOneOf(final double trueValue, final double falseValue) {
        this.trueValue = trueValue;
        this.falseValue = falseValue;
    }

    /**
     * Add a nominal value specifying a single value, the high and low values
     * will be 0.5 below and 0.5 above.
     *

     * @param inputField The input field to use.
     * @param value      The value to calculate the high and low values off of.
     */
    public void addItem(final InputField inputField, final double value) {
        addItem(inputField, value - 0.5, value + 0.5);
    }

    /**
     * Add a nominal item, specify the low and high values.
     *

     * @param inputField The input field to base everything from.
     * @param low        The high value for this nominal item.
     * @param high       The low value for this nominal item.
     */
    public void addItem(final InputField inputField, final double low,
                        final double high) {
        final NominalItem item = new NominalItem(inputField, low, high);
        this.items.add(item);
    }

    /**
     * Calculate the value for the specified subfield.
     *

     * @param subfield
     *                 The subfield to calculate for.
     *

     * @return The calculated value for this field.
     */
    public double calculate(final int subfield) {
        final NominalItem item = this.items.get(subfield);
        return item.isInRange() ? this.trueValue : this.falseValue;
    }

    /**
     * @return The false value.
     */
    public double getFalseValue() {
        return this.falseValue;
    }

    /**
     * @return The number of subfields, or nominal classes.
     */
    public int getSubfieldCount() {
        return this.items.size();
    }

    /**
     * @return The true value.
     */
    public double getTrueValue() {
        return this.trueValue;
    }

    /**
     * Not needed for this sort of output field.
     */
    public void rowInit() {
    }
}


text:
SYNONYM

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

#### Published in
null

#### Original name
Gymnosporangium durum F. Kern, 1907

### Remarks
null


text:
package com.cra.figaro.example

import com.cra.figaro.algorithm.sampling._
import com.cra.figaro.language._
import com.cra.figaro.library.atomic.continuous.{ Uniform, Normal }
import com.cra.figaro.library.atomic.discrete.{ Geometric, FromRange }
import com.cra.figaro.library.compound._
import com.cra.figaro.library.collection._
import com.cra.figaro.language.Universe._
import com.cra.figaro.util._

/**
 * An example of open universe reasoning.
 */
object OpenUniverse {
  createNew()

  private def source(): Element[Double] = {
    Uniform(0.0, 1.0)
  }

  private val numSources = FromRange(1,4)

  private val sources = MakeList(numSources, source _)

  private class Sample {
    val sourceNum = IntSelector(numSources)
    val source = Apply(sources, sourceNum, (s: Seq[Double], i: Int) => s(i))
    val position = NonCachingChain(source, (x: Double) => Normal(x, 1.0))
  }

  private val sample1 = new Sample
  private val sample2 = new Sample
  private val samples = List(sample1, sample2)
  private val numSamples = samples.length

  private val equal = sample1.source === sample2.source

  def chooseScheme(): ProposalScheme =
    DisjointScheme(
      (0.1, () => ProposalScheme(numSources)),
      (0.9, () => ProposalScheme.default))

  def main(args: Array[String]) = {
    sample1.position.addCondition((y: Double) => y >= 0.7 && y < 0.8)
    sample2.position.addCondition((y: Double) => y >= 0.7 && y < 0.8)
    val alg = MetropolisHastings(chooseScheme, 5000, equal)
    alg.start()
    Thread.sleep(10000)
    alg.stop()
    println(alg.probability(equal, true))
    println(alg.getSampleCount + " samples taken")
    alg.kill
  }
}


text:
<configuration>

<!--   <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/current.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <fileNamePattern>logs/%d{yyyy-MM-dd}.log</fileNamePattern>
      <maxHistory>30</maxHistory>
    </rollingPolicy>
    <encoder>
      <pattern>%date - [%level] - from %logger in %thread %n%message%n%xException%n</pattern>
    </encoder>
  </appender> -->

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%date - [%level] - %logger{15} - %message%n%xException{5}</pattern>
    </encoder>
  </appender>

  <logger name="app" level="DEBUG" />
  <logger name="Rabbit notifier" level="DEBUG" />

  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>

</configuration>


text:
package it.unitn.ing.rista.diffr.posext;

import java.lang.*;

import it.unitn.ing.rista.diffr.*;
import it.unitn.ing.rista.awt.*;
import it.unitn.ing.rista.util.*;

import java.awt.*;
import java.awt.*;
import java.awt.event.*;

/**
 *  The PositionExtnone is a class
 *
 *
 * @version $Revision: 1.5 $, $Date: 2005/05/06 18:07:27 $
 * @author Luca Lutterotti
 * @since JDK1.1
 */

public class PositionExtnone extends PositionExtractor {

  public static String[] diclistc = {};
  public static String[] diclistcrm = {};
  public static String[] classlistc = {};
  public static String[] classlistcs = {};

  public PositionExtnone(XRDcat aobj, String alabel) {
    super(aobj, alabel);
    initXRD();
    identifier = "none pe";
    IDlabel = "none pe";
    description = "select this to disable position extraction";
  }

  public PositionExtnone(XRDcat aobj) {
    this(aobj, "disable");
  }

  public void initConstant() {
    Nstring = 0;
    Nstringloop = 0;
    Nparameter = 0;
    Nparameterloop = 0;
    Nsubordinate = 0;
    Nsubordinateloop = 0;
  }

  public void initDictionary() {
    for (int i = 0; i < totsubordinateloop; i++)
      diclist[i] = diclistc[i];
    System.arraycopy(diclistcrm, 0, diclistRealMeaning, 0, totsubordinateloop);
    for (int i = 0; i < totsubordinateloop - totsubordinate; i++)
      classlist[i] = classlistc[i];
    for (int i = 0; i < totsubordinate - totparameterloop; i++)
      classlists[i] = classlistcs[i];
  }

  public void initParameters() {
    super.initParameters();
  }

  public PositionExtnone() {
    identifier = "none pe";
    IDlabel = "none pe";
    description = "select this to disable position extraction";

  }

}


text:
using Azure.Core;

namespace Azure.ResourceManager.Sql
{
    /// <summary> Client options for Sql. </summary>
    public class SqlManagementClientOptions : ClientOptions
    {
    }
}


text:
<?php

namespace directapi\services\bidmodifiers\models;

use directapi\components\Model;

class RegionalAdjustmentGet extends Model
{
    /**
     * @var int
     */
    public $RegionId;

    /**
     * @var int
     */
    public $BidModifier;

    /**
     * @var \directapi\common\enum\YesNoEnum
     */
    public $Enabled;
}


text:
$(function () {

  'use strict';

  var $image = $(window.createCropperImage());

  function isNumber(n) {
    return typeof n === 'number' && !isNaN(n);
  }

  $image.cropper({
    built: function () {

      QUnit.test('methods#getImageData', function (assert) {
        var data = $image.cropper('getImageData');

        // Not rotate
        assert.ok(isNumber(data.naturalWidth));
        assert.ok(isNumber(data.naturalHeight));
        assert.ok(isNumber(data.aspectRatio));
        assert.ok(isNumber(data.left));
        assert.ok(isNumber(data.top));
        assert.ok(isNumber(data.width));
        assert.ok(isNumber(data.height));
      });

    }
  });

});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Res. 98(10): 1192 (1994)

#### Original name
Phloeospora trichiliae M.D. Mehrotra & R.K. Verma

### Remarks
null


text:
package com.matchandtrade.test.helper;

import com.matchandtrade.persistence.entity.ArticleEntity;
import com.matchandtrade.persistence.entity.MembershipEntity;
import com.matchandtrade.persistence.facade.ArticleRepositoryFacade;
import com.matchandtrade.persistence.facade.MembershipRepositoryFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
@Commit
public class ListingHelper {

	@Autowired
	private ArticleRepositoryFacade articleRepositoryFacade;
	@Autowired
	private MembershipRepositoryFacade membershipRepositoryFacade;

	@Transactional
	public void createPersisted(Integer articleId, Integer membershipId) {
		ArticleEntity article = articleRepositoryFacade.findByArticleId(articleId);
		MembershipEntity membership = membershipRepositoryFacade.findByMembershipId(membershipId);
		membership.getArticles().add(article);
		membershipRepositoryFacade.save((membership));
	}

}


text:
namespace content {
class VideoCaptureBufferPool;
class VideoCaptureController;

// Receives events from the VideoCaptureDevice and posts them to a |controller_|
// on the IO thread. An instance of this class may safely outlive its target
// VideoCaptureController. This is a shallow class meant to convert incoming
// frames and holds no significant state.
//
// Methods of this class may be called from any thread, and in practice will
// often be called on some auxiliary thread depending on the platform and the
// device type; including, for example, the DirectShow thread on Windows, the
// v4l2_thread on Linux, and the UI thread for tab capture.
class CONTENT_EXPORT VideoCaptureDeviceClient
    : public media::VideoCaptureDevice::Client {
 public:
  VideoCaptureDeviceClient(
      const base::WeakPtr<VideoCaptureController>& controller,
      const scoped_refptr<VideoCaptureBufferPool>& buffer_pool);
  ~VideoCaptureDeviceClient() override;

  // VideoCaptureDevice::Client implementation.
  void OnIncomingCapturedData(
      const uint8* data,
      int length,
      const media::VideoCaptureFormat& frame_format,
      int rotation,
      const base::TimeTicks& timestamp) override;
  scoped_refptr<Buffer> ReserveOutputBuffer(media::VideoFrame::Format format,
                                            const gfx::Size& size) override;
  void OnIncomingCapturedVideoFrame(
      const scoped_refptr<Buffer>& buffer,
      const scoped_refptr<media::VideoFrame>& frame,
      const base::TimeTicks& timestamp) override;
  void OnError(const std::string& reason) override;
  void OnLog(const std::string& message) override;

 private:
  // The controller to which we post events.
  const base::WeakPtr<VideoCaptureController> controller_;

  // The pool of shared-memory buffers used for capturing.
  const scoped_refptr<VideoCaptureBufferPool> buffer_pool_;

  media::VideoPixelFormat last_captured_pixel_format_;

  DISALLOW_COPY_AND_ASSIGN(VideoCaptureDeviceClient);
};

}  // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_MEDIA_VIDEO_CAPTURE_DEVICE_CLIENT_H_


text:
package net.runelite.http.service;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import javax.naming.NamingException;
import net.runelite.http.service.util.InstantConverter;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.sql2o.Sql2o;
import org.sql2o.converters.Converter;
import org.sql2o.quirks.NoQuirks;

@SpringBootApplication
@EnableScheduling
public class SpringBootWebApplicationTest
{
	@Bean("Runelite SQL2O")
	Sql2o sql2o()
	{
		Map<Class, Converter> converters = new HashMap<>();
		converters.put(Instant.class, new InstantConverter());
		return new Sql2o("jdbc:mysql://192.168.1.2/runelite", "runelite", "runelite", new NoQuirks(converters));
	}

	@Bean("Runelite Cache SQL2O")
	Sql2o cacheSql2o() throws NamingException
	{
		Map<Class, Converter> converters = new HashMap<>();
		converters.put(Instant.class, new InstantConverter());
		return new Sql2o("jdbc:mysql://192.168.1.2/cache", "runelite", "runelite", new NoQuirks(converters));
	}

	@Bean("Runelite XP Tracker SQL2O")
	Sql2o xpSql2o() throws NamingException
	{
		Map<Class, Converter> converters = new HashMap<>();
		converters.put(Instant.class, new InstantConverter());
		return new Sql2o("jdbc:mysql://192.168.1.2/xptracker", "runelite", "runelite", new NoQuirks(converters));
	}

	@Test
	@Ignore
	public void test() throws InterruptedException
	{
		SpringApplication.run(SpringBootWebApplicationTest.class, new String[0]);
		for (;;)
		{
			Thread.sleep(100L);
		}
	}
}


text:
import numpy as np

def compute_fsd_features(im_label, K=128, Fs=6, Delta=8, rprops=None):
    """
    Calculates `Fourier shape descriptors` for each objects.

    Parameters
    ----------
    im_label : array_like
        A labeled mask image wherein intensity of a pixel is the ID of the
        object it belongs to. Non-zero values are considered to be foreground
        objects.
    K : int, optional
        Number of points for boundary resampling to calculate fourier
        descriptors. Default value = 128.
    Fs : int, optional
        Number of frequency bins for calculating FSDs. Default value = 6.
    Delta : int, optional
        Used to dilate nuclei and define cytoplasm region. Default value = 8.

    rprops : output of skimage.measure.regionprops, optional
        rprops = skimage.measure.regionprops( im_label ). If rprops is not
        passed then it will be computed inside which will increase the
        computation time.

    Returns
    -------
    fdata: Pandas data frame containing the FSD features for each
           object/label.

    References
    ----------
    .. [#] D. Zhang et al. "A comparative study on shape retrieval using
       Fourier descriptors with different shape signatures," In Proc.
       ICIMADE01, 2001.

    """
    import pandas as pd
    from skimage.measure import regionprops
    from skimage.segmentation import find_boundaries

    # List of feature names
    feature_list = []
    for i in range(0, Fs):
        feature_list = np.append(feature_list, 'Shape.FSD' + str(i+1))

    # get Label size x
    sizex = im_label.shape[0]
    sizey = im_label.shape[1]

    # get the number of objects in Label
    if rprops is None:
        rprops = regionprops(im_label)

    # create pandas data frame containing the features for each object
    numFeatures = len(feature_list)
    numLabels = len(rprops)
    fdata = pd.DataFrame(np.zeros((numLabels, numFeatures)),
                         columns=feature_list)

    # fourier descriptors, spaced evenly over the interval 1:K/2
    Interval = np.round(
        np.power(
            2, np.linspace(0, np.log2(K)-1, Fs+1, endpoint=True)
        )
    ).astype(np.uint8)

    for i in range(numLabels):
        # get bounds of dilated nucleus
        min_row, max_row, min_col, max_col = \
            _GetBounds(rprops[i].bbox, Delta, sizex, sizey)
        # grab label mask
        lmask = (
            im_label[min_row:max_row, min_col:max_col] == rprops[i].label
        ).astype(np.bool)
        # find boundaries
        Bounds = np.argwhere(
            find_boundaries(lmask, mode="inner").astype(np.uint8) == 1
        )
        # check length of boundaries
        if len(Bounds) < 2:
            fdata.iloc[i, :] = 0
        else:
            # compute fourier descriptors
            fdata.iloc[i, :] = _FSDs(Bounds[:, 0], Bounds[:, 1], K, Interval)

    return fdata

def _InterpolateArcLength(X, Y, K):
    """
    Resamples boundary points [X, Y] at L total equal arc-length locations.

    Parameters
    ----------
    X : array_like
        x points of boundaries
    Y : array_like
        y points of boundaries
    K : int
        Number of points for boundary resampling to calculate fourier
        descriptors. Default value = 128.

    Returns
    -------
    iX : array_like
        L-length vector of horizontal interpolated coordinates with equal
        arc-length spacing.
    iY : array_like
        L-length vector of vertical interpolated coordinates with equal
        arc-length spacing.

    """

    # generate spaced points 0, 1/k, 1
    interval = np.linspace(0, 1, K+1)
    # get segment lengths
    slens = np.sqrt(np.diff(X)**2 + np.diff(Y)**2)
    # normalize to unit length
    slens = np.true_divide(slens, slens.sum())
    # calculate cumulative length along boundary
    cumulative = np.zeros(len(slens)+1)
    cumulative[1:] = np.cumsum(slens)
    # place points in 'Interval' along boundary
    locations = np.digitize(interval, cumulative)
    # clip to ends
    locations[locations > len(slens)] = len(slens)
    # linear interpolation
    Lie = (interval - cumulative[locations-1])/slens[locations-1]
    iX = X[locations-1] + (X[locations]-X[locations-1])*Lie
    iY = Y[locations-1] + (Y[locations]-Y[locations-1])*Lie

    return iX, iY

def _FSDs(X, Y, K, Intervals):
    """
    Calculated FSDs from boundary points X,Y. Boundaries are resampled to have
    K equally spaced points (arclength) around the shape. The curvature is
    calculated using the cumulative angular function, measuring the
    displacement of the tangent angle from the starting point of the boundary.
    The K-length fft of the cumulative angular function is calculated, and
    then the elements of 'F' are summed as the spectral energy over
    'Intervals'.

    Parameters
    ----------
    X : array_like
        x points of boundaries
    Y : array_like
        y points of boundaries
    K : int
        Number of points for boundary resampling to calculate fourier
        descriptors. Default value = 128.
    Intervals : array_like
        Intervals spaced evenly over 1:K/2.

    Returns
    -------
    F : array_like
        length(Intervals) vector containing spectral energy of
        cumulative angular function, summed over defined 'Intervals'.

    """

    # check input 'Intervals'
    if Intervals[0] != 1.:
        Intervals = np.hstack((1., Intervals))
    if Intervals[-1] != (K / 2):
        Intervals = np.hstack((Intervals, float(K)))
    # get length of intervals
    L = len(Intervals)
    # initialize F
    F = np.zeros((L-1, )).astype(float)
    # interpolate boundaries
    iX, iY = _InterpolateArcLength(X, Y, K)
    # check if iXY.iX is not empty
    if iX.size:
        # calculate curvature
        Curvature = np.arctan2(
            (iY[1:] - iY[:-1]),
            (iX[1:] - iX[:-1])
        )
        # make curvature cumulative
        Curvature = Curvature - Curvature[0]
        # calculate FFT
        fX = np.fft.fft(Curvature).T
        # spectral energy
        fX = fX * fX.conj()
        fX = fX / fX.sum()
        # calculate 'F' values
        for i in range(L-1):
            F[i] = np.round(
                fX[Intervals[i]-1:Intervals[i+1]].sum(), L
            ).real.astype(float)

    return F

def _GetBounds(bbox, delta, M, N):
    """
    Returns bounds of object in global label image.

    Parameters
    ----------
    bbox : tuple
        Bounding box (min_row, min_col, max_row, max_col).
    delta : int
        Used to dilate nuclei and define cytoplasm region.
        Default value = 8.
    M : int
        X size of label image.
    N : int
        Y size of label image.

    Returns
    -------
    min_row : int
        Minum row of the region bounds.
    max_row : int
        Maximum row of the region bounds.
    min_col : int
        Minum column of the region bounds.
    max_col : int
        Maximum column of the region bounds.

    """

    min_row, min_col, max_row, max_col = bbox

    min_row_out = max(0, (min_row - delta))
    max_row_out = min(M-1, (max_row + delta))
    min_col_out = max(0, (min_col - delta))
    max_col_out = min(N-1, (max_col + delta))

    return min_row_out, max_row_out, min_col_out, max_col_out


text:
var parse = JSON.parse;

var store = new xStore('', localStorage);
var session = new xStore('', sessionStorage);

describe('xStore localStorage', function () {
	beforeEach(function () {
		store.empty();

		jasmine.addMatchers({
			toHaveLocalValue: function (utils, customEqualityTesters) {
				return {
					compare: function (actual, expected) {
						var notText = this.isNot ? ' not' : '';
						var passed = utils.equals(expected, parse(localStorage.getItem(actual)));
						return {
							pass: passed,
							message: 'Expected ' + expected + notText + ' to be value of ' + actual
						};
					}
				};
			}
		});
	});

	it('should be in the global scope', function () {
		expect(xStore).toBeDefined();
	});

	describe('set', function () {
		it('should be able to set a single value', function () {
			store.set('a', 'b');
			expect('a').toHaveLocalValue('b');
		});

		it('should be able to set multiple values', function () {
			store.set({
				a: 'a',
				b: 'b'
			});

			expect('a').toHaveLocalValue('a');
			expect('b').toHaveLocalValue('b');
		});

		it('should be able to set booleans', function () {
			store.set({
				a: true,
				b: false
			});

			expect('a').toHaveLocalValue(true);
			expect('b').toHaveLocalValue(false);
		});

		it('should be able to set numbers', function () {
			store.set({
				int: 42,
				negative: -42,
				float: 1.5
			});

			expect('int').toHaveLocalValue(42);
			expect('negative').toHaveLocalValue(-42);
			expect('float').toHaveLocalValue(1.5);
		});

		it('should be able to set arrays', function () {
			store.set('array', [1, 2, 3]);
			expect('array').toHaveLocalValue([1, 2, 3]);
		});

		it('should be able to set plain objects', function () {
			store.set('obj', {a: 1, b: 2});
			expect('obj').toHaveLocalValue({a: 1, b: 2});
		});

		it('should return the store object', function () {
			expect(store.set('a', 'b')).toBe(store);
		});

		it('should have the correct prefix', function () {
		  var prefixStore = new xStore('prefix:', localStorage);
		  prefixStore.set('a', 'b');
		  expect(store.get('prefix:a')).toBe('b');
		});
	});

	describe('get', function () {
		it('should return stored value', function () {
			store.set('a', 'b');
			expect(store.get('a')).toEqual('b');
		});

		it('should return the fallback for undefined keys', function () {
			expect(store.get('x', 'fallback')).toEqual('fallback');
		});

		it('should return an object with the correct values when passing in an array', function () {
			store.set('a', 1).set('b', 2);
			expect(store.get(['a', 'b'])).toEqual({a: 1, b: 2});
		});

		it('should accept fallbacks when passing in an array', function () {
			store.set('a', 1);
			expect(store.get(['a', 'b'], 42)).toEqual({a: 1, b: 42});
		});
	});

	describe('all', function () {
		it('should return all available values as an object', function () {
			store.set('a', 1).set('b', 2);
			expect(store.all()).toEqual({a: 1, b: 2});
		});
	});

	describe('remove', function () {
		it('should be able to remove a single key', function () {
			store.set('a', 1).remove('a');
			expect('a' in localStorage).toBe(false);
		});

		it('should be able to remove several keys', function () {
			store.set('a', 1).set('b', 2).remove('a', 'b');
			expect('a' in localStorage).toBe(false);
			expect('b' in localStorage).toBe(false);
		});

		it('should be able to remove several keys in an array', function () {
			store.set('a', 1).set('b', 2).remove(['a', 'b']);
			expect('a' in localStorage).toBe(false);
			expect('b' in localStorage).toBe(false);
		});

		it('should be able to deal with prefixes', function () {
		  var prefixStore = new xStore('prefix:', localStorage);
		  prefixStore.set('a', 'b').remove('a');
		  expect('prefix:a' in localStorage).toBe(false);
		});
	});

	describe('empty', function () {
		it('should remove all values', function () {
			store.set('a', 1).set('b', 2).empty();
			expect(localStorage.length).toBe(0);
		});

		it('should return the parent object', function () {
			expect(store.empty()).toBe(store);
		});
	});

	describe('invert', function () {
		it('should invert the value', function () {
			store.set('bool', true).invert('bool');
			expect('bool').toHaveLocalValue(false);
		});

		it('should return the parent object', function () {
			expect(store.invert('key')).toBe(store);
		});
	});

	describe('add', function () {
		it('should add to the value', function () {
			store.set('n', 40).add('n', 2);
			expect('n').toHaveLocalValue(42);
		});

		it('should return the parent object', function () {
			expect(store.add('key', 5)).toBe(store);
		});
	});

	describe('increase', function () {
		it('should increase the value by 1', function () {
			store.set('n', 40).increase('n');
			expect('n').toHaveLocalValue(41);
		});

		it('should accept a value to increase by', function () {
			store.set('n', 40).increase('n', 2);
			expect('n').toHaveLocalValue(42);
		});

		it('should return the parent object', function () {
			expect(store.increase('key', 5)).toBe(store);
		});
	});

	describe('decrease', function () {
		it('should decrease the value by 1', function () {
			store.set('n', 40).decrease('n');
			expect('n').toHaveLocalValue(39);
		});

		it('should accept a value to decrease by', function () {
			store.set('n', 40).decrease('n', 2);
			expect('n').toHaveLocalValue(38);
		});

		it('should return the parent object', function () {
			expect(store.decrease('key', 5)).toBe(store);
		});
	});

	describe('concat', function () {
		it('should concat the value', function () {
			store.set('str', 'Hello').concat('str', ' World');
			expect('str').toHaveLocalValue('Hello World');
		});

		it('should return the parent object', function () {
			expect(store.concat('key', 'str')).toBe(store);
		});
	});

	describe('push', function () {
		it('should push the value', function () {
			store.set('arr', [1, 2]).push('arr', 3, 4);
			expect('arr').toHaveLocalValue([1, 2, 3, 4]);
		});

		it("should create the array and push if it doesn't exist", function () {
			store.push('list', 1, 2);
			expect('list').toHaveLocalValue([1, 2]);
		});

		it('should return the parent object', function () {
			expect(store.push('key', 1)).toBe(store);
		});
	});

	describe('extend', function () {
		it('should extend the object with the key and value', function () {
			store.set('obj', {a: 1}).extend('obj', 'b', 2);
			expect('obj').toHaveLocalValue({a: 1, b: 2});
		});

		it('should be able to extend with an object', function () {
			store.set('obj', {a: 1}).extend('obj', {b: 2});
			expect('obj').toHaveLocalValue({a: 1, b: 2});
		});

		it("should create the object if it doesn't exist yet", function () {
			store.extend('obj', {a: 1});
			expect('obj').toHaveLocalValue({a: 1});
		});

		it('should return the parent object', function () {
			expect(store.extend('key', 'a', 1)).toBe(store);
		});
	});
});

describe('xStore sessionStorage', function () {
	it('should be operating with sessionstore', function () {
		session.set('a', 'b');
		expect(parse(sessionStorage.getItem('a'))).toBe('b');
	});
});


text:
=============================
ES2015 Symbols in Duktape 2.x
=============================

Overview
========

Duktape 2.x adds ES2015 Symbol support.  Duktape 1.x internal keys are unified
with the Symbol concept, and are considered a custom "hidden symbol" type
which is not normally visible to ECMAScript code.  C code can access hidden
symbols, however.

The internal implementation is similar to existing internal keys.  Symbols
are represented as ``duk_hstring`` heap objects, with the string data
containing a byte prefix which is invalid (extended) UTF-8 so that it can
never occur for normal ECMAScript strings, or even strings with non-BMP
codepoints.  Object coerced strings have a special object class and the
underlying symbol is stored in ``_Value`` similarly to e.g. Number object.

Representation basics:

* Symbols have an external type ``DUK_TYPE_STRING``.

* Symbols have internal type tag ``DUK_TAG_STRING``.

* Symbols can be distinguished internally from ordinary strings by looking
  up the ``DUK_HSTRING_FLAG_SYMBOL`` flag.  Hidden symbols also have the
  ``DUK_HSTRING_FLAG_HIDDEN`` set.

Behavior basics:

* Symbols are visible to ECMAScript code as required by ES2015 and later.
  Hidden symbols are not visible through e.g.
  ``Object.getOwnPropertySymbols()``.  They can only be accessed if a
  reference to the hidden symbol string is somehow available, e.g. via a
  C binding.

* Symbols are visible to the public C API as strings: ``duk_is_string()``
  is true, ``duk_get_string()`` returns a pointer to the symbol internal
  string representation, etc.  C code can create symbols simply by pushing
  C strings with a specific format, see below.

* While symbols are strings in the C API, coercion semantics are based on
  the ECMAScript behavior.  For example, ``duk_to_string()`` applied to a
  symbol throws a ``TypeError``.

See:

* https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol

* http://www.2ality.com/2014/12/es6-symbols.html

Internal key formats
====================

Initial bytes in the ranges [0x00,0x7F] and [0xC0,0xFE] are valid for Duktape's
extended UTF-8 flavor.  The byte 0xFF and the range [0x80,0xBF] are free to be
used as symbol markers.

+-----------------------------------------------+-----------------------------------------------------------------+
| Internal string format                        | Description                                                     |
+-----------------------------------------------+-----------------------------------------------------------------+
| <ff> anyValue                                 | Hidden symbol (Duktape specific) used by application code.      |
|                                               | Prior to Duktape 2.2 Duktape internal hidden symbols also used  |
|                                               | the 0xFF prefix followed by a capital letter (A-Z).  Starting   |
|                                               | from Duktape 2.2 all 0xFF prefixed strings are reserved for     |
|                                               | application code.                                               |
+-----------------------------------------------+-----------------------------------------------------------------+
| <80> symbolDescription                        | Global symbol with description 'symbolDescription' created      |
|                                               | using Symbol.for().                                             |
+-----------------------------------------------+-----------------------------------------------------------------+
| <81> symbolDescription <ff> uniqueSuffix      | Local symbol with description 'symbolDescription'.  Trailing    |
|                                               | unique string makes the symbol unique.  The unique suffix is    |
|                                               | opaque and chosen arbitrarily by Duktape.  It's unique within a |
|                                               | Duktape heap (across all global environments).                  |
+-----------------------------------------------+-----------------------------------------------------------------+
| <81> <ff> uniqueSuffix                        | Local symbol with an empty description.  Unique suffix makes    |
|                                               | each such symbol unique.  The unique suffix is arbitrary but    |
|                                               | must not contain the 0xFF byte.                                 |
+-----------------------------------------------+-----------------------------------------------------------------+
| <81> <ff> uniqueSuffix <ff>                   | Local symbol with undefined description.  ES2015 differentiates |
|                                               | internally between symbols with an empty string description vs. |
|                                               | symbols with an undefined description.                          |
+-----------------------------------------------+-----------------------------------------------------------------+
| <81> symbolDescription <ff>                   | Well known symbol with description 'symbolDescription'.  Well   |
|                                               | known symbols (like Symbol.iterator) are local symbols which    |
|                                               | are still shared across "code realms".  Any fixed suffix never  |
|                                               | colliding with runtime generated unique local symbols works,    |
|                                               | currently an empty suffix is used.                              |
+-----------------------------------------------+-----------------------------------------------------------------+
| <82> anyValue                                 | Hidden symbol (Duktape specific) used by Duktape internals.     |
|                                               | User code should never use this byte prefix or rely on any      |
|                                               | Duktape internal hidden Symbols.                                |
+-----------------------------------------------+-----------------------------------------------------------------+
| <83 to be>                                    | Reserved for future use, behavior is undefined (Duktape 2.1     |
|                                               | interprets as Symbols, Duktape 2.2 does not, don't rely on      |
|                                               | either behavior.                                                |
+-----------------------------------------------+-----------------------------------------------------------------+
| <bf>                                          | Initial byte marker for bytecode dump format since Duktape 2.2. |
+-----------------------------------------------+-----------------------------------------------------------------+
| <00 to 7f>                                    | Valid ASCII initial byte.                                       |
+-----------------------------------------------+-----------------------------------------------------------------+
| <c0 to f7>                                    | Valid standard UTF-8 (or CESU-8) initial byte.                  |
+-----------------------------------------------+-----------------------------------------------------------------+
| <f8 to fe>                                    | Valid extended UTF-8 initial byte.                              |
+-----------------------------------------------+-----------------------------------------------------------------+

There are public API macros (DUK_HIDDEN_SYMBOL() etc) to create symbol literals
from C code.

Global symbols
==============

Global symbols are the same across separate global environments and even across
Duktape heaps.  ES2015 Section 19.4.2.1:

    The GlobalSymbolRegistry is a List that is globally available.
    It is shared by all Code Realms.

and ES2015 Section 8.2:

    Before it is evaluated, all ECMAScript code must be associated with a Realm.
    Conceptually, a realm consists of a set of intrinsic objects, an ECMAScript
    global environment, all of the ECMAScript code that is loaded within the
    scope of that global environment, and other associated state and resources.

The current approach satisfies these simply by making a globally registered
Symbol have a fixed format so that if a Symbol with the same description is
created in another Duktape thread (or even Duktape heap), its internal
representation will be identical.  No explicit registry is maintained.

Well-known symbols
==================

Well-known symbols (such as ``Symbol.iterator``) are distinct from any local or
global symbols.  ES2015 Section 6.1.5.1:

    Well-known symbols are built-in Symbol values that are explicitly referenced
    by algorithms of this specification. They are typically used as the keys of
    properties whose values serve as extension points of a specification algorithm.
    Unless otherwise specified, well-known symbols values are shared by all Code
    Realms (8.2).

The fixed representation described above ensures that well-known symbols are
the same across all code realms (and even across Duktape heaps).  The internal
representation is essentially the same as for a unique local symbol, but the
suffix that makes local symbols unique is missing.  Thus, they behave like
local symbols other than having a fixed representation.

Unifying with Duktape internal keys
===================================

Necessary changes to add symbol behavior:

* Strings with initial byte 0x80, 0x81, 0x82 or 0xFF are flagged as symbols
  (``DUK_HSTRING_FLAG_SYMBOL``).  If the initial byte is 0xFF or 0x82, also
  the hidden symbol flag (``DUK_HSTRING_FLAG_HIDDEN``) is set.

* ``typeof(sym)`` should return "symbol" rather than string.  This is done
  for Duktape hidden symbols too.

* ``ToString(sym)`` must be rejected for a symbol, while ``String(sym)``
  must specifically check for symbols.  Coercion needs to strip possible
  "unique suffix" when coming up with the Symbol description.

* Symbols should be safe from accidental enumeration, JSON serialization, etc.
  This is actually already the case because internal keys are already excluded
  in Duktape 1.x.

* ``Object.getOwnPropertySymbols(``) should return a list of symbol properties
  for an object, but filter out Duktape hidden symbols.

* ``Object(sym)`` should create an object with internal class "Symbol",
  with the plain symbol value stored behind ``_Value`` (hidden symbol
  property) as for Number objects, etc.

* Non-strict comparison needs to handle symbols.  ToPrimitive() coercion
  is maybe enough to ensure ``sym == Object(sym)`` is accepted.

* Property code needs to accept plain Symbols as is (treated like any other
  strings), and Symbol objects should look up their internal string value
  (instead of being coerced to e.g. ``Symbol(symbolDescription)``.  Current
  code just uses ``ToString()`` which causes a TypeError.

* Dozens of similar semantics checks throughout the code base.

Some design questions
=====================

How should C code see Symbols?
------------------------------

Easiest approach:

* Symbols are not enumerated by duk_enum() unless requested.  Either fold in with
  internal keys, add a separate flags.  Maybe rename existing internal keys
  flag.

* Property operations work with symbols and internal keys without distinction.

* API call to create a symbol from C code.  Hides the construction of the internal
  string.

Best naming for Duktape internal keys
-------------------------------------

With https://github.com/svaarala/duktape/pull/979 Duktape internal properties
would become unreachable from ECMAScript code, even if you construct the
internal string using a buffer and then try to use it as an object key.
This offers more protection for sandboxing than ES2015 Symbols which can be
enumerated.

Current naming for Duktape 1.x internal keys is "hidden symbols".  Some
alternatives considered:

* Internal symbol: easy to confuse with specification symbols for example.
  One benefit would be that as a term close to "internal property".

* Hidden symbol: conveys semantics (assuming GH-797) pretty well.

* Private symbol

* Native symbol

* Invisible symbol


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Y!LDA: Unigram_Model_Synchronized_Training_Builder Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

Unigram_Model_Synchronized_Training_Builder Class Reference

#include <Unigram_Model_Synchronized_Training_Builder.h>

Inheritance diagram for Unigram_Model_Synchronized_Training_Builder:

  <map id="Unigram_Model_Synchronized_Training_Builder_map" name="Unigram_Model_Synchronized_Training_Builder_map">
<area href="class_unigram___model___training___builder.html" alt="Unigram_Model_Training_Builder" shape="rect" coords="0,56,285,80"/>
<area href="class_model___builder.html" alt="Model_Builder" shape="rect" coords="0,0,285,24"/>
</map>

List of all members.

Public Member Functions

 	Unigram_Model_Synchronized_Training_Builder ()

virtual 	~Unigram_Model_Synchronized_Training_Builder ()

virtual Execution_Strategy & 	create_execution_strategy (Pipeline &)

Protected Attributes

Synchronizer_Helper * 	_sync_helper

Constructor & Destructor Documentation

          Unigram_Model_Synchronized_Training_Builder::Unigram_Model_Synchronized_Training_Builder
          (

           )

          Unigram_Model_Synchronized_Training_Builder::~Unigram_Model_Synchronized_Training_Builder
          (

           )
           [virtual]

Member Function Documentation

          Execution_Strategy & Unigram_Model_Synchronized_Training_Builder::create_execution_strategy
          (
          Pipeline &
           pipeline
           )
           [virtual]

Reimplemented from Unigram_Model_Training_Builder.

Member Data Documentation

          Synchronizer_Helper* Unigram_Model_Synchronized_Training_Builder::_sync_helper [protected]

The documentation for this class was generated from the following files:

src/Unigram_Model/TopicLearner/Unigram_Model_Synchronized_Training_Builder.h

src/Unigram_Model/TopicLearner/Unigram_Model_Synchronized_Training_Builder.cpp

<address style="text-align: right;">Generated on Tue Jul 19 11:45:29 2011 for Y!LDA by

 1.6.3 </address>


text:
package org.keycloak.services.resources;

import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.common.ClientConnection;
import org.keycloak.common.util.MimeTypeUtil;
import org.keycloak.models.BrowserSecurityHeaders;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.services.ForbiddenException;
import org.keycloak.services.ServicesLogger;
import org.keycloak.services.managers.ApplianceBootstrap;
import org.keycloak.services.util.CacheControlUtil;
import org.keycloak.services.util.CookieHelper;
import org.keycloak.theme.BrowserSecurityHeaderSetup;
import org.keycloak.theme.FreeMarkerUtil;
import org.keycloak.theme.Theme;
import org.keycloak.theme.ThemeProvider;
import org.keycloak.utils.MediaType;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Stian Thorgersen
 */
@Path("/")
public class WelcomeResource {

    protected static final Logger logger = Logger.getLogger(WelcomeResource.class);

    private static final String KEYCLOAK_STATE_CHECKER = "KEYCLOAK_STATE_CHECKER";

    private boolean bootstrap;

    @Context
    protected HttpHeaders headers;

    @Context
    private UriInfo uriInfo;

    @Context
    private KeycloakSession session;

    public WelcomeResource(boolean bootstrap) {
        this.bootstrap = bootstrap;
    }

    /**
     * Welcome page of Keycloak
     *
     * @return
     * @throws URISyntaxException
     */
    @GET
    @Produces(MediaType.TEXT_HTML_UTF_8)
    public Response getWelcomePage() throws URISyntaxException {
        checkBootstrap();

        String requestUri = uriInfo.getRequestUri().toString();
        if (!requestUri.endsWith("/")) {
            return Response.seeOther(new URI(requestUri + "/")).build();
        } else {
            return createWelcomePage(null, null);
        }
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response createUser(final MultivaluedMap<String, String> formData) {
        checkBootstrap();

        if (!bootstrap) {
            return createWelcomePage(null, null);
        } else {
            if (!isLocal()) {
                ServicesLogger.LOGGER.rejectedNonLocalAttemptToCreateInitialUser(session.getContext().getConnection().getRemoteAddr());
                throw new WebApplicationException(Response.Status.BAD_REQUEST);
            }

            String cookieStateChecker = getCsrfCookie();
            String formStateChecker = formData.getFirst("stateChecker");
            csrfCheck(cookieStateChecker, formStateChecker);

            String username = formData.getFirst("username");
            String password = formData.getFirst("password");
            String passwordConfirmation = formData.getFirst("passwordConfirmation");

            if (username == null || username.length() == 0) {
                return createWelcomePage(null, "Username is missing");
            }

            if (password == null || password.length() == 0) {
                return createWelcomePage(null, "Password is missing");
            }

            if (!password.equals(passwordConfirmation)) {
                return createWelcomePage(null, "Password and confirmation doesn't match");
            }

            ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
            if (applianceBootstrap.isNoMasterUser()) {
                bootstrap = false;
                applianceBootstrap.createMasterRealmUser(username, password);

                ServicesLogger.LOGGER.createdInitialAdminUser(username);
                return createWelcomePage("User created", null);
            } else {
                ServicesLogger.LOGGER.initialUserAlreadyCreated();
                return createWelcomePage(null, "Users already exists");
            }
        }
    }

    /**
     * Resources for welcome page
     *
     * @param path
     * @return
     */
    @GET
    @Path("/welcome-content/{path}")
    @Produces(MediaType.TEXT_HTML_UTF_8)
    public Response getResource(@PathParam("path") String path) {
        try {
            InputStream resource = getTheme().getResourceAsStream(path);
            if (resource != null) {
                String contentType = MimeTypeUtil.getContentType(path);
                Response.ResponseBuilder builder = Response.ok(resource).type(contentType).cacheControl(CacheControlUtil.getDefaultCacheControl());
                return builder.build();
            } else {
                return Response.status(Response.Status.NOT_FOUND).build();
            }
        } catch (IOException e) {
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    private Response createWelcomePage(String successMessage, String errorMessage) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("bootstrap", bootstrap);
            if (bootstrap) {
                boolean isLocal = isLocal();
                map.put("localUser", isLocal);

                if (isLocal) {
                    String stateChecker = updateCsrfChecks();
                    map.put("stateChecker", stateChecker);
                }
            }
            if (successMessage != null) {
                map.put("successMessage", successMessage);
            }
            if (errorMessage != null) {
                map.put("errorMessage", errorMessage);
            }
            FreeMarkerUtil freeMarkerUtil = new FreeMarkerUtil();
            String result = freeMarkerUtil.processTemplate(map, "index.ftl", getTheme());

            ResponseBuilder rb = Response.status(errorMessage == null ? Status.OK : Status.BAD_REQUEST)
                    .entity(result)
                    .cacheControl(CacheControlUtil.noCache());
            BrowserSecurityHeaderSetup.headers(rb, BrowserSecurityHeaders.defaultHeaders);
            return rb.build();
        } catch (Exception e) {
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    private Theme getTheme() {
        Config.Scope config = Config.scope("theme");
        ThemeProvider themeProvider = session.getProvider(ThemeProvider.class, "extending");
        try {
            return themeProvider.getTheme(config.get("welcomeTheme"), Theme.Type.WELCOME);
        } catch (IOException e) {
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    private void checkBootstrap() {
        if (bootstrap) {
            bootstrap  = new ApplianceBootstrap(session).isNoMasterUser();
        }
    }

    private boolean isLocal() {
        try {
            ClientConnection clientConnection = session.getContext().getConnection();
            InetAddress remoteInetAddress = InetAddress.getByName(clientConnection.getRemoteAddr());
            InetAddress localInetAddress = InetAddress.getByName(clientConnection.getLocalAddr());
            String xForwardedFor = headers.getHeaderString("X-Forwarded-For");
            logger.debugf("Checking WelcomePage. Remote address: %s, Local address: %s, X-Forwarded-For header: %s", remoteInetAddress.toString(), localInetAddress.toString(), xForwardedFor);

            // Access through AJP protocol (loadbalancer) may cause that remoteAddress is "127.0.0.1".
            // So consider that welcome page accessed locally just if it was accessed really through "localhost" URL and without loadbalancer (x-forwarded-for header is empty).
            return isLocalAddress(remoteInetAddress) && isLocalAddress(localInetAddress) && xForwardedFor == null;
        } catch (UnknownHostException e) {
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    private boolean isLocalAddress(InetAddress inetAddress) {
        return inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress();
    }

    private String updateCsrfChecks() {
        String stateChecker = getCsrfCookie();
        if (stateChecker != null) {
            return stateChecker;
        } else {
            stateChecker = KeycloakModelUtils.generateSecret();
            String cookiePath = uriInfo.getPath();
            boolean secureOnly = uriInfo.getRequestUri().getScheme().equalsIgnoreCase("https");
            CookieHelper.addCookie(KEYCLOAK_STATE_CHECKER, stateChecker, cookiePath, null, null, -1, secureOnly, true);
            return stateChecker;
        }
    }

    private String getCsrfCookie() {
        Cookie cookie = headers.getCookies().get(KEYCLOAK_STATE_CHECKER);
        return cookie==null ? null : cookie.getValue();
    }

    private void csrfCheck(String cookieStateChecker, String formStateChecker) {
        if (cookieStateChecker == null || !cookieStateChecker.equals(formStateChecker)) {
            throw new ForbiddenException();
        }
    }

}


text:
<?php

namespace Google\AdsApi\Dfp\v201611;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class DeactivateLabels extends \Google\AdsApi\Dfp\v201611\LabelAction
{

    public function __construct()
    {

    }

}


text:
package webapi

import (
	"bufio"
	"encoding/json"
	"fmt"
	"sconsify/infrastructure"
	"github.com/zmb3/spotify"
	"golang.org/x/oauth2"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"time"
	"os/exec"
)

var token *oauth2.Token
var auth spotify.Authenticator

func Auth(spotifyClientId string, authRedirectUrl string, cacheWebApiToken bool, openBrowserCommand string) (*spotify.Client, error) {
	if spotifyClientId == "" {
		fmt.Print("Spotify Client ID not set")
		return nil, nil
	}

	auth = spotify.NewAuthenticator(authRedirectUrl,
		spotify.ScopeUserLibraryRead,
		spotify.ScopeUserFollowRead,
		spotify.ScopePlaylistReadCollaborative,
		spotify.ScopePlaylistReadPrivate)

	auth.SetAuthInfo(spotifyClientId, "")

	LoadTokenFromFile()
	if token == nil || HasTokenExpired() {
		url := auth.AuthURL("")
		url = strings.Replace(url, "response_type=code", "response_type=token", -1)

		if openBrowserCommand != "" {
			fmt.Printf("\nOpen browser command provided: %v %v\n\n", openBrowserCommand, url)
			cmd := exec.Command(openBrowserCommand, url)
			if err := cmd.Run(); err != nil {
				return nil, err
			}
		} else {
			fmt.Printf("For web api authorization go to url:\n\n%v\n\n", url)
		}

		fmt.Print("And paste the access token here: ")
		reader := bufio.NewReader(os.Stdin)
		accessToken, _ := reader.ReadString('\n')
		accessToken = strings.Trim(accessToken, " \n\r")

		result := strings.Split(accessToken, " ")

		seconds, err := strconv.ParseInt(strings.Split(result[2], ":")[1], 10, 64)
		if err != nil {
			fmt.Printf("Error %v\n", err)
			return nil, err
		}
		expiry := time.Now().Add(time.Duration(seconds) * time.Second)
		token = &oauth2.Token{
			AccessToken: strings.Split(result[0], ":")[1],
			TokenType:   strings.Split(result[1], ":")[1],
			Expiry:      expiry,
		}
		if cacheWebApiToken {
			persistToken(token)
		}
	} else {
		fmt.Println("Token still valid")
	}

	client := NewClient()
	return &client, nil
}

func NewClient() spotify.Client {
	return auth.NewClient(token)
}

func HasTokenExpired() bool {
	return hasExpired(token.Expiry)
}

func hasExpired(expiry time.Time) bool {
	return expiry.Before(time.Now())
}

func LoadTokenFromFile() {
	token = loadTokenFromFile()
}

func loadTokenFromFile() *oauth2.Token {
	if fileLocation := infrastructure.GetWebApiTokenLocation(); fileLocation != "" {
		if b, err := ioutil.ReadFile(fileLocation); err == nil {
			var token *oauth2.Token
			if err := json.Unmarshal(b, &token); err == nil {
				return token
			}
		}
	}
	return nil
}

func persistToken(token *oauth2.Token) {
	if b, err := json.Marshal(token); err == nil {
		if fileLocation := infrastructure.GetWebApiTokenLocation(); fileLocation != "" {
			infrastructure.SaveFile(fileLocation, b)
		}
	}
}


text:
"""Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import TracebackType
from typing import (  # noqa: F401 pylint: disable=unused-import
    Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union)

from homeassistant.loader import bind_hass
import homeassistant.util.dt as dt_util
from homeassistant.components.notify import (
    ATTR_MESSAGE, SERVICE_NOTIFY)
from homeassistant.components.sun import (
    STATE_ABOVE_HORIZON, STATE_BELOW_HORIZON)
from homeassistant.components.mysensors.switch import (
    ATTR_IR_CODE, SERVICE_SEND_IR_CODE)
from homeassistant.components.cover import (
    ATTR_POSITION, ATTR_TILT_POSITION)
from homeassistant.const import (
    ATTR_ENTITY_ID, ATTR_OPTION, SERVICE_ALARM_ARM_AWAY,
    SERVICE_ALARM_ARM_HOME, SERVICE_ALARM_DISARM, SERVICE_ALARM_TRIGGER,
    SERVICE_LOCK, SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_UNLOCK,
    SERVICE_OPEN_COVER,
    SERVICE_CLOSE_COVER, SERVICE_SET_COVER_POSITION,
    SERVICE_SET_COVER_TILT_POSITION, STATE_ALARM_ARMED_AWAY,
    STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED,
    STATE_CLOSED, STATE_HOME, STATE_LOCKED, STATE_NOT_HOME, STATE_OFF,
    STATE_ON, STATE_OPEN, STATE_UNKNOWN,
    STATE_UNLOCKED, SERVICE_SELECT_OPTION)
from homeassistant.core import (
    Context, State, DOMAIN as HASS_DOMAIN)
from homeassistant.util.async_ import run_coroutine_threadsafe
from .typing import HomeAssistantType

_LOGGER = logging.getLogger(__name__)

GROUP_DOMAIN = 'group'

# Update this dict of lists when new services are added to HA.
# Each item is a service with a list of required attributes.
SERVICE_ATTRIBUTES = {
    SERVICE_NOTIFY: [ATTR_MESSAGE],
    SERVICE_SEND_IR_CODE: [ATTR_IR_CODE],
    SERVICE_SELECT_OPTION: [ATTR_OPTION],
    SERVICE_SET_COVER_POSITION: [ATTR_POSITION],
    SERVICE_SET_COVER_TILT_POSITION: [ATTR_TILT_POSITION]
}

# Update this dict when new services are added to HA.
# Each item is a service with a corresponding state.
SERVICE_TO_STATE = {
    SERVICE_TURN_ON: STATE_ON,
    SERVICE_TURN_OFF: STATE_OFF,
    SERVICE_ALARM_ARM_AWAY: STATE_ALARM_ARMED_AWAY,
    SERVICE_ALARM_ARM_HOME: STATE_ALARM_ARMED_HOME,
    SERVICE_ALARM_DISARM: STATE_ALARM_DISARMED,
    SERVICE_ALARM_TRIGGER: STATE_ALARM_TRIGGERED,
    SERVICE_LOCK: STATE_LOCKED,
    SERVICE_UNLOCK: STATE_UNLOCKED,
    SERVICE_OPEN_COVER: STATE_OPEN,
    SERVICE_CLOSE_COVER: STATE_CLOSED
}

class AsyncTrackStates:
    """
    Record the time when the with-block is entered.

    Add all states that have changed since the start time to the return list
    when with-block is exited.

    Must be run within the event loop.
    """

    def __init__(self, hass: HomeAssistantType) -> None:
        """Initialize a TrackStates block."""
        self.hass = hass
        self.states = []  # type: List[State]

    # pylint: disable=attribute-defined-outside-init
    def __enter__(self) -> List[State]:
        """Record time from which to track changes."""
        self.now = dt_util.utcnow()
        return self.states

    def __exit__(self, exc_type: Optional[Type[BaseException]],
                 exc_value: Optional[BaseException],
                 traceback: Optional[TracebackType]) -> None:
        """Add changes states to changes list."""
        self.states.extend(get_changed_since(self.hass.states.async_all(),
                                             self.now))

def get_changed_since(states: Iterable[State],
                      utc_point_in_time: dt.datetime) -> List[State]:
    """Return list of states that have been changed since utc_point_in_time."""
    return [state for state in states
            if state.last_updated >= utc_point_in_time]

@bind_hass
def reproduce_state(hass: HomeAssistantType,
                    states: Union[State, Iterable[State]],
                    blocking: bool = False) -> None:
    """Reproduce given state."""
    return run_coroutine_threadsafe(  # type: ignore
        async_reproduce_state(hass, states, blocking), hass.loop).result()

@bind_hass
async def async_reproduce_state(
        hass: HomeAssistantType,
        states: Union[State, Iterable[State]],
        blocking: bool = False,
        context: Optional[Context] = None) -> None:
    """Reproduce a list of states on multiple domains."""
    if isinstance(states, State):
        states = [states]

    to_call = defaultdict(list)  # type: Dict[str, List[State]]

    for state in states:
        to_call[state.domain].append(state)

    async def worker(domain: str, data: List[State]) -> None:
        component = getattr(hass.components, domain)
        if hasattr(component, 'async_reproduce_states'):
            await component.async_reproduce_states(
                data,
                context=context)
        else:
            await async_reproduce_state_legacy(
                hass,
                domain,
                data,
                blocking=blocking,
                context=context)

    if to_call:
        # run all domains in parallel
        await asyncio.gather(*[
            worker(domain, data)
            for domain, data in to_call.items()
        ])

@bind_hass
async def async_reproduce_state_legacy(
        hass: HomeAssistantType,
        domain: str,
        states: Iterable[State],
        blocking: bool = False,
        context: Optional[Context] = None) -> None:
    """Reproduce given state."""
    to_call = defaultdict(list)  # type: Dict[Tuple[str, str], List[str]]

    if domain == GROUP_DOMAIN:
        service_domain = HASS_DOMAIN
    else:
        service_domain = domain

    for state in states:

        if hass.states.get(state.entity_id) is None:
            _LOGGER.warning("reproduce_state: Unable to find entity %s",
                            state.entity_id)
            continue

        domain_services = hass.services.async_services().get(service_domain)

        if not domain_services:
            _LOGGER.warning(
                "reproduce_state: Unable to reproduce state %s (1)", state)
            continue

        service = None
        for _service in domain_services.keys():
            if (_service in SERVICE_ATTRIBUTES and
                    all(attr in state.attributes
                        for attr in SERVICE_ATTRIBUTES[_service]) or
                    _service in SERVICE_TO_STATE and
                    SERVICE_TO_STATE[_service] == state.state):
                service = _service
            if (_service in SERVICE_TO_STATE and
                    SERVICE_TO_STATE[_service] == state.state):
                break

        if not service:
            _LOGGER.warning(
                "reproduce_state: Unable to reproduce state %s (2)", state)
            continue

        # We group service calls for entities by service call
        # json used to create a hashable version of dict with maybe lists in it
        key = (service,
               json.dumps(dict(state.attributes), sort_keys=True))
        to_call[key].append(state.entity_id)

    domain_tasks = []  # type: List[Awaitable[Optional[bool]]]
    for (service, service_data), entity_ids in to_call.items():
        data = json.loads(service_data)
        data[ATTR_ENTITY_ID] = entity_ids

        domain_tasks.append(
            hass.services.async_call(service_domain, service, data, blocking,
                                     context)
        )

    if domain_tasks:
        await asyncio.wait(domain_tasks, loop=hass.loop)

def state_as_number(state: State) -> float:
    """
    Try to coerce our state to a number.

    Raises ValueError if this is not possible.
    """
    from homeassistant.components.climate.const import (
        STATE_HEAT, STATE_COOL, STATE_IDLE)

    if state.state in (STATE_ON, STATE_LOCKED, STATE_ABOVE_HORIZON,
                       STATE_OPEN, STATE_HOME, STATE_HEAT, STATE_COOL):
        return 1
    if state.state in (STATE_OFF, STATE_UNLOCKED, STATE_UNKNOWN,
                       STATE_BELOW_HORIZON, STATE_CLOSED, STATE_NOT_HOME,
                       STATE_IDLE):
        return 0

    return float(state.state)


text:
<form>
    <input type="radio" name="q" value="one">
    <input type="radio" name="q" value="two">
    <input type="radio" name="q" value="three">
    <br>
    <input type="submit">
</form>


text:
<?php

class Google_Service_DisplayVideo_AdvertiserCreativeConfig extends Google_Model
{
  public $dynamicCreativeEnabled;
  public $iasClientId;
  public $obaComplianceDisabled;
  public $videoCreativeDataSharingAuthorized;

  public function setDynamicCreativeEnabled($dynamicCreativeEnabled)
  {
    $this->dynamicCreativeEnabled = $dynamicCreativeEnabled;
  }
  public function getDynamicCreativeEnabled()
  {
    return $this->dynamicCreativeEnabled;
  }
  public function setIasClientId($iasClientId)
  {
    $this->iasClientId = $iasClientId;
  }
  public function getIasClientId()
  {
    return $this->iasClientId;
  }
  public function setObaComplianceDisabled($obaComplianceDisabled)
  {
    $this->obaComplianceDisabled = $obaComplianceDisabled;
  }
  public function getObaComplianceDisabled()
  {
    return $this->obaComplianceDisabled;
  }
  public function setVideoCreativeDataSharingAuthorized($videoCreativeDataSharingAuthorized)
  {
    $this->videoCreativeDataSharingAuthorized = $videoCreativeDataSharingAuthorized;
  }
  public function getVideoCreativeDataSharingAuthorized()
  {
    return $this->videoCreativeDataSharingAuthorized;
  }
}


text:
package middleware

import (
	"net/http"
	"../controller"
)

func AuthMiddleware(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, *http.Request){
	err := controller.IsAdmin(w, r)
	if err != nil{
		http.Redirect(w, r, "/login", 303)
	}
	return w, r
}


text:
  <!doctype html>

      <meta charset="utf-8">
      <title>News Article</title>

      <link rel="canonical" href="<%host%>/samples_templates/news_article/">

      <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

A sample AMP Article

This is a sample article demonstrating how to write a news article in AMP. It demonstrates the usage of AMP components which works well in news articles. Examples include social sharing, image galleries, personalized content, ads, and more.

by Sebastian Benz

      <amp-social-share type="twitter" width="45" height="33"></amp-social-share>
      <amp-social-share type="facebook" width="45" height="33" data-attribution="254325784911610"></amp-social-share>
      <amp-social-share type="gplus" width="45" height="33"></amp-social-share>
      <amp-social-share type="email" width="45" height="33"></amp-social-share>
      <amp-social-share type="pinterest" width="45" height="33"></amp-social-share>

Lorem ipsum dolor sit amet, voluptua oporteat cum cu, eu vix interesset scribentur. Et iudico efficiendi duo, vim an odio iusto reformidans. At maluisset scripserit duo, cum in sumo delenit. Quot erant maiestatis usu ut. Ne mea maiorum vivendum argumentum, tale utinam postea mei in, eam in odio dicta patrioque.

      Cum ad graeci legimus, ut duo omnesque petentium, mei saepe explicari principes eu. Ex mei ocurreret expetendis, ex errem blandit has. Phaedrum mediocrem appellantur his ut. Erat viris mediocrem id ius, ad dicta appareat assentior sit. Nec et nullam singulis moderatius, est reque vidisse copiosae eu.

      Mutat dolores ea duo. Usu cu dico everti tincidunt, pri vero nullam vidisse no. Eam novum aeque populo cu. Verear contentiones ne quo, no sed consulatu definitionem.

        <amp-img src="/img/landscape_village_1280x853.jpg" width="1280" height="768" layout="responsive"></amp-img>

Here is a responsive image.

Lorem ipsum dolor sit amet, voluptua oporteat cum cu, eu vix interesset scribentur. Et iudico efficiendi duo, vim an odio iusto reformidans. At maluisset scripserit duo, cum in sumo delenit. Quot erant maiestatis usu ut. Ne mea maiorum vivendum argumentum, tale utinam postea mei in, eam in odio dicta patrioque.

        <amp-ad width="300" height="250"
                            type="a9"
                            data-aax_size="300x250"
                            data-aax_pubname="test123"
                            data-aax_src="302">
        </amp-ad>

      Cum ad graeci legimus, ut duo omnesque petentium, mei saepe explicari principes eu. Ex mei ocurreret expetendis, ex errem blandit has. Phaedrum mediocrem appellantur his ut. Erat viris mediocrem id ius, ad dicta appareat assentior sit. Nec et nullam singulis moderatius, est reque vidisse copiosae eu.

      Mutat dolores ea duo. Usu cu dico everti tincidunt, pri vero nullam vidisse no. Eam novum aeque populo cu. Verear contentiones ne quo, no sed consulatu definitionem.

      Cum ad graeci legimus, ut duo omnesque petentium, mei saepe explicari principes eu. Ex mei ocurreret expetendis, ex errem blandit has. Phaedrum mediocrem appellantur his ut. Erat viris mediocrem id ius, ad dicta appareat assentior sit. Nec et nullam singulis moderatius, est reque vidisse copiosae eu.

      Mutat dolores ea duo. Usu cu dico everti tincidunt, pri vero nullam vidisse no. Eam novum aeque populo cu. Verear contentiones ne quo, no sed consulatu definitionem.

      <amp-carousel width="1280" height="1000" layout="responsive" type="slides">

          <amp-img src="/img/landscape_lake_1280x857.jpg" width="1280" height="857" layout="responsive"></amp-img>

Each image has a different caption.

          <amp-img src="/img/landscape_village_1280x853.jpg" width="1280" height="853" layout="responsive"></amp-img>

This caption is different.

          <amp-img src="/img/landscape_desert_1280x853.jpg" width="1280" height="853" layout="responsive"></amp-img>

The third image has its caption.

      </amp-carousel>

Lorem ipsum dolor sit amet, voluptua oporteat cum cu, eu vix interesset scribentur. Et iudico efficiendi duo, vim an odio iusto reformidans. At maluisset scripserit duo, cum in sumo delenit. Quot erant maiestatis usu ut. Ne mea maiorum vivendum argumentum, tale utinam postea mei in, eam in odio dicta patrioque.

      Cum ad graeci legimus, ut duo omnesque petentium, mei saepe explicari principes eu. Ex mei ocurreret expetendis, ex errem blandit has. Phaedrum mediocrem appellantur his ut. Erat viris mediocrem id ius, ad dicta appareat assentior sit. Nec et nullam singulis moderatius, est reque vidisse copiosae eu.

      Mutat dolores ea duo. Usu cu dico everti tincidunt, pri vero nullam vidisse no. Eam novum aeque populo cu. Verear contentiones ne quo, no sed consulatu definitionem.

        <amp-iframe src="https://www.google.us/trends/embed/US_cu_82I1CVMBAACV6M_en/horserace_chart_3c6cdb21-e1eb-4412-9c28-707c3638ea35?hl=en&template=fe"
                    title="Interactive chart displaying 2016 Oscar Best Picture search interest by date"
                    height="360"
                    layout="fixed-height"
                    frameborder="0"
                    sandbox="allow-scripts allow-same-origin">
          <amp-img src="/img/oscars_placeholder_1.png"
                   layout="fixed-height"
                   height="360"
                   width="auto"
                   placeholder>
          </amp-img>
        </amp-iframe>

An interactive chart - in AMP!

Lorem ipsum dolor sit amet, voluptua oporteat cum cu, eu vix interesset scribentur. Et iudico efficiendi duo, vim an odio iusto reformidans. At maluisset scripserit duo, cum in sumo delenit. Quot erant maiestatis usu ut. Ne mea maiorum vivendum argumentum, tale utinam postea mei in, eam in odio dicta patrioque.

      Cum ad graeci legimus, ut duo omnesque petentium, mei saepe explicari principes eu. Ex mei ocurreret expetendis, ex errem blandit has. Phaedrum mediocrem appellantur his ut. Erat viris mediocrem id ius, ad dicta appareat assentior sit. Nec et nullam singulis moderatius, est reque vidisse copiosae eu.

      Mutat dolores ea duo. Usu cu dico everti tincidunt, pri vero nullam vidisse no. Eam novum aeque populo cu. Verear contentiones ne quo, no sed consulatu definitionem.

Related Articles

These articles might be interesting for you as well:

      <amp-list width="300" height="75" layout="responsive" src="/json/related_articles.json">
        <template type="amp-mustache">
          <amp-img width="101" height="75" src="{{thumbnail}}"></amp-img>{{title}}
        </template>
      </amp-list>

      <amp-user-notification class="cookie-disclaimer" layout="nodisplay" id="amp-user-notification1">
        This page might use cookies if your analytics vendor requires them.
        <button on="tap:amp-user-notification1.dismiss">Accept</button>
      </amp-user-notification>

      <amp-analytics type="googleanalytics">

      </amp-analytics>