text:
from itertools import chain

from nose.tools import assert_false
from nose.tools import assert_is_instance
from nose.tools import assert_is_none
from nose.tools import assert_raises
from nose.tools import eq_

from tests.utils import assert_raises_substring
from tests.utils import get_uuid4_str
from twapi_connection.exc import AuthenticationError
from twapi_connection.testing import MockConnection, MockResponse, \
    SuccessfulAPICall, UnsuccessfulAPICall

_STUB_URL_PATH = '/foo'

_STUB_RESPONSE = MockResponse({'foo': 'bar'})

_STUB_API_CALL_1 = SuccessfulAPICall(
    _STUB_URL_PATH,
    'GET',
    response=_STUB_RESPONSE,
    )

_STUB_API_CALL_2 = SuccessfulAPICall(
    _STUB_URL_PATH,
    'POST',
    response=_STUB_RESPONSE,
    )

class TestMockConnection(object):

    def test_get_request(self):
        connection = \
            self._make_connection_for_expected_api_call(_STUB_API_CALL_1)

        response = connection.send_get_request(_STUB_URL_PATH)

        self._assert_sole_api_call_equals(_STUB_API_CALL_1, connection)
        eq_(_STUB_RESPONSE, response)

    def test_get_request_with_query_string_args(self):
        query_string_args = {'foo': 'bar'}
        expected_api_call = SuccessfulAPICall(
            _STUB_URL_PATH,
            'GET',
            query_string_args,
            response=_STUB_RESPONSE,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        connection.send_get_request(_STUB_URL_PATH, query_string_args)

        self._assert_sole_api_call_equals(expected_api_call, connection)

    def test_head_request(self):
        expected_response = MockResponse(None)
        expected_api_call = SuccessfulAPICall(
            _STUB_URL_PATH,
            'HEAD',
            response=expected_response,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        response = connection.send_head_request(_STUB_URL_PATH)

        self._assert_sole_api_call_equals(expected_api_call, connection)
        eq_(expected_response, response)

    def test_head_request_with_query_string_args(self):
        query_string_args = {'foo': 'bar'}
        expected_api_call = SuccessfulAPICall(
            _STUB_URL_PATH,
            'HEAD',
            query_string_args,
            response=None,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        connection.send_head_request(_STUB_URL_PATH, query_string_args)

        self._assert_sole_api_call_equals(expected_api_call, connection)

    def test_post_request(self):
        expected_api_call = SuccessfulAPICall(
            _STUB_URL_PATH,
            'POST',
            response=_STUB_RESPONSE,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        response = connection.send_post_request(_STUB_URL_PATH)

        self._assert_sole_api_call_equals(expected_api_call, connection)
        eq_(_STUB_RESPONSE, response)

    def test_post_request_with_body(self):
        request_body_deserialization = {'foo': 'bar'}
        expected_api_call = SuccessfulAPICall(
            _STUB_URL_PATH,
            'POST',
            request_body_deserialization=request_body_deserialization,
            response=_STUB_RESPONSE,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        response = connection.send_post_request(
            _STUB_URL_PATH,
            request_body_deserialization,
            )

        self._assert_sole_api_call_equals(expected_api_call, connection)
        eq_(_STUB_RESPONSE, response)

    def test_put_request(self):
        request_body_deserialization = {'foo': 'bar'}
        expected_api_call = SuccessfulAPICall(
            _STUB_URL_PATH,
            'PUT',
            request_body_deserialization=request_body_deserialization,
            response=_STUB_RESPONSE,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        response = connection.send_put_request(
            _STUB_URL_PATH,
            request_body_deserialization,
            )

        self._assert_sole_api_call_equals(expected_api_call, connection)
        eq_(_STUB_RESPONSE, response)

    def test_delete_request(self):
        expected_api_call = SuccessfulAPICall(
            _STUB_URL_PATH,
            'DELETE',
            response=_STUB_RESPONSE,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        response = connection.send_delete_request(_STUB_URL_PATH)

        self._assert_sole_api_call_equals(expected_api_call, connection)
        eq_(_STUB_RESPONSE, response)

    def test_response_data_strings(self):
        connection = \
            self._make_connection_for_expected_api_call(_STUB_API_CALL_1)

        response = connection.send_get_request(_STUB_URL_PATH)

        # Inspect returned data
        _assert_dict_keys_and_values_are_strings(response.json())

        # Inspect stored data
        api_call = connection.api_calls[0]
        _assert_dict_keys_and_values_are_strings(api_call.response.json())

    def test_multiple_api_calls_simulators(self):
        connection = MockConnection(
            _ConstantCallable([_STUB_API_CALL_1]),
            _ConstantCallable([_STUB_API_CALL_2]),
            )

        assert_false(connection.api_calls)

        connection.send_get_request(_STUB_URL_PATH)
        eq_([_STUB_API_CALL_1], connection.api_calls)

        connection.send_post_request(_STUB_URL_PATH, None)
        eq_([_STUB_API_CALL_1, _STUB_API_CALL_2], connection.api_calls)

    def test_multiple_api_calls(self):
        connection = MockConnection(
            _ConstantCallable([_STUB_API_CALL_1, _STUB_API_CALL_2]),
            )

        assert_false(connection.api_calls)

        connection.send_get_request(_STUB_URL_PATH)
        eq_([_STUB_API_CALL_1], connection.api_calls)

        connection.send_post_request(_STUB_URL_PATH, None)
        eq_([_STUB_API_CALL_1, _STUB_API_CALL_2], connection.api_calls)

    def test_unsuccessful_api_call(self):
        exception = \
            AuthenticationError('Must authenticate', get_uuid4_str())
        expected_api_call = UnsuccessfulAPICall(
            _STUB_URL_PATH,
            'GET',
            exception=exception,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        with assert_raises(type(exception)) as context_manager:
            connection.send_get_request(_STUB_URL_PATH)

        eq_(exception, context_manager.exception)
        self._assert_sole_api_call_equals(expected_api_call, connection)

    def test_too_few_requests(self):
        connection = \
            self._make_connection_for_expected_api_call(_STUB_API_CALL_1)
        error_message = '1 more requests were expected'
        with assert_raises_substring(AssertionError, error_message):
            with connection:
                # Do not make any requests in the connection
                pass

    def test_correct_number_of_requests(self):
        connection = \
            self._make_connection_for_expected_api_call(_STUB_API_CALL_1)
        with connection:
            connection.send_get_request(_STUB_URL_PATH)

    def test_too_many_requests(self):
        connection = MockConnection()
        error_message = \
            'Not enough API calls for new requests (requested {!r})'.format(
                _STUB_URL_PATH,
                )
        with assert_raises_substring(AssertionError, error_message):
            connection.send_get_request(_STUB_URL_PATH)

    def test_exception_inside_context_manager(self):
        """The validation for the number of requests is skipped."""
        connection = \
            self._make_connection_for_expected_api_call(_STUB_API_CALL_1)
        error_message = 'Foo'
        with assert_raises_substring(AssertionError, error_message):
            with connection:
                assert False, error_message

    def test_unexpected_url_path(self):
        connection = \
            self._make_connection_for_expected_api_call(_STUB_API_CALL_1)

        url_path = _STUB_URL_PATH + '/foo'
        error_message = 'Expected URL {!r}, got {!r}'.format(
            _STUB_URL_PATH,
            url_path,
            )
        with assert_raises_substring(AssertionError, error_message):
            connection.send_get_request(url_path)

    def test_unexpected_http_method(self):
        connection = \
            self._make_connection_for_expected_api_call(_STUB_API_CALL_1)

        error_message = "Expected HTTP method 'GET', got 'POST'"
        with assert_raises_substring(AssertionError, error_message):
            connection.send_post_request(_STUB_URL_PATH, None)

    def test_unexpected_query_string_args(self):
        connection = \
            self._make_connection_for_expected_api_call(_STUB_API_CALL_1)

        query_string_args = {'a': 'b'}
        error_message = 'Expected query string arguments {!r}, got {!r}' \
            .format(None, query_string_args)
        with assert_raises_substring(AssertionError, error_message):
            connection.send_get_request(_STUB_URL_PATH, query_string_args)

    def test_unexpected_request_body_deserialization(self):
        expected_api_call = SuccessfulAPICall(
            _STUB_URL_PATH,
            'PUT',
            response=_STUB_RESPONSE,
            )
        connection = \
            self._make_connection_for_expected_api_call(expected_api_call)

        request_body_deserialization = {'a': 'b'}
        error_message = 'Expected request body deserialization {!r}, got {!r}' \
            .format(None, request_body_deserialization)
        with assert_raises_substring(AssertionError, error_message):
            connection.send_put_request(
                _STUB_URL_PATH,
                request_body_deserialization,
                )

    @staticmethod
    def _make_connection_for_expected_api_call(expected_api_call):
        expected_api_calls_simulator = _ConstantCallable([expected_api_call])
        connection = MockConnection(expected_api_calls_simulator)
        return connection

    @staticmethod
    def _assert_sole_api_call_equals(expected_api_call, connection):
        eq_([expected_api_call], connection.api_calls)

def _assert_dict_keys_and_values_are_strings(dict_):
    values = chain(dict_.keys(), dict_.values())
    for value in values:
        assert_is_instance(value, str)

class _ConstantCallable(object):

    def __init__(self, return_value):
        super(_ConstantCallable, self).__init__()

        self._return_value = return_value

    def __call__(self):
        return self._return_value

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Treelog

meta:
  nav: blog
  author: channingwalton
  pygments: true
---

[Lance Walton's](https://twitter.com/lancewalton) [Treelog](https://github.com/lancewalton/treelog) is the result of a real problem that arose in a trading system that we were working on:
> How can everything that happens to a trade be audited?

The first (and tedious) answer is copius logging by writing to some kind of audit data type or simple logger.

There are a number of problems with this approach:

- writing logging around computations often complicates the code as values must be extracted, recorded and then applied
- separating logic from the computation can lead to a mismatch between the log and the computation
- linear logs are very difficult to follow
- its not easy to control how much of a linear log to show a user if you do not know what is detail and what isn't

Treelog resolves these issues by making the log itself a tree, reflecting the computational tree it logs, and uses techniques described in the [Typeclassopedia](http://www.haskell.org/wikiupload/e/e9/Typeclassopedia.pdf) to bring logging closer to the computation: the `Writer` Monad, a Monad Transformer, and a cunning Monoid.

Note that this post is a more technical description of how Treelog was written. For a quick introduction of use please refer to the [README].
I will also refer you to Eugene Yokota's [excellent Scalaz tutorial](http://eed3si9n.com/learning-scalaz/) to study the details of Scalaz where appropriate.

Logging with Treelog
--------------------
Here is an example which illustrates how Treelog is used ([more examples](https://github.com/lancewalton/treelog#treelog-examples)):

```scala
val simple: DescribedComputation[Int] =
  "Calculating sum" ~< {
    for {
      x ← 11 ~> ("x = " + _)
      y ← 2 ~> ("y = " + _)
      sum ← (x + y) ~> ("Sum is " + _)
    } yield sum
```

`DescribedComputation[Value]` is just a type alias for `EitherT[LogTreeWriter, String, Value]`. `EitherT`, a [Monad Transformer](http://eed3si9n.com/learning-scalaz/Monad+transformers.html), enables success and failure to be represented and will be covered below.

The log and value can be retrieved with `result.run.written` and `result.run.value` respectively. The written tree will look like this:

```
Calculating sum
  x = 11
  y = 2
  Sum is 13
```

and the value will be `\/-(13)`, which is Scalaz's version of `Right`.

Tree Nodes
----------

The nodes of the tree contain a `LogTreeLabel`:

```scala
sealed trait LogTreeLabel[A] {
  def success: Boolean
  def annotations: Set[A]
  // ...
}

case class DescribedLogTreeLabel[A](description: String, success: Boolean, annotations: Set[A]) extends LogTreeLabel[A]

case class UndescribedLogTreeLabel[A](success: Boolean, annotations: Set[A]) extends LogTreeLabel[A]
```

The node is able to represent success or failure, may have a description, and a set of annotations. Annotations allow extra information to be carried in a Node which may be useful when working with the audit later. For our trading system that was other trades that were affected by the process as a side effect of processing a trade.

Treelog distinguishes between tree nodes that describe a computation, a `DescribedLogTreeLabel`, and an `UndescribedLogTreeLabel` which is a Tree with no description in the root. In the example above, the root node is a `DescribedLogTreeLabel` containing the text `Calculating sum`. This is an important distinction that informs the way trees must be combined by our Treelog monoid, which the `Writer` needs (see below).

Note that originally, `LogTreeLabel` was a case class defined like this:

```scala
case class LogTreeLabel(description: Option[String], success: Boolean, annotations: Set[Annotation])
```

This meant that `DescribedLogTreeLabel` and `UndescribedLogTreeLabel` were not necessary because the optional `description` carried the equivalent information. However, we found the formulation above easier to work with.

Syntactic Sugar
---------------

Treelog makes use of some syntactic sugar inspired by [Tony Morris's post](http://blog.tmorris.net/posts/the-writer-monad-using-scala-example/) on `Writer`. In the example above, `~>` is a method on an implicitly constructed class which takes any value `x: T` and returns a `DescribedComputation[T]`, representing the value `x` and a leaf node containing the description.

There is special support for `Boolean`s, `Option`s, `Either`s and `Traversable`s which you can learn about from the Treelog [README].

`Writer` and Monoid
-------------------

> Writer allows us to do computations while making sure that all the log values are combined into one log value that then gets attached to the result. – [LYAH](http://learnyouahaskell.com/for-a-few-monads-more)

`Writer`s allow us to write a log embedded within a computation.

Here is a simple example using Scalaz, see the references for more detailed examples.

```scala
val r: Writer[String, Int] =
  for {
    a ← 3.set("Got a 3.")
    b ← 5.set("Got a 5.")
  } yield a * b

println(r.written) // Got a 3.Got a 5.
println(r.value) // 15
```

The `Writer` uses a monoid for the written value (a `String` in this case) to combine the logs (concatenation for `String`s). For `List`s it is `:::` and `Nil`, etc.

Treelog's Monoid
----------------

Treelog uses a Scalaz [Writer](http://eed3si9n.com/learning-scalaz/Writer.html), [Tree](http://eed3si9n.com/learning-scalaz/Tree.html) and a custom [Monoid](http://eed3si9n.com/learning-scalaz/Monoid.html) implementation to record logs.

The monoid has to provide two things: a `zero` value, and a binary operation that combines two trees in a meaningful way. The `zero` value for Treelog is just a constant used internally to the `Monoid´ implementation and never leaks out since there is always at least one value being logged.

Combining trees is done as follows:

- a `zero` tree with a tree is just the tree
- two undescribed trees become a new undescribed tree with the children of the right tree appended to the children of the left tree
- an undescribed tree `T1`, and a described tree, `T2`, becomes an undescribed tree with *`T2` appended to the children of `T1`*
- a described tree, `T1`, and an undescribed tree, `T2`, is an undescribed tree with *`T1` prepended to the children of `T2`*
- two described trees are combined by creating an undescribed tree with the two trees as children

Note that the result is always an undescribed tree since there is no meaningful way to combine descriptions of child nodes. In the example above the tree contains two leaves: "Got a 3" and "Got a 5". Concatenating those descriptions isn't as meaningful as "Summing a and b", which could be done like this:

```scala
val r: Writer[String, Int] =
  "Summing a and b" ~< for {
    a ← 3.set("Got a 3.")
    b ← 5.set("Got a 5.")
  } yield a * b
```

The [quadratic roots](https://github.com/lancewalton/treelog/blob/5e36e0652b575d0102f45b1c284f68a02f148b04/src/test/scala/QuadraticRootsExample.scala) example is a good one to see this.

Success and Failure – `EitherT`
-------------------------------

The purpose of Treelog is to audit a computation, return the log and result, and indicate whether the computation was successful or not. The Writer with the Monoid described above satisfies the first two requirements, but not the third. To add success and failure, the writer needs to be combined with `Either`. What we need is a Monad Transformer.

> Monad Transformers are special types that allow us to roll two monads into a single one that shares the behaviour of both. – [Haskell Wikibook](http://en.wikibooks.org/wiki/Haskell/Monad_transformers)

`EitherT` is a monad transformer that combines some monad with `Either`, which is exactly what is needed. It is constructed with three types: `EitherT[M, A, B]` where `M` is the monad, `A` is the failure type and `B` is the success type. In Treelog, `M` is a `Writer`, `A` is a `String` and `B` is the type of the result.

Logtree includes the methods `def failure[V](description: String): DescribedComputation[V]` and `def success[V](value: V, description: String): DescribedComputation[V]` to support failure and success. They ensure that the failure case is included in the tree and that the nodes in the tree now reflect that the computation has failed.

Here is an example from Treelog:

```scala
val foo: String \/ Int = 11.right[String]
val bar: String \/ Int = "fubar".left[Int]

val leftEithers: DescribedComputation[Int] =
  "Calculating left either sum" ~< {
    for {
      x ← foo ~>? ("x = " + _)
      y ← bar ~>? ("y = " + _)
      sum ← (x + y) ~> (v ⇒ "Sum is " + v)
    } yield sum
  }

val leftEitherWriter: LogTreeWriter[String \/ Int] = leftEithers.run
println(leftEithers.run.written.shows)
```

To retrieve the underying value back from `EitherT`, we call `run` which returns the `Writer` containing Scalaz's version of `Either` (which is more useful than Scala's built-in `Either`).

The written value is:

```
Failed: Calculating left either sum
  x = 11
  Failed: fubar

Failure: Calculating left either sum
```

So the written log indicates that the whole computation failed, and the result is `-\/`, the `Left` for a Scalaz `Either`, containing "Failure: Calculating left either sum".

In Practice
-----------

Treelog is being used in earnest in a trading system, and the results have been a resounding success. And the level of accurate detail the system is able to show users has been invaluable in reducing support questions, which is always welcome.

Further Reading
---------------

- [Monad Transformers in Scala](http://debasishg.blogspot.co.uk/2011/07/monad-transformers-in-scala.html)
- [Monad Transformers in the Wild](http://www.slideshare.net/StackMob/monad-transformers-in-the-wild)


text:
class ResourceManager
{
public:
    ResourceManager(StateStack* sstack, GameResources::LoadingMode mode, std::string packfile = "");

    sf::Texture& getTexture(Textures::ID id);
    sf::Font& getFont(Fonts::ID id);
    sf::SoundBuffer& getSoundBuffer(Sound::ID id);

    void registerTexture(Textures::ID id, const std::string& filename);
    void registerFont(Fonts::ID id, const std::string& filename);
    void registerSoundBuffer(Sound::ID id, const std::string& filename);

    void loadResources(ResourcesSet rset);

    void unloadCheckResources();

private:
    TextureHolder textureHolder;
    FontHolder fontHolder;
    SoundBufferHolder soundBufferHolder;

    GameResources::LoadingMode mode;

    std::map<std::string, std::unique_ptr<char[]> > fontDataMap;

    StateStack* sstack;
};

#endif


text:
package de.mirkosertic.bytecoder.api;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface OpaqueProperty {

    String value() default "";
}


text:
package com.yooshsoft.volumescheduler.structures;

import android.media.AudioManager;
import android.os.Parcel;
import android.os.Parcelable;

public class VolumeSettings implements Parcelable{
	protected static VolumeSettings MAX_VOLUMES;

	protected int ringtone;
	protected int media;
	protected int notifications;
	protected int system;
	protected int ring_mode;

	public VolumeSettings(int ringtone, int media, int notifications, int system, int ring_mode) {
		this.ringtone = ringtone;
		this.media = media;
		this.notifications = notifications;
		this.system = system;
		this.ring_mode = ring_mode;
	}

	public VolumeSettings(int ringtone, int media, int notifications, int system) {
		if(ringtone >= 0) {
			this.ringtone = ringtone;
			this.media = media;
			this.notifications = notifications;
			this.system = system;
			this.ring_mode = AudioManager.RINGER_MODE_NORMAL;
		} else {
			this.ringtone = 0;
			this.media = media;
			this.notifications = 0;
			this.system = 0;
			this.ring_mode = AudioManager.RINGER_MODE_SILENT;
		}
	}

	public void setRingtone(int vol) {
		this.ringtone = vol;
	}

	public void setMedia(int vol) {
		this.media = vol;
	}

	public void setNotifications(int vol) {
		this.notifications = vol;
	}

	public void setSystem(int vol) {
		this.system = vol;
	}

	public void setRingMode(int ring_mode) {
		this.ring_mode = ring_mode;
	}

	public int getRingtone() {
		return this.ringtone;
	}

	public int getMedia() {
		return this.media;
	}

	public int getNotifications() {
		return this.notifications;
	}

	public int getSystem() {
		return this.system;
	}

	public int getRingMode() {
		return this.ring_mode;
	}

	public String toString() {
		String str;

		int ring_percent = (int) (((float) this.getRingtone() / (float) MAX_VOLUMES.getRingtone()) * 100.0);
		int media_percent = (int) (((float) this.getMedia() / (float) MAX_VOLUMES.getMedia()) * 100.0);
		int notif_percent = (int) (((float) this.getNotifications() / (float) MAX_VOLUMES.getNotifications()) * 100.0);
		int system_percent = (int) (((float) this.getSystem() / (float) MAX_VOLUMES.getSystem()) * 100.0);

		str = "R " + ring_percent + "% M " + media_percent + "% N " + notif_percent + "% S " + system_percent + "%";

		return str;
	}

	public static void setMaxVolumes(int ring, int media, int notif, int sys, int vibrate) {
		MAX_VOLUMES = new VolumeSettings(ring, media, notif, sys, vibrate);
	}

//	public static VolumeSettings getMaxVolumes()
//	{
//		return MAX_VOLUMES;
//	}

	//Parcelable Stuff

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeInt(this.ringtone);
		dest.writeInt(this.media);
		dest.writeInt(this.notifications);
		dest.writeInt(this.system);
		dest.writeInt(this.ring_mode);
	}

	//Parcel constructor
	public VolumeSettings(Parcel source)
	{
		this.ringtone = source.readInt();
		this.media = source.readInt();
		this.notifications = source.readInt();
		this.system = source.readInt();
		this.ring_mode = source.readInt();
	}

	public static final Creator<VolumeSettings> CREATOR = new Creator<VolumeSettings>() {
		@Override
		public VolumeSettings[] newArray(int size) {
			return new VolumeSettings[size];
		}

		@Override
		public VolumeSettings createFromParcel(Parcel source) {
			return new VolumeSettings(source);
		}
	};
}


text:
package softlayer_monitoring_agent_configuration_template_group_reference

// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED


text:
<?php namespace Ovide\Phest\Helper;

class Unit extends \Codeception\Module
{

}


text:
let presets = ["babel-preset-atomic"]

let plugins = []

module.exports = {
  presets: presets,
  plugins: plugins,
  exclude: ["node_modules/**", "lib/debugger/VendorLib/**"],
  sourceMap: "inline",
}


text:
require 'active_record/bogacs/version'
require 'active_record/bogacs/autoload'

if defined?(Rails::Railtie)
  require 'active_record/bogacs/railtie'
else
  require 'active_record'
  require 'active_record/connection_adapters/pool_class'
end


text:
package com.probossgamers.turtlemod.items;

import com.probossgamers.turtlemod.entities.EntityKunai;

import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Enchantments;
import net.minecraft.init.Items;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemArrow;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.StatList;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.world.World;

public class ItemKunai extends BasicWeapon
{
    public ItemKunai(String unlocalizedName)
    {
    	super(unlocalizedName, ModItems.Kunai);
        this.maxStackSize = 16;
    }

    /**
     * Gets the velocity of the entity from the charge
     */
    public static float getVelocity(int charge)
    {
        float f = (float)charge / 20.0F;
        f = (f * f + f * 2.0F) / 3.0F;

        if (f > 1.0F)
        {
            f = 1.0F;
        }

        return f;
    }
    /**
     * How long it takes to use or consume an item
     */
    @Override
    public int getMaxItemUseDuration(ItemStack stack)
    {
        return 5000;
    }

    /**
     * returns the action that specifies what animation to play when the items is being used
     */
    public EnumAction getItemUseAction(ItemStack stack)
    {
        return EnumAction.BOW;
    }

    @Override
    public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityLivingBase entityLiving, int timeLeft)
    {
        int i = this.getMaxItemUseDuration(stack) - timeLeft;
        float f = getVelocity(i);
        if (entityLiving instanceof EntityPlayer)
        {
            EntityPlayer entityplayer = (EntityPlayer)entityLiving;
            if ((double)f >= 0.1D)
            {
                boolean flag1 = entityplayer.capabilities.isCreativeMode || (stack.getItem() instanceof ItemKunai && ((ItemKunai) stack.getItem()).isInfinite(stack, entityplayer));

                if (!worldIn.isRemote)
                {

                    EntityKunai entityKunai = new EntityKunai(worldIn, entityLiving);
                    entityKunai.setHeadingFromThrower(entityplayer, entityplayer.rotationPitch, entityplayer.rotationYaw, 0.0F, f * 3.0F, 1.0F);

                    if (f == 1.0F)
                    {
                        entityKunai.setIsCritical(true);
                    }

                    int j = EnchantmentHelper.getEnchantmentLevel(Enchantments.POWER, stack);

                    if (j > 0)
                    {
                        entityKunai.setDamage(entityKunai.getDamage() + (double)j * 0.5D + 0.5D);
                    }

                    int k = EnchantmentHelper.getEnchantmentLevel(Enchantments.PUNCH, stack);

                    if (k > 0)
                    {
                        entityKunai.setKnockbackStrength(k);
                    }

                    if (EnchantmentHelper.getEnchantmentLevel(Enchantments.FLAME, stack) > 0)
                    {
                        entityKunai.setFire(100);
                    }

                    stack.damageItem(1, entityplayer);

                    /*
                   if (flag1 || entityplayer.capabilities.isCreativeMode)
                   {
                   entityKunai.pickupStatus = EntityArrow.PickupStatus.CREATIVE_ONLY;
                   }
                   */

                    worldIn.spawnEntity(entityKunai);
                }

                worldIn.playSound((EntityPlayer)null, entityplayer.posX, entityplayer.posY, entityplayer.posZ, SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.PLAYERS, 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + f * 0.5F);

                if (!flag1 && !entityplayer.capabilities.isCreativeMode)
                {
                    stack.shrink(1);

                    if (stack.isEmpty())
                    {
                        entityplayer.inventory.deleteStack(stack);
                    }
                }

            }

        }
    }
    public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn)
    {
        ItemStack itemStackIn = playerIn.getHeldItem(handIn);

        playerIn.setActiveHand(handIn);
        return new ActionResult(EnumActionResult.SUCCESS, itemStackIn);
    }

    public boolean isInfinite(ItemStack stack, EntityPlayer player)
    {
        int enchant = net.minecraft.enchantment.EnchantmentHelper.getEnchantmentLevel(net.minecraft.init.Enchantments.INFINITY, stack);
        return enchant > 0;
    }
}


text:
using WebKit::WebDocument;
using WebKit::WebFrame;
using WebKit::WebView;

namespace extensions {

namespace {

static base::LazyInstance<ChromeV8Extension::InstanceSet> g_instances =
    LAZY_INSTANCE_INITIALIZER;

}  // namespace

// static
content::RenderView* ChromeV8Extension::GetCurrentRenderView() {
  WebFrame* webframe = WebFrame::frameForCurrentContext();
  DCHECK(webframe) << "RetrieveCurrentFrame called when not in a V8 context.";
  if (!webframe)
    return NULL;

  WebView* webview = webframe->view();
  if (!webview)
    return NULL;  // can happen during closing

  content::RenderView* renderview = content::RenderView::FromWebView(webview);
  DCHECK(renderview) << "Encountered a WebView without a WebViewDelegate";
  return renderview;
}

ChromeV8Extension::ChromeV8Extension(Dispatcher* dispatcher)
    // TODO(svenpanne) It would be nice to remove the GetCurrent() call and use
    // an additional constructor parameter instead, but this would involve too
    // many changes for now.
    : NativeHandler(v8::Isolate::GetCurrent()),
      dispatcher_(dispatcher) {
  g_instances.Get().insert(this);
}

ChromeV8Extension::~ChromeV8Extension() {
  g_instances.Get().erase(this);
}

// static
const ChromeV8Extension::InstanceSet& ChromeV8Extension::GetAll() {
  return g_instances.Get();
}

const Extension* ChromeV8Extension::GetExtensionForCurrentRenderView() const {
  content::RenderView* renderview = GetCurrentRenderView();
  if (!renderview)
    return NULL;  // this can happen as a tab is closing.

  WebDocument document = renderview->GetWebView()->mainFrame()->document();
  GURL url = document.url();
  const ExtensionSet* extensions = dispatcher_->extensions();
  if (!extensions->ExtensionBindingsAllowed(
      ExtensionURLInfo(document.securityOrigin(), url)))
    return NULL;

  return extensions->GetExtensionOrAppByURL(
      ExtensionURLInfo(document.securityOrigin(), url));
}

}  // namespace extensions


text:
namespace Speedioc.Registration.Core
{
	/// <summary>
	/// Represents a property that is set with a specified value after
	/// an instance of the registered type is created.
	/// </summary>
	/// <seealso cref="IValueProperty"/>
	/// <seealso cref="IProperty"/>
	/// <seealso cref="IResolvedProperty"/>
	/// <seealso cref="IValueFactoryProperty"/>
	public class ValueProperty : IValueProperty
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="ValueProperty" /> class.
		/// </summary>
		/// <param name="name">The name of the property to be set.</param>
		/// <param name="value">The value to be set.</param>
		public ValueProperty(string name, object value)
		{
			Name = name;
			Value = value;
		}

		/// <summary>
		/// Gets the name of the property to be set.
		/// </summary>
		/// <value>
		/// The name of the property to be set.
		/// </value>
		public string Name { get; private set; }

		/// <summary>
		/// Gets the value that should be set.
		/// </summary>
		/// <value>
		/// The value that should be set.
		/// </value>
		public object Value { get; private set; }
	}
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0   http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.opengeo</groupId>
        <artifactId>suite</artifactId>
        <version>4-SNAPSHOT</version>
    </parent>
    <groupId>org.opengeo</groupId>
    <artifactId>geoexplorer</artifactId>
    <packaging>jar</packaging>
    <name>OpenGeo Suite GeoExplorer</name>
    <properties>
        <war-src>${project.build.directory}/${project.artifactId}-src</war-src>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.ringojs</groupId>
            <artifactId>ringojs</artifactId>
            <version>0.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-continuation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-xml</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.6.16</version>
        </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <testSourceDirectory>test</testSourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-dependency-plugin</artifactId>
                <configuration>
                    <outputDirectory>${war-src}/WEB-INF/lib</outputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <phase>initialize</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <configuration>
                            <tasks>
                                <copy todir="${war-src}/WEB-INF/app">
                                    <fileset dir="app">
                                        <exclude name="**/externals/**"/>
                                        <exclude name="**/script/**"/>
                                    </fileset>
                                </copy>
                                <!-- copy stick -->
                                <copy todir="${war-src}/WEB-INF/app/stick">
                                    <fileset dir="externals/stick">
                                        <include name="**/lib/**"/>
                                        <include name="package.json"/>
                                    </fileset>
                                </copy>
                                <!-- copy Ext resources -->
                                <copy todir="${war-src}/WEB-INF/app/static/externals/ext">
                                    <fileset dir="app/static/externals/ext">
                                        <exclude name="**/*debug*.js"/>
                                        <exclude name="**/ext-all-notheme.css"/>
                                        <exclude name="**/xtheme-blue.css"/>
                                    </fileset>
                                </copy>
                                <!-- copy OpenLayers resources -->
                                <copy todir="${war-src}/WEB-INF/app/static/externals/openlayers/theme">
                                    <fileset dir="app/static/externals/openlayers/theme"/>
                                </copy>
                                <!-- copy GeoExt resources -->
                                <copy todir="${war-src}/WEB-INF/app/static/externals/geoext/resources">
                                    <fileset dir="app/static/externals/geoext/resources">
                                        <exclude name="**/geoext-all-debug.css"/>
                                        <exclude name="**/gxtheme-slate.css"/>
                                        <exclude name="**/slate/**"/>
                                    </fileset>
                                </copy>
                                <!-- copy gxp resources -->
                                <copy todir="${war-src}/WEB-INF/app/static/externals/gxp/src/theme">
                                    <fileset dir="app/static/externals/gxp/src/theme"/>
                                </copy>
                                <!-- copy PrintPreview resources -->
                                <copy todir="${war-src}/WEB-INF/app/static/externals/printpreview/resources">
                                    <fileset dir="app/static/externals/printpreview/resources"/>
                                </copy>
                                <!-- build JavaScript -->
                                <mkdir dir="${war-src}/WEB-INF/app/static/script"/>
                                <!-- uncompressed -->
                                <java classname="org.ringojs.tools.launcher.Main" failonerror="true" fork="true">
                                    <classpath>
                                        <fileset dir="${war-src}/WEB-INF/lib">
                                            <include name="**/*.jar"/>
                                        </fileset>
                                    </classpath>
                                    <sysproperty key="ringo.home" path="${war-src}/WEB-INF"/>
                                    <arg path="externals/buildkit/lib/buildkit/build.js"/>
                                    <arg value="-u"/>
                                    <arg value="-o"/>
                                    <arg path="${war-src}/WEB-INF/app/static/script"/>
                                    <arg path="buildjs.cfg"/>
                                </java>
                                <move
                                    file="${war-src}/WEB-INF/app/static/script/GeoExplorer.js"
                                    tofile="${war-src}/WEB-INF/app/static/script/GeoExplorer-debug.js"/>
                                <!-- compressed -->
                                <java classname="org.ringojs.tools.launcher.Main" failonerror="true" fork="true">
                                    <classpath>
                                        <fileset dir="${war-src}/WEB-INF/lib">
                                            <include name="**/*.jar"/>
                                        </fileset>
                                    </classpath>
                                    <sysproperty key="ringo.home" path="${war-src}/WEB-INF"/>
                                    <arg path="externals/buildkit/lib/buildkit/build.js"/>
                                    <arg value="-o"/>
                                    <arg path="${war-src}/WEB-INF/app/static/script"/>
                                    <arg path="buildjs.cfg"/>
                                </java>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <warName>${project.artifactId}</warName>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                    <webappDirectory>${project.build.directory}/${project.artifactId}</webappDirectory>
                    <webResources>
                        <resource>
                            <directory>${war-src}/WEB-INF</directory>
                            <targetPath>WEB-INF</targetPath>
                        </resource>
                    </webResources>
                </configuration>
                <executions>
                    <execution>
                        <phase>install</phase>
                        <goals>
                            <goal>war</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
import * as React from 'react';
import { SxProps } from '@material-ui/system';
import { InternalStandardProps as StandardProps, Theme } from '..';
import { ListItemIconClasses } from './listItemIconClasses';

export interface ListItemIconProps extends StandardProps<React.HTMLAttributes<HTMLDivElement>> {
  /**
   * The content of the component, normally `Icon`, `SvgIcon`,
   * or a `@material-ui/icons` SVG icon element.
   */
  children?: React.ReactNode;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<ListItemIconClasses>;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme>;
}

/**
 * A simple wrapper to apply `List` styles to an `Icon` or `SvgIcon`.
 *
 * Demos:
 *
 * - [Lists](https://material-ui.com/components/lists/)
 *
 * API:
 *
 * - [ListItemIcon API](https://material-ui.com/api/list-item-icon/)
 */
export default function ListItemIcon(props: ListItemIconProps): JSX.Element;


text:
@interface TouchableTextsDetail : UIViewController  <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate> {
	UITableView *tableview;
	UITextField *vartitle;
	UITextView *varcurrentvalue;
}

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) UITextField *vartitle;
@property (nonatomic, strong) UITextView *varcurrentvalue;

@end


text:
.class Lcom/android/internal/telephony/gsm/GSMPhone$Cfu;
.super Ljava/lang/Object;
.source "GSMPhone.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/telephony/gsm/GSMPhone;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Cfu"
.end annotation

# instance fields
.field final mOnComplete:Landroid/os/Message;

.field final mSetCfNumber:Ljava/lang/String;

# direct methods
.method constructor <init>(Ljava/lang/String;Landroid/os/Message;)V
    .locals 0
    .param p1, "cfNumber"    # Ljava/lang/String;
    .param p2, "onComplete"    # Landroid/os/Message;

    .prologue
    .line 324
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 325
    iput-object p1, p0, Lcom/android/internal/telephony/gsm/GSMPhone$Cfu;->mSetCfNumber:Ljava/lang/String;

    .line 326
    iput-object p2, p0, Lcom/android/internal/telephony/gsm/GSMPhone$Cfu;->mOnComplete:Landroid/os/Message;

    .line 327
    return-void
.end method


text:
<?php
namespace Concrete\DocumentationGenerator\Generator\Vendor;

use Concrete\DocumentationGenerator\Generator\AbstractGenerator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class VendorLibraryListGenerator extends AbstractGenerator
{

    public function getHandle()
    {
        return "vendor_library_list";
    }

    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     *
     * @return null|int null or 0 if everything went fine, or an error code
     */
    public function generate(InputInterface $input, OutputInterface $output)
    {
        $libraries = json_decode(file_get_contents(DIR_BASE_CORE . "/composer.lock"), true);

        $output->writeln(array(
            "# Composer Libraries",
            "",
            " Handle | Version | Description ",
            " ------ | ------- | ----------- "));

        foreach ($libraries['packages'] as $package) {
            $output->writeln(
                "[{$package['name']}]({$package['source']['url']}) | {$package['version']} | {$package['description']}"
            );
        }
    }

}


text:
var pact = require('../pact.js');

exports.main = function(req, res){
  pact.models.posts.find({}).limit(10).sort('-date').exec(function(err, data){
    if(err) { throw err; }
    res.render('index', {
      title: 'Welcome',
      user: req.session.user,
      posts: data
    });
  });
};


text:
{% extends "_base.html" %}
{% block bodycontent %}

Sign up!

    <form action="/signup" method="post" name="signupForm">

Your Email

{{ user_email }}

First name

<input type="text" name="firstname" id="firstname" value="{{ profile.first_name }}"/>

Last name

<input type="text" name="lastname" id="lastname" value="{{ profile.last_name }}"/>

Time zone

	            <select name='timezone' id="timezone">
	                <option {% ifequal profile.timezone "est"%} selected {% endifequal %} value="est">(GMT-5:00) Eastern Time</option>
	                <option {% ifequal profile.timezone "cst"%} selected {% endifequal %} value="cst">(GMT-6:00) Central Time</option>
	                <option {% ifequal profile.timezone "mst"%} selected {% endifequal %} value="mst">(GMT-7:00) Mountain Time</option>
	                <option {% ifequal profile.timezone "pst"%} selected {% endifequal %} value="pst">(GMT-8:00) Pacific Time</option>
	            </select>

			<input type="submit" value="Continue »"></input>

    </form>

{% endblock %}


text:
package eth

import (
	"context"
	"fmt"
	"math/big"
	"strings"
	"sync"
	"time"

	ethereum "github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	ethcommon "github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/event"
	"github.com/golang/glog"
	"github.com/livepeer/go-livepeer/common"
)

// The default price bump required by geth is 10%
// We add a little extra in addition to the 10% price bump just to be safe
// priceBump is a % value from 0-100
const priceBump uint64 = 11

type transactionSenderReader interface {
	ethereum.TransactionSender
	ethereum.TransactionReader
	// Required for bind.DeployBackend argument in bind.WaitMined
	CodeAt(context.Context, ethcommon.Address, *big.Int) ([]byte, error)
}

type transactionSigner interface {
	SignTx(tx *types.Transaction) (*types.Transaction, error)
}

type TransactionManager struct {
	txTimeout       time.Duration
	maxReplacements int

	queue transactionQueue

	// subscriptions
	feed  event.Feed
	scope event.SubscriptionScope

	eth transactionSenderReader
	gpm *GasPriceMonitor
	sig transactionSigner

	cond *sync.Cond

	quit chan struct{}
}

type transactionQueue []*types.Transaction

type transactionReceipt struct {
	originTxHash ethcommon.Hash
	types.Receipt
	err error
}

func (tq *transactionQueue) add(tx *types.Transaction) {
	*tq = append(*tq, tx)
}

func (tq *transactionQueue) pop() *types.Transaction {
	if tq.length() == 0 {
		return nil
	}
	tx := (*tq)[0]
	*tq = (*tq)[1:]
	return tx
}

func (tq transactionQueue) length() int {
	return len(tq)
}

func (tq transactionQueue) peek() *types.Transaction {
	if tq.length() == 0 {
		return nil
	}
	return tq[0]
}

func NewTransactionManager(eth transactionSenderReader, gpm *GasPriceMonitor, signer transactionSigner, txTimeout time.Duration, maxReplacements int) *TransactionManager {
	return &TransactionManager{
		cond:            sync.NewCond(&sync.Mutex{}),
		txTimeout:       txTimeout,
		maxReplacements: maxReplacements,
		eth:             eth,
		gpm:             gpm,
		sig:             signer,
		queue:           transactionQueue{},
		quit:            make(chan struct{}),
	}
}

func (tm *TransactionManager) SendTransaction(ctx context.Context, tx *types.Transaction) error {
	sendErr := tm.eth.SendTransaction(ctx, tx)

	txLog, err := newTxLog(tx)
	if err != nil {
		txLog.method = "unknown"
	}

	if sendErr != nil {
		glog.Infof("\n%vEth Transaction%v\n\nInvoking transaction: \"%v\". Inputs: \"%v\"   \nTransaction Failed: %v\n\n%v\n", strings.Repeat("*", 30), strings.Repeat("*", 30), txLog.method, txLog.inputs, sendErr, strings.Repeat("*", 75))
		return sendErr
	}

	// Add transaction to queue
	tm.cond.L.Lock()
	tm.queue.add(tx)
	tm.cond.L.Unlock()
	tm.cond.Signal()

	glog.Infof("\n%vEth Transaction%v\n\nInvoking transaction: \"%v\". Inputs: \"%v\"  Hash: \"%v\". \n\n%v\n", strings.Repeat("*", 30), strings.Repeat("*", 30), txLog.method, txLog.inputs, tx.Hash().String(), strings.Repeat("*", 75))

	return nil
}

func (tm *TransactionManager) Subscribe(sink chan<- *transactionReceipt) event.Subscription {
	return tm.scope.Track(tm.feed.Subscribe(sink))
}

func (tm *TransactionManager) Start() {
	tm.checkTxLoop()
}

func (tm *TransactionManager) Stop() {
	tm.scope.Close()
	close(tm.quit)
}

func (tm *TransactionManager) wait(tx *types.Transaction) (*types.Receipt, error) {
	ctx, cancel := context.WithTimeout(context.Background(), tm.txTimeout)
	defer cancel()

	return bind.WaitMined(ctx, tm.eth, tx)
}

func (tm *TransactionManager) replace(tx *types.Transaction) (*types.Transaction, error) {
	_, pending, err := tm.eth.TransactionByHash(context.Background(), tx.Hash())
	// Only return here if the error is not related to the tx not being found
	// Presumably the provided tx was already broadcasted at some point, so even if for some reason the
	// node being used cannot find it, the originally broadcasted tx is still valid and might be sitting somewhere
	if err != nil && err != ethereum.NotFound {
		return nil, err
	}
	// If tx was found
	// If `pending` is false, the tx was mined and included in a block
	if err == nil && !pending {
		return nil, ErrReplacingMinedTx
	}

	newRawTx := newReplacementTx(tx)

	// Bump gas price exceeds max gas price, return early
	max := tm.gpm.MaxGasPrice()
	newGasPrice := calcGasPrice(newRawTx)
	if max != nil && newGasPrice.Cmp(max) > 0 {
		return nil, fmt.Errorf("replacement gas price exceeds max gas price suggested=%v max=%v", newGasPrice, max)
	}

	newSignedTx, err := tm.sig.SignTx(newRawTx)
	if err != nil {
		return nil, err
	}

	sendErr := tm.eth.SendTransaction(context.Background(), newSignedTx)
	txLog, err := newTxLog(tx)
	if err != nil {
		txLog.method = "unknown"
	}
	if sendErr != nil {
		glog.Infof("\n%vEth Transaction%v\n\nReplacement transaction: \"%v\". \nTransaction Failed: %v\n\n%v\n", strings.Repeat("*", 30), strings.Repeat("*", 30), txLog.method, sendErr, strings.Repeat("*", 75))
	} else {
		glog.Infof("\n%vEth Transaction%v\n\nReplacement transaction: \"%v\".  Hash: \"%v\". \n\n%v\n", strings.Repeat("*", 30), strings.Repeat("*", 30), txLog.method, newSignedTx.Hash().String(), strings.Repeat("*", 75))
	}

	return newSignedTx, sendErr
}

func (tm *TransactionManager) checkTxLoop() {
	for {
		tm.cond.L.Lock()
		for tm.queue.length() == 0 {
			tm.cond.Wait()

			select {
			case <-tm.quit:
				tm.cond.L.Unlock()
				glog.V(common.DEBUG).Info("Stopping transaction manager")
				return
			default:
			}
		}

		tx := tm.queue.pop()
		tm.cond.L.Unlock()

		originHash := tx.Hash()

		var txReceipt types.Receipt

		receipt, err := tm.wait(tx)

		// context.DeadlineExceeded indicates that we hit the txTimeout
		// If we hit the txTimeout, replace the tx up to maxReplacements times
		for i := 0; err == context.DeadlineExceeded && i < tm.maxReplacements; i++ {
			tx, err = tm.replace(tx)
			// Do not attempt additional replacements if there was an error submitting this
			// replacement tx
			if err != nil {
				break
			}
			receipt, err = tm.wait(tx)
		}

		if receipt == nil {
			txReceipt = types.Receipt{}
		} else {
			txReceipt = *(receipt)
		}

		tm.feed.Send(&transactionReceipt{
			originTxHash: originHash,
			Receipt:      txReceipt,
			err:          err,
		})

	}
}

func applyPriceBump(val *big.Int, priceBump uint64) *big.Int {
	a := big.NewInt(100 + int64(priceBump))
	b := new(big.Int).Mul(a, val)
	// div round up
	return b.Div(new(big.Int).Add(b, big.NewInt(99)), big.NewInt(100))
}

// Calculate the gas price as gas tip cap + base fee
func calcGasPrice(tx *types.Transaction) *big.Int {
	if tx.GasFeeCap() == nil {
		// legacy tx, not London ready
		return tx.GasPrice()
	} else {
		// Assume that the gas fee cap is calculated as gas tip cap + (baseFee * 2)
		baseFee := new(big.Int).Div(new(big.Int).Sub(tx.GasFeeCap(), tx.GasTipCap()), big.NewInt(2))
		return new(big.Int).Add(baseFee, tx.GasTipCap())
	}
}

func newReplacementTx(tx *types.Transaction) *types.Transaction {
	var baseTx types.TxData
	if tx.GasFeeCap() == nil {
		// legacy tx, not London ready
		baseTx = &types.LegacyTx{
			Nonce:    tx.Nonce(),
			GasPrice: applyPriceBump(tx.GasPrice(), priceBump),
			Gas:      tx.Gas(),
			To:       tx.To(),
			Value:    tx.Value(),
			Data:     tx.Data(),
		}
	} else {
		baseTx = &types.DynamicFeeTx{
			Nonce: tx.Nonce(),
			// geth requires the price bump to be applied to both the gas tip cap and gas fee cap
			GasFeeCap: applyPriceBump(tx.GasFeeCap(), priceBump),
			GasTipCap: applyPriceBump(tx.GasTipCap(), priceBump),
			Gas:       tx.Gas(),
			Value:     tx.Value(),
			Data:      tx.Data(),
			To:        tx.To(),
		}
	}

	return types.NewTx(baseTx)
}


text:
@interface XLFormOptionsViewController : UITableViewController<XLFormRowDescriptorViewController, XLFormRowDescriptorPopoverViewController>

- (id)initWithStyle:(UITableViewStyle)style;

- (id)initWithStyle:(UITableViewStyle)style
    titleHeaderSection:(NSString *)titleHeaderSection
    titleFooterSection:(NSString *)titleFooterSection;

@end


text:
<?php

namespace Omnipay\Braintree\Message;

use Braintree\Configuration;
use Braintree\Result\Error;
use Braintree\Result\Successful;
use Omnipay\Tests\TestCase;

class ResponseTest extends TestCase
{
    /**
     * @var AuthorizeRequest
     */
    private $request;

    public function setUp()
    {
        parent::setUp();

        $this->request = new AuthorizeRequest($this->getHttpClient(), $this->getHttpRequest(), Configuration::gateway());
    }

    public function testSuccess()
    {
        $data = new Successful(1, 'transaction');

        $response = new Response($this->request, $data);

        $this->assertTrue($response->isSuccessful());
        $this->assertFalse($response->isRedirect());
        $this->assertEmpty($response->getMessage());
    }

    public function testError()
    {
        $data = new Error(array('errors' => array(), 'params' => array(), 'message' => 'short message'));

        $response = new Response($this->request, $data);

        $this->assertFalse($response->isSuccessful());
        $this->assertFalse($response->isRedirect());
        $this->assertEquals('short message', $response->getMessage());
    }

}


text:
![Kafka Dashboard][1]

## Overview

This Agent check only collects metrics for message offsets. If you want to collect JMX metrics from the Kafka brokers or Java-based consumers/producers, see the kafka check.

This check fetches the highwater offsets from the Kafka brokers, consumer offsets that are stored in Kafka or zookeeper (for old-style consumers), and the calculated consumer lag (which is the difference between the broker offset and the consumer offset).

**Note:** This integration ensures that consumer offsets are checked before broker offsets because worst case is that consumer lag is a little overstated. Doing it in reverse can understate consumer lag to the point of having negative values, which is a dire scenario usually indicating messages are being skipped.

## Setup

### Installation

The Agent's Kafka consumer check is included in the [Datadog Agent][2] package. No additional installation is needed on your Kafka nodes.

### Configuration

<!-- xxx tabs xxx -->
<!-- xxx tab "Host" xxx -->

#### Host

To configure this check for an Agent running on a host:

##### Metric collection

1. Edit the `kafka_consumer.d/conf.yaml` file, in the `conf.d/` folder at the root of your [Agent's configuration directory][3]. See the [sample kafka_consumer.d/conf.yaml][4] for all available configuration options.

2. [Restart the Agent][5].

##### Log collection

This check does not collect additional logs. To collect logs from Kafka brokers, see [log collection instructions for Kafka][6].

<!-- xxz tab xxx -->
<!-- xxx tab "Containerized" xxx -->

#### Containerized

For containerized environments, see the [Autodiscovery with JMX][7] guide.

<!-- xxz tab xxx -->
<!-- xxz tabs xxx -->

### Validation

[Run the Agent's status subcommand][8] and look for `kafka_consumer` under the Checks section.

## Data Collected

### Metrics

See [metadata.csv][9] for a list of metrics provided by this check.

### Events

**consumer_lag**:<br>
The Datadog Agent emits an event when the value of the `consumer_lag` metric goes below 0, tagging it with `topic`, `partition` and `consumer_group`.

### Service Checks

The Kafka-consumer check does not include any service checks.

## Troubleshooting

- [Troubleshooting and Deep Dive for Kafka][10]
- [Agent failed to retrieve RMIServer stub][11]

**Kerberos GSSAPI Authentication**

Depending on your Kafka cluster's Kerberos setup, you may need to configure the following:

* Kafka client configured for the Datadog Agent to connect to the Kafka broker. The Kafka client should be added as a Kerberos principal and added to a Kerberos keytab. The Kafka client should also have a valid kerberos ticket.
* TLS certificate to authenticate a secure connection to the Kafka broker.
  * If JKS keystore is used, a certificate needs to be exported from the keystore and the file path should be configured with the applicable `tls_cert` and/or `tls_ca_cert` options.
  * If a private key is required to authenticate the certificate, it should be configured with the `tls_private_key` option. If applicable, the private key password should be configured with the `tls_private_key_password`.
* `KRB5_CLIENT_KTNAME` environment variable pointing to the Kafka client's Kerberos keytab location if it differs from the default path (for example, `KRB5_CLIENT_KTNAME=/etc/krb5.keytab`)
* `KRB5CCNAME` environment variable pointing to the Kafka client's Kerberos credentials ticket cache if it differs from the default path (for example, `KRB5CCNAME=/tmp/krb5cc_xxx`)
* If the Datadog Agent is unable to access the environment variables, configure the environment variables in a Datadog Agent service configuration override file for your operating system. The procedure for modifying the Datadog Agent service unit file may vary for different Linux operating systems. For example, in a Linux `systemd` environment:

**Linux Systemd Example**

1. Configure the environment variables in an environment file.
   For example: `/path/to/environment/file`

  ```
  KRB5_CLIENT_KTNAME=/etc/krb5.keytab
  KRB5CCNAME=/tmp/krb5cc_xxx
  ```

2. Create a Datadog Agent service configuration override file: `sudo systemctl edit datadog-agent.service`

3. Configure the following in the override file:

  ```
  [Service]
  EnvironmentFile=/path/to/environment/file
  ```

4. Run the following commands to reload the systemd daemon, datadog-agent service, and Datadog Agent:

```
sudo systemctl daemon-reload
sudo systemctl restart datadog-agent.service
sudo service datadog-agent restart
```

## Further Reading

- [Monitoring Kafka performance metrics][13]
- [Collecting Kafka performance metrics][14]
- [Monitoring Kafka with Datadog][15]

[1]: https://raw.githubusercontent.com/DataDog/integrations-core/master/kafka_consumer/images/kafka_dashboard.png
[2]: https://app.datadoghq.com/account/settings#agent
[3]: https://docs.datadoghq.com/agent/guide/agent-configuration-files/#agent-configuration-directory
[4]: https://github.com/DataDog/integrations-core/blob/master/kafka_consumer/datadog_checks/kafka_consumer/data/conf.yaml.example
[5]: https://docs.datadoghq.com/agent/guide/agent-commands/#start-stop-and-restart-the-agent
[6]: https://docs.datadoghq.com/integrations/kafka/#log-collection
[7]: https://docs.datadoghq.com/agent/guide/autodiscovery-with-jmx/?tab=containerizedagent
[8]: https://docs.datadoghq.com/agent/guide/agent-commands/#agent-status-and-information
[9]: https://github.com/DataDog/integrations-core/blob/master/kafka_consumer/metadata.csv
[10]: https://docs.datadoghq.com/integrations/faq/troubleshooting-and-deep-dive-for-kafka/
[11]: https://docs.datadoghq.com/integrations/guide/agent-failed-to-retrieve-rmiserver-stub/
[13]: https://www.datadoghq.com/blog/monitoring-kafka-performance-metrics
[14]: https://www.datadoghq.com/blog/collecting-kafka-performance-metrics
[15]: https://www.datadoghq.com/blog/monitor-kafka-with-datadog


text:
from unittest import mock

from tornado.testing import AsyncHTTPTestCase, ExpectLog
from remoteappmanager.file_config import FileConfig

from remoteappmanager.tests.mocking import dummy
from remoteappmanager.tests.temp_mixin import TempMixin

class TestBaseHandler(TempMixin, AsyncHTTPTestCase):
    def get_file_config(self):
        file_config = FileConfig()
        file_config.database_class = \
            'remoteappmanager.tests.mocking.dummy.DummyDB'
        file_config.database_kwargs = {}
        return file_config

    def get_app(self):
        file_config = self.get_file_config()

        app = dummy.create_application(file_config=file_config)
        app.hub.get_user.return_value = {
            'pending': None,
            'name': app.settings['user'],
            'admin': False,
            'server': app.settings['base_urlpath']}
        return app

@mock.patch.dict('os.environ', {"JUPYTERHUB_CLIENT_ID": 'client-id'})
@mock.patch('jupyterhub.services.auth.HubOAuth.get_user')
class TestBaseHandlerInvalidAccounting(TestBaseHandler):
    def get_file_config(self):
        file_config = super().get_file_config()
        file_config.database_class = 'this_should_fail'
        return file_config

    def test_home_internal_error(self, mock_get_user):
        with ExpectLog('tornado.application', ''), \
                ExpectLog('tornado.access', ''):
            res = self.fetch("/user/johndoe/",
                             headers={
                                 "Cookie": "jupyter-hub-token-johndoe=foo"
                             }
                             )

        self.assertEqual(res.code, 500)
        self.assertIn('Internal Server Error', str(res.body))
        self.assertIn(" Ref.:", str(res.body))

@mock.patch.dict('os.environ', {"JUPYTERHUB_CLIENT_ID": 'client-id'})
@mock.patch('jupyterhub.services.auth.HubOAuth.get_user')
class TestBaseHandlerDatabaseError(TestBaseHandler):
    def get_file_config(self):
        file_config = super().get_file_config()
        file_config.database_class = "remoteappmanager.db.orm.ORMDatabase"
        return file_config

    def test_home_internal_error(self, mock_get_user):
        with ExpectLog('tornado.application', ''), \
                ExpectLog('tornado.access', ''):
            res = self.fetch("/user/johndoe/",
                             headers={
                                 "Cookie": "jupyter-hub-token-johndoe=foo"
                             }
                             )

        self.assertEqual(res.code, 500)
        self.assertIn('Internal Server Error', str(res.body))
        self.assertIn("The database is not initialised properly. Ref.:",
                      str(res.body))

@mock.patch.dict('os.environ', {"JUPYTERHUB_CLIENT_ID": 'client-id'})
@mock.patch('jupyterhub.services.auth.HubOAuth.get_user')
class TestBaseHandlerGATracking(TestBaseHandler):
    def get_file_config(self):
        file_config = super().get_file_config()
        file_config.ga_tracking_id = "UA-12345-6"
        return file_config

    def test_ga_tracking(self, mock_get_user):
        res = self.fetch("/user/johndoe/",
                         headers={
                             "Cookie": "jupyter-hub-token-johndoe=foo"
                         }
                         )

        self.assertEqual(res.code, 200)
        self.assertIn("UA-12345-6", str(res.body))