text:
// Copyright (c) 2020 The DÃSH Core Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_QT_APPEARANCEWIDGET_H
#define BITCOIN_QT_APPEARANCEWIDGET_H

#include <QWidget>

#include <qt/guiutil.h>

namespace Ui {
class AppearanceWidget;
}

class OptionsModel;

class QDataWidgetMapper;
class QSlider;
class QComboBox;

class AppearanceWidget : public QWidget
{
    Q_OBJECT

public:
    explicit AppearanceWidget(QWidget* parent = 0);
    ~AppearanceWidget();

    void setModel(OptionsModel* model);

Q_SIGNALS:
    void appearanceChanged();

public Q_SLOTS:
    void accept();

private Q_SLOTS:
    void updateTheme(const QString& toTheme = QString());
    void updateFontFamily(int index);
    void updateFontScale(int nScale);
    void updateFontWeightNormal(int nValue, bool fForce = false);
    void updateFontWeightBold(int nValue, bool fForce = false);

private:
    Ui::AppearanceWidget* ui;
    QDataWidgetMapper* mapper;
    OptionsModel* model;
    bool fAcceptChanges;
    QString prevTheme;
    int prevScale;
    GUIUtil::FontFamily prevFontFamily;
    QFont::Weight prevWeightNormal;
    QFont::Weight prevWeightBold;

    void updateWeightSlider(bool fForce = false);
};

#endif // BITCOIN_QT_APPEARANCEWIDGET_H


text:
using System;
using System.Linq;
using System.Collections.Generic;
using bugTrapKit.DoneDone;
using bugTrapKit.Pivotal;
using bugTrapKit.Jira;
using System.Threading.Tasks;

namespace bugTrapKit
{
	public class TrackerService
	{
		// static readonly TrackerService shared = new TrackerService ();

		public static TrackerService Shared { get; } = new TrackerService ();

		public TrackerService ()
		{

		}

		// trackerType drives the state of the app
		// (i.e. if there is a trackerType set, we know we're in a 'new Issue' flow)
		// So it's very important to set it back to .None
		TrackerType trackerType = TrackerType.None;

		Dictionary<TrackerType, Tracker> trackers = new Dictionary<TrackerType, Tracker> ();

		public async void Authenticate ()
		{
			var tasks = new List<Task<bool>> ();

			foreach (var type in TrackerTypes.Values.Where(t => t.Enabled())) {

				tasks.Add(GetTrackerInstance(type).Authenticate(TrackerHasAuthCredentials(type)));
			}

			await Task.WhenAll(tasks);
		}

		public Tracker CurrentTracker {
			get { return trackerType.Enabled() ? trackers[trackerType] ?? GetTrackerInstance(trackerType) : null; }
		}

		public bool HasCurrentAuthenticatedTracker {
			get { return trackerType != TrackerType.None && CurrentTracker != null && CurrentTracker.Authenticated; }
		}

		public void ResetAndRemoveCurrentTracker ()
		{
			CurrentTracker.TrackerState.Reset();
			trackerType = TrackerType.None;
		}

		public List<TrackerType> GetTrackerTypesByStatus (TrackerStatus status)
		{
			return TrackerTypes.Values.Where(t => t.Status() == status).ToList();
		}

		public Dictionary<TrackerStatus, List<TrackerType>> GetTrackerTypesByStatus ()
		{
			return TrackerTypes.Values.GroupBy(t => t.Status(), t => t).ToDictionary(g => g.Key, v => v.ToList());
		}

		public Dictionary<TrackerType, string> GetUsernamesForEnabledTrackerTypes (List<TrackerType> enabledTrackerTypes)
		{
			var dictionary = new Dictionary<TrackerType, string> ();

			foreach (var t in enabledTrackerTypes) {

				var username = string.Empty;

				(new Keychain<TrackerType> (t))?.GetStoredKeyValues()?.TryGetValue(DataKeys.UserName, out username);

				dictionary.Add(t, username);

				// if (!string.IsNullOrEmpty(username)) dictionary.Add(t, username);
			}

			return dictionary;
			// return enabledTrackerTypes.ToDictionary(t => t, v => (new Keychain<TrackerType> (v))?.GetStoredKeyValues()?[DataKeys.UserName] ?? string.Empty);
		}

		/// <summary>
		/// Sets the type of the current tracker.
		/// </summary>
		/// <returns><c>true</c>, if the keys needed are in the keychain, <c>false</c> otherwise.</returns>
		/// <param name="trackerType">Tracker type.</param>
		public bool SetCurrentTrackerType (TrackerType trackerType)
		{
			this.trackerType = trackerType;

			return trackerType == TrackerType.None || TrackerHasAuthCredentials(trackerType) != null;
		}

		/// <summary>
		/// Trackers the has auth credentials.
		/// </summary>
		/// <returns>the dictionary if the keys needed are in the keychain, <c>null</c> otherwise.</returns>
		/// <param name="trackerType">Tracker type.</param>
		public Dictionary<DataKeys, string> TrackerHasAuthCredentials (TrackerType trackerType)
		{
			var storedValues = new Keychain<TrackerType> (trackerType).GetStoredKeyValues();

			return trackerType.Valid(storedValues) ? storedValues : null;
		}

		public Tracker GetTrackerInstance (TrackerType trackerType)
		{
			if (trackers.ContainsKey(trackerType)) return trackers[trackerType];

			switch (trackerType) {
			case TrackerType.DoneDone:
				trackers[trackerType] = new DoneDoneTracker (trackerType);
				break;
			case TrackerType.PivotalTracker:
				trackers[trackerType] = new PivotalTracker (trackerType);
				break;
			case TrackerType.JIRA:
				trackers[trackerType] = new JiraTracker (trackerType);
				break;
			default:
				return null;
			}

			return trackers[trackerType];
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

describe Redis::Store::VERSION do
  it 'returns current version' do
    Redis::Store::VERSION.must_equal '1.1.4'
  end
end


text:
module Storey
  class GenDumpCommand

    def self.call(
      database_url: Storey.configuration.database_url,
      database: nil,
      host: nil,
      username: nil,
      structure_only: false,
      file: nil,
      schemas: nil,
      password: nil
    )
      switches = {}

      if database_url.nil?
        if database.blank?
          raise ArgumentError, 'database must be supplied'
        end

        switches['host'] = host if host.present?
        switches['username'] = username if username.present?
      end

      switches['schema-only'] = nil if structure_only
      switches['no-privileges'] = nil
      switches['no-owner'] = nil
      switches[:file] = Shellwords.escape(file)

      if schemas
        schemas = schemas.split(',')
        schemas_switches = schemas.map do |part|
          Utils.command_line_switches_from({schema: Shellwords.escape(part) })
        end
      end

      command_parts = []
      if password.present?
        command_parts << "PGPASSWORD=#{password}"
      end
      command_parts << "pg_dump"
      command_parts << database_url if database_url.present?
      command_parts += [
        Utils.command_line_switches_from(switches),
        schemas_switches,
      ]
      command_parts << database if database_url.blank?
      command_parts.compact.join(' ')
    end

  end
end


text:
ACCEPTED

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

#### Published in
null

#### Original name
Sphaeria frit Fr., 1823

### Remarks
null


text:
package org.apache.openwhisk.core.service

import akka.actor.{Actor, ActorRef, ActorRefFactory, ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestActor, TestActorRef, TestKit, TestProbe}
import akka.util.Timeout
import common.StreamLogging
import org.apache.openwhisk.core.entity.SchedulerInstanceId
import org.junit.runner.RunWith
import org.scalamock.scalatest.MockFactory
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.junit.JUnitRunner
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}

import scala.collection.mutable
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random

@RunWith(classOf[JUnitRunner])
class DataManagementServiceTests
    extends TestKit(ActorSystem("DataManagementService"))
    with ImplicitSender
    with FlatSpecLike
    with ScalaFutures
    with Matchers
    with MockFactory
    with BeforeAndAfterAll
    with StreamLogging {

  implicit val timeout: Timeout = Timeout(5.seconds)
  implicit val ec: ExecutionContext = system.dispatcher

  val schedulerId = SchedulerInstanceId("scheduler0")
  val instanceId = schedulerId
  val leaseService = TestProbe()
  val watcherName = "data-management-service"
  leaseService.setAutoPilot((sender: ActorRef, msg: Any) =>
    msg match {
      case GetLease =>
        sender ! Lease(10, 10)
        TestActor.KeepRunning

      case _ =>
        TestActor.KeepRunning
  })

  private def etcdWorkerFactory(actor: ActorRef) = { (_: ActorRefFactory) =>
    actor
  }

  behavior of "DataManagementService"

  it should "distribute work to etcd worker" in {
    val watcherService = TestProbe()
    val worker = TestProbe()

    val key = "testKey"
    val value = "testValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, etcdWorkerFactory(worker.ref)))

    val requests = Seq(
      RegisterData(key, value),
      ElectLeader(key, value, self),
      RegisterInitialData(key, value, recipient = Some(testActor)),
      WatcherClosed(key, false))

    requests.foreach { request =>
      service ! request
      worker.expectMsg(request)

      service ! FinishWork(key)
    }
  }

  it should "handle request sequentially for a same key" in {
    val queue = mutable.Queue.empty[String]
    val watcherService = TestProbe()
    val workerFactory = (f: ActorRefFactory) =>
      f.actorOf(Props(new Actor {
        override def receive: Receive = {
          case request: RegisterData =>
            if (request.value == "async")
              Future {
                Thread.sleep(1000)
                queue.enqueue(request.value)
                context.parent ! FinishWork(request.key)
              } else {
              queue.enqueue(request.value)
              context.parent ! FinishWork(request.key)
            }
        }
      }))

    val key = "testKey"
    val value = "testValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, workerFactory))

    // the first request will be handled asynchronously, but as the second request has the same key, it will always
    // processed after the first request is finished
    val requests = Seq(RegisterData(key, "async"), RegisterData(key, value))

    requests.foreach { request =>
      service ! request
    }

    Thread.sleep(2000) // wait for two requests are completed
    queue.dequeue() shouldBe "async"
    queue.dequeue() shouldBe value // the second request should be wait for the first one finished
    queue.size shouldBe 0
  }

  it should "handle request concurrently for different keys" in {
    val queue = mutable.Queue.empty[String]
    val watcherService = TestProbe()
    val workerFactory = (f: ActorRefFactory) =>
      f.actorOf(Props(new Actor {
        override def receive: Receive = {
          case request: RegisterData =>
            if (request.value == "async")
              Future {
                Thread.sleep(1000)
                queue.enqueue(request.value)
                context.parent ! FinishWork(request.key)
              } else {
              queue.enqueue(request.value)
              context.parent ! FinishWork(request.key)
            }
        }
      }))

    val key = "testKey"
    val key2 = "testKey2"
    val value = "testValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, workerFactory))

    val requests = Seq(RegisterData(key, "async"), RegisterData(key2, value))

    requests.foreach { request =>
      service ! request
    }

    Thread.sleep(2000) // wait for two requests are completed
    queue.dequeue() shouldBe value // the second request should be completed first because it doesn't wait
    queue.dequeue() shouldBe "async"
    queue.size shouldBe 0
  }

  it should "remove unnecessary operation" in {
    val watcherService = TestProbe()
    val worker = TestProbe()

    val key = "testKey"
    val value = "testValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, etcdWorkerFactory(worker.ref)))

    service ! RegisterData(key, value) // occupy the resource
    worker.expectMsg(RegisterData(key, value))

    service ! RegisterInitialData(key, value) // this request should also be removed

    val requests = Random.shuffle(
      Seq(RegisterData(key, value), RegisterData(key, value), WatcherClosed(key, false), WatcherClosed(key, false)))
    // below requests will be merged into one request and wait in the queue
    requests.foreach { request =>
      service ! request
    }
    worker.expectNoMessage()

    service ! FinishWork(key) // release the resource

    worker.expectMsg(requests(3)) // only the last one should be distributed
  }

  it should "register data when the target endpoint is removed" in {
    val watcherService = TestProbe()
    val worker = TestProbe()
    val key = "testKey"
    val value = "testValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, etcdWorkerFactory(worker.ref)))

    // no new watcher is registered as it assumes the one is already registered.
    service ! WatchEndpointRemoved(key, key, value, isPrefix = false)
    worker.expectMsg(RegisterInitialData(key, value, false, None))
  }

  it should "ignore prefixed endpoint-removed results" in {
    val watcherService = TestProbe()
    val worker = TestProbe()
    val key = "testKey"
    val value = "testValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, etcdWorkerFactory(worker.ref)))
    service ! WatchEndpointRemoved("", key, value, isPrefix = true)

    worker.expectNoMessage()
  }

  it should "deregister data" in {
    val watcherService = TestProbe()
    val worker = TestProbe()
    watcherService.setAutoPilot((sender, msg) => {
      msg match {
        case UnwatchEndpoint(key, isPrefix, _, _) =>
          sender ! WatcherClosed(key, isPrefix)
          TestActor.KeepRunning
      }
    })
    val key = "testKey"

    val service = TestActorRef(new DataManagementService(watcherService.ref, etcdWorkerFactory(worker.ref)))
    service ! UnregisterData(key)

    watcherService.expectMsg(UnwatchEndpoint(key, isPrefix = false, watcherName, true))
    worker.expectMsg(WatcherClosed(key, false))
  }

  it should "store the resource data" in {
    val watcherService = TestProbe()
    val worker = TestProbe()
    val key = "testKey"
    val value = "testValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, etcdWorkerFactory(worker.ref)))
    service ! UpdateDataOnChange(key, value)

    worker.expectMsg(RegisterData(key, value))
    service.underlyingActor.dataCache.size shouldBe 1
  }

  it should "not store the resource data if there is no change from the last one" in {
    val watcherService = TestProbe()
    val worker = TestProbe()
    val key = "testKey"
    val value = "testValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, etcdWorkerFactory(worker.ref)))
    service ! UpdateDataOnChange(key, value)

    worker.expectMsg(RegisterData(key, value))
    service.underlyingActor.dataCache.size shouldBe 1

    service ! UpdateDataOnChange(key, value)
    worker.expectNoMessage()
    service.underlyingActor.dataCache.size shouldBe 1
  }

  it should "store the resource data if there is change from the last one" in {
    val watcherService = TestProbe()
    val worker = TestProbe()
    val key = "testKey"
    val value = "testValue"
    val newValue = "newTestValue"

    val service = TestActorRef(new DataManagementService(watcherService.ref, etcdWorkerFactory(worker.ref)))
    service ! UpdateDataOnChange(key, value)

    worker.expectMsg(RegisterData(key, value))
    service.underlyingActor.dataCache.size shouldBe 1

    service ! FinishWork(key)
    service ! UpdateDataOnChange(key, newValue)
    worker.expectMsg(RegisterData(key, newValue, false))
    service.underlyingActor.dataCache.size shouldBe 1
  }
}


text:
Please see [CONTRIBUTING.md](CONTRIBUTING.md) for more guidelines on
contributing to Hoodie.

Hoodie uses the [Standard](https://github.com/feross/standard) JavaScript
coding style.

This file explains coding-style considerations that are beyond the syntax check
of *Standard*.

There are three sections:

- *General*: coding styles that are applicable to all JavaScript code.
- *Client*: coding styles that are only applicable to in-browser code.
- *Server*: coding styles that are only applicable in server code.

*Note: Client and Server coding styles can be contradicting, make sure to read
these carefully*.

## General

### File Structure

A typical JavaScript file looks like this (without the comments).
Sort all modules that you `require` alphabetically within their blocks.

```js
// If your module exports something, put it on top
module.exports = myMethod

// require Node.js core modules in the 1st block (separaeted by empty line).
// These are modules that come with Node.js and are not listed in package.json.
// See https://nodejs.org/api/ for a list of Node.js core modules
var EventEmitter = require('events').EventEmitter
var util = require('util')

// In the 2nd block, require all modules listed in package.json
var async = require('async')
var lodash = require('lodash')

// in the 3rd block, require all modules using relative paths
var helpers = require('./utils/helpers')
var otherMethod = require('./other-method')

function myMethod () {
  // code here
}
```

### Avoid "this" and object-oriented coding styles.

Do this

```js
function MyApi (options) {
  var state = {
    foo: options.foo
  }
  return {
    doSomething: doSomething.bind(null, state)
  }
}

function doSomething (state) {
  return state.foo ? 'foo!' : 'bar'
}
```

Instead of

```js
function MyApi (options) {
  this.foo = options.foo
}

MyApi.prototype.doSomething = function () {
  return this.foo ? 'foo!' : 'bar'
}
```

The [bind method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)
allows for [partially applied functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Partially_applied_functions_%28currying%29), that way we can pass internal state between
different methods without exposing in the public API. At the same time we can
easily test the different methods in isolation by setting the internal state to
what ever context we want to test with.

### Folder Structure

In the root, have

- `package.json`
- `.gitignore` (should at least list node_modules)
- `README.md`
- `LICENSE` (Apache License Version 2.0)

In most cases you will have `index.js` file which is listed in `package.json`
as the `"main"` property.

If you want to split up logic into separate files, move them into a `server/` folder.
Put reusable, state-less helper methods into `server/utils/`

For tests, create a `test/` folder. If your module becomes a bit more complex,
split up the tests in `test/unit` and `test/integration/`. All files that contain
tests should end with `-test.js`.

### Misc

- Prefer [lodash](https://lodash.com) over [underscore](http://underscorejs.org "Underscore.js").

## Client

### Testing

Client code should be tested using [tape](https://www.npmjs.com/package/tape).
The reason we use tape is its support for [browserify](https://www.npmjs.com/package/browserify).

### Libraries with sub-modules that can be required individually, like lodash

For client-side JavaScript code, it is important to limit the amount of code
that is downloaded to the client to the code that is actually needed. The
[loadash](https://lodash.com) library is a collection of utilities that are
useful individually and in combination.

For example, if you want to use the `merge` function of lodash, require it like
this:

```javascript
var merge = require('lodash/merge')
```

If you want to use more than one function within one module, or if you want to
combine multiple functions for a single operation, require the full lodash
module:

```javascript
var _ = require('lodash')
```

If multiple modules use the same lodash function, [our frontend bundling
tool](http://browserify.org "Browserify") will do the right thing and only
include that code once.

## Server

### Testing

Server code should be tested using [tap](https://www.npmjs.com/package/tap).

### Libraries with sub-modules that can be required individually, like lodash

For server-side code, it is important to load the minimal amount of code into
memory.

On the server require the full library, e.g.

```javascript
var _ = require('lodash')

var c = _.merge(a, b)
```

That way, all of our server code will only ever load a single instance of
lodash into memory.


text:
<?php

class LoginController {

    private $errors;
    private $loginType;
    private $username;
    private $userRemembered;
    private $subdomain;
    private $apiVersion;
    private $startUrl;
    private $oauthEnabled;
    private $oauthRequired;
    private $termsRequired;
    private $termsFile;

    function __construct() {
        $this->errors = array();
        if (isset($_REQUEST['error'])) {
            $this->addError($_REQUEST['error'] .
                            (isset($_REQUEST['error_description'])
                                ? (": " . $_REQUEST['error_description'])
                                : ""));
        }

        $this->loginType = isset($_REQUEST['loginType'])
                             ? $_REQUEST['loginType']
                             : WorkbenchConfig::get()->value("defaultLoginType");

        $this->username = isset($_REQUEST['un'])
                             ? $_REQUEST['un']
                             : (isset($_COOKIE['user'])
                                 ? $_COOKIE['user']
                                 : "");

        $this->userRemembered = isset($_COOKIE['user']);

        $this->subdomain = isset($_REQUEST['inst'])
                             ? $_REQUEST['inst']
                             : WorkbenchConfig::get()->value("defaultInstance");

        $this->apiVersion = isset($_REQUEST['api'])
                              ? $_REQUEST['api']
                              : WorkbenchConfig::get()->value("defaultApiVersion");

        $this->startUrl = isset($_REQUEST['startUrl'])
                              ? $_REQUEST['startUrl']
                              : "select.php";

        $this->oauthEnabled = false;
        foreach (WorkbenchConfig::get()->value('oauthConfigs') as $host => $hostInfo) {
            if (!empty($hostInfo["label"]) && !empty($hostInfo["key"]) && !empty($hostInfo["secret"])) {
                $this->oauthEnabled = true;
                break;
            }
        }

        $this->oauthRequired = WorkbenchConfig::get()->value("oauthRequired");
        if ($this->oauthRequired) {
            $this->loginType = "oauth";
        }

        if ($this->oauthRequired && !$this->oauthEnabled) {
            throw new Exception("OAuth is required, but not enabled.");
        }

        $this->termsFile = WorkbenchConfig::get()->value("termsFile");
        if (!empty($this->termsFile)) {
            if (!is_file($this->termsFile)) {
                $termsHttpHeaders = get_headers($this->termsFile);
                if ($termsHttpHeaders === FALSE || strpos($termsHttpHeaders[0], "200 OK") === FALSE) {
                    throw new Exception("Could not find Terms of Service.");
                }
            }

            $this->termsRequired = true;
        }
    }

    public function processRequest() {

        if ((isset($_POST['signed_request']))){
            $this->processSignedRequest($_POST['signed_request']);
            return;
        }

        if (isset($_REQUEST["code"])) {
            if (!isset($_REQUEST['state'])) {
                throw new Exception("Invalid OAuth State");
            }

            $state = json_decode($_REQUEST['state']);

            if (WorkbenchConfig::get()->value("loginCsrfEnabled")) {
                $_REQUEST['CSRF_TOKEN'] = $state->csrfToken;
                validateCsrfToken();
            }

            $this->oauthProcessLogin($_REQUEST["code"], $state->host, $state->apiVersion);
            return;
        }

        if (WorkbenchConfig::get()->value("loginCsrfEnabled")) {
            if (!validateCsrfToken(false)) {
                $this->addError('This login method is not supported.');
                return;
            }
        }

        if ($this->termsRequired && !isset($_POST['termsAccepted'])) {
            $this->addError("You must agree to terms of service.");
            return;
        }

        if (isset($_REQUEST['loginType']) && $_REQUEST['loginType'] == "oauth") {
            if (!isset($_POST["oauth_host"]) || !isset($_POST["api"])) {
                throw new Exception("Invalid parameters for Oauth login");
            }

            $state = json_encode(array(
                "host" => $_POST["oauth_host"],
                "apiVersion" => $_POST["oauth_apiVersion"],
                "csrfToken" => getCsrfToken()
            ));

            $this->oauthRedirect($_POST["oauth_host"], $state);
        } else {
            $pw   = isset($_REQUEST['pw'])  ? $_REQUEST['pw']  : null;
            $sid  = isset($_REQUEST['sid']) ? $_REQUEST['sid'] : null;
            $serverUrl = $this->buildServerUrl();

            // special-cases for UI vs API logins
            if (isset($_POST['uiLogin'])) {
                $this->processRememberUserCookie();
            } else {
                $_REQUEST['autoLogin'] = 1;
            }

            $this->processLogin($this->username, $pw, $serverUrl, $sid, $this->startUrl);
        }
    }

    private function processSignedRequest($signedRequest) {
        $sep = strpos($signedRequest, '.');
        $encodedSig = substr($signedRequest, 0, $sep);
        $encodedEnv = substr($signedRequest, $sep + 1);

        $req = json_decode(base64_decode($encodedEnv));

        preg_match("/https:\/\/(.*)\//", $req->client->instanceUrl, $m);
        $host = $m[1];

        // resolve to login url // TODO: this used to be in signed request. investigate this. replace with client->clientId lookup...
        if (strpos($host, "cs") == 0 || strpos($host, "tapp0") == 0) {
            $host = "test.salesforce.com";
        } else {
            $host = "login.salesforce.com";
        }

        $oauthConfigs = WorkbenchConfig::get()->value("oauthConfigs");
        if (!isset($oauthConfigs[$host]['key']) || !isset($oauthConfigs[$host]['secret'])) {
            throw new Exception("Misconfigured OAuth Host: $host");
        }
        $secret = $oauthConfigs[$host]['secret'];

        $calcedSig = base64_encode(hash_hmac("sha256", $encodedEnv, $secret, true));
        if ($calcedSig != $encodedSig) {
            throw new WorkbenchAuthenticationException("Signed request authentication failed");
        }

        $this->processLogin(null, null, $req->client->instanceUrl . $req->context->links->partnerUrl, $req->client->oauthToken, "select.php");
    }

    public function processRememberUserCookie() {
        if (isset($_POST['rememberUser']) && $_POST['rememberUser'] == 'on') {
            setcookie('user', $this->username, time() + 60 * 60 * 24 * 7);
            $this->userRemembered = true;
        } else {
            setcookie('user', NULL, time() - 3600);
            $this->userRemembered = false;
        }
    }

    private function buildServerUrl() {
        // constructed on client side for UI logins -- take as is
        if (isset($_REQUEST['serverUrl'])) {
            return $_REQUEST['serverUrl'];
        }

        // API clients can provide just prefix or pieces of serverUrl, so build here
        $serverUrl = "";

        if (isset($_REQUEST['serverUrlPrefix'])) {
            $serverUrl .= $_REQUEST['serverUrlPrefix'];
        } else {
            $serverUrl .= "http";

            if (WorkbenchConfig::get()->value("useHTTPS") && !stristr(WorkbenchConfig::get()->value("defaultInstance"), 'localhost')) {
                $serverUrl .= "s";
            }

            $serverUrl .= "://" . $this->subdomain . ".salesforce.com";

            if (isset($_REQUEST['port'])) {
                $serverUrl .= ":" . $_REQUEST['port'];
            }
        }

        $serverUrl .= "/services/Soap/u/" . $this->apiVersion;
        return $serverUrl;
    }

    private function processLogin($username, $password, $serverUrl, $sessionId, $actionJump) {
        if ($username && $password && $sessionId) {
            $this->addError('Provide only username and password OR session id, but not all three.');
            return;
        }

        //block connections to localhost
        if (stripos($serverUrl,'localhost')) {
            if (isset($GLOBALS['internal']['localhostLoginError'])) {
                $this->addError($GLOBALS['internal']['localhostLoginError']);
            } else {
                $this->addError("Must not connect to 'localhost'");
            }

            return;
        }

        if (WorkbenchContext::isEstablished()) {
            // cache clearing shouldn't be needed since we're releasing on the next line,
            // but doing it just in case someone puts a cache key outside the WbCtx scope
            WorkbenchContext::get()->clearCache();
            WorkbenchContext::get()->release();
        }

        // TODO: clean up this hackiness due to in-progress context refactoring...
        $savedOauthConfig = isset($_SESSION['oauth']) ? $_SESSION['oauth'] : null;
        session_unset();
        session_destroy();
        session_start();
        $_SESSION['oauth'] = $savedOauthConfig;

        $overriddenClientId = isset($_REQUEST["clientId"]) ? $_REQUEST["clientId"] : null;
        if ($username && $password && !$sessionId) {
             if ($this->oauthRequired) {
                throw new WorkbenchHandledException("OAuth login is required");
            }

            $orgId = isset($_REQUEST["orgId"]) ? $_REQUEST["orgId"] : WorkbenchConfig::get()->value("loginScopeHeader_organizationId");
            $portalId = isset($_REQUEST["portalId"]) ? $_REQUEST["portalId"] : WorkbenchConfig::get()->value("loginScopeHeader_portalId");

            WorkbenchContext::establish(ConnectionConfiguration::fromUrl($serverUrl, null, $overriddenClientId));
            try {
                WorkbenchContext::get()->login($username, $password, $orgId, $portalId);
            } catch (Exception $e) {
                WorkbenchContext::get()->release();
                $this->addError($e->getMessage());
                return;
            }
        } else if ($sessionId && $serverUrl && !($username && $password)) {
            $serverUrlHost = parse_url($serverUrl, PHP_URL_HOST);
            $loginHosts = array("login.salesforce.com", "test.salesforce.com", "prerellogin.pre.salesforce.com");
            if (in_array($serverUrlHost, $loginHosts)) {
                $this->addError('Must not connect to login server (www, login, test, or prerellogin) if providing a session id. ' .
                               'Choose your specific Salesforce instance on the QuickSelect menu when using a session id; ' .
                               'otherwise, provide a username and password and choose the appropriate a login server.');
                return;
            }

            WorkbenchContext::establish(ConnectionConfiguration::fromUrl($serverUrl, $sessionId, $overriddenClientId));
            WorkbenchContext::get()->setIsUiSessionLikelySet(true);
        } else {
            $this->addError('Invalid login parameters.');
            return;
        }

        // todo: put in WbCtx?
        if (stripos(WorkbenchContext::get()->getHost(),'localhost')) {
            if (isset($GLOBALS['internal']['localhostLoginRedirectError'])) {
                $this->addError($GLOBALS['internal']['localhostLoginRedirectError']);
            } else {
                $this->addError("Must not connect to 'localhost'");
            }

            return;
        }

        if (isset($_POST['termsAccepted'])) {
            WorkbenchContext::get()->agreeToTerms();
        }

        // test the connection and prime the UserInfo cache
        // exceptions will be caught by top-level handler
        $userInfo = WorkbenchContext::get()->getUserInfo();

        // do org id whitelist/blacklisting
        $orgId15 = substr($userInfo->organizationId,0,15);
        $orgIdWhiteList = array_map('trim',explode(",",WorkbenchConfig::get()->value("orgIdWhiteList")));
        $orgIdBlackList = array_map('trim',explode(",",WorkbenchConfig::get()->value("orgIdBlackList")));
        $isAllowed = true;
        foreach ($orgIdWhiteList as $allowedOrgId) {
            if ($allowedOrgId === "") {
                continue;
            } else if ($orgId15 === substr($allowedOrgId,0,15)) {
                $isAllowed = true;
                break;
            } else {
                // there is something on the whitelist that's not us
                // disallow and keep looking until we find our org id
                $isAllowed = false;
            }
        }

        foreach ($orgIdBlackList as $disallowedOrgId) {
            if ($orgId15 ===  substr($disallowedOrgId,0,15)) {
                $isAllowed = false;
                break;
            }
        }

        if (!$isAllowed) {
            throw new WorkbenchAuthenticationException("Requests for organization $orgId15 are not allowed");
        }

        if (isset($_REQUEST['autoLogin'])) {
            $actionJump .= (strpos($actionJump, "?") > -1 ? "&" :  "?") . "autoLogin=1";
            if (isset($_REQUEST['skipVC'])) $actionJump .= "&skipVC=1";
            if (isset($_GET['clientId'])) $_SESSION['tempClientId'] = $_GET['clientId'];
        }

        header("Location: $actionJump");
    }

    private function oauthRedirect($hostName, $state) {
        if (!$this->oauthEnabled) {
            throw new Exception("OAuth not enabled");
        }

        $oauthConfigs = WorkbenchConfig::get()->value("oauthConfigs");
        $authUrl = "https://" . $hostName .
                    "/services/oauth2/authorize?response_type=code&display=popup".
                    "&client_id=" . urlencode($oauthConfigs[$hostName]["key"]) .
                    "&redirect_uri=" . urlencode($this->oauthBuildRedirectUrl()) .
                    "&state=" . urlencode($state);

        header('Location: ' . $authUrl);
    }

    private function oauthProcessLogin($code, $hostName, $apiVersion) {
        if (!$this->oauthEnabled) {
            throw new Exception("OAuth not enabled");
        }

        // we set this again below to the real value returned,
        // but in case it fails prior, need to set for logout iframe hack
        if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) {
            $_SESSION['oauth']['serverUrlPrefix'] = "https://" . parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
        }

        $oauthConfigs = WorkbenchConfig::get()->value("oauthConfigs");

        $tokenUrl =  "https://" . $hostName . "/services/oauth2/token";

        if (!isset($oauthConfigs[$hostName]['key']) || !isset($oauthConfigs[$hostName]['secret'])) {
            throw new Exception("Misconfigured OAuth Host");
        }

        $params = "code=" . $code
                  . "&grant_type=authorization_code"
                  . "&client_id=" . $oauthConfigs[$hostName]['key']
                  . "&client_secret=" . $oauthConfigs[$hostName]['secret']
                  . "&redirect_uri=" . urlencode($this->oauthBuildRedirectUrl());

        $curl = curl_init($tokenUrl);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);  //TODO: use ca-bundle instead

        $proxySettings = getProxySettings();
        if ($proxySettings != null) {
            curl_setopt($curl, CURLOPT_PROXY, $proxySettings["proxy_host"]);
            curl_setopt($curl, CURLOPT_PROXYPORT, $proxySettings["proxy_port"]);
            curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxySettings["proxy_username"] . ":" . $proxySettings["proxy_password"]);
        }

        try {
            $json_response = curl_exec($curl);

            if (curl_error($curl) != null) {
                // not printing exception because it could contain the secret
                throw new Exception("Unknown OAuth Error");
            }

            $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $response = json_decode($json_response, true);

            curl_close($curl);
        } catch (Exception $e) {
            throw new WorkbenchAuthenticationException("OAuth authentication failed connect to: " . $tokenUrl);
        }

        if (isset($response["error"]) && isset($response["error_description"])) {
            throw new WorkbenchAuthenticationException($response["error"] . ": " . $response["error_description"]);
        } else if ($status != 200) {
            throw new WorkbenchAuthenticationException("Unknown OAuth Error. Status Code: $status");
        }

        $accessToken = $response['access_token'];
        $serverUrlPrefix = $response['instance_url'];
        $_SESSION['oauth']['serverUrlPrefix'] = $serverUrlPrefix;

        if (empty($accessToken)) {
            throw new Exception("OAuth response missing access token");
        }

        if (empty($serverUrlPrefix)) {
            throw new Exception("OAuth response missing instance name");
        }

        $_POST['termsAccepted'] = 1; // re-apply terms acceptance on oauth redirect

        $this->processLogin(null, null, $serverUrlPrefix . "/services/Soap/u/" . $apiVersion, $accessToken, "select.php"); // TODO: work w/ startUrls
    }

    private function oauthBuildRedirectUrl() {
        return "http" . (usingSslFromUserToWorkbench() ? "s" : "") ."://" .
                WorkbenchConfig::get()->valueOrElse("oauthRedirectHost", $_SERVER['HTTP_HOST']) .
                str_replace('\\', '/', dirname(htmlspecialchars($_SERVER['PHP_SELF']))) .
                (strlen(dirname(htmlspecialchars($_SERVER['PHP_SELF']))) == 1 ? "" : "/") .
                basename($_SERVER['SCRIPT_NAME']);
    }

    public function isOAuthEnabled() {
        return $this->oauthEnabled;
    }

    public function isOAuthRequired() {
        return $this->oauthRequired;
    }

    public function getErrors() {
        return $this->errors;
    }

    public function getLoginType() {
        return $this->loginType;
    }

    public function getUsername() {
        return $this->username;
    }

    public function isUserRemembered() {
        return $this->userRemembered;
    }

    public function getSubdomain() {
        return $this->subdomain;
    }

    public function getApiVersion() {
        return $this->apiVersion;
    }

    public function getStartUrl() {
        return $this->startUrl;
    }

    public function getTermsFile() {
        return $this->termsFile;
    }

    public function getSubdomainSelectOptions() {
        $subdomains = array();
        foreach (WorkbenchConfig::get()->valuesToLabels("defaultInstance") as $subdomain => $info) {
            $subdomains[$subdomain] = $info[0];
        }
        return $subdomains;
    }

    public function getOauthHostSelectOptions() {
        $hosts = array();
        foreach (WorkbenchConfig::get()->value('oauthConfigs') as $host => $hostInfo) {
            if (empty($hostInfo["label"]) || empty($hostInfo["key"]) || empty($hostInfo["secret"])) {
                continue;
            }

            $hosts[$host] = $hostInfo["label"];
        }

        if (array_key_exists("login.salesforce.com", $hosts)) {
            $loginHost = $hosts["login.salesforce.com"];
            unset($hosts["login.salesforce.com"]);
            $hosts = array_unshift_assoc($hosts, "login.salesforce.com", $loginHost);
        }

        return $hosts;
    }

    public function getApiVersionSelectOptions() {
        return WorkbenchConfig::get()->valuesToLabels("defaultApiVersion");
    }

    public function getStartUrlSelectOptions() {
        $urls = array();
        $urls["select.php"] = "";
        foreach ($GLOBALS["MENUS"] as $pages) {
            foreach ($pages as $href => $page) {
                if ($page->onMenuSelect) $urls[$href] = $page->title;
            }
        }
        return $urls;
    }

    public function getServerIdMap() {
        $serverIdMap = array();
        foreach (WorkbenchConfig::get()->valuesToLabels("defaultInstance") as $subdomain => $info) {
            if (isset($info[1]) && $info[1] != "") {
                $serverIdMap[$info[1]] = $subdomain;
            }
        }
        return $serverIdMap;
    }

    public function getJsConfig() {
        $jsConfig = array();
        $jsConfig['useHTTPS'] = (bool) WorkbenchConfig::get()->value('useHTTPS');
        $jsConfig['customServerUrl'] = isset($_REQUEST['serverUrl']) ? $_REQUEST['serverUrl'] : "";
        $jsConfig['serverIdMap'] = $this->getServerIdMap();

        return json_encode($jsConfig);
    }

    private function addError($error) {
        array_push($this->errors, $error);
    }
}
?>


text:
require 'detectify/version'
require 'detectify/config'
require 'detectify/query_builder/base'
require 'detectify/query_builder/sql'
require 'detectify/detector'
require 'detectify/middleware'

module Detectify
  def self.configure
    yield(config)
  end

  def self.config
    @config || reset_config
  end

  def self.reset_config(config = Config.new)
    @config = config
  end

  def self.entity_class
    if config.entity_class.is_a?(String)
      Object.const_get(config.entity_class)
    else
      config.entity_class
    end
  end
end

require 'detectify/railtie' if defined?(::Rails)


text:
package org.kuali.rice.krms.impl.ui;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ojb.broker.metadata.ClassNotPersistenceCapableException;
import org.kuali.rice.core.api.data.DataType;
import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
import org.kuali.rice.core.api.uif.RemotableAttributeField;
import org.kuali.rice.core.api.uif.RemotableTextInput;
import org.kuali.rice.core.api.util.tree.Node;
import org.kuali.rice.core.api.util.tree.Tree;
import org.kuali.rice.core.impl.cache.DistributedCacheManagerDecorator;
import org.kuali.rice.krad.maintenance.Maintainable;
import org.kuali.rice.krad.maintenance.MaintainableImpl;
import org.kuali.rice.krad.maintenance.MaintenanceDocument;
import org.kuali.rice.krad.uif.container.CollectionGroup;
import org.kuali.rice.krad.uif.container.Container;
import org.kuali.rice.krad.uif.view.View;
import org.kuali.rice.krad.uif.view.ViewModel;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.ObjectUtils;
import org.kuali.rice.krad.web.form.MaintenanceDocumentForm;
import org.kuali.rice.krms.api.KrmsConstants;
import org.kuali.rice.krms.api.repository.action.ActionDefinition;
import org.kuali.rice.krms.api.repository.agenda.AgendaDefinition;
import org.kuali.rice.krms.api.repository.agenda.AgendaItemDefinition;
import org.kuali.rice.krms.api.repository.agenda.AgendaTreeDefinition;
import org.kuali.rice.krms.api.repository.context.ContextDefinition;
import org.kuali.rice.krms.api.repository.function.FunctionDefinition;
import org.kuali.rice.krms.api.repository.operator.CustomOperator;
import org.kuali.rice.krms.api.repository.proposition.PropositionDefinition;
import org.kuali.rice.krms.api.repository.proposition.PropositionParameterType;
import org.kuali.rice.krms.api.repository.rule.RuleDefinition;
import org.kuali.rice.krms.api.repository.term.TermDefinition;
import org.kuali.rice.krms.api.repository.term.TermResolverDefinition;
import org.kuali.rice.krms.api.repository.term.TermSpecificationDefinition;
import org.kuali.rice.krms.api.repository.type.KrmsAttributeDefinition;
import org.kuali.rice.krms.api.repository.type.KrmsTypeDefinition;
import org.kuali.rice.krms.impl.repository.ActionAttributeBo;
import org.kuali.rice.krms.impl.repository.ActionBo;
import org.kuali.rice.krms.impl.repository.AgendaBo;
import org.kuali.rice.krms.impl.repository.AgendaItemBo;
import org.kuali.rice.krms.impl.repository.ContextBoService;
import org.kuali.rice.krms.impl.repository.KrmsAttributeDefinitionService;
import org.kuali.rice.krms.impl.repository.KrmsRepositoryServiceLocator;
import org.kuali.rice.krms.impl.repository.PropositionBo;
import org.kuali.rice.krms.impl.repository.PropositionParameterBo;
import org.kuali.rice.krms.impl.repository.RepositoryBoIncrementer;
import org.kuali.rice.krms.impl.repository.RuleAttributeBo;
import org.kuali.rice.krms.impl.repository.RuleBo;
import org.kuali.rice.krms.impl.repository.TermBo;
import org.kuali.rice.krms.impl.repository.TermParameterBo;
import org.kuali.rice.krms.impl.util.KrmsImplConstants;
import org.kuali.rice.krms.impl.util.KrmsRetriever;
import org.kuali.rice.krms.impl.util.KrmsServiceLocatorInternal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.kuali.rice.krms.impl.repository.BusinessObjectServiceMigrationUtils.findSingleMatching;

/**
 * {@link Maintainable} for the {@link AgendaEditor}
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class AgendaEditorMaintainable extends MaintainableImpl {

    private static final long serialVersionUID = 1L;

    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(
            AgendaEditorMaintainable.class);

    public static final String NEW_AGENDA_EDITOR_DOCUMENT_TEXT = "New Agenda Editor Document";
    private static final RepositoryBoIncrementer termIdIncrementer = new RepositoryBoIncrementer(TermBo.TERM_SEQ_NAME);
    private static final RepositoryBoIncrementer termParameterIdIncrementer = new RepositoryBoIncrementer(TermParameterBo.TERM_PARM_SEQ_NAME);

    private transient KrmsRetriever krmsRetriever = new KrmsRetriever();

    /**
     * return the contextBoService
     */
    private ContextBoService getContextBoService() {
        return KrmsRepositoryServiceLocator.getContextBoService();
    }

    public List<RemotableAttributeField> retrieveAgendaCustomAttributes(View view, Object model, Container container) {
        AgendaEditor agendaEditor = getAgendaEditor(model);
        return krmsRetriever.retrieveAgendaCustomAttributes(agendaEditor);
    }

    /**
     * Retrieve a list of {@link RemotableAttributeField}s for the parameters (if any) required by the resolver for
     * the selected term in the proposition that is under edit.
     */
    public List<RemotableAttributeField> retrieveTermParameters(View view, Object model, Container container) {

        List<RemotableAttributeField> results = new ArrayList<RemotableAttributeField>();

        AgendaEditor agendaEditor = getAgendaEditor(model);

        // Figure out which rule is being edited
        RuleBo rule = agendaEditor.getAgendaItemLine().getRule();
        if (null != rule) {

            // Figure out which proposition is being edited
            Tree<RuleTreeNode, String> propositionTree = rule.getPropositionTree();
            Node<RuleTreeNode, String> editedPropositionNode = findEditedProposition(propositionTree.getRootElement());

            if (editedPropositionNode != null) {
                PropositionBo propositionBo = editedPropositionNode.getData().getProposition();
                if (StringUtils.isEmpty(propositionBo.getCompoundOpCode()) && CollectionUtils.size(
                        propositionBo.getParameters()) > 0) {
                    // Get the term ID; if it is a new parameterized term, it will have a special prefix
                    PropositionParameterBo param = propositionBo.getParameters().get(0);
                    if (StringUtils.isNotBlank(param.getValue()) &&
                            param.getValue().startsWith(KrmsImplConstants.PARAMETERIZED_TERM_PREFIX)) {
                        String termSpecId = param.getValue().substring(
                                KrmsImplConstants.PARAMETERIZED_TERM_PREFIX.length());
                        TermResolverDefinition simplestResolver = getSimplestTermResolver(termSpecId,
                                rule.getNamespace());

                        // Get the parameters and build RemotableAttributeFields
                        if (simplestResolver != null) {
                            List<String> parameterNames = new ArrayList<String>(simplestResolver.getParameterNames());
                            Collections.sort(parameterNames); // make param order deterministic

                            for (String parameterName : parameterNames) {
                                // TODO: also allow for DD parameters if there are matching type attributes
                                RemotableTextInput.Builder controlBuilder = RemotableTextInput.Builder.create();
                                controlBuilder.setSize(64);

                                RemotableAttributeField.Builder builder = RemotableAttributeField.Builder.create(
                                        parameterName);

                                builder.setRequired(true);
                                builder.setDataType(DataType.STRING);
                                builder.setControl(controlBuilder);
                                builder.setLongLabel(parameterName);
                                builder.setShortLabel(parameterName);
                                builder.setMinLength(Integer.valueOf(1));
                                builder.setMaxLength(Integer.valueOf(64));

                                results.add(builder.build());
                            }
                        }
                    }
                }
            }
        }
        return results;
    }

    /**
     * finds the term resolver with the fewest parameters that resolves the given term specification
     *
     * @param termSpecId the id of the term specification
     * @param namespace the  namespace of the term specification
     * @return the simples {@link TermResolverDefinition} found, or null if none was found
     */
    // package access so that AgendaEditorController can use it too
    static TermResolverDefinition getSimplestTermResolver(String termSpecId,
            String namespace) {// Get the term resolver for the term spec

        List<TermResolverDefinition> resolvers =
                KrmsRepositoryServiceLocator.getTermBoService().findTermResolversByOutputId(termSpecId, namespace);

        TermResolverDefinition simplestResolver = null;

        for (TermResolverDefinition resolver : resolvers) {
            if (simplestResolver == null || simplestResolver.getParameterNames().size() < resolver.getParameterNames()
                    .size()) {
                simplestResolver = resolver;
            }
        }

        return simplestResolver;
    }

    /**
     * Find and return the node containing the proposition that is in currently in edit mode
     *
     * @param node the node to start searching from (typically the root)
     * @return the node that is currently being edited, if any.  Otherwise, null.
     */
    private Node<RuleTreeNode, String> findEditedProposition(Node<RuleTreeNode, String> node) {
        Node<RuleTreeNode, String> result = null;
        if (node.getData() != null && node.getData().getProposition() != null && node.getData().getProposition()
                .getEditMode()) {
            result = node;
        } else {
            for (Node<RuleTreeNode, String> child : node.getChildren()) {
                result = findEditedProposition(child);
                if (result != null) {
                    break;
                }
            }
        }
        return result;
    }

    /**
     * Get the AgendaEditor out of the MaintenanceDocumentForm's newMaintainableObject
     *
     * @param model the MaintenanceDocumentForm
     * @return the AgendaEditor
     */
    private AgendaEditor getAgendaEditor(Object model) {
        MaintenanceDocumentForm maintenanceForm = (MaintenanceDocumentForm) model;
        return (AgendaEditor) maintenanceForm.getDocument().getNewMaintainableObject().getDataObject();
    }

    public List<RemotableAttributeField> retrieveRuleActionCustomAttributes(View view, Object model,
            Container container) {
        AgendaEditor agendaEditor = getAgendaEditor((MaintenanceDocumentForm) model);
        return krmsRetriever.retrieveRuleActionCustomAttributes(agendaEditor);
    }

    /**
     * This only supports a single action within a rule.
     */
    public List<RemotableAttributeField> retrieveRuleCustomAttributes(View view, Object model, Container container) {
        AgendaEditor agendaEditor = getAgendaEditor((MaintenanceDocumentForm) model);
        return krmsRetriever.retrieveRuleCustomAttributes(agendaEditor);
    }

    @Override
    public Object retrieveObjectForEditOrCopy(MaintenanceDocument document, Map<String, String> dataObjectKeys) {
        Object dataObject = null;

        try {
            // Since the dataObject is a wrapper class we need to build it and populate with the agenda bo.
            AgendaEditor agendaEditor = new AgendaEditor();
            AgendaBo agenda = findSingleMatching(getDataObjectService(),
                    ((AgendaEditor) getDataObject()).getAgenda().getClass(), dataObjectKeys);

            // HACK: force lazy loaded items to be fetched
            forceLoadLazyRelations(agenda);

            if (KRADConstants.MAINTENANCE_COPY_ACTION.equals(getMaintenanceAction())) {
                String dateTimeStamp = (new Date()).getTime() + "";
                String newAgendaName = AgendaItemBo.COPY_OF_TEXT + agenda.getName() + " " + dateTimeStamp;

                AgendaBo copiedAgenda = agenda.copyAgenda(newAgendaName, dateTimeStamp);

                document.getDocumentHeader().setDocumentDescription(NEW_AGENDA_EDITOR_DOCUMENT_TEXT);
                document.setFieldsClearedOnCopy(true);
                agendaEditor.setAgenda(copiedAgenda);
            } else {
                // set custom attributes map in AgendaEditor
                //                agendaEditor.setCustomAttributesMap(agenda.getAttributes());
                agendaEditor.setAgenda(agenda);
            }
            agendaEditor.setCustomAttributesMap(agenda.getAttributes());

            // set extra fields on AgendaEditor
            agendaEditor.setNamespace(agenda.getContext().getNamespace());
            agendaEditor.setContextName(agenda.getContext().getName());

            dataObject = agendaEditor;
        } catch (ClassNotPersistenceCapableException ex) {
            if (!document.getOldMaintainableObject().isExternalBusinessObject()) {
                throw new RuntimeException("Data Object Class: "
                        + getDataObjectClass()
                        + " is not persistable and is not externalizable - configuration error");
            }
            // otherwise, let fall through
        }

        return dataObject;
    }

    private void forceLoadLazyRelations(AgendaBo agenda) {
        for (AgendaItemBo item : agenda.getItems()) {
            for (ActionBo action : item.getRule().getActions()) {
                if (CollectionUtils.isEmpty(action.getAttributeBos())) { continue; }

                for (ActionAttributeBo actionAttribute : action.getAttributeBos()) {
                    actionAttribute.getAttributeDefinition();
                }
            }

            Tree propTree = item.getRule().refreshPropositionTree(true);
            walkPropositionTree(item.getRule().getProposition());

            for (RuleAttributeBo ruleAttribute : item.getRule().getAttributeBos()) {
                ruleAttribute.getAttributeDefinition();
            }
        }
    }

    private void walkPropositionTree(PropositionBo prop) {
        if (prop == null) { return; }

        if (prop.getParameters() != null) for (PropositionParameterBo param : prop.getParameters()) {
            param.getPropId();
        }

        if (prop.getCompoundComponents() != null) for (PropositionBo childProp : prop.getCompoundComponents()) {
            walkPropositionTree(childProp);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void processAfterNew(MaintenanceDocument document, Map<String, String[]> requestParameters) {
        super.processAfterNew(document, requestParameters);
        document.getDocumentHeader().setDocumentDescription(NEW_AGENDA_EDITOR_DOCUMENT_TEXT);
    }

    @Override
    public void processAfterEdit(MaintenanceDocument document, Map<String, String[]> requestParameters) {
        super.processAfterEdit(document, requestParameters);
        document.getDocumentHeader().setDocumentDescription("Modify Agenda Editor Document");
    }

    @Override
    public void processAfterCopy(MaintenanceDocument document,
            Map<String, String[]> parameters) {
        super.processAfterCopy(document, parameters);
        AgendaBo agendaBo = ((AgendaEditor) document.getDocumentDataObject()).getAgenda();
        agendaBo.setVersionNumber(null);

        for (AgendaItemBo agendaItem : agendaBo.getItems()) {
            agendaItem.setVersionNumber(null);
        }
    }
    @Override
    public void prepareForSave() {
        // set agenda attributes
        AgendaEditor agendaEditor = (AgendaEditor) getDataObject();
        agendaEditor.getAgenda().setAttributes(agendaEditor.getCustomAttributesMap());
    }

    @Override
    public void saveDataObject() {
        AgendaBo agendaBo = ((AgendaEditor) getDataObject()).getAgenda();

        // handle saving new parameterized terms and processing custom operators
        for (AgendaItemBo agendaItem : agendaBo.getItems()) {
            PropositionBo propositionBo = agendaItem.getRule().getProposition();
            if (propositionBo != null) {
                saveNewParameterizedTerms(propositionBo);
                processCustomOperators(propositionBo);
            }
        }

        if (agendaBo != null) {
            flushCacheBeforeSave();

            /*
             AgendaItemBo has columns alwaysId, whenFirstId and whenLastId
             that have fk constraints to a column (agendaItemid) on the same
             table.

             With hibernate in this scenario caching all inserts causes them
             to be executed at the same time in the DB and we get an integrity
             violation exception.

             The solution is to decouple AgendaBo from AgendaItemBo persist
             the agenaItems one at at time and flush, causing the items
             to be persisted avoiding the integrity constraint
            */

            if(this.getMaintenanceAction() != null &&
                    this.getMaintenanceAction().equals(KRADConstants.MAINTENANCE_COPY_ACTION)){
                List<AgendaItemBo> agendaItems = agendaBo.getItems();
                agendaBo.setItems(new ArrayList<AgendaItemBo>());
                getDataObjectService().save(agendaBo);

                for(AgendaItemBo item : agendaItems) {
                    getDataObjectService().save(item);
                    getDataObjectService().flush(AgendaItemBo.class);
                }

                agendaBo.setItems(agendaItems);
            }else{
                getDataObjectService().save(agendaBo);
            }
        } else {
            throw new RuntimeException("Cannot save object of type: " + agendaBo + " with business object service");
        }
    }

    private void addItemsToListForDeletion(List<AgendaItemBo> deletionOrder, AgendaItemBo agendaItemBo){
        if (!deletionOrder.contains(agendaItemBo) && ObjectUtils.isNotNull(agendaItemBo)) {
            deletionOrder.add(agendaItemBo);
        }
        if (ObjectUtils.isNotNull(agendaItemBo)) {
            if (StringUtils.isNotBlank(agendaItemBo.getWhenTrueId()) &&
                !deletionOrder.contains(agendaItemBo.getWhenTrue())) {
                    deletionOrder.add(agendaItemBo.getWhenTrue());
                    addItemsToListForDeletion (deletionOrder, agendaItemBo.getWhenTrue());
            }
            if (StringUtils.isNotBlank(agendaItemBo.getWhenFalseId()) &&
                !deletionOrder.contains(agendaItemBo.getWhenFalse())) {
                    deletionOrder.add(agendaItemBo.getWhenFalse());
                    addItemsToListForDeletion (deletionOrder, agendaItemBo.getWhenFalse());
            }
            if (StringUtils.isNotBlank(agendaItemBo.getAlwaysId()) &&
                !deletionOrder.contains(agendaItemBo.getAlways())) {
                    deletionOrder.add(agendaItemBo.getAlways());
                    addItemsToListForDeletion (deletionOrder,agendaItemBo.getAlways());
            }
        }
    }

    private void flushCacheBeforeSave(){
        //flush krms caches
        DistributedCacheManagerDecorator distributedCacheManagerDecorator =
                GlobalResourceLoader.getService(KrmsConstants.KRMS_DISTRIBUTED_CACHE);

        distributedCacheManagerDecorator.getCache(ActionDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(AgendaItemDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(AgendaTreeDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(AgendaDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(ContextDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(KrmsAttributeDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(KrmsTypeDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(RuleDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(PropositionDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(RuleDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(TermDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(TermResolverDefinition.Cache.NAME).clear();
        distributedCacheManagerDecorator.getCache(TermSpecificationDefinition.Cache.NAME).clear();
    }

    /**
     * walk the proposition tree and save any new parameterized terms that are contained therein
     *
     * @param propositionBo the root proposition from which to search
     */
    private void saveNewParameterizedTerms(PropositionBo propositionBo) {
        if (StringUtils.isBlank(propositionBo.getCompoundOpCode())) {
            // it is a simple proposition
            if (!propositionBo.getParameters().isEmpty() && propositionBo.getParameters().get(0).getValue().startsWith(
                    KrmsImplConstants.PARAMETERIZED_TERM_PREFIX)) {
                String termId = propositionBo.getParameters().get(0).getValue();
                String termSpecId = termId.substring(KrmsImplConstants.PARAMETERIZED_TERM_PREFIX.length());
                // create new term
                TermBo newTerm = new TermBo();
                newTerm.setDescription(propositionBo.getNewTermDescription());
                newTerm.setSpecificationId(termSpecId);
                newTerm.setId(termIdIncrementer.getNewId());

                List<TermParameterBo> params = new ArrayList<TermParameterBo>();
                for (Map.Entry<String, String> entry : propositionBo.getTermParameters().entrySet()) {
                    TermParameterBo param = new TermParameterBo();
                    param.setTerm(newTerm);
                    param.setName(entry.getKey());
                    param.setValue(entry.getValue());
                    param.setId(termParameterIdIncrementer.getNewId());

                    params.add(param);
                }

                newTerm.setParameters(params);

                getLegacyDataAdapter().linkAndSave(newTerm);
                propositionBo.getParameters().get(0).setValue(newTerm.getId());
            }
        } else {
            // recurse
            for (PropositionBo childProp : propositionBo.getCompoundComponents()) {
                saveNewParameterizedTerms(childProp);
            }
        }
    }

    /**
     * walk the proposition tree and process any custom operators found, converting them to custom function invocations.
     *
     * @param propositionBo the root proposition from which to search and convert
     */
    private void processCustomOperators(PropositionBo propositionBo) {
        if (StringUtils.isBlank(propositionBo.getCompoundOpCode())) {
            // if it is a simple proposition with a custom operator
            if (!propositionBo.getParameters().isEmpty() && propositionBo.getParameters().get(2).getValue().startsWith(
                    KrmsImplConstants.CUSTOM_OPERATOR_PREFIX)) {
                PropositionParameterBo operatorParam = propositionBo.getParameters().get(2);

                CustomOperator customOperator =
                        KrmsServiceLocatorInternal.getCustomOperatorUiTranslator().getCustomOperator(operatorParam.getValue());

                FunctionDefinition operatorFunctionDefinition = customOperator.getOperatorFunctionDefinition();

                operatorParam.setParameterType(PropositionParameterType.FUNCTION.getCode());
                operatorParam.setValue(operatorFunctionDefinition.getId());
            }
        } else {
            // recurse
            for (PropositionBo childProp : propositionBo.getCompoundComponents()) {
                processCustomOperators(childProp);
            }
        }
    }

    /**
     * Build a map from attribute name to attribute definition from all the defined attribute definitions for the
     * specified agenda type
     *
     * @param agendaTypeId
     * @return
     */
    private Map<String, KrmsAttributeDefinition> buildAttributeDefinitionMap(String agendaTypeId) {
        KrmsAttributeDefinitionService attributeDefinitionService =
                KrmsRepositoryServiceLocator.getKrmsAttributeDefinitionService();

        // build a map from attribute name to definition
        Map<String, KrmsAttributeDefinition> attributeDefinitionMap = new HashMap<String, KrmsAttributeDefinition>();

        List<KrmsAttributeDefinition> attributeDefinitions = attributeDefinitionService.findAttributeDefinitionsByType(
                agendaTypeId);

        for (KrmsAttributeDefinition attributeDefinition : attributeDefinitions) {
            attributeDefinitionMap.put(attributeDefinition.getName(), attributeDefinition);
        }
        return attributeDefinitionMap;
    }

    @Override
    public boolean isOldDataObjectInDocument() {
        boolean isOldDataObjectInExistence = true;

        if (getDataObject() == null) {
            isOldDataObjectInExistence = false;
        } else {
            // dataObject contains a non persistable wrapper - use agenda from the wrapper object instead
            Map<String, ?> keyFieldValues = getLegacyDataAdapter().getPrimaryKeyFieldValues(
                    ((AgendaEditor) getDataObject()).getAgenda());
            for (Object keyValue : keyFieldValues.values()) {
                if (keyValue == null) {
                    isOldDataObjectInExistence = false;
                } else if ((keyValue instanceof String) && StringUtils.isBlank((String) keyValue)) {
                    isOldDataObjectInExistence = false;
                }

                if (!isOldDataObjectInExistence) {
                    break;
                }
            }
        }

        return isOldDataObjectInExistence;
    }

    // Since the dataObject is a wrapper class we need to return the agendaBo instead.
    @Override
    public Class getDataObjectClass() {
        return AgendaBo.class;
    }

    @Override
    public boolean isLockable() {
        return true;
    }

    @Override
    public void processBeforeAddLine(ViewModel model, Object addLine, String collectionId, String collectionPath) {
        AgendaEditor agendaEditor = getAgendaEditor(model);
        if (addLine instanceof ActionBo) {
            ((ActionBo) addLine).setNamespace(agendaEditor.getAgendaItemLine().getRule().getNamespace());
        }

        super.processBeforeAddLine(model, addLine, collectionId, collectionPath);
    }
}


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/html; charset=utf-8" />

    <title>Index — Python 2.7.12 documentation</title>

    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.12 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="top" title="Python 2.7.12 documentation" href="contents.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />

Navigation

          index

          modules |

Python »

          2.7.12
          Documentation »

Index – Y

Y2K

ycor() (in module turtle)

year (datetime.date attribute)

(datetime.datetime attribute)

Year 2000

Year 2038

yeardatescalendar() (calendar.Calendar method)

yeardays2calendar() (calendar.Calendar method)

yeardayscalendar() (calendar.Calendar method)

YESEXPR (in module locale)

    yield

expression

keyword

statement

YIELD_VALUE (opcode)

yiq_to_rgb() (in module colorsys)

yview() (ttk.Treeview method)

Index

Symbols
     | _
     | A
     | B
     | C
     | D
     | E
     | F
     | G
     | H
     | I
     | J
     | K
     | L
     | M
     | N
     | O
     | P
     | Q
     | R
     | S
     | T
     | U
     | V
     | W
     | X
     | Y
     | Z

Full index on one page

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

Python »

          2.7.12
          Documentation »

    © Copyright 1990-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Jun 25, 2016.
    Found a bug?

    Created using Sphinx 1.3.3.


text:
#include "usTestModuleBService.h"

#include <usModuleActivator.h>
#include <usModuleContext.h>

US_BEGIN_NAMESPACE

struct TestModuleImportedByB : public TestModuleBService
{

  TestModuleImportedByB(ModuleContext* mc)
  {
    US_INFO << "Registering TestModuleImportedByB";
    mc->RegisterService<TestModuleBService>(this);
  }

};

class TestModuleImportedByBActivator : public ModuleActivator
{
public:

  TestModuleImportedByBActivator() : s(0) {}
  ~TestModuleImportedByBActivator() { delete s; }

  void Load(ModuleContext* context)
  {
    s = new TestModuleImportedByB(context);
  }

  void Unload(ModuleContext*)
  {
  }

private:

  TestModuleImportedByB* s;
};

US_END_NAMESPACE

US_EXPORT_MODULE_ACTIVATOR(TestModuleImportedByB, US_PREPEND_NAMESPACE(TestModuleImportedByBActivator))


text:
"""
    Cloudbreak API

    Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloudbreak is a RESTful application development platform with the goal of helping developers to build solutions for deploying Hadoop YARN clusters in different environments. Once it is deployed in your favourite servlet container it exposes a REST API allowing to span up Hadoop clusters of arbitary sizes and cloud providers. Provisioning Hadoop has never been easier. Cloudbreak is built on the foundation of cloud providers API (Amazon AWS, Microsoft Azure, Google Cloud Platform, Openstack), Apache Ambari, Docker lightweight containers, Swarm and Consul. For further product documentation follow the link: http://hortonworks.com/apache/cloudbreak/

    OpenAPI spec version: 2.9.0

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from pprint import pformat
from six import iteritems
import re

class WorkspaceRequest(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'name': 'str',
        'description': 'str'
    }

    attribute_map = {
        'name': 'name',
        'description': 'description'
    }

    def __init__(self, name=None, description=None):
        """
        WorkspaceRequest - a model defined in Swagger
        """

        self._name = None
        self._description = None

        if name is not None:
          self.name = name
        if description is not None:
          self.description = description

    @property
    def name(self):
        """
        Gets the name of this WorkspaceRequest.
        name of the resource

        :return: The name of this WorkspaceRequest.
        :rtype: str
        """
        return self._name

    @name.setter
    def name(self, name):
        """
        Sets the name of this WorkspaceRequest.
        name of the resource

        :param name: The name of this WorkspaceRequest.
        :type: str
        """
        if name is not None and len(name) > 100:
            raise ValueError("Invalid value for `name`, length must be less than or equal to `100`")
        if name is not None and len(name) < 5:
            raise ValueError("Invalid value for `name`, length must be greater than or equal to `5`")
        if name is not None and not re.search('(^[a-z][-a-z0-9]*[a-z0-9]$)', name):
            raise ValueError("Invalid value for `name`, must be a follow pattern or equal to `/(^[a-z][-a-z0-9]*[a-z0-9]$)/`")

        self._name = name

    @property
    def description(self):
        """
        Gets the description of this WorkspaceRequest.
        description of the resource

        :return: The description of this WorkspaceRequest.
        :rtype: str
        """
        return self._description

    @description.setter
    def description(self, description):
        """
        Sets the description of this WorkspaceRequest.
        description of the resource

        :param description: The description of this WorkspaceRequest.
        :type: str
        """
        if description is not None and len(description) > 1000:
            raise ValueError("Invalid value for `description`, length must be less than or equal to `1000`")
        if description is not None and len(description) < 0:
            raise ValueError("Invalid value for `description`, length must be greater than or equal to `0`")

        self._description = description

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        if not isinstance(other, WorkspaceRequest):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
package cn.nec.nlc.example.activitytest28loader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Loader;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;

// Loader class allow you to load data asynchronously in an activity or fragment.
// They can monitor the source of the data and deliver new results when the content changes.
// They also persist data between configuration changes.
// If the result is retrieved by the Loader after the object has been disconnected from its
// parent (activity or fragment), it can cache the data.
public class MainActivity extends Activity
	implements LoaderManager.LoaderCallbacks<SharedPreferences> {
	private static final String KEY = "prefs";
	private TextView textView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView) findViewById(R.id.prefs);
		// initLoader():
		// The first parameter is a unique ID which can be used by the callback
		// class to identify that Loader later.
		// The second parameter is a bundle which can be given to the callback class
		// for more information.
		// The third parameter of initLoader() is the class which is called once the
		// initialization has been started (callback class). This class must implement
		// the LoaderManager.LoaderCallbacks interface.
		getLoaderManager().initLoader(0, null, this);
	}

	@Override
	public Loader<SharedPreferences> onCreateLoader(int id, Bundle args) {
		return (new SharedPreferencesLoader(this));
	}

	@SuppressLint("CommitPrefEdits")
	@Override
	public void onLoadFinished(Loader<SharedPreferences> loader,
			SharedPreferences prefs) {
		int value = prefs.getInt(KEY, 0); // Key and Default value
		value += 1;
		textView.setText(String.valueOf(value));
		// update value
		SharedPreferences.Editor editor = prefs.edit(); // @SuppressLint("CommitPrefEdits")
		editor.putInt(KEY, value);
		SharedPreferencesLoader.persist(editor);
	}

	@Override
	public void onLoaderReset(Loader<SharedPreferences> arg0) {
		// not in use
	}
}


text:
using namespace std;

inline
void use_io_optimizations()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
}

int main()
{
    use_io_optimizations();

    unsigned int lonely_integer;

    unsigned int integers;
    cin >> integers;

    for (unsigned int i {0}; i < integers; ++i)
    {
        unsigned int integer;
        cin >> integer;

        lonely_integer ^= integer;
    }

    cout << lonely_integer << '\n';

    return 0;
}


text:
<?php

/**
 * PHPExcel_RichText_Run
 *
 * @category   PHPExcel
 * @package    PHPExcel_RichText
 * @copyright  Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel)
 */
class PHPExcel_RichText_Run extends PHPExcel_RichText_TextElement implements PHPExcel_RichText_ITextElement
{
	/**
	 * Font
	 *
	 * @var PHPExcel_Style_Font
	 */
	private $_font;

    /**
     * Create a new PHPExcel_RichText_Run instance
     *
     * @param 	string		$pText		Text
     */
    public function __construct($pText = '')
    {
    	// Initialise variables
    	$this->setText($pText);
    	$this->_font = new PHPExcel_Style_Font();
    }

	/**
	 * Get font
	 *
	 * @return PHPExcel_Style_Font
	 */
	public function getFont() {
		return $this->_font;
	}

	/**
	 * Set font
	 *
	 * @param	PHPExcel_Style_Font		$pFont		Font
	 * @throws 	Exception
	 * @return PHPExcel_RichText_ITextElement
	 */
	public function setFont(PHPExcel_Style_Font $pFont = null) {
		$this->_font = $pFont;
		return $this;
	}

	/**
	 * Get hash code
	 *
	 * @return string	Hash code
	 */
	public function getHashCode() {
    	return md5(
    		  $this->getText()
    		. $this->_font->getHashCode()
    		. __CLASS__
    	);
    }

	/**
	 * Implement PHP __clone to create a deep clone, not just a shallow copy.
	 */
	public function __clone() {
		$vars = get_object_vars($this);
		foreach ($vars as $key => $value) {
			if (is_object($value)) {
				$this->$key = clone $value;
			} else {
				$this->$key = $value;
			}
		}
	}
}


text:
interface I {
  String foo(Foo i);
}

interface Bar {
  String foo();
}

class Foo implements Bar {
  public String foo() {
    return null;
  }

  String foo(int i) {
    return null;
  }

  static String foo(Foo foo) {
    return null;
  }

  public static void main(String[] args) {
    I i = Bar::foo;
  }
}


text:
package com.davidbracewell.parsing.expressions;

import com.davidbracewell.parsing.ParserToken;
import lombok.NonNull;

/**
 * An Expression representing an prefix expression
 *
 * @author David B. Bracewell
 */
public class PrefixOperatorExpression extends Expression {
   /**
    * The operator
    */
   public final ParserToken operator;

   /**
    * The expression which the operator is operating on
    */
   public final Expression right;

   /**
    * Default Constructor
    *
    * @param operator The prefix operator
    * @param right    The expression on the right
    */
   public PrefixOperatorExpression(@NonNull ParserToken operator, @NonNull Expression right) {
      super(operator.type);
      this.operator = operator;
      this.right = right;
   }

   @Override
   public String toString() {
      return "(" + operator.text + right.toString() + ")";
   }

}//END OF PrefixOperatorExpression


text:
/*
 * Created on Sep 26, 2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package net.reliableresponse.notification.broker;

import java.io.InputStream;
import java.util.Map;

import net.sf.jasperreports.engine.JasperReport;

/**
 * @author drig
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public interface ReportBroker {

	public String[] getReportNames();

	public String getReportDescription(String name);

	public Map getParameterTypes (String name);

	public InputStream getReportStream(String name);

	public JasperReport getReport (String name);
}


text:
ActiveRecord::Schema.define(version: 20150504043356) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "campaigns", force: :cascade do |t|
    t.string   "subject"
    t.text     "body"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "campaigns", ["user_id"], name: "index_campaigns_on_user_id", using: :btree

  create_table "lists", force: :cascade do |t|
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "subscribers", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.integer  "list_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "subscribers", ["list_id"], name: "index_subscribers_on_list_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string   "password_digest"
    t.string   "username",        limit: 30
    t.string   "email"
    t.datetime "created_at",                 null: false
    t.datetime "updated_at",                 null: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree

  add_foreign_key "campaigns", "users"
  add_foreign_key "subscribers", "lists"
end


text:
using Nancy;
using Nancy.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace api_server
{
    public class Arena
    {
        public ConcurrentQueue<string> operationQueue = new ConcurrentQueue<string>();

        public int curPlayer = 0;

        List<Player> playerList = new List<Player>();

        ConcurrentDictionary<string, int> tokenIdDict = new ConcurrentDictionary<string, int>();
        ConcurrentDictionary<int, string> idTokenDict = new ConcurrentDictionary<int, string>();

        public ConcurrentDictionary<string, string> carInfoDict = new ConcurrentDictionary<string, string>();

        public string register(string name, string color, string type)
        {
            string token = Guid.NewGuid().ToString("D");

            int id = curPlayer;
            tokenIdDict[token] = id;
            idTokenDict[id] = token;
            curPlayer++;

            var player = new Player(name, color, type);
            playerList.Add(player);
            carInfoDict[id.ToString()] = player.ToString();

            return token;
        }

        public void run()
        {
            while (true)
            {
                int counter = 0;
                while (operationQueue.IsEmpty == false || counter >= 100)
                {
                    string operation = "";
                    if (operationQueue.TryDequeue(out operation) == false) continue;

                    string[] op = operation.Split(':');
                    string token = op[1];
                    int id = tokenIdDict[token];
                    switch (op[0])
                    {
                        case "accel":
                            playerList[id].car.throttle += double.Parse(op[2]);
                            playerList[id].car.brake = 0;
                            break;
                        case "handle":
                            playerList[id].car.steerAngle += double.Parse(op[2]);
                            break;
                        case "brake":
                            playerList[id].car.throttle = 0;
                            playerList[id].car.brake = 100;
                            break;
                    }
                    counter++;
                }

                StringBuilder result = new StringBuilder();
                result.Append("{");
                foreach (var id in Enumerable.Range(0, playerList.Count))
                {
                    var player = playerList[id];
                    player.car.simulate(0.001);

                    if (id == 0)
                    {
                        result.Append(string.Format("\"{0}\":\"{1},{2},{3},{4}\"",
                            id,
                            player.car.positionWC.x,
                            player.car.positionWC.y,
                            player.car.steerAngle,
                            player.car.throttle));
                    }
                    else
                    {
                        result.Append(string.Format(",\"{0}\":\"{1},{2},{3},{4}\"",
                            id,
                            player.car.positionWC.x,
                            player.car.positionWC.y,
                            player.car.steerAngle,
                            player.car.throttle));
                    }
                }
                result.Append("}");
                int pos = (ArenaApiModule.currentCarPos + 1) % ArenaApiModule.carPosArray.Length;
                ArenaApiModule.carPosArray[pos] = result.ToString();
                ArenaApiModule.currentCarPos = pos;

                Thread.Sleep(20);
            }
        }

        public bool validateToken(string token)
        {
            return tokenIdDict.Keys.Contains(token);
        }
    }
}


text:
package com.mauriciotogneri.common.utils;

import android.text.TextUtils;

public class EncodingHelper
{
    private static final String UTF_8 = "UTF-8";

    public static byte[] getStringAsBytes(String input)
    {
        if (TextUtils.isEmpty(input))
        {
            return new byte[0];
        }
        else
        {
            try
            {
                return input.getBytes(EncodingHelper.UTF_8);
            }
            catch (Exception e)
            {
                return new byte[0];
            }
        }
    }

    public static String getBytesAsString(byte[] data)
    {
        if ((data == null) || (data.length == 0))
        {
            return null;
        }
        else
        {
            try
            {
                return new String(data, EncodingHelper.UTF_8);
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }
}