text:
package com.google.gwtmockito;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwtmockito.fakes.FakeProvider;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link GwtMockito} when not running with
 * {@link GwtMockitoTestRunner}, as would be the case for JUnit3 or in tests
 * that must use a different runner.
 */
@RunWith(JUnit4.class)
public class GwtMockitoRunnerlessTest {

  @GwtMock SampleInterface mockedInterface;

  @Before
  public void setUp() {
    GwtMockito.initMocks(this);
  }

  @After
  public void tearDown() {
    GwtMockito.tearDown();
  }

  @Test
  public void shouldReturnMocksFromGwtCreate() {
    SampleInterface createdInterface = GWT.create(SampleInterface.class);
    createdInterface.doSomething();
    verify(mockedInterface).doSomething();
  }

  @Test
  public void shouldCreateFakeUiBinders() {
    SampleWidget widget = new SampleWidget() {
      @Override
      protected void initWidget(Widget widget) { /* disarm */ }
    };
    widget.setText("text");
    verify(widget.label).setText("text");
  }

  @Test
  public void canUseProvidersForTypes() {
    GwtMockito.useProviderForType(AnotherInterface.class, new FakeProvider<AnotherInterface>() {
      @Override
      public AnotherInterface getFake(Class<?> type) {
        return new AnotherInterface() {
          @Override
          public String doSomethingElse() {
            return "some value";
          }
        };
      }
    });

    AnotherInterface result = GWT.create(AnotherInterface.class);

    assertEquals("some value", result.doSomethingElse());
  }

  @Test(expected = UnsupportedOperationException.class)
  public void shouldRestoreGwtCreateAfterTearDown() {
    GwtMockito.tearDown();
    GWT.create(SampleInterface.class);
  }

  private interface SampleInterface {
    String doSomething();
  }

  private interface AnotherInterface {
    String doSomethingElse();
  }

  private static class SampleWidget extends Composite {

    interface MyUiBinder extends UiBinder<Widget, SampleWidget> {}

    @UiField Label label;

    SampleWidget() {
      MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
      initWidget(uiBinder.createAndBindUi(this));
    }

    void setText(String text) {
      label.setText(text);
    }
  }
}


text:
using UnityEngine;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;

/// <summary>
/// Scoreflex exposes via static methods the whole of Scoreflex's behavior.
/// </summary>
public partial class Scoreflex : MonoBehaviour
{
	public string ClientId;
	public string ClientSecret;
	public bool Sandbox;

	public enum Gravity { Default = 0, Bottom = 1, Top = 2 };

	/// <summary>
	/// Scoreflex.View instances are associated with panel views; they allow you to close them.
	/// </summary>
	public class View
	{
		public readonly int handle;

		public View(int _handle)
		{
			handle = _handle;
		}

		/// <summary>
		/// Close an on-screen panel view.
		/// </summary>
		public void Close()
		{
			#if UNITY_IPHONE
			Scoreflex.scoreflexHidePanelView(handle);
			#elif UNITY_ANDROID
			if(Scoreflex.Instance != null) Scoreflex.Instance._HidePanelView(handle);
			#endif
		}
	}

	private static Scoreflex Instance;

	private bool initialized = false;

	/// <summary>
	/// Checks if <see cref="Scoreflex"/> is initialized.
	/// </summary>
	/// <value><c>true</c> if live; otherwise, <c>false</c>.</value>
	public static bool Live {
		get {
			return Instance != null && Instance.initialized;
		}
	}

	private const string ErrorNotLive = "Scoreflex: Method called while not live.";

	/// <summary>
	/// Methods added to this delegate will be called when Scoreflex wishes
	/// to start a solo play session. The single argument is the leaderboard ID.
	/// </summary>
	public static System.Action<string> PlaySoloHandlers = null;

	/// <summary>
	/// Methods added to this delegate will be called when the Scoreflex user
	/// wants to play an accepted challenge. Challenges should be handled by
	/// calling up the relevant level and allowing the player to make their move,
	/// followed by a call to Scoreflex.SubmitTurn.
	/// </summary>
	public static System.Action<Dictionary<string,object>> ChallengeHandlers = null;

	private const Gravity SuperDefaultGravity = Gravity.Top;
	public static Gravity DefaultGravity = SuperDefaultGravity;

	private static Gravity FilterGravity(Gravity gravity)
	{
		if(gravity == Gravity.Default) gravity = DefaultGravity;
		if(gravity == Gravity.Default) gravity = SuperDefaultGravity;
		return gravity;
	}

	// CALLBACK FACILITY //

	public delegate void Callback(bool success, Dictionary<string,object> response);

	public delegate void ModelCallback<T>(bool success, T result);

	private readonly Dictionary<string,Callback> CallbackTable = new Dictionary<string,Callback>();

	string RegisterCallback(Callback callback)
	{
		string key;
		var random = new System.Random();
		do {
			key = random.Next().ToString();
		} while(CallbackTable.ContainsKey(key));

		CallbackTable[key] = callback;

		return key;
	}

	void HandleCallback(string figure)
	{
		if(figure.Contains(":"))
		{
			bool success = figure.Contains("success");
			string handlerKey = figure.Split(':')[0];
			string jsonString = figure.Substring(handlerKey.Length + ":success:".Length); // :failure is the same length

			var dictionary = new Dictionary<string,object>();

			try
			{
				if(jsonString.Length > 0)
				{
					var parsed = MiniJSON.Json.Deserialize(jsonString) as Dictionary<string,object>;

					foreach(var kvp in parsed)
					{
						dictionary.Add(kvp.Key, kvp.Value);
					}
				}
			}
			catch(System.Exception ex)
			{
				Debug.LogException(ex);
				Debug.LogError("Scoreflex: Received unparsable JSON code: " + jsonString);
			}

			if(CallbackTable.ContainsKey(handlerKey))
			{
				CallbackTable[handlerKey](success, dictionary);
				CallbackTable.Remove(handlerKey);
			}
			else
			{
				Debug.Log("Scoreflex: Received invalid callback code from native library: " + handlerKey);
			}
		}
		else
		{
			Debug.Log("Scoreflex: Received invalid callback code from native library: " + figure);
		}
	}

	void HandlePlaySolo(string figure)
	{
		if(PlaySoloHandlers == null)
		{
			Debug.LogError("Scoreflex: Instructed to play solo, but no handlers configured! Please assign to Scoreflex.Instance.PlaySoloHandlers");
		}
		else
		{
			PlaySoloHandlers(figure);
		}
	}

	void HandleChallenge(string figure)
	{
		if(ChallengeHandlers == null)
		{
			Debug.LogError("Scoreflex: Received challenge, but found no challenge handler! Please assign to Scoreflex.Instance.ChallengeHandlers");
		}
		else
		{
			var dict = MiniJSON.Json.Deserialize(figure) as Dictionary<string,object>;
			ChallengeHandlers(dict);
		}
	}

	// WRAPPERS //

	/// <summary>
	/// Gets the current language used by Scoreflex.
	/// </summary>
	/// <returns>Valid figures are:
	/// af, ar, be,	bg, bn, ca, cs, da, de, el, en, en_GB, en_US,
	/// es, es_ES, es_MX, et, fa, fi, fr, fr_FR, fr_CA,
	/// he, hi, hr, hu, id, is, it, ja, ko, lt, lv,
	/// mk, ms, nb, nl, pa, pl, pt, pt_PT, pt_BR, ro,
	/// ru, sk, sl, sq, sr, sv, sw, ta, th, tl, tr,
	/// uk, vi, zh, zh_CN, zh_TW, zh_HK
	/// </returns>
	public static string GetLanguageCode()
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			return string.Empty;
		}
		else
			return Instance._GetLanguageCode();
	}

	/// <summary>
	/// Sets the Scoreflex language.
	/// </summary>
	/// <param name="languageCode">Language code.
	/// Valid figures are:
	/// af, ar, be,	bg, bn, ca, cs, da, de, el, en, en_GB, en_US,
	/// es, es_ES, es_MX, et, fa, fi, fr, fr_FR, fr_CA,
	/// he, hi, hr, hu, id, is, it, ja, ko, lt, lv,
	/// mk, ms, nb, nl, pa, pl, pt, pt_PT, pt_BR, ro,
	/// ru, sk, sl, sq, sr, sv, sw, ta, th, tl, tr,
	/// uk, vi, zh, zh_CN, zh_TW, zh_HK</param>
	public static void SetLanguageCode(string languageCode)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._SetLanguageCode(languageCode);
	}

	/// <summary>
	/// If network is available, preload a view with the specified ressource and
	/// hold a reference on it until the view is shown or freed.
	/// </summary>
	/// <param name="resource">Name of the resource to preload.</param>
	public static void PreloadResource(string resource)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._PreloadResource(resource);
	}

	/// <summary>
	/// Frees the preloaded resource.
	/// </summary>
	/// <param name="resource">Name of the preloaded resource.</param>
	public static void FreePreloadedResource(string resource)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._FreePreloadedResource(resource);
	}

	/// <summary>
	/// Identifies whether the Scoreflex server is reachable.
	/// </summary>
	/// <value><c>true</c> if the server is reachable; otherwise, <c>false</c>.</value>
	public static bool IsReachable {
		get {
			if(!Live) {
				Debug.Log(ErrorNotLive);
				return false;
			}
			else
				return Instance._IsReachable;
		}
	}

	/// <summary>
	/// Gets the player identifier.
	/// </summary>
	/// <returns>The player identifier.</returns>
	public static string GetPlayerId()
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			return string.Empty;
		}
		else
			return Instance._GetPlayerId();
	}

	/// <summary>
	/// Returns the time interval between when <see cref="StartPlayingSession"/> and
	/// <see cref="StopPlayingSession"/> have been called.
	/// </summary>
	/// <returns>The playing time.</returns>
	public static float GetPlayingTime()
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			return 0f;
		}
		else
			return Instance._GetPlayingTime();
	}

	/// <summary>
	/// Call up a given full screen view.
	/// </summary>
	/// <param name="resource">Scoreflex resource name.</param>
	/// <param name="parameters">Parameters. These will be encoded as JSON and passed up to the server with the REST call.</param>
	public static void ShowFullscreenView(string resource, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowFullscreenView(resource, parameters);
	}

	/// <summary>
	/// Call up a given panel view.
	/// </summary>
	/// <returns>A <see cref="Scoreflex.View"/> instance which can close the panel view at any time.</returns>
	/// <param name="resource">Scoreflex resource name.</param>
	/// <param name="parameters">Parameters. These will be encoded as JSON and passed up to the server with the REST call.</param>
	/// <param name="gravity">Vertical alignment. Can be Scoreflex.Gravity.Top, .Bottom or .Default.</param>
	public static View ShowPanelView(string resource, Dictionary<string,object> parameters = null, Gravity gravity = Gravity.Top)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			return null;
		}
		else
			return Instance._ShowPanelView(resource, parameters, gravity);
	}

	/// <summary>
	/// Sets the device token. This interface is for iOS push notifications.
	/// </summary>
	/// <param name="deviceToken">Device token.</param>
	public static void SetDeviceToken(string deviceToken)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._SetDeviceToken(deviceToken);
	}

	/// <summary>
	/// Shows (fullscreen) other games from the given developer.
	/// </summary>
	/// <param name="developerId">Developer identifier.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowDeveloperGames(string developerId, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowDeveloperGames(developerId, parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the developer profile.
	/// </summary>
	/// <param name="developerId">Developer identifier.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowDeveloperProfile(string developerId, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowDeveloperProfile(developerId, parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the game details.
	/// </summary>
	/// <param name="gameId">Game identifier.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowGameDetails(string gameId, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowGameDetails(gameId, parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the game players.
	/// </summary>
	/// <param name="gameId">Game identifier.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowGamePlayers(string gameId, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowGamePlayers(gameId, parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the given leaderboard.
	/// </summary>
	/// <param name="leaderboardId">Leaderboard identifier.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowLeaderboard(string leaderboardId, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowLeaderboard(leaderboardId, parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the leaderboard overview.
	/// </summary>
	/// <param name="leaderboardId">Leaderboard identifier.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowLeaderboardOverview(string leaderboardId, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowLeaderboardOverview(leaderboardId, parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the player challenges.
	/// </summary>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowPlayerChallenges(Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowPlayerChallenges(parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the player friends.
	/// </summary>
	/// <param name="playerId">Player identifier.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowPlayerFriends(string playerId = null, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowPlayerFriends(playerId, parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the player's news feed.
	/// </summary>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowPlayerNewsFeed(Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowPlayerNewsFeed(parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the player profile.
	/// </summary>
	/// <param name="playerId">Player identifier.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowPlayerProfile(string playerId = null, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowPlayerProfile(playerId, parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the player profile edit.
	/// </summary>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowPlayerProfileEdit(Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowPlayerProfileEdit(parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the player rating.
	/// </summary>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowPlayerRating(Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowPlayerRating(parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the player settings.
	/// </summary>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowPlayerSettings(Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowPlayerSettings(parameters);
	}

	/// <summary>
	/// Shows (fullscreen) the search.
	/// </summary>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	public static void ShowSearch(Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowSearch(parameters);
	}

	/// <summary>
	/// Show the ranks panel immediately with a given score. The score will not be sent up to the server. Call this in
	/// conjunction with SubmitScore which will asynchronously push the score up to the server.
	/// </summary>
	/// <param name="leaderboardId">Leaderboard identifier.</param>
	/// <param name="score">Score.</param>
	/// <param name="parameters">Parameters which will be passed up with the REST call. Optional; can be null.</param>
	/// <param name="gravity">Vertical alignment. Can be Scoreflex.Gravity.Top, .Bottom or .Default.</param>
	public static void ShowRanksPanel(string leaderboardId, long score, Dictionary<string,object> parameters = null, Gravity gravity = Gravity.Top)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._ShowRanksPanel(leaderboardId, score, parameters, gravity);
	}

	/// <summary>
	/// Hide the ranks panel if it is on screen.
	/// </summary>
	public static void HideRanksPanel()
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._HideRanksPanel();
	}

	/// <summary>
	/// Start a play session.
	/// </summary>
	public static void StartPlayingSession()
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._StartPlayingSession();
	}

	/// <summary>
	/// Stops timing the play session.
	/// </summary>
	public static void StopPlayingSession()
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._StopPlayingSession();
	}

	/// <summary>
	/// A GET request to the Scoreflex server.
	/// </summary>
	/// <param name="resource">The Scoreflex resource.</param>
	/// <param name="parameters">Parameters passed up with the REST query.</param>
	/// <param name="callback">The response handler.</param>
	public static void Get(string resource, Dictionary<string,object> parameters, Callback callback)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			callback(false, new Dictionary<string,object>());
		}
		else
			Instance._Get(resource, parameters, callback);
	}

	/// <summary>
	/// A PUT request to the Scoreflex server.
	/// </summary>
	/// <param name="resource">The Scoreflex resource.</param>
	/// <param name="parameters">Parameters passed up with the REST query.</param>
	/// <param name="callback">The response handler.</param>
	public static void Put(string resource, Dictionary<string,object> parameters, Callback callback)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			callback(false, new Dictionary<string,object>());
		}
		else
			Instance._Put(resource, parameters, callback);
	}

	/// <summary>
	/// A POST request to the Scoreflex server.
	/// </summary>
	/// <param name="resource">The Scoreflex resource.</param>
	/// <param name="parameters">Parameters passed up with the REST query.</param>
	/// <param name="callback">The response handler.</param>
	public static void Post(string resource, Dictionary<string,object> parameters, Callback callback)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			callback(false, new Dictionary<string,object>());
		}
		else
			Instance._Post(resource, parameters, callback);
	}

	/// <summary>
	/// An HTTP POST request that is guaranteed to be executed when a network
	/// connection is present, surviving application reboot. The responseHandler
	/// will be called only if the network is present when the request is first run.
	/// </summary>
	/// <param name="resource">The Scoreflex resource.</param>
	/// <param name="parameters">Parameters passed up with the REST query.</param>
	/// <param name="callback">The response handler.</param>
	public static void PostEventually(string resource, Dictionary<string,object> parameters, Callback callback)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			callback(false, new Dictionary<string,object>());
		}
		else
			Instance._PostEventually(resource, parameters, callback);
	}

	/// <summary>
	/// A DELETE request to the Scoreflex server.
	/// </summary>
	/// <param name="resource">The Scoreflex resource.</param>
	/// <param name="parameters">Parameters passed up with the REST query.</param>
	/// <param name="callback">The response handler.</param>
	public static void Delete(string resource, Dictionary<string,object> parameters, Callback callback)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			callback(false, new Dictionary<string,object>());
		}
		else
			Instance._Delete(resource, parameters, callback);
	}

	/// <summary>
	/// A helper method that submits a turn to a challenge instance.
	/// </summary>
	/// <param name="challengeInstanceId">Challenge instance identifier.</param>
	/// <param name="score">Score.</param>
	/// <param name="parameters">Additional parameters which will be passed up with the REST call. Optional; may be null.</param>
	/// <param name="callback">The response handler.</param>
	public static void SubmitTurn(string challengeInstanceId, long score, Dictionary<string,object> parameters = null, Callback callback = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			if(callback != null) callback(false, new Dictionary<string,object>());
		}
		else
			Instance._SubmitTurn(challengeInstanceId, score, parameters, callback);
	}

	/// <summary>
	/// A helper method that submits a score to a leaderboard.
	/// </summary>
	/// <param name="leaderboardId">Leaderboard identifier.</param>
	/// <param name="score">Score.</param>
	/// <param name="parameters">Additional parameters which will be passed up with the REST call. Optional; may be null.</param>
	/// <param name="callback">The response handler.</param>
	public static void SubmitScore(string leaderboardId, long score, Dictionary<string,object> parameters = null, Callback callback = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
			if(callback != null) callback(false, new Dictionary<string,object>());
		}
		else
			Instance._SubmitScore(leaderboardId, score, parameters, callback);
	}

	/// <summary>
	/// A helper method which submits a score to the server and immediately brings up a ranks panel view
	/// which can be dismissed with <see cref="HideRanksPanel"/>.
	/// </summary>
	/// <param name="leaderboardId">Leaderboard identifier.</param>
	/// <param name="score">Score.</param>
	/// <param name="parameters">Additional parameters which will be passed up with the REST call. Optional; may be null.</param>
	/// <param name="gravity">Vertical alignment. Can be Scoreflex.Gravity.Top, .Bottom or .Default.</param>
	public static void SubmitScoreAndShowRanksPanel(string leaderboardId, long score, Dictionary<string,object> parameters = null, Gravity gravity = Gravity.Top)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._SubmitScoreAndShowRanksPanel(leaderboardId, score, parameters, gravity);
	}

	/// <summary>
	/// A helper method which submits a turn to the server and, once the call is successful, brings up the
	/// full screen challenge detail view.
	/// </summary>
	/// <param name="challengeInstanceId">Challenge instance identifier.</param>
	/// <param name="score">Score.</param>
	/// <param name="parameters">Additional parameters which will be passed up with the REST call. Optional; may be null.</param>
	public static void SubmitTurnAndShowChallengeDetail(string challengeInstanceId, long score, Dictionary<string,object> parameters = null)
	{
		if(!Live) {
			Debug.Log(ErrorNotLive);
		}
		else
			Instance._SubmitTurnAndShowChallengeDetail(challengeInstanceId, score, parameters);
	}

}

redpajama_set_name: RedPajamaGithub


text:
function dmeshScript(index)

cd /media/External/Images/0'56D Series JPGS'/

addpath(genpath('~/code/matlab'))

load ~/code/matfiles/session_05_28_2010.mat

dmesh = contourGrid(secdoc(index:4:end), 'd01', '', int16(4), 512, 5);

save(sprintf('/home/larry/code/matfiles/dmesh_%d.mat', index), 'dmesh');


text:
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.immutable;

import com.google.errorprone.annotations.Immutable;
import java.util.Date;
import java.util.List;
import org.zalando.techtalks.hackingjava.defectanalysis.baseline.immutable.AbstractFakeImmutableUser;
import org.zalando.techtalks.hackingjava.defectanalysis.baseline.marker.IllBehaved;

@Immutable
public class FakeErrorProneImmutableUser extends AbstractFakeImmutableUser implements IllBehaved {
    private String name;
    private List<String> nickNames;
    private Date birthDate;

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(final String name) {
        this.name = name;
    }

    @Override
    public List<String> getNickNames() {
        return nickNames;
    }

    @Override
    public void setNickNames(final List<String> nickNames) {
        this.nickNames = nickNames;
    }

    @Override
    public Date getBirthDate() {
        return birthDate;
    }

    @Override
    public void setBirthDate(final Date birthDate) {
        this.birthDate = birthDate;
    }
}


text:
const debug = require('debug')('init');
const Bluebird = require('bluebird');
const config = require('./config');

const init_path = config.get('auth.init');
if (typeof init_path !== 'string' || init_path.length < 1) return;

const init = require(init_path); // nosemgrep: javascript.lang.security.detect-non-literal-require.detect-non-literal-require
if (typeof init !== 'function')
  return debug('no intialization function available');

debug('Running init function from %s', init_path);
Bluebird.try(() => init(config)).then(() => debug('Initialization complete.'));


text:
package io.softape.burst_espresso;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.test.InstrumentationRegistry;

import com.squareup.burst.BurstJUnit4;
import com.squareup.burst.annotation.Burst;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.List;

@RunWith(BurstJUnit4.class)
public class DeeplinkTest {

    static final String MAIN_ACTIVITY = MainActivity.class.getCanonicalName();

    @SuppressWarnings("unused")
    public enum SchemaConfiguration {
        https("https://bloglovin.com"),
        https_www("http://www.bloglovin.com"),
        http("http://bloglovin.com"),
        http_www("http://www.bloglovin.com");

        public final String domain;

        SchemaConfiguration(final String domain) {
            this.domain = domain;
        }
    }

    @SuppressWarnings("unused")
    public enum DeeplinkTestCase {

        collection("/collections/1239", MAIN_ACTIVITY),
        collection2("/collections/abc-1239", MAIN_ACTIVITY);

        public final String path;
        private final String resolvedActivityName;

        DeeplinkTestCase(String path, String resolvedActivityName) {
            this.path = path;
            this.resolvedActivityName = resolvedActivityName;
        }
    }

    @Burst
    SchemaConfiguration schemaConfiguration;
    @Burst
    DeeplinkTestCase deeplinkTestCase;

    @Test
    public void testDeeplinks() throws Exception {
        String url = schemaConfiguration.domain + deeplinkTestCase.path;

        Context appContext = InstrumentationRegistry.getTargetContext();
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        PackageManager packageManager = appContext.getPackageManager();
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
        for (ResolveInfo single : resolveInfos) {
            //This is to handle when we have different flavor of the app installed on the device,we want to make sure the package name is the same.
            if (single.activityInfo.packageName.equalsIgnoreCase(appContext.getPackageName())) {
                if (single.activityInfo.name.equalsIgnoreCase(deeplinkTestCase.resolvedActivityName)) {
                    return;
                }
            }

        }
        junit.framework.Assert.fail(url + " " + "is not resolved while it should be resolvable as " + deeplinkTestCase.resolvedActivityName);
    }
}


text:
"""
    SleekXMPP: The Sleek XMPP Library
    Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout
    This file is part of SleekXMPP.

    See the file LICENSE for copying permission.
"""

from sleekxmpp.thirdparty import OrderedDict
from sleekxmpp.xmlstream import ET, ElementBase

class Headers(ElementBase):
    name = 'headers'
    namespace = 'http://jabber.org/protocol/shim'
    plugin_attrib = 'headers'
    interfaces = set(['headers'])
    is_extension = True

    def get_headers(self):
        result = OrderedDict()
        headers = self.xml.findall('{%s}header' % self.namespace)
        for header in headers:
            name = header.attrib.get('name', '')
            value = header.text
            if name in result:
                if not isinstance(result[name], set):
                    result[name] = [result[name]]
                else:
                    result[name] = []
                result[name].add(value)
            else:
                result[name] = value
        return result

    def set_headers(self, values):
        self.del_headers()
        for name in values:
            vals = values[name]
            if not isinstance(vals, (list, set)):
                vals = [values[name]]
            for value in vals:
                header = ET.Element('{%s}header' % self.namespace)
                header.attrib['name'] = name
                header.text = value
                self.xml.append(header)

    def del_headers(self):
        headers = self.xml.findall('{%s}header' % self.namespace)
        for header in headers:
            self.xml.remove(header)


text:
<?php

namespace SMW\Tests\Utils;

use SMW\Tests\Utils\Mock\MockSuperUser;

use ApiResult;
use ApiMain;
use RequestContext;
use WebRequest;
use FauxRequest;

/**
 * Class contains Api related request methods
 *
 * @license GNU GPL v2+
 * @since   1.9
 *
 * @author mwjames
 */
class MwApiFactory {

	/**
	 * @param array $params
	 *
	 * @return ApiMain
	 */
	public function newApiMain( array $params ) {
		return new ApiMain( $this->newRequestContext( $params ), true );
	}

	/**
	 * @param array $params
	 *
	 * @return ApiResult
	 */
	public function newApiResult( array $params ) {
		return new ApiResult( $this->newApiMain( $params ) );
	}

	/**
	 * Returns Api results
	 *
	 * The returned value is an array containing
	 * - the result data (array)
	 *
	 * @param array $params
	 *
	 * @return array
	 */
	public function doApiRequest( array $params ) {

		$api = $this->newApiMain( $params );
		$api->execute();

		return $api->getResultData();
	}

	private function newRequestContext( $request = array() ) {

		$context = new RequestContext();

		if ( $request instanceof WebRequest ) {
			$context->setRequest( $request );
		} else {
			$context->setRequest( new FauxRequest( $request, true ) );
		}

		$context->setUser( new MockSuperUser() );

		return $context;
	}

}


text:
package de.javagl.nd.tuples.j;

import java.util.stream.LongStream;
import java.util.stream.StreamSupport;

/*
 * Note: This class is automatically generated. Do not modify this class
 * directly. See https://github.com/javagl/ND/tree/master/nd-gen/ for
 * further information.
 */

/**
 * Methods to create streams from {@link LongTuple} instances.
 */
class LongTupleStreams
{
    /**
     * Returns a stream of the contents of the given {@link LongTuple}
     *
     * @param tuple The tuple
     * @return The stream
     */
    static LongStream stream(LongTuple tuple)
    {
        return stream(tuple, 0, tuple.getSize());
    }

    /**
     * Returns a stream of the specified range of the given {@link LongTuple}
     *
     * @param tuple The tuple
     * @param startInclusive The start index, inclusive
     * @param endExclusive  The end index, exclusive
     * @return The stream
     */
    static LongStream stream(
        LongTuple tuple, int startInclusive, int endExclusive)
    {
        LongTupleSpliterator longTupleSpliterator =
            new LongTupleSpliterator(
                tuple, startInclusive, endExclusive);
        return StreamSupport.longStream(longTupleSpliterator, false);
    }

    /**
     * Private constructor to prevent instantiation
     */
    private LongTupleStreams()
    {
        // Private constructor to prevent instantiation
    }

}


text:
//  *************************************************************
// <copyright file="SeealsoMarkdownNodeParser.cs" company="None">
//     Copyright (c) 2014 andy.  All rights reserved.
// </copyright>
// <license>MIT Licence</license>
// <author>andy</author>
// <email>andy.augustin@t-online.de</email>
// *************************************************************

namespace DocToMarkdown
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    using DocToMarkdown.Common;

    /// <summary>
    /// See also markdown node parser.
    /// </summary>
    /// <example>
    /// For using the <c>seealso</c> tag are found at
    /// <see href="http://msdn.microsoft.com/en-us/library/xhd7ehkk.aspx"/>
    /// </example>
    internal class SeealsoMarkdownNodeParser : IMarkdownNodeParser
    {
        #region fields

        private readonly Dictionary<String, String> _templateDictionary = new Dictionary<String, String>();

        #endregion

        #region ctors

        /// <summary>
        /// Initializes a new instance of the <see cref="SeealsoMarkdownNodeParser"/> class.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <param name="markdownType">The markdown type.</param>
        internal SeealsoMarkdownNodeParser(IEnvironment environment, MarkdownType markdownType)
        {
            this.InitTemplate(environment, markdownType);
        }

        #endregion

        #region methods

        /// <summary>
        /// Parses to markdown.
        /// The <paramref name="element"/> is the element to parse.
        /// </summary>
        /// <returns>The parsed markdown.</returns>
        /// <param name="element">The element.</param>
        public String ParseToMarkdown(XElement element)
        {
            if (element.Name != "seealso")
            {
                return null;
            }

            var anchorAttr = element.Attribute("cref");
            var key = anchorAttr == null ? "href" : "cref";

            anchorAttr = anchorAttr ?? element.Attribute("href");

            if (anchorAttr == null)
            {
                return null;
            }

            var template = this._templateDictionary[key];

            var val = anchorAttr.Value;

            return String.Format(
                template,
                val,
                val.ToLower());
        }

        #endregion

        #region helper methods

        private void InitTemplate(IEnvironment environment, MarkdownType markdownType)
        {
            if (this._templateDictionary.Any())
            {
                return;
            }

            var hyperRefTemp = markdownType == MarkdownType.GithubFlavoredMarkdown ?
                String.Format(
                                   "{0}{1}",
                                   "{0}",
                                   environment.NewLine) :
                String.Format(
                                   "[{0}](#{1}){2}",
                                   "{0}",
                                   "{1}",
                                   environment.NewLine);

            this._templateDictionary.Add("href", hyperRefTemp);

            var classRefTemp = markdownType == MarkdownType.GithubFlavoredMarkdown ?
                String.Format(
                                   "**{0}**{1}",
                                   "{0}",
                                   environment.NewLine)
                : String.Format(
                                   "[{0}](#{1}){2}",
                                   "{0}",
                                   "{1}",
                                   environment.NewLine);

            this._templateDictionary.Add("cref", classRefTemp);
        }

        #endregion
    }
}


text:
package com.facebook.fbreact.specs;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReactModuleWithSpec;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.turbomodule.core.interfaces.TurboModule;

public abstract class NativeDatePickerAndroidSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule {
  public NativeDatePickerAndroidSpec(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @ReactMethod
  public abstract void open(ReadableMap options, Promise promise);
}


text:
using System;
using Azure.Core;

namespace Azure.Communication.JobRouter
{
    /// <summary> Describes a label selector that will always be attached. </summary>
    public partial class StaticWorkerSelectorAttachment : WorkerSelectorAttachment
    {
        /// <summary> Initializes a new instance of StaticWorkerSelectorAttachment. </summary>
        /// <param name="labelSelector"> Describes a condition that must be met against a set of labels for worker selection. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="labelSelector"/> is null. </exception>
        public StaticWorkerSelectorAttachment(WorkerSelector labelSelector)
        {
            Argument.AssertNotNull(labelSelector, nameof(labelSelector));

            LabelSelector = labelSelector;
            Kind = "static";
        }

        /// <summary> Initializes a new instance of StaticWorkerSelectorAttachment. </summary>
        /// <param name="kind"> The type discriminator describing the type of label selector attachment. </param>
        /// <param name="labelSelector"> Describes a condition that must be met against a set of labels for worker selection. </param>
        internal StaticWorkerSelectorAttachment(string kind, WorkerSelector labelSelector) : base(kind)
        {
            LabelSelector = labelSelector;
            Kind = kind ?? "static";
        }

        /// <summary> Describes a condition that must be met against a set of labels for worker selection. </summary>
        public WorkerSelector LabelSelector { get; set; }
    }
}


text:
var BaseCtrl = require('./_base.controller');
var constants = require('../constants');

var ical = require('ical-generator');
var fileSaver = require('file-saver');

var MILLISECONDS_PER_MINUTE = 60 * 1000;

function getStartDate() {
  return new Date(2016, 7, 24);
}

var repeatingByDayAbbrvs = {
  Sunday: 'su',
  Monday: 'mo',
  Tuesday: 'tu',
  Wednesday: 'we',
  Thursday: 'th',
  Friday: 'fr',
  Saturday: 'sa'
};

ExportToCalendarDialogCtrl.prototype = Object.create(BaseCtrl.prototype);
function ExportToCalendarDialogCtrl($state, $window, $mdDialog, schedulingOptionsService, termAbbrev, schedule) {
  BaseCtrl.call(this, $state, $window, schedulingOptionsService);

  var vm = this;
  vm.schedule = schedule;
  vm.calendarFilename = constants.termName(termAbbrev) + ' academic calendar.ics';
  vm.download = download;
  vm.cancel = cancel;

  var repeatingUntil = constants.termLastDay(termAbbrev);
  var calendar = ical({
    domain: 'berkeleyscheduler.com',
    prodId: {
      company: 'Berkeley Scheduler',
      product: 'berkeleyscheduler.com',
      language: 'EN'
    },
    name: constants.termName(termAbbrev) + ' Academic Calendar',
    url: vm.getHref('schedule.viewSchedule', {
      scheduleId: schedule.id,
      noTimeConflicts: schedulingOptionsService.getAllSchedulingOptions().noTimeConflicts
    }),
    timezone: 'America/Los_Angeles',
    method: 'add'
  });

  Object.keys(vm.schedule.courseInstances).forEach(function(courseInstanceId) {
    vm.schedule.courseInstances[courseInstanceId].forEach(function(section) {
      var course = section.owner.course;
      section.meetings.forEach(function(meeting) {
        var repeatingByDay = [];
        for (var day in repeatingByDayAbbrvs) {
          if (meeting.days[day]) {
            repeatingByDay.push(repeatingByDayAbbrvs[day]);
          }
        }

        if (repeatingByDay.length > 0) {
          var startDate = getStartDate();
          startDate.setHours(meeting.startTime.hours, meeting.startTime.minutes);
          var endDate = new Date(startDate.getTime() + meeting.getTotalMinutes() * MILLISECONDS_PER_MINUTE);
          calendar.createEvent({
            uid: termAbbrev + '/' + course.id + '/' + section.id,
            start: startDate,
            end: endDate,
            repeating: {
              freq: 'WEEKLY',
              until: repeatingUntil,
              byDay: repeatingByDay
            },
            summary: course.department + ' ' + course.courseNumber + ' ' + section.type + ' ' + section.number,
            description: course.description,
            location: meeting.location,
            organizer: {
              name: 'Berkeley Scheduler',
              email: 'berkeley-scheduler@berkeley.edu'
            },
            url: vm.getHref('schedule.viewCourse', {id: course.id})
          });
        }
      });
    });
  });

  function download() {
    var blob = new Blob([calendar.toString()], {type: 'text/calendar;charset=utf-8'});
    fileSaver.saveAs(blob, vm.calendarFilename);
    $mdDialog.hide();
  }

  function cancel() {
    $mdDialog.hide();
  }
}
angular.module('berkeleyScheduler').controller('ExportToCalendarDialogCtrl', [
  '$state',
  '$window',
  '$mdDialog',
  'schedulingOptionsService',
  'termAbbrev',
  'schedule',
  ExportToCalendarDialogCtrl
]);


text:
import logging

from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import messages

from openstack_dashboard import api

LOG = logging.getLogger(__name__)

class UpdateVPNService(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    vpnservice_id = forms.CharField(
        label=_("ID"),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    description = forms.CharField(
        required=False, max_length=80, label=_("Description"))
    # TODO(amotoki): make UP/DOWN translatable
    admin_state_up = forms.ChoiceField(choices=[(True, 'UP'), (False, 'DOWN')],
                                       label=_("Admin State"))

    failure_url = 'horizon:project:vpn:index'

    def handle(self, request, context):
        context['admin_state_up'] = (context['admin_state_up'] == 'True')
        try:
            data = {'vpnservice': {'name': context['name'],
                                   'description': context['description'],
                                   'admin_state_up': context['admin_state_up'],
                                   }}
            vpnservice = api.vpn.vpnservice_update(
                request, context['vpnservice_id'], **data)
            msg = (_('VPN Service %s was successfully updated.')
                   % context['name'])
            LOG.debug(msg)
            messages.success(request, msg)
            return vpnservice
        except Exception as e:
            msg = _('Failed to update VPN Service %s') % context['name']
            LOG.info('%s: %s' % (msg, e))
            redirect = reverse(self.failure_url)
            exceptions.handle(request, msg, redirect=redirect)

class UpdateIKEPolicy(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    ikepolicy_id = forms.CharField(
        label=_("ID"),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    description = forms.CharField(
        required=False, max_length=80, label=_("Description"))
    # Currently this field has only one choice, so mark it as readonly.
    auth_algorithm = forms.ChoiceField(
        label=_("Authorization algorithm"),
        choices=[('sha1', _('sha1'))],
        widget=forms.Select(attrs={'readonly': 'readonly'}))
    encryption_algorithm = forms.ChoiceField(
        label=_("Encryption algorithm"),
        choices=[('3des', _('3des')),
                 ('aes-128', _('aes-128')),
                 ('aes-192', _('aes-192')),
                 ('aes-256', _('aes-256'))])
    ike_version = forms.ChoiceField(
        label=_("IKE version"),
        choices=[('v1', _('v1')),
                 ('v2', _('v2'))])
    # Currently this field has only one choice, so mark it as readonly.
    lifetime_units = forms.ChoiceField(
        label=_("Lifetime units for IKE keys"),
        choices=[('seconds', _('seconds'))],
        widget=forms.Select(attrs={'readonly': 'readonly'}))
    lifetime_value = forms.IntegerField(
        min_value=60,
        label=_("Lifetime value for IKE keys"),
        help_text=_("Equal to or greater than 60"))
    pfs = forms.ChoiceField(
        label=_("Perfect Forward Secrecy"),
        choices=[('group2', _('group2')),
                 ('group5', _('group5')),
                 ('group14', _('group14'))])
    # Currently this field has only one choice, so mark it as readonly.
    phase1_negotiation_mode = forms.ChoiceField(
        label=_("IKE Phase1 negotiation mode"),
        choices=[('main', 'main')],
        widget=forms.Select(attrs={'readonly': 'readonly'}))

    failure_url = 'horizon:project:vpn:index'

    def handle(self, request, context):
        try:
            data = {'ikepolicy':
                    {'name': context['name'],
                     'description': context['description'],
                     'auth_algorithm': context['auth_algorithm'],
                     'encryption_algorithm': context['encryption_algorithm'],
                     'ike_version': context['ike_version'],
                     'lifetime': {'units': context['lifetime_units'],
                                  'value': context['lifetime_value']},
                     'pfs': context['pfs'],
                     'phase1_negotiation_mode':
                     context['phase1_negotiation_mode'],
                     }}
            ikepolicy = api.vpn.ikepolicy_update(
                request, context['ikepolicy_id'], **data)
            msg = (_('IKE Policy %s was successfully updated.')
                   % context['name'])
            LOG.debug(msg)
            messages.success(request, msg)
            return ikepolicy
        except Exception as e:
            msg = _('Failed to update IKE Policy %s') % context['name']
            LOG.info('%s: %s' % (msg, e))
            redirect = reverse(self.failure_url)
            exceptions.handle(request, msg, redirect=redirect)

class UpdateIPSecPolicy(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    ipsecpolicy_id = forms.CharField(
        label=_("ID"),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    description = forms.CharField(
        required=False, max_length=80, label=_("Description"))
    # Currently this field has only one choice, so mark it as readonly.
    auth_algorithm = forms.ChoiceField(
        label=_("Authorization algorithm"),
        choices=[('sha1', _('sha1'))],
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    encapsulation_mode = forms.ChoiceField(
        label=_("Encapsulation mode"),
        choices=[('tunnel', _('tunnel')),
                 ('transport', _('transport'))])
    encryption_algorithm = forms.ChoiceField(
        label=_("Encryption algorithm"),
        choices=[('3des', _('3des')),
                 ('aes-128', _('aes-128')),
                 ('aes-192', _('aes-192')),
                 ('aes-256', _('aes-256'))])
    # Currently this field has only one choice, so mark it as readonly.
    lifetime_units = forms.ChoiceField(
        label=_("Lifetime units"),
        choices=[('seconds', _('seconds'))],
        widget=forms.Select(attrs={'readonly': 'readonly'}))
    lifetime_value = forms.IntegerField(
        min_value=60,
        label=_("Lifetime value"),
        help_text=_("Equal to or greater than 60"))
    pfs = forms.ChoiceField(
        label=_("Perfect Forward Secrecy"),
        choices=[('group2', _('group2')),
                 ('group5', _('group5')),
                 ('group14', _('group14'))])
    transform_protocol = forms.ChoiceField(
        label=_("Transform Protocol"),
        choices=[('esp', _('esp')),
                 ('ah', _('ah')),
                 ('ah-esp', _('ah-esp'))])

    failure_url = 'horizon:project:vpn:index'

    def handle(self, request, context):
        try:
            data = {'ipsecpolicy':
                    {'name': context['name'],
                     'description': context['description'],
                     'auth_algorithm': context['auth_algorithm'],
                     'encapsulation_mode': context['encapsulation_mode'],
                     'encryption_algorithm': context['encryption_algorithm'],
                     'lifetime': {'units': context['lifetime_units'],
                                  'value': context['lifetime_value']},
                     'pfs': context['pfs'],
                     'transform_protocol': context['transform_protocol'],
                     }}
            ipsecpolicy = api.vpn.ipsecpolicy_update(
                request, context['ipsecpolicy_id'], **data)
            msg = (_('IPSec Policy %s was successfully updated.')
                   % context['name'])
            LOG.debug(msg)
            messages.success(request, msg)
            return ipsecpolicy
        except Exception as e:
            msg = _('Failed to update IPSec Policy %s') % context['name']
            LOG.info('%s: %s' % (msg, e))
            redirect = reverse(self.failure_url)
            exceptions.handle(request, msg, redirect=redirect)

class UpdateIPSecSiteConnection(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    ipsecsiteconnection_id = forms.CharField(
        label=_("ID"),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    description = forms.CharField(
        required=False, max_length=80, label=_("Description"))
    peer_address = forms.IPField(
        label=_("Peer gateway public IPv4/IPv6 Address or FQDN"),
        help_text=_("Peer gateway public IPv4/IPv6 address or FQDN for "
                    "the VPN Connection"),
        version=forms.IPv4 | forms.IPv6,
        mask=False)
    peer_id = forms.IPField(
        label=_("Peer router identity for authentication (Peer ID)"),
        help_text=_("Peer router identity for authentication. "
                    "Can be IPv4/IPv6 address, e-mail, key ID, or FQDN"),
        version=forms.IPv4 | forms.IPv6,
        mask=False)
    peer_cidrs = forms.MultiIPField(
        label=_("Remote peer subnet(s)"),
        help_text=_("Remote peer subnet(s) address(es) "
                    "with mask(s) in CIDR format "
                    "separated with commas if needed "
                    "(e.g. 20.1.0.0/24, 21.1.0.0/24)"),
        version=forms.IPv4 | forms.IPv6,
        mask=True)
    psk = forms.CharField(
        max_length=80, label=_("Pre-Shared Key (PSK) string"))
    mtu = forms.IntegerField(
        min_value=68,
        label=_("Maximum Transmission Unit size for the connection"),
        help_text=_("Equal to or greater than 68 if the local subnet is IPv4. "
                    "Equal to or greater than 1280 if the local subnet "
                    "is IPv6."))
    dpd_action = forms.ChoiceField(
        label=_("Dead peer detection actions"),
        choices=[('hold', _('hold')),
                 ('clear', _('clear')),
                 ('disabled', _('disabled')),
                 ('restart', _('restart')),
                 ('restart-by-peer', _('restart-by-peer'))])
    dpd_interval = forms.IntegerField(
        min_value=1,
        label=_("Dead peer detection interval"),
        help_text=_("Valid integer"))
    dpd_timeout = forms.IntegerField(
        min_value=1,
        label=_("Dead peer detection timeout"),
        help_text=_("Valid integer greater than the DPD interval"))
    initiator = forms.ChoiceField(
        label=_("Initiator state"),
        choices=[('bi-directional', _('bi-directional')),
                 ('response-only', _('response-only'))])
    # TODO(amotoki): make UP/DOWN translatable
    admin_state_up = forms.ChoiceField(choices=[(True, 'UP'), (False, 'DOWN')],
                                       label=_("Admin State"))

    failure_url = 'horizon:project:vpn:index'

    def handle(self, request, context):
        context['admin_state_up'] = (context['admin_state_up'] == 'True')
        try:
            data = {'ipsec_site_connection':
                    {'name': context['name'],
                     'description': context['description'],
                     'peer_address': context['peer_address'],
                     'peer_id': context['peer_id'],
                     'peer_cidrs': context[
                         'peer_cidrs'].replace(" ", "").split(","),
                     'psk': context['psk'],
                     'mtu': context['mtu'],
                     'dpd': {'action': context['dpd_action'],
                             'interval': context['dpd_interval'],
                             'timeout': context['dpd_timeout']},
                     'initiator': context['initiator'],
                     'admin_state_up': context['admin_state_up'],
                     }}
            ipsecsiteconnection = api.vpn.ipsecsiteconnection_update(
                request, context['ipsecsiteconnection_id'], **data)
            msg = (_('IPSec Site Connection %s was successfully updated.')
                   % context['name'])
            LOG.debug(msg)
            messages.success(request, msg)
            return ipsecsiteconnection
        except Exception as e:
            msg = (_('Failed to update IPSec Site Connection %s')
                   % context['name'])
            LOG.info('%s: %s' % (msg, e))
            redirect = reverse(self.failure_url)
            exceptions.handle(request, msg, redirect=redirect)


text:
typedef enum {
    Cmd_Nop,
    Cmd_ButtonPress,
    Cmd_SayTime,            //2
    Cmd_PlayFileName,       //3
    Cmd_PlayFileHandle,     //4
    Cmd_FinishedPlay,       //5
    Cmd_ButtonRelease,
    Cmd_ClockTick,
} command_t;

typedef struct {
    command_t cmd;
    union {
        uint16_t arg1i;
        void* arg1p;
    };
    // uint16_t arg2;
} message_t;

#define MAX_MSG_BUF_LEN         4

typedef struct {
    message_t       msg_buf[MAX_MSG_BUF_LEN];
    int8_t          wrpos;
    int8_t          rdpos;
} message_buffer_t;

extern message_buffer_t g_message_buffer;

void loop_init(void);

message_t *loop_put_msg_begin(void);

void loop_put_msg_end(message_t *msg);

void loop_loop(int8_t once);

#endif


text:
/* eslint-disable no-new */
import * as url from 'url';

import * as sinon from 'sinon';
import * as proxyquire from 'proxyquire';
import test from 'ava';

import { delay } from '../../src/lib/utils/misc';
import { RuleScope } from '../../src/lib/enums/rulescope';

const resourceLoader = {
    loadConnector() {
        return () => { };
    },
    loadRules() { }
};
const eventEmitter = { EventEmitter2: function EventEmitter2() { } };

eventEmitter.EventEmitter2.prototype.on = () => { };
eventEmitter.EventEmitter2.prototype.emitAsync = () => {
    return Promise.resolve([]);
};

proxyquire('../../src/lib/sonarwhal', {
    './utils/resource-loader': resourceLoader,
    eventemitter2: eventEmitter
});

import { Sonarwhal } from '../../src/lib/sonarwhal';

test.beforeEach((t) => {
    t.context.resourceLoader = resourceLoader;
    t.context.eventemitter = eventEmitter.EventEmitter2;
});

test.afterEach.always((t) => {
    if (t.context.resourceLoader.loadRules.restore) {
        t.context.resourceLoader.loadRules.restore();
    }
    if (t.context.resourceLoader.loadConnector.restore) {
        t.context.resourceLoader.loadConnector.restore();
    }
});

test(`If config is an empty object, we should throw an error`, (t) => {
    t.throws(() => {
        // <any>{} to avoid the type checking if not is not possible to use just {}
        new Sonarwhal({} as any);
    }, Error);
});

test(`If config doesn't have any rule, we shouldn't create any rules`, (t) => {
    sinon.spy(t.context.resourceLoader, 'loadRules');

    new Sonarwhal({ connector: 'connector' });

    t.false(t.context.resourceLoader.loadRules.called);
});

test(`If the config object is invalid, we should throw an error`, (t) => {
    t.throws(() => {
        new Sonarwhal({
            invalidProperty: 'invalid',
            randomProperty: 'random'
        } as any);
    }, Error);
});

test(`If a rule config is invalid, we should throw an error`, (t) => {
    t.throws(() => {
        new Sonarwhal({
            connector: 'connector',
            rules: { 'disallowed-headers': 'invalid-severity' }
        });
    }, Error);
});

test(`If a rule doesn't exist, we should throw an error`, (t) => {
    t.throws(() => {
        new Sonarwhal({
            connector: 'connector',
            rules: { 'invalid-rule': 'error' }
        });
    }, Error);
});

test.serial(`If config.browserslist is an string, we should initilize the property targetedBrowsers`, (t) => {
    sinon.spy(t.context.resourceLoader, 'loadRules');

    const sonarwhalObject = new Sonarwhal({
        browserslist: '> 5%',
        connector: 'connector'
    });

    t.true(sonarwhalObject.targetedBrowsers.length > 0);

    t.false(t.context.resourceLoader.loadRules.called);
});

/*
 * test.serial('If config.plugins is an array we should create just those plugins', (t) => {
 *     const plugin = {
 *         create() {
 *             return {};
 *         }
 *     };
 *     sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
 *     t.context.plugin = plugin;
 *     sinon.stub(t.context.resourceLoader, 'getPlugins').returns(new Map([
 *         ['plugin1Name', plugin],
 *         ['plugin2Name', plugin],
 *         ['plubin3Name', plugin]
 *     ]));
 *     sinon.stub(plugin, 'create')
 *         .onFirstCall()
 *         .returns({ 'fetch::end': () => { } })
 *         .onSecondCall()
 *         .returns({
 *             'fetch::end': () => { },
 *             'fetch::error': () => { }
 *         });
 *     new Sonarwhal({ connector: 'connector', plugins: ['plugin1Name', 'plugin2Name'] });
 *     t.true(t.context.resourceLoader.getPlugins.called);
 *     t.is(t.context.plugin.create.callCount, 2);
 *     t.is(t.context.eventemitter.prototype.on.callCount, 3);
 *     t.is(t.context.eventemitter.prototype.on.args[0][0], 'fetch::end');
 *     t.is(t.context.eventemitter.prototype.on.args[1][0], 'fetch::end');
 *     t.is(t.context.eventemitter.prototype.on.args[2][0], 'fetch::error');
 *     t.context.eventemitter.prototype.on.restore();
 * });
 */

test.serial('If config.rules is an object with rules, we should create just those rules', (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create')
        .onFirstCall()
        .returns({ 'fetch::end': () => { } })
        .onSecondCall()
        .returns({ 'fetch::error': () => { } });

    new Sonarwhal({
        connector: 'connector',
        rules: {
            'disallowed-headers': 'warning',
            'manifest-exists': 'warning'
        }
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.rule.create.calledTwice);
    t.true(t.context.eventemitter.prototype.on.calledTwice);
    t.is(t.context.eventemitter.prototype.on.args[0][0], 'fetch::end');
    t.is(t.context.eventemitter.prototype.on.args[1][0], 'fetch::error');

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If config.rules has some rules "off", we shouldn't create those rules`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });

    new Sonarwhal({
        connector: 'connector',
        rules: {
            'disallowed-headers': 'warning',
            'manifest-exists': 'off'
        }
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.rule.create.calledOnce);

    t.context.eventemitter.prototype.on.restore();
});

test.serial('If config.rules is an array with rules, we should create just those rules', (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create')
        .onFirstCall()
        .returns({ 'fetch::end': () => { } })
        .onSecondCall()
        .returns({ 'fetch::error': () => { } });

    new Sonarwhal({
        connector: 'connector',
        rules: [
            'disallowed-headers:warning',
            'manifest-exists:warning'
        ]
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.rule.create.calledTwice);
    t.true(t.context.eventemitter.prototype.on.calledTwice);
    t.is(t.context.eventemitter.prototype.on.args[0][0], 'fetch::end');
    t.is(t.context.eventemitter.prototype.on.args[1][0], 'fetch::error');

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If config.rules is an array and has some rules "off", we shouldn't create those rules`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });

    new Sonarwhal({
        connector: 'connector',
        rules: [
            'disallowed-headers:warning',
            'manifest-exists:off'
        ]
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.rule.create.calledOnce);

    t.context.eventemitter.prototype.on.restore();
});

test.serial('If config.rules is an array with shorthand warning rules, we should create just those rules', (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create')
        .onFirstCall()
        .returns({ 'fetch::end': () => { } })
        .onSecondCall()
        .returns({ 'fetch::error': () => { } });

    new Sonarwhal({
        connector: 'connector',
        rules: [
            '?disallowed-headers',
            'manifest-exists:warning'
        ]
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.rule.create.calledTwice);
    t.true(t.context.eventemitter.prototype.on.calledTwice);
    t.is(t.context.eventemitter.prototype.on.args[0][0], 'fetch::end');
    t.is(t.context.eventemitter.prototype.on.args[1][0], 'fetch::error');

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If config.rules is an array and has some rules "off", we shouldn't create those rules`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });

    new Sonarwhal({
        connector: 'connector',
        rules: [
            'disallowed-headers:warning',
            '-manifest-exists'
        ]
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.rule.create.calledOnce);

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If a rule has the metadata "ignoredConnectors" set up, we shouldn't ignore those rules if the connector isn't in that property`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: { ignoredConnectors: ['chrome'] }
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create')
        .onFirstCall()
        .returns({ 'fetch::end': () => { } })
        .onSecondCall()
        .returns({ 'fetch::error': () => { } });

    new Sonarwhal({
        connector: 'jsdom',
        rules: {
            'disallowed-headers': 'warning',
            'manifest-exists': 'warning'
        }
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.rule.create.calledTwice);
    t.true(t.context.eventemitter.prototype.on.calledTwice);
    t.is(t.context.eventemitter.prototype.on.args[0][0], 'fetch::end');
    t.is(t.context.eventemitter.prototype.on.args[1][0], 'fetch::error');

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If a rule has the metadata "ignoredConnectors" set up, we should ignore those rules if the connector is in that property`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };
    const ruleWithIgnoredConnector = {
        create() {
            return {};
        },
        meta: { ignoredConnectors: ['chrome'] }
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    t.context.ruleWithIgnoredConnector = ruleWithIgnoredConnector;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', ruleWithIgnoredConnector],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });
    sinon.spy(ruleWithIgnoredConnector, 'create');
    new Sonarwhal({
        connector: 'chrome',
        rules: {
            'disallowed-headers': 'warning',
            'manifest-exists': 'warning'
        }
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.false(t.context.ruleWithIgnoredConnector.create.called);
    t.true(t.context.rule.create.calledOnce);

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If the rule scope is 'local' and the connector isn't local the rule should be ignored`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };
    const ruleWithScopeLocal = {
        create() {
            return {};
        },
        meta: { scope: RuleScope.local }
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    t.context.ruleWithScopeLocal = ruleWithScopeLocal;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', ruleWithScopeLocal],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });
    sinon.spy(ruleWithScopeLocal, 'create');
    new Sonarwhal({
        connector: 'chrome',
        rules: {
            'disallowed-headers': 'warning',
            'manifest-exists': 'warning'
        }
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.false(t.context.ruleWithScopeLocal.create.called);
    t.true(t.context.rule.create.calledOnce);

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If the rule scope is 'site' and the connector is local the rule should be ignored`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };
    const ruleWithScopeSite = {
        create() {
            return {};
        },
        meta: { scope: RuleScope.site }
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    t.context.ruleWithScopeSite = ruleWithScopeSite;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', ruleWithScopeSite],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });
    sinon.spy(ruleWithScopeSite, 'create');
    new Sonarwhal({
        connector: 'local',
        rules: {
            'disallowed-headers': 'warning',
            'manifest-exists': 'warning'
        }
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.false(t.context.ruleWithScopeSite.create.called);
    t.true(t.context.rule.create.calledOnce);

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If the rule scope is 'any' and the connector is local the rule should be used`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };
    const ruleWithScopeSite = {
        create() {
            return {};
        },
        meta: { scope: RuleScope.any }
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    t.context.ruleWithScopeSite = ruleWithScopeSite;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', ruleWithScopeSite],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });
    sinon.spy(ruleWithScopeSite, 'create');
    new Sonarwhal({
        connector: 'local',
        rules: {
            'disallowed-headers': 'warning',
            'manifest-exists': 'warning'
        }
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.ruleWithScopeSite.create.called);
    t.true(t.context.rule.create.calledOnce);

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If the rule scope is 'any' and the connector isn't local the rule should be used`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };
    const ruleWithScopeSite = {
        create() {
            return {};
        },
        meta: { scope: RuleScope.any }
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    t.context.ruleWithScopeSite = ruleWithScopeSite;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', ruleWithScopeSite],
        ['manifest-exists', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });
    sinon.spy(ruleWithScopeSite, 'create');
    new Sonarwhal({
        connector: 'jsdom',
        rules: {
            'disallowed-headers': 'warning',
            'manifest-exists': 'warning'
        }
    });

    t.true(t.context.resourceLoader.loadRules.called);
    t.true(t.context.ruleWithScopeSite.create.called);
    t.true(t.context.rule.create.calledOnce);

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If an event is emitted for an ignored url, it shouldn't propagate`, async (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    t.context.rule = rule;
    sinon.spy(eventEmitter.EventEmitter2.prototype, 'emitAsync');
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });

    const sonarwhalObject = new Sonarwhal({
        connector: 'connector',
        ignoredUrls: [{
            domain: '.*\\.domain1\.com/.*', // eslint-disable-line no-useless-escape
            rules: ['*']
        }],
        rules: { 'disallowed-headers': 'warning' }
    });

    await sonarwhalObject.emitAsync('event', { resource: 'http://www.domain1.com/test' });

    t.false(t.context.eventemitter.prototype.emitAsync.called);

    t.context.eventemitter.prototype.emitAsync.restore();
});

test.serial(`If a rule is ignoring some url, it shouldn't run the event`, (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule]
    ]));
    sinon.stub(rule, 'create').returns({ 'fetch::end': () => { } });

    new Sonarwhal({
        connector: 'connector',
        ignoredUrls: [{
            domain: '.*\\.domain1\.com/.*', // eslint-disable-line no-useless-escape
            rules: ['disallowed-headers']
        }, {
            domain: '.*\\.domain2\.com/.*', // eslint-disable-line no-useless-escape
            rules: ['disallowed-headers']
        }],
        rules: { 'disallowed-headers': 'warning' }
    });

    const eventHandler = t.context.eventemitter.prototype.on.args[0][1];

    t.is(eventHandler({ resource: 'http://www.domain1.com/test' }), null);

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If a rule is taking too much time, it should be ignored after the configured timeout`, async (t) => {
    const rule = {
        create() {
            return {};
        },
        meta: {}
    };

    sinon.spy(eventEmitter.EventEmitter2.prototype, 'on');
    t.context.rule = rule;
    sinon.stub(t.context.resourceLoader, 'loadRules').returns(new Map([
        ['disallowed-headers', rule]
    ]));
    sinon.stub(rule, 'create').returns({
        'fetch::end': async () => {
            await delay(5000);

            return 'finish';
        }
    });

    new Sonarwhal({
        connector: 'connector',
        rules: { 'disallowed-headers': 'warning' },
        rulesTimeout: 1000
    });

    const eventHandler = t.context.eventemitter.prototype.on.args[0][1];

    t.is(await eventHandler.bind({ event: 'fetch::end::html' })({ resource: 'http://www.test.com/' }), null);

    t.context.eventemitter.prototype.on.restore();
});

test.serial(`If connectorId doesn't exist, it should throw an error`, (t) => {
    sinon.stub(t.context.resourceLoader, 'loadConnector').returns(null);

    try {
        new Sonarwhal({ connector: 'invalidConnector' });

        t.false(true);
    } catch (err) {
        t.is(err.message, 'Connector "invalidConnector" not found');
    }
});

test.serial('If connectorId is valid, we should init the connector', (t) => {
    t.context.connectorFunction = () => { };

    sinon.stub(t.context, 'connectorFunction').returns({});
    sinon.stub(t.context.resourceLoader, 'loadConnector').returns(t.context.connectorFunction);

    new Sonarwhal({ connector: 'myconnector' });

    t.true(t.context.connectorFunction.called);
});

test.serial('If connector is an object with valid data, we should init the connector', (t) => {
    t.context.connectorFunction = () => { };

    sinon.stub(t.context, 'connectorFunction').returns({});
    sinon.stub(t.context.resourceLoader, 'loadConnector').returns(t.context.connectorFunction);

    new Sonarwhal({
        connector: {
            name: 'myconnector',
            options: {}
        }
    });

    t.true(t.context.connectorFunction.called);
});

test.serial('formatter should return the formatter configured', (t) => {
    const sonarwhalObject = new Sonarwhal({
        connector: 'connector',
        formatters: ['formatter']
    });

    t.is(sonarwhalObject.formatters[0], 'formatter');
});

test.serial('pageContent should return the HTML', async (t) => {
    const html = '<html></html>';

    t.context.connectorFunction = () => { };
    sinon.stub(t.context, 'connectorFunction').returns({ html });
    sinon.stub(t.context.resourceLoader, 'loadConnector').returns(t.context.connectorFunction);

    const sonarwhalObject = new Sonarwhal({
        connector: {
            name: 'myconnector',
            options: {}
        }
    });

    t.is(await sonarwhalObject.pageContent, html);
});

test.serial(`pageHeaders should return the page's response headers`, (t) => {
    const headers = { header1: 'value1' };

    t.context.connectorFunction = () => { };
    sinon.stub(t.context, 'connectorFunction').returns({ headers });
    sinon.stub(t.context.resourceLoader, 'loadConnector').returns(t.context.connectorFunction);

    const sonarwhalObject = new Sonarwhal({
        connector: {
            name: 'myconnector',
            options: {}
        }
    });

    t.is(sonarwhalObject.pageHeaders, headers);
});

test.serial('If connector.collect fails, it should return an error', async (t) => {
    t.context.collect = () => {
        throw new Error('Error runing collect');
    };
    t.context.connectorFunction = () => { };
    sinon.stub(t.context, 'connectorFunction').returns({ collect: t.context.collect });
    sinon.stub(t.context.resourceLoader, 'loadConnector').returns(t.context.connectorFunction);

    const sonarwhalObject = new Sonarwhal({
        connector: {
            name: 'myconnector',
            options: {}
        }
    });

    const localUrl = new url.URL('http://localhost/');

    try {
        await sonarwhalObject.executeOn(localUrl);
        t.false(true);
    } catch (err) {
        t.is(err.message, 'Error runing collect');
    }
});

test.serial('executeOn should return all messages', async (t) => {
    t.context.collect = () => { };
    t.context.connectorFunction = () => { };
    sinon.stub(t.context, 'connectorFunction').returns({ collect: t.context.collect });
    sinon.stub(t.context.resourceLoader, 'loadConnector').returns(t.context.connectorFunction);

    const sonarwhalObject = new Sonarwhal({
        connector: {
            name: 'myconnector',
            options: {}
        }
    });

    const localUrl = new url.URL('http://localhost/');

    sonarwhalObject.report('1', 1, 'node', { column: 1, line: 1 }, 'message', 'resource');
    sonarwhalObject.report('2', 1, 'node', { column: 1, line: 2 }, 'message2', 'resource2');

    const result = await sonarwhalObject.executeOn(localUrl);

    t.is(result.length, 2);
});


text:
.. _license:

=======
License
=======

---------------
Project License
---------------

.. literalinclude:: ../LICENSE.txt
    :language: text

------------
Logo License
------------

The "gitexplorer logo" is a derivative of the original "`Git Logo`_" by `Jason Long`_, used under
`Creative Commons Attribution 3.0 Unported License`_. "gitexplorer logo" itself is licensed under
`Creative Commons Attribution 3.0 Unported License`_ by Peer Wagner.

.. _`Git Logo`: https://git-scm.com/downloads/logos
.. _`Jason Long`: https://twitter.com/jasonlong
.. _`Creative Commons Attribution 3.0 Unported License`: https://creativecommons.org/licenses/by/3.0/