text:
using System;
using System.Threading;
using bytePassion.Lib.Communication.State;
using bytePassion.Lib.ConcurrencyLib;
using OQF.AnalysisAndProgress.ProgressUtils;
using OQF.Bot.Contracts;
using OQF.Bot.Contracts.Coordination;
using OQF.Bot.Contracts.GameElements;
using OQF.Bot.Contracts.Moves;
using OQF.PlayerVsBot.Contracts;
using OQF.Utils.Enum;

namespace OQF.PlayerVsBot.GameLogic
{
	public class GameService : IGameService
	{
		private readonly bool disableBotTimeout;
		private readonly ISharedStateWriteOnly<bool> isBoardRotatedVariable;

		public event Action<BoardState> NewBoardStateAvailable;
		public event Action<string> NewDebugMsgAvailable;
		public event Action<Player, WinningReason, Move> WinnerAvailable;
		public event Action<GameStatus> NewGameStatusAvailable;

		private TimeoutBlockingQueue<Move> humenMoves;
		private IGameLoopThread gameLoopThread;
		private IQuoridorBot quoridorBot;
		private BoardState currentBoardState;
		private GameStatus currentGameStatus;

		public GameService(bool disableBotTimeout, ISharedStateWriteOnly<bool> isBoardRotatedVariable)
		{
			this.disableBotTimeout = disableBotTimeout;
			this.isBoardRotatedVariable = isBoardRotatedVariable;
			CurrentBoardState = null;
			gameLoopThread = null;
			CurrentGameStatus = GameStatus.Unloaded;
		}

		public BoardState CurrentBoardState
		{
			get { return currentBoardState; }
			private set
			{
				if (value != currentBoardState)
				{
					currentBoardState = value;
					NewBoardStateAvailable?.Invoke(currentBoardState);
				}
			}
		}

		public GameStatus CurrentGameStatus
		{
			get { return currentGameStatus; }
			private set
			{
				if (currentGameStatus != value)
				{
					currentGameStatus = value;
					NewGameStatusAvailable?.Invoke(currentGameStatus);
				}
			}
		}

		public PlayerType HumanPlayerPosition { get; private set; }

		public void CreateGame(IQuoridorBot uninitializedBot, string botName, GameConstraints gameConstraints,
							   PlayerType startingPosition, QProgress initialProgress)
		{
			HumanPlayerPosition = startingPosition;
			isBoardRotatedVariable.Value = startingPosition == PlayerType.TopPlayer;

			if (gameLoopThread != null)
			{
				StopGame();
			}

			var finalGameConstraints = disableBotTimeout
											? new GameConstraints(Timeout.InfiniteTimeSpan,gameConstraints.MaximalMovesPerPlayer)
											: gameConstraints;

			quoridorBot = uninitializedBot;
			quoridorBot.DebugMessageAvailable += OnDebugMessageAvailable;

			humenMoves = new TimeoutBlockingQueue<Move>(200);

			gameLoopThread = startingPosition == PlayerType.BottomPlayer
										? (IGameLoopThread) new GameLoopThreadPvB(quoridorBot, botName, humenMoves, finalGameConstraints, initialProgress)
										: (IGameLoopThread) new GameLoopThreadBvP(quoridorBot, botName, humenMoves, finalGameConstraints, initialProgress);

			gameLoopThread.NewBoardStateAvailable += OnNewBoardStateAvailable;
			gameLoopThread.WinnerAvailable        += OnWinnerAvailable;

			CurrentGameStatus = GameStatus.Active;

			new Thread(gameLoopThread.Run).Start();
		}

		private void OnWinnerAvailable(Player player, WinningReason winningReason, Move invalidMove)
		{
			WinnerAvailable?.Invoke(player, winningReason, invalidMove);
			CurrentGameStatus = GameStatus.Finished;
		}

		private void OnNewBoardStateAvailable (BoardState boardState)
		{
			CurrentBoardState = boardState;
		}

		private void OnDebugMessageAvailable(string s)
		{
			NewDebugMsgAvailable?.Invoke(s);
		}

		public void ReportHumanMove(Move move)
		{
			humenMoves.Put(move);
		}

		public void StopGame()
		{
			if (gameLoopThread != null)
			{
				quoridorBot.DebugMessageAvailable -= OnDebugMessageAvailable;

				gameLoopThread.Stop();

				gameLoopThread.NewBoardStateAvailable -= OnNewBoardStateAvailable;
				gameLoopThread.WinnerAvailable -= OnWinnerAvailable;

				gameLoopThread = null;
				CurrentBoardState = null;
			}

			CurrentGameStatus = GameStatus.Unloaded;
		}
	}
}


text:
<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/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.fabric8.funktion.examples</groupId>
    <artifactId>examples</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>example-java</artifactId>
  <packaging>jar</packaging>

  <name>Example Java</name>
  <description>Funktion :: Examples :: Java</description>

  <properties>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.fabric8.funktion</groupId>
      <artifactId>funktion-runtime</artifactId>
    </dependency>

    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>

    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>${rest-assured.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>io.fabric8</groupId>
        <artifactId>fabric8-maven-plugin</artifactId>
        <configuration>
         <enricher>
            <config>
              <fmp-service>
                <port>80</port>
              </fmp-service>
            </config>
          </enricher>
        </configuration>
      </plugin>

    </plugins>
  </build>

  <profiles>
    <profile>
      <id>k8s</id>
      <build>
        <plugins>
          <plugin>
            <groupId>io.fabric8</groupId>
            <artifactId>fabric8-maven-plugin</artifactId>
            <configuration>
              <enricher>
                <config>
                  <fmp-service>
                   <port>80</port>
                   <type>LoadBalancer</type>
                  </fmp-service>
                </config>
              </enricher>
            </configuration>
            <executions>
              <execution>
                <goals>
                  <goal>resource</goal>
                  <goal>build</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>

redpajama_set_name: RedPajamaGithub


text:
package com.cr5315.jSmite;

import com.eclipsesource.json.JsonObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Smite {
    private String developerId;
    private String authKey;
    private String sessionId;
    private long sessionStart;

    public static final String RESPONSE_TYPE_JSON = "json";
    public static final String RESPONSE_TYPE_XML = "xml";
    private String responseFormat = RESPONSE_TYPE_JSON;

    private static final String BASE_URL = "http://api.smitegame.com/smiteapi.svc/";

    public Smite(String developerId, String authKey) {
        this.developerId = developerId;
        this.authKey = authKey;
        sessionStart = 0;
    }

    /**
     * A quick way of validating access to the Hi-Rez API.
     */
    public String ping() {
        return get(BASE_URL + "ping" + responseFormat);
    }

    /**
     * A required step to Authenticate the developerId/signature for further API use.
     * jSmite automatically creates a new session when required.
     */
    private boolean createSession() {
        String result = get(combine(new String[]{
                BASE_URL + "createsessionjson",
                developerId,
                getSignature("createsession"),
                getTimestamp()
        }, "/"));
        if (result == null) return false;

        JsonObject object = JsonObject.readFrom(result);
        if (object.get("ret_msg").asString().equals("Approved")) {
            sessionId = object.getString("session_id", null);
            sessionStart = System.currentTimeMillis();
            return true;
        } else {
            return false;
        }
    }

    /**
     * A means of validating that a session is established.
     */
    public String testSession() {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "testsession" + responseFormat,
                developerId,
                getSignature("testsession"),
                sessionId,
                getTimestamp()
        }, "/"));
    }

    /**
     * Returns API Developer daily usage limits and the current status against those limits.
     */
    public String getDataUsed() {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getdataused" + responseFormat,
                developerId,
                getSignature("getdataused"),
                sessionId,
                getTimestamp()
        }, "/"));
    }

    /**
     * Returns information regarding a particular match.  Rarely used in lieu of getMatchDetails().
     */
    public String getDemoDetails(String matchId) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getdemodetails" + responseFormat,
                developerId,
                getSignature("getdemodetails"),
                sessionId,
                getTimestamp(),
                matchId
        }, "/"));
    }

    /**
     * Returns the matchup information for each matchup for the current eSports Pro League season.  An important return value is "match_status" which represents a match being scheduled (1), in-progress (2), or complete (3).
     */
    public String getEsportsProLeagueDetails() {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getesportsproleaguedetails" + responseFormat,
                developerId,
                getSignature("getesportsproleaguedetails"),
                sessionId,
                getTimestamp()
        }, "/"));
    }

    /**
     * Returns the Smite User names of each of the player's friends.
     */
    public String getFriends(String player) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getfriends" + responseFormat,
                developerId,
                getSignature("getfriends"),
                sessionId,
                getTimestamp(),
                player
        }, "/"));
    }

    /**
     * Returns the Rank and Worshippers value for each God a player has played.
     */
    public String getGodRanks(String player) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getgodranks" + responseFormat,
                developerId,
                getSignature("getgodranks"),
                sessionId,
                getTimestamp(),
                player
        }, "/"));
    }

    /**
     * Returns all Gods and their various attributes.
     */
    public String getGods(LanguageCode languageCode) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getgods" + responseFormat,
                developerId,
                getSignature("getgods"),
                sessionId,
                getTimestamp(),
                String.valueOf(languageCode.getValue())
        }, "/"));
    }

    /**
     * Returns the Recommended Items for a particular God.
     */
    public String getGodRecommendedItems(String godId, LanguageCode languageCode) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getgodrecommendeditems" + responseFormat,
                developerId,
                getSignature("getgodrecommendeditems"),
                sessionId,
                getTimestamp(),
                godId,
                String.valueOf(languageCode.getValue())
        }, "/"));
    }

    /**
     * Returns all Items and their various attributes.
     */
    public String getItems(LanguageCode languageCode) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getitems" + responseFormat,
                developerId,
                getSignature("getitems"),
                sessionId,
                getTimestamp(),
                String.valueOf(languageCode.getValue())
        }, "/"));
    }

    /**
     * Returns the statistics for a particular completed match.
     */
    public String getMatchDetails(String matchId) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getmatchdetails" + responseFormat,
                developerId,
                getSignature("getmatchdetails"),
                sessionId,
                getTimestamp(),
                matchId
        }, "/"));
    }

    /**
     * Lists all Match IDs for a particular Match Queue; useful for API developers interested in constructing data by Queue.  To limit the data returned, an {hour} parameter was added (valid values: 0 - 23).  An {hour} parameter of -1 represents the entire day, but be warned that this may be more data than we can return for certain queues.  Also, a returned "active_flag" means that there is no match information/stats for the corresponding match.  Usually due to a match being in-progress, though there could be other reasons.
     */
    public String getMatchIdsByQueue(Queue queue, String date, int hour) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getmatchidsbyqueue" + responseFormat,
                developerId,
                getSignature("getmatchidsbyqueue"),
                sessionId,
                getTimestamp(),
                String.valueOf(queue.getValue()),
                date,
                String.valueOf(hour)
        }, "/"));
    }

    /**
     * Returns the top players for a particular league (as indicated by the queue/tier/season parameters).
     */
    public String getLeagueLeaderboard(Queue queue, Tier tier, int season) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getleagueleaderboard" + responseFormat,
                developerId,
                getSignature("getloeagueleaderboard"),
                sessionId,
                getTimestamp(),
                String.valueOf(queue.getValue()),
                String.valueOf(tier.getValue()),
                String.valueOf(season)
        }, "/"));
    }

    /**
     * Provides a list of seasons (including the single active season) for a match queue.
     */
    public String getLeagueSeasons(Queue queue) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getleagueseasons" + responseFormat,
                developerId,
                getSignature("getleagueseasons"),
                sessionId,
                getTimestamp(),
                String.valueOf(queue.getValue())
        }, "/"));
    }

    /**
     * Gets recent matches and high level match statistics for a particular player.
     */
    public String getMatchHistory(String player) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getmatchhistory" + responseFormat,
                developerId,
                getSignature("getmatchhistory"),
                sessionId,
                getTimestamp(),
                player
        }, "/"));
    }

    /**
     * Returns league and other high level data for a particular player.
     */
    public String getPlayer(String player) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getplayer" + responseFormat,
                developerId,
                getSignature("getplayer"),
                sessionId,
                getTimestamp(),
                player
        }, "/"));
    }

    /**
     * Returns player status as follows:
     * 0 - Offline
     * 1 - In Lobby  (basically anywhere except god selection or in game)
     * 2 - god Selection (player has accepted match and is selecting god before start of game)
     * 3 - In Game (match has started)
     * 4 - Online (player is logged in, but may be blocking broadcast of player state)
     */
    public String getPlayerStatus(String player) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getplayerstatus" + responseFormat,
                developerId,
                getSignature("getplayerstatus"),
                sessionId,
                getTimestamp(),
                player
        }, "/"));
    }

    /**
     * Returns match summary statistics for a (player, queue) combination grouped by gods played.
     */
    public String getQueueStats(String player, Queue queue) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getqueuestats" + responseFormat,
                developerId,
                getSignature("getqueuestats"),
                sessionId,
                getTimestamp(),
                player,
                String.valueOf(queue.getValue())
        }, "/"));
    }

    /**
     * Lists the number of players and other high level details for a particular clan.
     */
    public String getTeamDetails(String clanId) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getteamdetails" + responseFormat,
                developerId,
                getSignature("getteamdetails"),
                sessionId,
                getTimestamp(),
                clanId
        }, "/"));
    }

    /**
     * Gets recent matches and high level match statistics for a particular clan/team.
     */
    public String getTeamMatchHistory(String clanId) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getteammatchhistory" + responseFormat,
                developerId,
                getSignature("getteammatchhistory"),
                sessionId,
                getTimestamp(),
                clanId
        }, "/"));
    }

    /**
     * Lists the players for a particular clan.
     */
    public String getTeamPlayers(String clanId) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "getteamplayers" + responseFormat,
                developerId,
                getSignature("getteamplayers"),
                sessionId,
                getTimestamp(),
                clanId
        }, "/"));
    }

    /**
     * Lists the 50 most watched / most recent recorded matches.
     */
    public String getTopMatches() {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "gettopmatches" + responseFormat,
                developerId,
                getSignature("gettopmatches"),
                sessionId,
                getTimestamp()
        }, "/"));
    }

    /**
     * Returns high level information for Team names containing the "searchTeam" string.
     */
    public String searchTeams(String searchTeam) {
        if (!isSessionValid() && !createSession()) return null;
        return get(combine(new String[] {
                BASE_URL + "searchteams" + responseFormat,
                developerId,
                getSignature("searchteams"),
                sessionId,
                getTimestamp(),
                searchTeam
        }, "/"));
    }

    private String get(String url) {
        return HttpClient.fetch(url);
    }

    private String combine(String[] items, String delimiter) {
        int k = items.length;
        if (k == 0) return null;

        StringBuilder builder = new StringBuilder();
        builder.append(items[0]);

        for (int i = 1; i < items.length; i++) {
            builder.append(delimiter).append(items[i]);
        }

        return builder.toString();
    }

    /**
     * Returns whether the current API session is valid based on the criteria of one session lasting 15 minutes.
     */
    private boolean isSessionValid() {
        return sessionId != null && Math.abs(System.currentTimeMillis() - sessionStart) <= 15 * 60 * 1000;
    }

    /**
     * Get the current UTC timestamp formatted yyyyMMddHHmmss
     */
    public String getTimestamp() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return dateFormat.format(new Date());
    }

    /**
     * Create the signature parameter required for each API call
     */
    private String getSignature(String method) {
        return getMD5(developerId+ method + authKey+ getTimestamp());
    }

    /**
     * Generate an MD5 hash for an input String
     * http://www.mkyong.com/java/java-md5-hashing-example/
     */
    public String getMD5(String input) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(input.getBytes());

            byte[] data = messageDigest.digest();

            // Convert from byte to hex
            StringBuilder stringBuffer = new StringBuilder();
            for (byte b : data) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) stringBuffer.append("0");
                stringBuffer.append(hex);
            }

            return stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * Sets the default response format.
     */
    public void setResponseFormat(String responseFormat) {
        if (responseFormat.equals(RESPONSE_TYPE_JSON) || responseFormat.equals(RESPONSE_TYPE_XML))
            this.responseFormat = responseFormat;
    }

    public String getResponseFormat() {
        return responseFormat;
    }

    public enum LanguageCode {
        ENGLISH (1),
        GERMAN (2),
        FRENCH (3),
        SPANISH (7),
        SPANISH_LATIN_AMERICA (9),
        PORTUGUESE (10),
        RUSSIAN (11),
        POLISH (12),
        TURKISH (13);

        private final int value;

        private LanguageCode(int value) {
            this.value = value;
        }

        public int getValue() {
            return this.value;
        }
    }

    public enum Queue {
        CONQUEST_5V5 (423),
        NOVICE_QUEUE (424),
        CONQUEST (426),
        PRACTICE (427),
        CONQUEST_CHALLENGE (429),
        CONQUEST_RANKED (430),
        DOMINATION (433),
        MOTD (434),
        ARENA (435),
        ARENA_CHALLENGE (438),
        DOMINATION_CHALLENGE (439),
        JOUST_LEAGUE (440),
        JOUST_CHALLENGE (441),
        ASSAULT (445),
        ASSAULT_CHALLENGE (446),
        JOUST_3V3 (448),
        CONQUEST_LEAGUE (451),
        ARENA_LEAGUE (452);

        private final int value;

        private Queue(int value) {
            this.value = value;
        }

        public int getValue() {
            return this.value;
        }
    }

    public enum Tier {
        BRONZE_V (1), BRONZE_IV (2), BRONZE_III (3), BRONZE_II (4), BRONZE_I (5),
        SILVER_V (6), SILVER_IV (7), SILVER_III (8), SILVER_II (9), SILVER_I (10),
        GOLD_V (11), GOLD_IV (12), GOLD_III (13), GOLD_II (14), GOLD_I (15),
        PLATINUM_V (16), PLATINUM_IV (17), PLATINUM_III (18), PLATINUM_II (19), PLATINUM_I (20),
        DIAMOND_V (21), DIAMOND_IV (22), DIAMOND_III (23), DIAMOND_II (24), DIAMOND_I (25),
        MASTERS_I (26);

        private final int value;

        private Tier(int value) {
            this.value = value;
        }

        public int getValue() {
            return this.value;
        }
    }
}


text:
// Copyright (c) 2011, David J. Pearce (djp@ecs.vuw.ac.nz)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//    * Redistributions of source code must retain the above copyright
//      notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//    * Neither the name of the <organization> nor the
//      names of its contributors may be used to endorse or promote products
//      derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package wyjc.runtime;

import java.math.BigInteger;
import java.util.Collections;
import java.util.Map;

public final class WyList extends java.util.ArrayList {
	/**
	 * The reference count is use to indicate how many variables are currently
	 * referencing this compound structure. This is useful for making imperative
	 * updates more efficient. In particular, when the refCount is
	 * 1 we can safely perform an in-place update of the structure.
	 */
	int refCount = 100; // temporary measure

	// ================================================================================
	// Generic Operations
	// ================================================================================

	public WyList() {
		super();
	}

	public WyList(int size) {
		super(size);
	}

	WyList(java.util.Collection items) {
		super(items);
		for(Object o : items) {
			Util.incRefs(o);
		}
	}

	public String toString() {
		String r = "[";
		boolean firstTime=true;
		for(Object o : this) {
			if(!firstTime) {
				r += ", ";
			}
			firstTime=false;
			r += whiley.lang.Any$native.toString(o);
		}
		return r + "]";
	}

	// ================================================================================
	// List Operations
	// ================================================================================

	public static Object get(WyList list, BigInteger index) {
		Object item = list.get(index.intValue());
		return Util.incRefs(item);
	}

	public static WyList set(WyList list, final BigInteger index, final Object value) {
		Util.countRefs(list);
		if(list.refCount > 0) {
			Util.countClone(list);
			// in this case, we need to clone the list in question
			list = new WyList(list);
		} else {
			Util.nlist_inplace_updates++;
		}
		Object v = list.set(index.intValue(),value);
		Util.decRefs(v);
		Util.incRefs(value);
		return list;
	}

	public static WyList sublist(final WyList list, final BigInteger start, final BigInteger end) {
		Util.countRefs(list);
		int st = start.intValue();
		int en = end.intValue();

		if(list.refCount == 0) {
			Util.nlist_inplace_updates++;
			if(st <= en) {
				for(int i=0;i!=st;++i) {
					Util.decRefs(list.get(i));
				}
				for(int i=en;i!=list.size();++i) {
					Util.decRefs(list.get(i));
				}
				list.removeRange(0,st);
				list.removeRange(en-st,list.size());
				return list;
			} else {
				for(int i=0;i!=en;++i) {
					Util.decRefs(list.get(i));
				}
				for(int i=st;i!=list.size();++i) {
					Util.decRefs(list.get(i));
				}
				list.removeRange(0,en);
				list.removeRange(st-en,list.size());
				Collections.reverse(list);
				return list;
			}
		} else {
			WyList r;
			if(st <= en) {
				r = new WyList(en-st);
				for (int i = st; i != en; ++i) {
					Object item = list.get(i);
					Util.incRefs(item);
					r.add(item);
				}
			} else {
				r = new WyList(st-en);
				for (int i = (st-1); i >= en; --i) {
					Object item = list.get(i);
					Util.incRefs(item);
					r.add(item);
				}
			}
			Util.countClone(r);
			return r;
		}
	}

	public static BigInteger length(WyList list) {
		return BigInteger.valueOf(list.size());
	}

	public static WyList append(WyList lhs, WyList rhs) {
		Util.countRefs(lhs);
		Util.countRefs(rhs);
		if(lhs.refCount == 0) {
			Util.nlist_inplace_updates++;
		} else {
			Util.countClone(lhs);
			lhs = new WyList(lhs);
		}

		lhs.addAll(rhs);

		for(Object o : rhs) {
			Util.incRefs(o);
		}

		return lhs;
	}

	public static WyList append(WyList list, final Object item) {
		Util.countRefs(list);
		if(list.refCount == 0) {
			Util.nlist_inplace_updates++;
		} else {
			Util.countClone(list);
			list = new WyList(list);
		}
		list.add(item);
		Util.incRefs(item);
		return list;
	}

	public static WyList append(final Object item, WyList list) {
		Util.countRefs(list);
		if(list.refCount == 0) {
			Util.nlist_inplace_updates++;
		} else {
			Util.countClone(list);
			list = new WyList(list);
		}
		list.add(0,item);
		Util.incRefs(item);
		return list;
	}

	public static int size(final WyList list) {
		return list.size();
	}

	/**
	 * This method is not intended for public consumption. It is used internally
	 * by the compiler during object construction only.
	 *
	 * @param list
	 * @param item
	 * @return
	 */
	public static WyList internal_add(WyList list, final Object item) {
		list.add(item);
		return list;
	}

	/**
	 * This method is not intended for public consumption. It is used internally
	 * by the compiler during imperative updates only.
	 *
	 * @param list
	 * @param item
	 * @return
	 */
	public static Object internal_get(WyList list, BigInteger index) {
		Object item = list.get(index.intValue());
		if(list.refCount > 0) {
			Util.incRefs(item);
		}
		return item;
	}

	public static java.util.Iterator iterator(WyList list) {
		return list.iterator();
	}
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.8-2-b-3
description: >
    Object.seal - the [[Configurable]] attribute of all own properties
    of 'O' are set from true to false and other attributes of the
    property are unaltered
includes: [propertyHelper.js]
---*/

var obj = {};
obj.variableForHelpVerify = "data";

Object.defineProperty(obj, "foo1", {
    value: 10,
    writable: true,
    enumerable: true,
    configurable: true
});

function set_func(value) {
    obj.variableForHelpVerify = value;
}
function get_func() {
    return 10;
}
Object.defineProperty(obj, "foo2", {
    get: get_func,
    set: set_func,
    enumerable: true,
    configurable: true
});
var preCheck = Object.isExtensible(obj);
Object.seal(obj);

if (!preCheck) {
    $ERROR('Expected preCheck to be true, actually ' + preCheck);
}

verifyEqualTo(obj, "foo1", 10);

verifyWritable(obj, "foo1");

verifyEnumerable(obj, "foo1");

verifyNotConfigurable(obj, "foo1");

verifyEqualTo(obj, "foo2", get_func());

verifyWritable(obj, "foo2", "variableForHelpVerify");

verifyEnumerable(obj, "foo2");

verifyNotConfigurable(obj, "foo2");


text:
#include "ltr_state.h"
#include <ltlib_int.h>

TrackerState *TrackerState::ts = NULL;

TrackerState& TrackerState::trackerStateInst()
{
  if(ts == NULL){
    ts = new TrackerState();
  }
  return *ts;
}

TrackerState::TrackerState()
{
  timer = new QTimer(this);
  connect(timer, SIGNAL(timeout()), this, SLOT(pollState()));
  prev_state = STOPPED;
  timer->start(200);
}

TrackerState::~TrackerState()
{
  delete timer;
}

/*
linuxtrack_state_type TrackerState::getCurrentState()
{
  return ltr_int_get_tracking_state();
}
*/

void TrackerState::pollState()
{
  linuxtrack_state_type current_state = ltr_int_get_tracking_state();
  if(prev_state != current_state){
    emit stateChanged(current_state);
  }
  prev_state = current_state;
}


text:
package middleman.utils;

public interface Block<T> {
    void yield(T item);
}


text:
%=================================================================
\ifx%
\wholebook%
\relax%
\else
% --------------------------------------------
% Lulu:
	\documentclass[a4paper,10pt,twoside]{book}
	\usepackage[
		papersize={6.13in,9.21in},
		hmargin={.75in,.75in},
		vmargin={.75in,1in},
		ignoreheadfoot
	]{geometry}
	\input{../common.tex}
	\setboolean{lulu}{true}
% --------------------------------------------
% A4:
%	\documentclass[a4paper,11pt,twoside]{book}
%	\input{../common.tex}
%	\usepackage{a4wide}
% --------------------------------------------
    \graphicspath{{figures/} {../figures/}}
    \begin{document}
\fi
%=================================================================
%\renewcommand{\nnbb}[2]{} % Disable editorial comments
\sloppy
%=================================================================
\chapter { Advanced topics subscriptions }
\chalabel{advancedTopicsSubscription}

					\section{Adapting incoming data}

						Topic connections are typed, what is obviously needed for high-performance transference, but it makes to repeat a lot of code, just because types just not match.

						A common example is to have a code that works with a Pose type:

						\begin{lstlisting}[language=bash,title={ rosmsg - show }]
						 pharos@PhaROS:~$ rosmsg show geometry_msgs/Pose

						 geometry_msgs/Point position
							  float64 x
							  float64 y
							  float64 z
						geometry_msgs/Quaternion orientation
							  float64 x
							  float64 y
							  float64 z
							  float64 w
						\end{lstlisting}

						But we are subscribing to a PoseStamped type:

						\begin{lstlisting}[language=bash,title={ rosmsg - show }]
						 pharos@PhaROS:~$ rosmsg show geometry_msgs/PoseStamped

						 std_msgs/Header header
								  uint32 seq
								  time stamp
								  string frame_id
						geometry_msgs/Pose pose
							  geometry_msgs/Point position
								    float64 x
								    float64 y
								    float64 z
						  	  geometry_msgs/Quaternion orientation
								    float64 x
								    float64 y
								    float64 z
								    float64 w

						\end{lstlisting}

						so, we will need to write a different callback for each case, just because the type is not the same.

						Or even better, we may have a piece of software that uses instead of a ROS type, a domain type, which is always mapped the same way from a given ROS type.

						For solving this kind of problems we have a concept called Adaption.

						\subsection{Navigating data}

							A common case then, is to need by example, the pose, instead the pose stamped. For this case, what we need is to adapt the incoming data, in order to execute the callback with the information available in the pose field of the object.

							\begin{code}
				(self controller node buildConnectionFor: '/example/pose/stamped' )
					typedAs: 'geometry_msgs/PoseStamped';
					adaption: #pose;
					for: [ : pose |  Transcript show: pose ];
					connect .

							\end{code}

							This means that the result subscription will have an adaption object that will send the pose message to the given object, and send the result to the callback.

							What happen if we need to get the position of the pose, and not the pose.

							Not big deal, we just need to:

							\begin{code}
				(self controller node buildConnectionFor: '/example/pose/stamped' )
					typedAs: 'geometry_msgs/PoseStamped';
					adaption: #pose \> #position;
					for: [ : position |  Transcript show: position ];
					connect .

							\end{code}

							the

							\begin{code}

							\>

							\end{code}

							operator is an operator that defines a chain of transformations. This means that, after send the message pose, it will send the message position, and use that as input of our callback.

							Like this, we can navigate any kind of object. The main cons is that we cannot receive any but the value of one field. (we cannot yet choose more than one field). What means that we will lose the rest of the data if we use this.

						\subsection{Transforming data}

							Other of the common problems are the reifications. ROS Types are just for sending information, but they are not domain objects. They are generated on demand, i order to make light weight the image. This means that the object i will receive in my callback is always a dumb object that cannot do but set and get attributes.

							There are, however, some objects that are commonly transformed to domain objects, that can be usually mapped from one type to other. By example, \fwkName{} comes with a class named PhaROSPose. This class has implemented for it objects several methods for conversion an measures. In other words, when we are working with poses, in almost cases we will want to deal with this object and not with the generated one.

							For this can of cases, we can add to our chain of adaption a transformation of types

							Lets picture that we have a topic typed as Pose, we can connect it as

							\begin{code}
				(self controller node buildConnectionFor: '/example/pose' )
					typedAs: 'geometry_msgs/Pose';
					adaption: PhaROSPose;
					for: [ : pose |  Transcript show: pose ];
					connect .

							\end{code}

							The received pose, it will be of type PhaROSPose.

							Again, if we need the position instead of the pose, we can write it in two ways

							\begin{code}
				(self controller node buildConnectionFor: '/example/pose' )
					typedAs: 'geometry_msgs/Pose';
					adaption: PhaROSPose \> position;
					for: [ : position |  Transcript show: pose ];
					connect .

							\end{code}

							This will convert the pose to a PhaROSPose and then ask for the position. Or, for making less computations

							\begin{code}
				(self controller node buildConnectionFor: '/example/pose' )
					typedAs: 'geometry_msgs/Pose';
					adaption: #position \> PhaROSPosition;
					for: [ : position |  Transcript show: pose ];
					connect .

							\end{code}

							This will first navigate to the position field, for converting it content to a PhaROSPosition type. Which is the type of the position component of a PhaROSPose.

							How this bizarre mechanism works? Because is not really easy to map two types, it cannot be free, and, actually is not.

							This notation allow us to have the transformation of a type coded in just one place, and even hide the name of the conversion.

							For having this conversion available, the class that is wanted to be created should have a constructor named from{ClassNameOfTheROSType).

							If we browse the class side of PhaROSPose and PhaROSPosition we will find

					\begin{code}
PhaROSPose>>#fromGeometry_msgsPose: aPose
	^ self position: (PhaROSPosition from: aPose position) orientation: (PhaROSQuaternion from: aPose orientation)

PhaROSPosition>>#fromGeometry_msgsPosition: aPosition
	^ PhaROSPosition from: aPosition

					\end{code}

							If you are asking why the PhaROSPosition constructor is so generic, it is because it construct it self from any object that understands the messages \#x \#y and \#z.

							This mechanism have also the same problem, there is information that we will lost and do not be able to recover.

					\section {Conditionals}

							Usually what happens is that we need some part of the information for conditions, or even that the acceptance condition of a packet of data is complex enough to want it out of the callback logic.

							For this usage we have the message \#when: that can be sent to the connection builder.

							The usage is quite simple

							Picture that we want the pose object, but we don't want all the poses, just the poses that are as older 1 second.
							This is a quite common restriction, since we want data to be fresh as possible (even 1 second is chosen to make the example easier, but is maybe a lot of time)

							\begin{code}
				(self controller node buildConnectionFor: '/example/pose' )
					typedAs: 'geometry_msgs/Pose';
					adaption: #position \> PhaROSPosition;
					when:[ : message | DateAndTime now - (message header stamp) < = 1 second ];
					for: [ : position |  Transcript show: pose ];
					connect .

							\end{code}

							So, the callback will be executed only when the lifetime of the pose stamped is less than 1 second. If is more, it will be rejected.
							Is important to see that the conditional block will receive the raw information, so, when you want to make some conditions related to information that you don't need in your callback, you just use a conditional block. Then the callback can remains easy and domain oriented.

					\section {Time stamp}

						One of the problems of all this machinery is that we may still needing the timestamp for, maybe, synchronising data, or for other kind of calculations.
						For this cases, where the only thing we need from a data packet, but one concrete field, is the time stamp related with the header, or the packet it self, we can rely not the optional parameters of a callback

						And we can rely in this parameter always, when the first type has a header, the stamp will be the defined in it

						\begin{code}
				(self controller node buildConnectionFor: '/example/pose' )
					typedAs: 'geometry_msgs/PoseStamped';
					adaption: #pose \> PhaROSPose;
					when:[ : message | DateAndTime now - (message header stamp) < = 1 second ];
					for: [ :position :channel :stamp |  Transcript show: stamp  ];
					connect .

						\end{code}

					And when we have no header

						\begin{code}
				(self controller node buildConnectionFor: '/example/pose' )
					typedAs: 'geometry_msgs/Pose';
					adaption: PhaROSPose;
					for: [ :position :channel :stamp |  Transcript show: stamp  ];
					connect .

						\end{code}

					The stamp received will be the stamp of the reception of the packet

					The restriction of this mechanism are

					\begin{itemize}
						\item The algorithm check for a header in the first type, it does not do it in inner types. So, if the header is in the an inner type it will not be minded
						\item The stamp mechanism is only available in the callback scope, not in the conditional scope. Thats why our second example of usage has not when: message.
					\end{itemize}

					\section {Callbacks}

						There are times where we need to configure our connection in one part and set the callback in other place, in a place that you don't want to use a builder, but the real topic subscription.
						 In this cases you just need define your connection as always but do not use the for: message during the configuration.

						The builder will set a default callback that writes in the transcript this legend 'Warning! This topic conection it has no callback configured! ', in order to do not let you forget the fact that you have a thread running, receiving information that is not being used.

						Then, where you receive the connection, you can send to the topic the messages \#for: and \#callback: Both do the same, but express different semantics.

						\begin{code}
						connection := (self controller node buildConnectionFor: '/example/pose' )
									typedAs: 'geometry_msgs/Pose';
									adaption: PhaROSPose;
									connect .

						connection for: [ :position :channel :stamp |  Transcript show: stamp  ].
						\end{code}

						If you don't mind to use a builder object, and have the connect message in the receiver context, we recommend to use the builder, so you are sure that there is always a useful callback setter.

						\begin{code}
						connectionBuilder := (self controller node buildConnectionFor: '/example/pose' )
									typedAs: 'geometry_msgs/Pose';
									adaption: PhaROSPose.

						connection := connectionBuilder for: [ :position :channel :stamp |  Transcript show: stamp  ];	connect.
						\end{code}

					\section{Tip about performance}

						One implementation detail that is important is the fact that a topic is connected one time per node. Since we are always working with the same node inside the package definition, all the times that we connect to a topic, we are using always the same connection, but defining different objects for callback management.

						This is an important trade off. We can have then several callbacks for a topic, each one with it own full configuration. This is flexble, and reduces the IO work.
						In exchange, the same thread that does the IO work, is working on the callbacks. So, the more callbacks you define, the more work have the thread in between input and other, making the available messages to read quite bigger, and losing efficiency in the reading, what have impact in the how-fresh is a data.

						So, take this in care when you are deciding to have more than one connection to the same topic from the same instance.

					\section {Brief}

						\begin{itemize}
							\item Adapting incoming data\begin{itemize}

								\item Add the message \#adaption: to the connection building chain of messages to shape the message that it will be received by your callback.
								\item Use symbols to adapt sending messages
								\item Use class names to make conversions (Reminding to implement the needed class methods)
								\item Combine your adaptions with the \verb|\>| operator.
							\end{itemize}
							\item Add the message \#when: to define a callback based on raw data to accept or reject a received packet
							\item Let your callbacks rely on the third optional parameter to have the time stamp of the packet reception.
							\item Divide your connection building from the callback setting to be able to split the name and type of a topic from your behaviour code.
							\item Mind the thread architecture when you do strange stuff in your callbacks.
						\end{itemize}

%\chapterauthor{\authorjankurs{} \\ \authorguillaume{} \\ \authorlukas{}}

%=============================================================
\ifx\wholebook\relax\else

\end{document}

\fi
%=============================================================


text:
"""Utility functions for NumPy arrays."""

#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------

import os
import os.path as op
from math import floor
from operator import mul
from functools import reduce
import math

import numpy as np
from six import integer_types, string_types

from .logging import warn
from ._types import _as_tuple, _as_array

#------------------------------------------------------------------------------
# Utility functions
#------------------------------------------------------------------------------

def _range_from_slice(myslice, start=None, stop=None, step=None, length=None):
    """Convert a slice to an array of integers."""
    assert isinstance(myslice, slice)
    # Find 'step'.
    step = step if step is not None else myslice.step
    if step is None:
        step = 1
    # Find 'start'.
    start = start if start is not None else myslice.start
    if start is None:
        start = 0
    # Find 'stop' as a function of length if 'stop' is unspecified.
    stop = stop if stop is not None else myslice.stop
    if length is not None:
        stop_inferred = floor(start + step * length)
        if stop is not None and stop < stop_inferred:
            raise ValueError("'stop' ({stop}) and ".format(stop=stop) +
                             "'length' ({length}) ".format(length=length) +
                             "are not compatible.")
        stop = stop_inferred
    if stop is None and length is None:
        raise ValueError("'stop' and 'length' cannot be both unspecified.")
    myrange = np.arange(start, stop, step)
    # Check the length if it was specified.
    if length is not None:
        assert len(myrange) == length
    return myrange

def _unique(x):
    """Faster version of np.unique().

    This version is restricted to 1D arrays of non-negative integers.

    It is only faster if len(x) >> len(unique(x)).

    """
    if x is None or len(x) == 0:
        return np.array([], dtype=np.int64)
    # WARNING: only keep positive values.
    # cluster=-1 means "unclustered".
    x = _as_array(x)
    x = x[x >= 0]
    bc = np.bincount(x)
    return np.nonzero(bc)[0]

def _ensure_unique(func):
    """Apply unique() to the output of a function."""
    def wrapped(*args, **kwargs):
        out = func(*args, **kwargs)
        return _unique(out)
    return wrapped

def _normalize(arr, keep_ratio=False):
    """Normalize an array into [0, 1]."""
    (x_min, y_min), (x_max, y_max) = arr.min(axis=0), arr.max(axis=0)

    if keep_ratio:
        a = 1. / max(x_max - x_min, y_max - y_min)
        ax = ay = a
        bx = .5 - .5 * a * (x_max + x_min)
        by = .5 - .5 * a * (y_max + y_min)
    else:
        ax = 1. / (x_max - x_min)
        ay = 1. / (y_max - y_min)
        bx = -x_min / (x_max - x_min)
        by = -y_min / (y_max - y_min)

    arr_n = arr.copy()
    arr_n[:, 0] *= ax
    arr_n[:, 0] += bx
    arr_n[:, 1] *= ay
    arr_n[:, 1] += by

    return arr_n

def _index_of(arr, lookup):
    """Replace scalars in an array by their indices in a lookup table.

    Implicitely assume that:

    * All elements of arr and lookup are non-negative integers.
    * All elements or arr belong to lookup.

    This is not checked for performance reasons.

    """
    # Equivalent of np.digitize(arr, lookup) - 1, but much faster.
    # TODO: assertions to disable in production for performance reasons.
    m = (lookup.max() if len(lookup) else 0) + 1
    tmp = np.zeros(m + 1, dtype=np.int)
    # Ensure that -1 values are kept.
    tmp[-1] = -1
    if len(lookup):
        tmp[lookup] = np.arange(len(lookup))
    return tmp[arr]

def index_of_small(arr, lookup):
    """Faster on small arrays with large values."""
    return np.searchsorted(lookup, arr)

def _partial_shape(shape, trailing_index):
    """Return the shape of a partial array."""
    if shape is None:
        shape = ()
    if trailing_index is None:
        trailing_index = ()
    trailing_index = _as_tuple(trailing_index)
    # Length of the selection items for the partial array.
    len_item = len(shape) - len(trailing_index)
    # Array for the trailing dimensions.
    _arr = np.empty(shape=shape[len_item:])
    try:
        trailing_arr = _arr[trailing_index]
    except IndexError:
        raise ValueError("The partial shape index is invalid.")
    return shape[:len_item] + trailing_arr.shape

def _pad(arr, n, dir='right'):
    """Pad an array with zeros along the first axis.

    Parameters
    ----------

    n : int
        Size of the returned array in the first axis.
    dir : str
        Direction of the padding. Must be one 'left' or 'right'.

    """
    assert dir in ('left', 'right')
    if n < 0:
        raise ValueError("'n' must be positive: {0}.".format(n))
    elif n == 0:
        return np.zeros((0,) + arr.shape[1:], dtype=arr.dtype)
    n_arr = arr.shape[0]
    shape = (n,) + arr.shape[1:]
    if n_arr == n:
        assert arr.shape == shape
        return arr
    elif n_arr < n:
        out = np.zeros(shape, dtype=arr.dtype)
        if dir == 'left':
            out[-n_arr:, ...] = arr
        elif dir == 'right':
            out[:n_arr, ...] = arr
        assert out.shape == shape
        return out
    else:
        if dir == 'left':
            out = arr[-n:, ...]
        elif dir == 'right':
            out = arr[:n, ...]
        assert out.shape == shape
        return out

def _start_stop(item):
    """Find the start and stop indices of a __getitem__ item.

    This is used only by ConcatenatedArrays.

    Only two cases are supported currently:

    * Single integer.
    * Contiguous slice in the first dimension only.

    """
    if isinstance(item, tuple):
        item = item[0]
    if isinstance(item, slice):
        # Slice.
        if item.step not in (None, 1):
            return NotImplementedError()
        return item.start, item.stop
    elif isinstance(item, (list, np.ndarray)):
        # List or array of indices.
        return np.min(item), np.max(item)
    else:
        # Integer.
        return item, item + 1

def _len_index(item, max_len=0):
    """Return the expected length of the output of __getitem__(item)."""
    if isinstance(item, (list, np.ndarray)):
        return len(item)
    elif isinstance(item, slice):
        stop = item.stop or max_len
        start = item.start or 0
        step = item.step or 1
        start = np.clip(start, 0, stop)
        assert 0 <= start <= stop
        return 1 + ((stop - 1 - start) // step)
    else:
        return 1

def _fill_index(arr, item):
    if isinstance(item, tuple):
        item = (slice(None, None, None),) + item[1:]
        return arr[item]
    else:
        return arr

def _in_polygon(points, polygon):
    """Return the points that are inside a polygon."""
    from matplotlib.path import Path
    points = _as_array(points)
    polygon = _as_array(polygon)
    assert points.ndim == 2
    assert polygon.ndim == 2
    path = Path(polygon, closed=True)
    return path.contains_points(points)

def _concatenate(arrs):
    if arrs is None:
        return
    arrs = [_as_array(arr) for arr in arrs if arr is not None]
    if not arrs:
        return
    return np.concatenate(arrs, axis=0)

# -----------------------------------------------------------------------------
# I/O functions
# -----------------------------------------------------------------------------

def _prod(l):
    return reduce(mul, l, 1)

class LazyMemmap(object):
    """A memmapped array that only opens the file handle when required."""
    def __init__(self, path, dtype=None, shape=None, mode='r'):
        assert isinstance(path, string_types)
        assert dtype
        self._path = path
        self._f = None
        self.mode = mode
        self.dtype = dtype
        self.shape = shape
        self.ndim = len(shape) if shape else None

    def _open_file_if_needed(self):
        if self._f is None:
            self._f = np.memmap(self._path,
                                dtype=self.dtype,
                                shape=self.shape,
                                mode=self.mode,
                                )
            self.shape = self._f.shape
            self.ndim = self._f.ndim

    def __getitem__(self, item):
        self._open_file_if_needed()
        return self._f[item]

    def __len__(self):
        self._open_file_if_needed()
        return len(self._f)

    def __del__(self):
        if self._f is not None:
            del self._f

def _memmap(f_or_path, dtype=None, shape=None, lazy=True):
    if not lazy:
        return np.memmap(f_or_path, dtype=dtype, shape=shape, mode='r')
    else:
        return LazyMemmap(f_or_path, dtype=dtype, shape=shape, mode='r')

def _file_size(f_or_path):
    if isinstance(f_or_path, string_types):
        with open(f_or_path, 'rb') as f:
            return _file_size(f)
    else:
        return os.fstat(f_or_path.fileno()).st_size

def _load_ndarray(f_or_path, dtype=None, shape=None, memmap=False, lazy=False):
    if dtype is None:
        return f_or_path
    else:
        if not memmap:
            arr = np.fromfile(f_or_path, dtype=dtype)
            if shape is not None:
                arr = arr.reshape(shape)
        else:
            # memmap doesn't accept -1 in shapes, but we can compute
            # the missing dimension from the file size.
            if shape and shape[0] == -1:
                n_bytes = _file_size(f_or_path)
                n_items = n_bytes // np.dtype(dtype).itemsize
                n_rows = n_items // _prod(shape[1:])
                shape = (n_rows,) + shape[1:]
                assert _prod(shape) == n_items
            arr = _memmap(f_or_path, dtype=dtype, shape=shape, lazy=lazy)
        return arr

def _save_arrays(path, arrays):
    """Save multiple arrays in a single file by concatenating them along
    the first axis.

    A second array is stored with the offsets.

    """
    assert path.endswith('.npy')
    path = op.splitext(path)[0]
    offsets = np.cumsum([arr.shape[0] for arr in arrays])
    if not len(arrays):
        return
    concat = np.concatenate(arrays, axis=0)
    np.save(path + '.npy', concat)
    np.save(path + '.offsets.npy', offsets)

def _load_arrays(path):
    assert path.endswith('.npy')
    if not op.exists(path):
        return []
    path = op.splitext(path)[0]
    concat = np.load(path + '.npy')
    offsets = np.load(path + '.offsets.npy')
    return np.split(concat, offsets[:-1], axis=0)

# -----------------------------------------------------------------------------
# Chunking functions
# -----------------------------------------------------------------------------

def _excerpt_step(n_samples, n_excerpts=None, excerpt_size=None):
    """Compute the step of an excerpt set as a function of the number
    of excerpts or their sizes."""
    assert n_excerpts >= 2
    step = max((n_samples - excerpt_size) // (n_excerpts - 1),
               excerpt_size)
    return step

def chunk_bounds(n_samples, chunk_size, overlap=0):
    """Return chunk bounds.

    Chunks have the form:

        [ overlap/2 | chunk_size-overlap | overlap/2 ]
        s_start   keep_start           keep_end     s_end

    Except for the first and last chunks which do not have a left/right
    overlap.

    This generator yields (s_start, s_end, keep_start, keep_end).

    """
    s_start = 0
    s_end = chunk_size
    keep_start = s_start
    keep_end = s_end - overlap // 2
    yield s_start, s_end, keep_start, keep_end

    while s_end - overlap + chunk_size < n_samples:
        s_start = s_end - overlap
        s_end = s_start + chunk_size
        keep_start = keep_end
        keep_end = s_end - overlap // 2
        if s_start < s_end:
            yield s_start, s_end, keep_start, keep_end

    s_start = s_end - overlap
    s_end = n_samples
    keep_start = keep_end
    keep_end = s_end
    if s_start < s_end:
        yield s_start, s_end, keep_start, keep_end

def excerpts(n_samples, n_excerpts=None, excerpt_size=None):
    """Yield (start, end) where start is included and end is excluded."""
    assert n_excerpts >= 2
    step = _excerpt_step(n_samples,
                         n_excerpts=n_excerpts,
                         excerpt_size=excerpt_size)
    for i in range(n_excerpts):
        start = i * step
        if start >= n_samples:
            break
        end = min(start + excerpt_size, n_samples)
        yield start, end

def data_chunk(data, chunk, with_overlap=False):
    """Get a data chunk."""
    assert isinstance(chunk, tuple)
    if len(chunk) == 2:
        i, j = chunk
    elif len(chunk) == 4:
        if with_overlap:
            i, j = chunk[:2]
        else:
            i, j = chunk[2:]
    else:
        raise ValueError("'chunk' should have 2 or 4 elements, "
                         "not {0:d}".format(len(chunk)))
    return data[i:j, ...]

def get_excerpts(data, n_excerpts=None, excerpt_size=None):
    assert n_excerpts is not None
    assert excerpt_size is not None
    if len(data) < n_excerpts * excerpt_size:
        return data
    elif n_excerpts == 0:
        return data[:0]
    elif n_excerpts == 1:
        return data[:excerpt_size]
    out = np.concatenate([data_chunk(data, chunk)
                          for chunk in excerpts(len(data),
                                                n_excerpts=n_excerpts,
                                                excerpt_size=excerpt_size)])
    assert len(out) <= n_excerpts * excerpt_size
    return out

def regular_subset(spikes=None, n_spikes_max=None):
    """Prune the current selection to get at most n_spikes_max spikes."""
    assert spikes is not None
    # Nothing to do if the selection already satisfies n_spikes_max.
    if n_spikes_max is None or len(spikes) <= n_spikes_max:
        return spikes
    step = math.ceil(np.clip(1. / n_spikes_max * len(spikes),
                             1, len(spikes)))
    step = int(step)
    # Random shift.
    # start = np.random.randint(low=0, high=step)
    # Note: randomly-changing selections are confusing...
    start = 0
    my_spikes = spikes[start::step][:n_spikes_max]
    assert len(my_spikes) <= len(spikes)
    assert len(my_spikes) <= n_spikes_max
    return my_spikes

# -----------------------------------------------------------------------------
# Spike clusters utility functions
# -----------------------------------------------------------------------------

def _spikes_in_clusters(spike_clusters, clusters):
    """Return the ids of all spikes belonging to the specified clusters."""
    if len(spike_clusters) == 0 or len(clusters) == 0:
        return np.array([], dtype=np.int)
    # spikes_per_cluster case.
    if isinstance(spike_clusters, dict):
        return np.sort(np.concatenate([spike_clusters[cluster]
                                       for cluster in clusters]))
    return np.nonzero(np.in1d(spike_clusters, clusters))[0]

def _spikes_per_cluster(spike_ids, spike_clusters):
    """Return a dictionary {cluster: list_of_spikes}."""
    if not len(spike_ids):
        return {}
    rel_spikes = np.argsort(spike_clusters)
    abs_spikes = spike_ids[rel_spikes]
    spike_clusters = spike_clusters[rel_spikes]

    diff = np.empty_like(spike_clusters)
    diff[0] = 1
    diff[1:] = np.diff(spike_clusters)

    idx = np.nonzero(diff > 0)[0]
    clusters = spike_clusters[idx]

    spikes_in_clusters = {clusters[i]: np.sort(abs_spikes[idx[i]:idx[i + 1]])
                          for i in range(len(clusters) - 1)}
    spikes_in_clusters[clusters[-1]] = np.sort(abs_spikes[idx[-1]:])

    return spikes_in_clusters

def _flatten_spikes_per_cluster(spikes_per_cluster):
    """Convert a dictionary {cluster: list_of_spikes} to a
    spike_clusters array."""
    clusters = sorted(spikes_per_cluster)
    clusters_arr = np.concatenate([(cluster *
                                   np.ones(len(spikes_per_cluster[cluster])))
                                   for cluster in clusters]).astype(np.int64)
    spikes_arr = np.concatenate([spikes_per_cluster[cluster]
                                 for cluster in clusters])
    spike_clusters = np.vstack((spikes_arr, clusters_arr))
    ind = np.argsort(spike_clusters[0, :])
    return spike_clusters[1, ind]

def _concatenate_per_cluster_arrays(spikes_per_cluster, arrays):
    """Concatenate arrays from a {cluster: array} dictionary."""
    assert set(arrays) <= set(spikes_per_cluster)
    clusters = sorted(arrays)
    # Check the sizes of the spikes per cluster and the arrays.
    n_0 = [len(spikes_per_cluster[cluster]) for cluster in clusters]
    n_1 = [len(arrays[cluster]) for cluster in clusters]
    assert n_0 == n_1

    # Concatenate all spikes to find the right insertion order.
    if not len(clusters):
        return np.array([])

    spikes = np.concatenate([spikes_per_cluster[cluster]
                             for cluster in clusters])
    idx = np.argsort(spikes)
    # NOTE: concatenate all arrays along the first axis, because we assume
    # that the first axis represents the spikes.
    arrays = np.concatenate([_as_array(arrays[cluster])
                             for cluster in clusters])
    return arrays[idx, ...]

def _subset_spc(spc, clusters):
    return {c: s for c, s in spc.items()
            if c in clusters}

class PerClusterData(object):
    """Store data associated to every spike.

    This class provides several data structures, with per-spike data and
    per-cluster data. It also defines a `subset()` method that allows to
    make a subset of the data using either spikes or clusters.

    """
    def __init__(self,
                 spike_ids=None, array=None, spike_clusters=None,
                 spc=None, arrays=None):
        if (array is not None and spike_ids is not None):
            # From array to per-cluster arrays.
            self._spike_ids = _as_array(spike_ids)
            self._array = _as_array(array)
            self._spike_clusters = _as_array(spike_clusters)
            self._check_array()
            self._split()
            self._check_dict()
        elif (arrays is not None and spc is not None):
            # From per-cluster arrays to array.
            self._spc = spc
            self._arrays = arrays
            self._check_dict()
            self._concatenate()
            self._check_array()
        else:
            raise ValueError()

    @property
    def spike_ids(self):
        """Sorted array of all spike ids."""
        return self._spike_ids

    @property
    def spike_clusters(self):
        """Array with the cluster id of every spike."""
        return self._spike_clusters

    @property
    def array(self):
        """Data array.

        The first dimension of the array corresponds to the spikes in the
        cluster.

        """
        return self._array

    @property
    def arrays(self):
        """Dictionary of arrays `{cluster: array}`.

        The first dimension of the arrays correspond to the spikes in the
        cluster.

        """
        return self._arrays

    @property
    def spc(self):
        """Spikes per cluster dictionary."""
        return self._spc

    @property
    def cluster_ids(self):
        """Sorted list of clusters."""
        return self._cluster_ids

    @property
    def n_clusters(self):
        return len(self._cluster_ids)

    def _check_dict(self):
        assert set(self._arrays) == set(self._spc)
        clusters = sorted(self._arrays)
        n_0 = [len(self._spc[cluster]) for cluster in clusters]
        n_1 = [len(self._arrays[cluster]) for cluster in clusters]
        assert n_0 == n_1

    def _check_array(self):
        assert len(self._array) == len(self._spike_ids)
        assert len(self._spike_clusters) == len(self._spike_ids)

    def _concatenate(self):
        self._cluster_ids = sorted(self._spc)
        n = len(self.cluster_ids)
        if n == 0:
            self._array = np.array([])
            self._spike_clusters = np.array([], dtype=np.int32)
            self._spike_ids = np.array([], dtype=np.int64)
        elif n == 1:
            c = self.cluster_ids[0]
            self._array = _as_array(self._arrays[c])
            self._spike_ids = self._spc[c]
            self._spike_clusters = c * np.ones(len(self._spike_ids),
                                               dtype=np.int32)
        else:
            # Concatenate all spikes to find the right insertion order.
            spikes = np.concatenate([self._spc[cluster]
                                     for cluster in self.cluster_ids])
            idx = np.argsort(spikes)
            self._spike_ids = np.sort(spikes)
            # NOTE: concatenate all arrays along the first axis, because we
            # assume that the first axis represents the spikes.
            # TODO OPTIM: use ConcatenatedArray and implement custom indices.
            # array = ConcatenatedArrays([_as_array(self._arrays[cluster])
            #                             for cluster in self.cluster_ids])
            array = np.concatenate([_as_array(self._arrays[cluster])
                                    for cluster in self.cluster_ids])
            self._array = array[idx]
            self._spike_clusters = _flatten_spikes_per_cluster(self._spc)

    def _split(self):
        self._spc = _spikes_per_cluster(self._spike_ids,
                                        self._spike_clusters)
        self._cluster_ids = sorted(self._spc)
        n = len(self.cluster_ids)
        # Optimization for single cluster.
        if n == 0:
            self._arrays = {}
        elif n == 1:
            c = self._cluster_ids[0]
            self._arrays = {c: self._array}
        else:
            self._arrays = {}
            for cluster in sorted(self._cluster_ids):
                spk = _as_array(self._spc[cluster])
                spk_rel = _index_of(spk, self._spike_ids)
                self._arrays[cluster] = self._array[spk_rel]

    def subset(self, spike_ids=None, clusters=None, spc=None):
        """Return a new PerClusterData instance with a subset of the data.

        There are three ways to specify the subset:

        * With a list of spikes
        * With a list of clusters
        * With a dictionary of `{cluster: some_spikes}`

        """
        if spike_ids is not None:
            if np.array_equal(spike_ids, self._spike_ids):
                return self
            assert np.all(np.in1d(spike_ids, self._spike_ids))
            spike_ids_s_rel = _index_of(spike_ids, self._spike_ids)
            array_s = self._array[spike_ids_s_rel]
            spike_clusters_s = self._spike_clusters[spike_ids_s_rel]
            return PerClusterData(spike_ids=spike_ids,
                                  array=array_s,
                                  spike_clusters=spike_clusters_s,
                                  )
        elif clusters is not None:
            assert set(clusters) <= set(self._cluster_ids)
            spc_s = {clu: self._spc[clu] for clu in clusters}
            arrays_s = {clu: self._arrays[clu] for clu in clusters}
            return PerClusterData(spc=spc_s, arrays=arrays_s)
        elif spc is not None:
            clusters = sorted(spc)
            assert set(clusters) <= set(self._cluster_ids)
            arrays_s = {}
            for cluster in clusters:
                spk_rel = _index_of(_as_array(spc[cluster]),
                                    _as_array(self._spc[cluster]))
                arrays_s[cluster] = _as_array(self._arrays[cluster])[spk_rel]
            return PerClusterData(spc=spc, arrays=arrays_s)

# -----------------------------------------------------------------------------
# PartialArray
# -----------------------------------------------------------------------------

class PartialArray(object):
    """Proxy to a view of an array, allowing selection along the first
    dimensions and fixing the trailing dimensions."""
    def __init__(self, arr, trailing_index=None):
        self._arr = arr
        self._trailing_index = _as_tuple(trailing_index)
        self.shape = _partial_shape(arr.shape, self._trailing_index)
        self.dtype = arr.dtype
        self.ndim = len(self.shape)

    def __getitem__(self, item):
        if self._trailing_index is None:
            return self._arr[item]
        else:
            item = _as_tuple(item)
            k = len(item)
            n = len(self._arr.shape)
            t = len(self._trailing_index)
            if k < (n - t):
                item += (slice(None, None, None),) * (n - k - t)
            item += self._trailing_index
            if len(item) != n:
                raise ValueError("The array selection is invalid: "
                                 "{0}".format(str(item)))
            return self._arr[item]

    def __len__(self):
        return self.shape[0]

class ConcatenatedArrays(object):
    """This object represents a concatenation of several memory-mapped
    arrays."""
    def __init__(self, arrs):
        assert isinstance(arrs, list)
        self.arrs = arrs
        self.offsets = np.concatenate([[0], np.cumsum([arr.shape[0]
                                                       for arr in arrs])],
                                      axis=0)
        self.dtype = arrs[0].dtype if arrs else None
        self.shape = (self.offsets[-1],) + arrs[0].shape[1:]

    def _get_recording(self, index):
        """Return the recording that contains a given index."""
        assert index >= 0
        recs = np.nonzero((index - self.offsets[:-1]) >= 0)[0]
        if len(recs) == 0:
            # If the index is greater than the total size,
            # return the last recording.
            return len(self.arrs) - 1
        # Return the last recording such that the index is greater than
        # its offset.
        return recs[-1]

    def __getitem__(self, item):
        # Get the start and stop indices of the requested item.
        start, stop = _start_stop(item)
        # Return the concatenation of all arrays.
        if start is None and stop is None:
            return np.concatenate(self.arrs, axis=0)
        if start is None:
            start = 0
        if stop is None:
            stop = self.offsets[-1]
        if stop < 0:
            stop = self.offsets[-1] + stop
        # Get the recording indices of the first and last item.
        rec_start = self._get_recording(start)
        rec_stop = self._get_recording(stop)
        assert 0 <= rec_start <= rec_stop < len(self.arrs)
        # Find the start and stop relative to the arrays.
        start_rel = start - self.offsets[rec_start]
        stop_rel = stop - self.offsets[rec_stop]
        # Single array case.
        if rec_start == rec_stop:
            # Apply the rest of the index.
            return _fill_index(self.arrs[rec_start][start_rel:stop_rel],
                               item)
        chunk_start = self.arrs[rec_start][start_rel:]
        chunk_stop = self.arrs[rec_stop][:stop_rel]
        # Concatenate all chunks.
        l = [chunk_start]
        if rec_stop - rec_start >= 2:
            warn("Loading a full virtual array: this might be slow "
                 "and something might be wrong.")
            l += [self.arrs[r][...] for r in range(rec_start + 1,
                                                   rec_stop)]
        l += [chunk_stop]
        # Apply the rest of the index.
        return _fill_index(np.concatenate(l, axis=0), item)

    def __len__(self):
        return self.shape[0]

class VirtualMappedArray(object):
    """A virtual mapped array that yields null arrays to any selection."""
    def __init__(self, shape, dtype, fill=0):
        self.shape = shape
        self.dtype = dtype
        self.ndim = len(self.shape)
        self._fill = fill

    def __getitem__(self, item):
        if isinstance(item, integer_types):
            return self._fill * np.ones(self.shape[1:], dtype=self.dtype)
        else:
            assert not isinstance(item, tuple)
            n = _len_index(item, max_len=self.shape[0])
            return self._fill * np.ones((n,) + self.shape[1:],
                                        dtype=self.dtype)

    def __len__(self):
        return self.shape[0]

def _concatenate_virtual_arrays(arrs):
    """Return a virtual concatenate of several NumPy arrays."""
    n = len(arrs)
    if n == 0:
        return None
    elif n == 1:
        return arrs[0]
    return ConcatenatedArrays(arrs)


text:
@implementation MainMenuLayer

// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];

	// 'layer' is an autorelease object.
	MainMenuLayer *layer = [MainMenuLayer node];

	// add layer as a child to scene
	[scene addChild: layer];

	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super's" return value
	if( (self=[super init]) ) {

		// create and initialize a Label
		CCLabelTTF *label = [CCLabelTTF labelWithString:@"Ship Attack!" fontName:@"Marker Felt" fontSize:64];

		// ask director for the window size
		CGSize size = [[CCDirector sharedDirector] winSize];

		// position the label on the center of the screen
		label.position =  ccp( size.width /2, size.height/2 + 60 );

		// add the label as a child to this Layer
		[self addChild: label];

		// Default font size will be 28 points.
		[CCMenuItemFont setFontSize:28];

		// Start Game Menu Item using blocks
		CCMenuItem *itemStartGame = [CCMenuItemFont itemWithString:@"Start Game" block:^(id sender) {
			[[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:0.5 scene:[GameplayScene node]]];
		}];

		CCMenu *menu = [CCMenu menuWithItems:itemStartGame, nil];

		[menu alignItemsHorizontallyWithPadding:20];
		[menu setPosition:ccp( size.width/2, size.height/2 - 30)];

		// Add the menu to the layer
		[self addChild:menu];

	}
	return self;
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)

	// don't forget to call "super dealloc"
	[super dealloc];
}
@end


text:
      <button mat-button [matMenuTriggerFor]="menu">
        <mat-icon>palette</mat-icon>
        <mat-icon>arrow_drop_down</mat-icon>
      </button>
      <mat-menu #menu="matMenu">
        <button mat-menu-item *ngFor="let theme of themes" color="primary" (click)="changeTheme(theme, darkTheme)">
          <mat-icon *ngIf="theme.value === currentTheme.value" class="theme-item-color" [ngStyle]="{ 'background-color': theme.primary }">
            check_circle
          </mat-icon>

          {{ theme.name }}
        </button>
      </mat-menu>

      <mat-slide-toggle [(ngModel)]="darkTheme" (change)="changeTheme(currentTheme, darkTheme)">Dark</mat-slide-toggle>

        It seems that it's your first time here, welcome! Start by filling in some information about your self, or import your profile from
        linkedin. Save the page when you're happy with the result :)

      <app-summary
        [picture]="resume.pictureUrl"
        [name]="resume.name"
        [description]="resume.summary"
        [title]="resume.title"
        [phone]="resume.phone"
        [email]="resume.email"
        [socials]="resume.social"
        [skills]="resume.skills"
      >
      </app-summary>

      <app-experience [positions]="resume.positions" *ngIf="isPosistionsVisible()"> </app-experience>

      <app-education [educations]="resume.educations" *ngIf="isEducationsVisible()"> </app-education>

      <app-project [projects]="resume.projects" [skills]="resume.skills" *ngIf="isProjectsVisible()"> </app-project>

    Generated with resume generator


text:
namespace net {

class URLRequestContext;

// Sets the MessageLoop for OCSP to the current message loop.
// This should be called before EnsureOCSPInit() if you want to
// control the message loop for OCSP.
void SetMessageLoopForOCSP();

// Initializes OCSP handlers for NSS.  This must be called before any
// certificate verification functions.  This function is thread-safe, and OCSP
// handlers will only ever be initialized once.  ShutdownOCSP() must be called
// on shutdown.
void EnsureOCSPInit();

// This should be called once on shutdown to stop issuing URLRequests for OCSP.
void ShutdownOCSP();

// Set URLRequestContext for OCSP handlers.
void SetURLRequestContextForOCSP(URLRequestContext* request_context);
URLRequestContext* GetURLRequestContextForOCSP();

}  // namespace net

#endif  // NET_OCSP_NSS_OCSP_H_


text:
using System;
using Azure.Core;

namespace Azure.Communication.CallingServer
{
    /// <summary> The MediaStreamingConfiguration. </summary>
    internal partial class MediaStreamingOptionsInternal
    {
        /// <summary> Initializes a new instance of MediaStreamingOptionsInternal. </summary>
        /// <param name="transportUrl"> Transport URL for media streaming. </param>
        /// <param name="transportType"> The type of transport to be used for media streaming, eg. Websocket. </param>
        /// <param name="contentType"> Content type to stream, eg. audio, audio/video. </param>
        /// <param name="audioChannelType"> Audio channel type to stream, eg. unmixed audio, mixed audio. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="transportUrl"/> is null. </exception>
        public MediaStreamingOptionsInternal(string transportUrl, MediaStreamingTransport transportType, MediaStreamingContent contentType, MediaStreamingAudioChannel audioChannelType)
        {
            Argument.AssertNotNull(transportUrl, nameof(transportUrl));

            TransportUrl = transportUrl;
            TransportType = transportType;
            ContentType = contentType;
            AudioChannelType = audioChannelType;
        }

        /// <summary> Transport URL for media streaming. </summary>
        public string TransportUrl { get; }
        /// <summary> The type of transport to be used for media streaming, eg. Websocket. </summary>
        public MediaStreamingTransport TransportType { get; }
        /// <summary> Content type to stream, eg. audio, audio/video. </summary>
        public MediaStreamingContent ContentType { get; }
        /// <summary> Audio channel type to stream, eg. unmixed audio, mixed audio. </summary>
        public MediaStreamingAudioChannel AudioChannelType { get; }
    }
}


text:
package org.wso2.carbon.device.mgt.core.app.mgt;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Implements Application Manager interface
 */
public class ApplicationManagerProviderServiceImpl implements ApplicationManagementProviderService {

    private DeviceDAO deviceDAO;
    private ApplicationDAO applicationDAO;
    private ApplicationMappingDAO applicationMappingDAO;

    private static final String GET_APP_LIST_URL = "store/apis/assets/mobileapp?domain=carbon.super&page=1";
    private static final Log log = LogFactory.getLog(ApplicationManagerProviderServiceImpl.class);

    public ApplicationManagerProviderServiceImpl(AppManagementConfig appManagementConfig) {
        this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
        this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO();
        this.applicationMappingDAO = DeviceManagementDAOFactory.getApplicationMappingDAO();
    }

    ApplicationManagerProviderServiceImpl() {
        this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
        this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO();
        this.applicationMappingDAO = DeviceManagementDAOFactory.getApplicationMappingDAO();
    }

    @Override
    public Application[] getApplications(String domain, int pageNumber, int size)
            throws ApplicationManagementException {
        return new Application[0];
    }

    @Override
    public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
                                        String status) throws ApplicationManagementException {

    }

    @Override
    public String getApplicationStatus(DeviceIdentifier deviceId,
                                       Application application) throws ApplicationManagementException {
        return null;
    }

    @Override
    public Activity installApplicationForDevices(Operation operation, List<DeviceIdentifier> deviceIds)
            throws ApplicationManagementException {
        try {
            //TODO: Fix this properly later adding device type to be passed in when the task manage executes "addOperations()"
            String type = null;
            if (deviceIds.size() > 0) {
                type = deviceIds.get(0).getType().toLowerCase();
            }
            Activity activity = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
                    addOperation(type, operation, deviceIds);
            DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().notifyOperationToDevices
                    (operation, deviceIds);
            return activity;
        } catch (OperationManagementException e) {
            throw new ApplicationManagementException("Error in add operation at app installation", e);
        } catch (DeviceManagementException e) {
            throw new ApplicationManagementException("Error in notify operation at app installation", e);
        } catch (InvalidDeviceException e) {
            throw new ApplicationManagementException("Invalid DeviceIdentifiers found.", e);
        }
    }

    @Override
    public Activity installApplicationForUsers(Operation operation, List<String> userNameList)
            throws ApplicationManagementException {

        String userName = null;
        try {
            List<Device> deviceList;
            List<DeviceIdentifier> deviceIdentifierList = new ArrayList<>();
            DeviceIdentifier deviceIdentifier;

            for (String user : userNameList) {
                userName = user;
                deviceList = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevicesOfUser
                        (user);
                for (Device device : deviceList) {
                    deviceIdentifier = new DeviceIdentifier();
                    deviceIdentifier.setId(Integer.toString(device.getId()));
                    deviceIdentifier.setType(device.getType());

                    deviceIdentifierList.add(deviceIdentifier);
                }
            }
            //TODO: Fix this properly later adding device type to be passed in when the task manage executes "addOperations()"
            String type = null;
            if (deviceIdentifierList.size() > 0) {
                type = deviceIdentifierList.get(0).getType();
            }

            return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider()
                    .addOperation(type, operation, deviceIdentifierList);
        } catch (InvalidDeviceException e) {
            throw new ApplicationManagementException("Invalid DeviceIdentifiers found.", e);
        } catch (DeviceManagementException e) {
            throw new ApplicationManagementException("Error in get devices for user: " + userName +
                    " in app installation", e);

        } catch (OperationManagementException e) {
            throw new ApplicationManagementException("Error in add operation at app installation", e);

        }
    }

    @Override
    public Activity installApplicationForUserRoles(Operation operation, List<String> userRoleList)
            throws ApplicationManagementException {

        String userRole = null;
        try {
            List<Device> deviceList;
            List<DeviceIdentifier> deviceIdentifierList = new ArrayList<>();
            DeviceIdentifier deviceIdentifier;

            for (String role : userRoleList) {
                userRole = role;
                deviceList = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider()
                        .getAllDevicesOfRole(userRole);
                for (Device device : deviceList) {
                    deviceIdentifier = new DeviceIdentifier();
                    deviceIdentifier.setId(Integer.toString(device.getId()));
                    deviceIdentifier.setType(device.getType());

                    deviceIdentifierList.add(deviceIdentifier);
                }
            }
            //TODO: Fix this properly later adding device type to be passed in when the task manage executes "addOperations()"
            String type = null;
            if (deviceIdentifierList.size() > 0) {
                type = deviceIdentifierList.get(0).getType();
            }
            return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().addOperation(type, operation,
                    deviceIdentifierList);
        } catch (InvalidDeviceException e) {
            throw new ApplicationManagementException("Invalid DeviceIdentifiers found.", e);
        } catch (DeviceManagementException e) {
            throw new ApplicationManagementException("Error in get devices for user role " + userRole +
                    " in app installation", e);

        } catch (OperationManagementException e) {
            throw new ApplicationManagementException("Error in add operation at app installation", e);

        }
    }

    @Override
    public void updateApplicationListInstalledInDevice(
            DeviceIdentifier deviceIdentifier,
            List<Application> applications) throws ApplicationManagementException {
        List<Application> installedAppList = getApplicationListForDevice(deviceIdentifier);
        try {
            int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            DeviceManagementDAOFactory.beginTransaction();
            Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);

            if (log.isDebugEnabled()) {
                log.debug("Device:" + device.getId() + ":identifier:" + deviceIdentifier.getId());
            }

            if (log.isDebugEnabled()) {
                log.debug("num of apps installed:" + installedAppList.size());
            }
            List<Application> appsToAdd = new ArrayList<>();
            List<Integer> appIdsToRemove = new ArrayList<>(installedAppList.size());

            for (Application installedApp : installedAppList) {
                if (!applications.contains(installedApp)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Remove app Id:" + installedApp.getId());
                    }
                    appIdsToRemove.add(installedApp.getId());
                }
            }
            applicationMappingDAO.removeApplicationMapping(device.getId(), appIdsToRemove, tenantId);
            Application installedApp;
            List<Integer> applicationIds = new ArrayList<>();

            for (Application application : applications) {
                if (!installedAppList.contains(application)) {
                    installedApp = applicationDAO.getApplication(application.getApplicationIdentifier(),
                            application.getVersion(), tenantId);
                    if (installedApp == null) {
                        appsToAdd.add(application);
                    } else {
                        applicationIds.add(installedApp.getId());
                    }
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("num of apps add:" + appsToAdd.size());
            }
            applicationIds.addAll(applicationDAO.addApplications(appsToAdd, tenantId));

            if (log.isDebugEnabled()) {
                log.debug("num of app Ids:" + applicationIds.size());
            }
            applicationMappingDAO.addApplicationMappings(device.getId(), applicationIds, tenantId);

            if (log.isDebugEnabled()) {
                log.debug("num of remove app Ids:" + appIdsToRemove.size());
            }

            DeviceManagementDAOFactory.commitTransaction();
        } catch (DeviceManagementDAOException e) {
            DeviceManagementDAOFactory.rollbackTransaction();
            throw new ApplicationManagementException("Error occurred saving application list to the device", e);
        } catch (TransactionManagementException e) {
            throw new ApplicationManagementException("Error occurred while initializing transaction", e);
        } finally {
            DeviceManagementDAOFactory.closeConnection();
        }
    }

    @Override
    public List<Application> getApplicationListForDevice(
            DeviceIdentifier deviceId) throws ApplicationManagementException {
        Device device;
        try {
            int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            DeviceManagementDAOFactory.openConnection();
            device = deviceDAO.getDevice(deviceId, tenantId);
            if (device == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No device is found upon the device identifier '" + deviceId.getId() +
                            "' and type '" + deviceId.getType() + "'. Therefore returning null");
                }
                return null;
            }
            return applicationDAO.getInstalledApplications(device.getId());
        } catch (DeviceManagementDAOException e) {
            throw new ApplicationManagementException("Error occurred while fetching the Application List of '" +
                    deviceId.getType() + "' device carrying the identifier'" + deviceId.getId(), e);
        } catch (SQLException e) {
            throw new ApplicationManagementException("Error occurred while opening a connection to the data source", e);
        } finally {
            DeviceManagementDAOFactory.closeConnection();
        }
    }

}


text:
bool DynamicExclusionListEntry::is_match(DynamicExclusionMatchQuery &q) const {
	return std::abs(q.mz - mz) <= q.mz_tolerance;
}


text:
Ruby Gem to make API requests to the [Spark Cloud API](http://docs.spark.io/#/api)

## Obtaining a Spark Core Access Token and Core ID

Assuming at this point you've followed the Spark Core's [Getting Started](http://docs.spark.io/#/start) guides and connected your Core with the Spark Cloud.

Head over to the [Spark Build IDE](https://www.spark.io/build). In the Settings tab you can get your Access Token, and you can fetch your Device ID from the Cores tab. You'll need these both to authenticate your API calls, and the Device ID to direct them.

## Installation

To use this gem, install it with `gem install ruby_spark` or add this line to your Gemfile:

```ruby
gem 'ruby_spark'
```

and install it with `bundle install`

## Usage

Load:

```ruby
require 'ruby_spark'
```

Configure:

```ruby
# config/initializers/ruby_spark.rb

RubySpark.configuration do |config|
  config.access_token = "spark_api_access_token"
  config.timeout      = 10.seconds # defaults to 30 seconds
end
```

### Core API

To instantiate a Core, you need to pass it's `device_id`. If you have your `access_token` setup ahead of time using the `config.access_token` then the second argument is optional.

```ruby
core = RubySpark::Core.new("core_device_id")
# or
core = RubySpark::Core.new("core_device_id", "spark_api_access_token")
```

Fire away:

```ruby
core.info                        #=> { info hash }

core.variable("something")       #=> number (for now)
core.function("foo", "argument") #=> number
```

### Tinker API

The tinker class provides `digital_read`, `digital_write`, `analog_read`, and `analog_write` for the default spark core code. This is the same interface as the tinker app.

```ruby
core = RubySpark::Tinker.new("core_device_id")
# or
core = RubySpark::Tinker.new("core_device_id", "spark_api_access_token")
```

Fire away:

```ruby
core.info                      #=> { info hash }

core.digital_write(3, "HIGH")  #=> true or false
core.digital_read(5)           #=> "HIGH" or "LOW"
```

## Contributing

Happily accepting contributions. To contribute, fork, develop, add some specs, and pull request.

Note about the specs. All API requests make use of the [VCR](https://github.com/vcr/vcr) gem. To contribute without exposing your Access Token and Core ID, run the specs with your real authentication, and then find-and-replace your Access Token and Core ID with fake values in the spec and any VCR cassettes.


text:
package com.microsoft.bingads.api.test.entities.negative_site.ad_group.sites;

import com.microsoft.bingads.api.test.entities.Util;
import com.microsoft.bingads.bulk.entities.BulkAdGroupNegativeSite;
import com.microsoft.bingads.bulk.entities.BulkAdGroupNegativeSites;
import com.microsoft.bingads.bulk.entities.BulkEntity;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;

public class BulkAdGroupNegativeSitesReadWriteTest {

    @Test
    public void readBulkAdGroupNegativeSitesWithDifferentAdGroupIds() {
        ArrayList<BulkEntity> negativeSites = new ArrayList<BulkEntity>();

        BulkAdGroupNegativeSite site = new BulkAdGroupNegativeSite();
        site.setAdGroupId(1001L);
        site.setWebsite("http://microsoft.com");
        negativeSites.add(site);

        site = new BulkAdGroupNegativeSite();
        site.setAdGroupId(1002L);
        site.setWebsite("http://google.com");
        negativeSites.add(site);

        ArrayList<BulkEntity> readBack = Util.WriteAndReadBack(negativeSites);
        Assert.assertEquals(2, readBack.size());

        BulkAdGroupNegativeSites a = (BulkAdGroupNegativeSites) readBack.get(0);
        Assert.assertEquals(1001L, a.getAdGroupNegativeSites().getAdGroupId().longValue());
        Assert.assertEquals(
                "http://microsoft.com",
                a.getNegativeSites().get(0).getWebsite()
        );

        BulkAdGroupNegativeSites b = (BulkAdGroupNegativeSites) readBack.get(1);
        Assert.assertEquals(1002L, b.getAdGroupNegativeSites().getAdGroupId().longValue());
        Assert.assertEquals(
                "http://google.com",
                b.getNegativeSites().get(0).getWebsite()
        );
    }
}


text:
class Blotter
  BLOTTER_KEY = "blotter"

  def self.set(opts)
    $redis.with do |conn|
      conn.set(BLOTTER_KEY, {
        icon: 'fa-exclamation-circle'
      }.merge(opts).compact.to_json)
    end
  end

  def self.get
    JSON.parse($redis.with {|conn| conn.get(BLOTTER_KEY) })
  rescue
    nil
  end

  def self.clear
    $redis.with {|conn| conn.del(BLOTTER_KEY) }
  end
end


text:
Switching servos with Arduino
=============================

cmd_runner contains a simple Arduino program that
listens to commands sent over the serial/USB
connection. The main command is 'reset' which will
initate a reset procedure by switcing a servo.
See the source of cmd_runner for details.

Building
========

Install the Arduino IDE on Linux via

$ apt-get intall arduino

and then run 'arduino' from the command line.
This will open the Arduino IDE where you can open the
cmd_runner program.

Attach the Arduino board and upload the program.
See https://www.arduino.cc/ for more documentation.

Downloading and Installing Libraries
=====================

The Servo shield requires the [Adafruit PWM Servo Driver Library](https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library)

Download the release from GitHub, extract it and rename the folder to
Adafruit_PWMServoDriver.  Then, place it in the libraries folder of your Arduino IDE
installation. Restart the IDE.