text:
package schoperation.schopcraft.util;

import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

public class ProximityDetect {

	/*
	 * This is called whenever the mod wants to detect a block near the player. narf
	 * These methods should only be called on the server unless you like crashes.
	 */

	/* =========================================================
	 *           SAME Y-LEVEL AS PLAYER
	 * ==========================================================
	 */

	// Returns true if the block is right next to the player, horizontally/diagonally.
	public static boolean isBlockNextToPlayer(int posX, int posY, int posZ, Block block, Entity player) {

		// Basic variables.
		World world = player.world;
		boolean result = false;
		int x = 0;
		int z = 0;

		// Just iterate through all of the possible positions around the player! CODING!
		// I've redone this four times already, and this one is more straightforward and NOT AS tedious.
		for (int pos = 0; pos < 9; pos++) {

			// These are the block positions; kek is the one being looped through.
			Block kek = world.getBlockState(new BlockPos(posX+x,posY,posZ+z)).getBlock();

			if (x == 0 && z == 0) { z--; }
			else if (x == 0 && z == -1) { x++; }
			else if (x == 1 && z == -1) { z++; }
			else if (x == 1 && z == 0) { z++; }
			else if (x == 1 && z == 1) { x--; }
			else if (x == 0 && z == 1) { x--; }
			else if (x == -1 && z == 1) { z--; }
			else if (x == -1 && z == 0) { z--; }
			else if (x == -1 && z == -1) { x++; }

			// See if that block is the specified block.
			if (kek == block) {

				result = true;
				pos = 9;
			}
		}

		return result;
	}

	// Returns true if the block is within two blocks of the player, horizontally.
	public static boolean isBlockNearPlayer2(int posX, int posY, int posZ, Block block, Entity player, boolean throughBlock) {

		// Basic variables.
		World world = player.world;
		Block air = Block.getBlockFromName("minecraft:air");
		boolean result = false;
		boolean noWall = true;
		int x = 0;
		int z = 0;

		for (int pos = 0; pos < 17; pos++) {

			// These are the block positions; kek is the one being looped through; the others are where a wall could be, blocking heat.
			Block kek = world.getBlockState(new BlockPos(posX+x,posY,posZ+z)).getBlock();
			Block blockingNorth = world.getBlockState(new BlockPos(posX+x,posY,posZ+z+1)).getBlock();
			Block blockingEast = world.getBlockState(new BlockPos(posX+x-1,posY,posZ+z)).getBlock();
			Block blockingSouth = world.getBlockState(new BlockPos(posX+x,posY,posZ+z-1)).getBlock();
			Block blockingWest = world.getBlockState(new BlockPos(posX+x+1,posY,posZ+z)).getBlock();
			Block blockingNortheast = world.getBlockState(new BlockPos(posX+x-1,posY,posZ+z+1)).getBlock();
			Block blockingSoutheast = world.getBlockState(new BlockPos(posX+x-1,posY,posZ+z-1)).getBlock();
			Block blockingSouthwest = world.getBlockState(new BlockPos(posX+x+1,posY,posZ+z-1)).getBlock();
			Block blockingNorthwest = world.getBlockState(new BlockPos(posX+x+1,posY,posZ+z+1)).getBlock();

			if (x == 0 && z == 0) { z = -2; }
			else if (x == 0 && z == -2) { x++; if (blockingNorth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 1 && z == -2) { x++; if (blockingNorth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == -2) { z++; if (blockingNortheast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == -1) { z++; if (blockingEast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 0) { z++; if (blockingEast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 1) { z++; if (blockingEast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 2) { x--; if (blockingSoutheast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 1 && z == 2) { x--; if (blockingSouth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 0 && z == 2) { x--; if (blockingSouth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -1 && z == 2) { x--; if (blockingSouth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 2) { z--; if (blockingSouthwest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 1) { z--; if (blockingWest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 0) { z--; if (blockingWest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == -1) { z--; if (blockingWest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == -2) { x++; if (blockingNorthwest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -1 && z == -2) { x++; if (blockingNorth != air && !throughBlock) { noWall = false; } else { noWall = true; } }

			// See if that block is the specified block.
			if (kek == block && noWall) {

				result = true;
				pos = 17;
			}
		}

		return result;
	}

	/* =============================================
	 *              UNDER THE PLAYER
	 * ============================================
	 */

	// Returns true if the block is right UNDER the player, horizontally/diagonally. One block radius.
	public static boolean isBlockUnderPlayer(int posX, int posY, int posZ, Block block, Entity player) {

		// Basic variables.
		World world = player.world;
		boolean result = false;
		int x = 0;
		int z = 0;

		// Just iterate through all of the possible positions around the player! CODING!
		// I've redone this four times already, and this one is more straightforward and NOT AS tedious.
		for (int pos = 0; pos < 9; pos++) {

			// These are the block positions; kek is the one being looped through.
			Block kek = world.getBlockState(new BlockPos(posX+x,posY-1,posZ+z)).getBlock();

			if (x == 0 && z == 0) { z--; }
			else if (x == 0 && z == -1) { x++; }
			else if (x == 1 && z == -1) { z++; }
			else if (x == 1 && z == 0) { z++; }
			else if (x == 1 && z == 1) { x--; }
			else if (x == 0 && z == 1) { x--; }
			else if (x == -1 && z == 1) { z--; }
			else if (x == -1 && z == 0) { z--; }
			else if (x == -1 && z == -1) { x++; }

			// See if that block is the specified block.
			if (kek == block) {

				result = true;
				pos = 9;
			}
		}

		return result;
	}

	// Returns true if the block is within two blocks of the player, horizontally.
	public static boolean isBlockUnderPlayer2(int posX, int posY, int posZ, Block block, Entity player, boolean throughBlock) {

		// Basic variables.
		World world = player.world;
		Block air = Block.getBlockFromName("minecraft:air");
		boolean result = false;
		boolean noWall = true;
		int x = 0;
		int z = 0;

		for (int pos = 0; pos < 17; pos++) {

			// These are the block positions; kek is the one being looped through; the others are where a wall could be, blocking heat.
			Block kek = world.getBlockState(new BlockPos(posX+x,posY-1,posZ+z)).getBlock();
			Block blockingNorth = world.getBlockState(new BlockPos(posX+x,posY,posZ+z+1)).getBlock();
			Block blockingEast = world.getBlockState(new BlockPos(posX+x-1,posY,posZ+z)).getBlock();
			Block blockingSouth = world.getBlockState(new BlockPos(posX+x,posY,posZ+z-1)).getBlock();
			Block blockingWest = world.getBlockState(new BlockPos(posX+x+1,posY,posZ+z)).getBlock();
			Block blockingNortheast = world.getBlockState(new BlockPos(posX+x-1,posY,posZ+z+1)).getBlock();
			Block blockingSoutheast = world.getBlockState(new BlockPos(posX+x-1,posY,posZ+z-1)).getBlock();
			Block blockingSouthwest = world.getBlockState(new BlockPos(posX+x+1,posY,posZ+z-1)).getBlock();
			Block blockingNorthwest = world.getBlockState(new BlockPos(posX+x+1,posY,posZ+z+1)).getBlock();
			Block blockingNorthDown = world.getBlockState(new BlockPos(posX+x,posY-1,posZ+z+1)).getBlock();
			Block blockingEastDown = world.getBlockState(new BlockPos(posX+x-1,posY-1,posZ+z)).getBlock();
			Block blockingSouthDown = world.getBlockState(new BlockPos(posX+x,posY-1,posZ+z-1)).getBlock();
			Block blockingWestDown = world.getBlockState(new BlockPos(posX+x+1,posY-1,posZ+z)).getBlock();
			Block blockingNortheastDown = world.getBlockState(new BlockPos(posX+x-1,posY-1,posZ+z+1)).getBlock();
			Block blockingSoutheastDown = world.getBlockState(new BlockPos(posX+x-1,posY-1,posZ+z-1)).getBlock();
			Block blockingSouthwestDown = world.getBlockState(new BlockPos(posX+x+1,posY-1,posZ+z-1)).getBlock();
			Block blockingNorthwestDown = world.getBlockState(new BlockPos(posX+x+1,posY-1,posZ+z+1)).getBlock();

			if (x == 0 && z == 0) { z = -2; }
			else if (x == 0 && z == -2) { x++; if (blockingNorth != air && !throughBlock && blockingNorthDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == 1 && z == -2) { x++; if (blockingNorth != air && !throughBlock && blockingNorthDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == -2) { z++; if (blockingNortheast != air && !throughBlock && blockingNortheastDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == -1) { z++; if (blockingEast != air && !throughBlock && blockingEastDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 0) { z++; if (blockingEast != air && !throughBlock && blockingEastDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 1) { z++; if (blockingEast != air && !throughBlock && blockingEastDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 2) { x--; if (blockingSoutheast != air && !throughBlock && blockingSoutheastDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == 1 && z == 2) { x--; if (blockingSouth != air && !throughBlock && blockingSouthDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == 0 && z == 2) { x--; if (blockingSouth != air && !throughBlock && blockingSouthDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == -1 && z == 2) { x--; if (blockingSouth != air && !throughBlock && blockingSouthDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 2) { z--; if (blockingSouthwest != air && !throughBlock && blockingSouthwestDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 1) { z--; if (blockingWest != air && !throughBlock && blockingWestDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 0) { z--; if (blockingWest != air && !throughBlock && blockingWestDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == -1) { z--; if (blockingWest != air && !throughBlock && blockingWestDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == -2) { x++; if (blockingNorthwest != air && !throughBlock && blockingNorthwestDown != air) { noWall = false; } else { noWall = true; } }
			else if (x == -1 && z == -2) { x++; if (blockingNorth != air && !throughBlock && blockingNorthDown != air) { noWall = false; } else { noWall = true; } }

			// See if that block is the specified block.
			if (kek == block && noWall) {

				result = true;
				pos = 17;
			}
		}

		return result;
	}

	/* =============================================
	 *         SAME Y-LEVEL AS PLAYER'S FACE
	 * ============================================
	 */

	// Returns true if the block is right at the player's face, horizontally/diagonally. One block radius.
	public static boolean isBlockAtPlayerFace(int posX, int posY, int posZ, Block block, Entity player) {

		// Basic variables
		World world = player.world;
		boolean result = false;
		int x = 0;
		int z = 0;

		// Just iterate through all of the possible positions around the player! CODING!
		// I've redone this four times already, and this one is more straightforward and NOT AS tedious.
		for (int pos = 0; pos < 9; pos++) {

			// These are the block positions; kek is the one being looped through
			Block kek = world.getBlockState(new BlockPos(posX+x,posY+1,posZ+z)).getBlock();

			if (x == 0 && z == 0) { z--; }
			else if (x == 0 && z == -1) { x++; }
			else if (x == 1 && z == -1) { z++; }
			else if (x == 1 && z == 0) { z++; }
			else if (x == 1 && z == 1) { x--; }
			else if (x == 0 && z == 1) { x--; }
			else if (x == -1 && z == 1) { z--; }
			else if (x == -1 && z == 0) { z--; }
			else if (x == -1 && z == -1) { x++; }

			// See if that block is the specified block
			if (kek == block) {

				result = true;
				pos = 9;
			}
		}

		return result;
	}

	// Returns true if the block is right at the player's face, horizontally/diagonally. Two block radius.
	public static boolean isBlockAtPlayerFace2(int posX, int posY, int posZ, Block block, Entity player, boolean throughBlock) {

		// Basic variables
		World world = player.world;
		Block air = Block.getBlockFromName("minecraft:air");
		boolean result = false;
		boolean noWall = true;
		int x = 0;
		int z = 0;

		for (int pos = 0; pos < 17; pos++) {

			// These are the block positions; kek is the one being looped through; the others are where a wall could be, blocking heat.
			Block kek = world.getBlockState(new BlockPos(posX+x,posY+1,posZ+z)).getBlock();
			Block blockingNorth = world.getBlockState(new BlockPos(posX+x,posY+1,posZ+z+1)).getBlock();
			Block blockingEast = world.getBlockState(new BlockPos(posX+x-1,posY+1,posZ+z)).getBlock();
			Block blockingSouth = world.getBlockState(new BlockPos(posX+x,posY+1,posZ+z-1)).getBlock();
			Block blockingWest = world.getBlockState(new BlockPos(posX+x+1,posY+1,posZ+z)).getBlock();
			Block blockingNortheast = world.getBlockState(new BlockPos(posX+x-1,posY+1,posZ+z+1)).getBlock();
			Block blockingSoutheast = world.getBlockState(new BlockPos(posX+x-1,posY+1,posZ+z-1)).getBlock();
			Block blockingSouthwest = world.getBlockState(new BlockPos(posX+x+1,posY+1,posZ+z-1)).getBlock();
			Block blockingNorthwest = world.getBlockState(new BlockPos(posX+x+1,posY+1,posZ+z+1)).getBlock();

			if (x == 0 && z == 0) { z = -2; }
			else if (x == 0 && z == -2) { x++; if (blockingNorth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 1 && z == -2) { x++; if (blockingNorth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == -2) { z++; if (blockingNortheast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == -1) { z++; if (blockingEast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 0) { z++; if (blockingEast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 1) { z++; if (blockingEast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 2 && z == 2) { x--; if (blockingSoutheast != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 1 && z == 2) { x--; if (blockingSouth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == 0 && z == 2) { x--; if (blockingSouth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -1 && z == 2) { x--; if (blockingSouth != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 2) { z--; if (blockingSouthwest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 1) { z--; if (blockingWest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == 0) { z--; if (blockingWest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == -1) { z--; if (blockingWest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -2 && z == -2) { x++; if (blockingNorthwest != air && !throughBlock) { noWall = false; } else { noWall = true; } }
			else if (x == -1 && z == -2) { x++; if (blockingNorth != air && !throughBlock) { noWall = false; } else { noWall = true; } }

			// See if that block is the specified block.
			if (kek == block && noWall) {

				result = true;
				pos = 17;
			}
		}

		return result;
	}
}


text:
{% load cms_tags %}

{% block one %}
	{% placeholder "one" %}
{% endblock %}

{% block two %}
	{% placeholder "two" %}
{% endblock %}

{% block three %}
	{% placeholder "three" %}
{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
//
//      Copyright (C) 2012-2014 DataStax Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

using Cassandra.IntegrationTests.TestBase;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Cassandra.Serialization;

namespace Cassandra.IntegrationTests.Core
{
    [TestFixture, Category("long")]
    public class LargeDataTests : TestGlobals
    {
        private const int Key = 0;
        private const string KeyspaceNameDefault = "largedatatests";
        ISession _session = null;

        [SetUp]
        public void SetupFixture()
        {
            _session = TestClusterManager.GetTestCluster(1).Session;
        }

        /// <summary>
        ///  Test a wide row
        /// </summary>
        [Test]
        public void WideRows()
        {
            string uniqueTableName = "wide_rows_" + Randomm.RandomAlphaNum(16);
            TestWideRows(_session, uniqueTableName);
        }

        /// <summary>
        ///  Test a batch that writes a row of size 10,000
        /// </summary>
        [Test]
        public void WideBatchRows()
        {
            string uniqueTableName = "wide_batch_rows" + Randomm.RandomAlphaNum(16);
            TestWideBatchRows(_session, uniqueTableName);
        }

        /// <summary>
        ///  Test a wide row consisting of a ByteBuffer
        /// </summary>
        [Test]
        public void WideByteRows()
        {
            string uniqueTableName = "wide_byte_rows" + Randomm.RandomAlphaNum(16);
            TestByteRows(_session, uniqueTableName);
        }

        /// <summary>
        ///  Test a row with a single extra large text value
        /// </summary>
        [Test]
        public void LargeText()
        {
            string uniqueTableName = "large_text_" + Randomm.RandomAlphaNum(16);
            TestLargeText(_session, uniqueTableName);
        }

        /// <summary>
        ///  Creates a table with 330 columns
        /// </summary>
        [Test]
        public void WideTable()
        {
            string uniqueTableName = "wide_table" + Randomm.RandomAlphaNum(16);
            TestWideTable(_session, uniqueTableName);
        }

        /// <summary>
        ///  Test list with a single large text value
        /// </summary>
        [Test]
        public void LargeListText()
        {
            string uniqueTableName = GetUniqueTableName();
            CreateTable(_session, uniqueTableName, "list<text>");

            string b = new string('8', UInt16.MaxValue);
            _session.Execute(string.Format("INSERT INTO {0}(k,i) VALUES({1},['{2}'])", uniqueTableName, Key, b), ConsistencyLevel.Quorum);

            using (var rs = _session.Execute(string.Format("SELECT * FROM {0} WHERE k = {1}", uniqueTableName, Key.ToString()), ConsistencyLevel.Quorum))
            {
                Row row = rs.GetRows().FirstOrDefault();
                Assert.True(b.Equals(((List<string>)row["i"])[0]));
            }
        }

        /// <summary>
        ///  Test set with max allowed value size
        /// </summary>
        [Test]
        public void Set_Val_Max()
        {
            string uniqueTableName = GetUniqueTableName();
            CreateTable(_session, uniqueTableName, "set<text>");

            // according to specs it should accept  full UInt16.MaxValue, but for some reason it throws "The sum of all clustering columns is too long"
            string setVal = new string('a', UInt16.MaxValue - 9);
            _session.Execute(string.Format("INSERT INTO {0}(k,i) VALUES({1},{{'{2}'}})", uniqueTableName, Key, setVal, ConsistencyLevel.Quorum));

            using (var rs = _session.Execute(string.Format("SELECT * FROM {0} WHERE k = {1}", uniqueTableName, Key), ConsistencyLevel.Quorum))
            {
                Row row = rs.GetRows().FirstOrDefault();
                Assert.AreEqual(setVal, ((List<string>)row["i"]).First());
            }
        }

        /// <summary>
        ///  Test set with max allowed value size plus one
        /// </summary>
        [Test]
        public void Set_Val_MaxPlusOne()
        {
            string uniqueTableName = GetUniqueTableName();
            CreateTable(_session, uniqueTableName, "set<text>");

            // given MAX = 65535
            // for C* 2.1.x, set string value max = MAX - 8
            // for C* 2.0.x, set string value max = MAX - 6
            string setVal = new string('a', UInt16.MaxValue - 6);
            try
            {
                _session.Execute(string.Format("INSERT INTO {0}(k,i) VALUES({1},{{'{2}'}})", uniqueTableName, Key, setVal, ConsistencyLevel.Quorum));
                Assert.Fail("Expected exception was not thrown!");
            }
            catch (Cassandra.InvalidQueryException e)
            {
                string expectedErrMsg = "The sum of all clustering columns is too long";
                Assert.True(e.Message.Contains(expectedErrMsg), "Exception message {0} did not contain expected error message {1}.", e.Message, expectedErrMsg);
            }
        }

        /// <summary>
        ///  Test map with max allowed key and value size
        /// </summary>
        [Test]
        public void Map_Key_Max_Val_Max()
        {
            string uniqueTableName = GetUniqueTableName();
            CreateTable(_session, uniqueTableName, "map<text, text>");

            // given MAX = 65535, map string key max = MAX - 9 and map string value max = MAX
            string mapKey = new string('a', UInt16.MaxValue - 9);
            string mapVal = new string('b', UInt16.MaxValue);
            _session.Execute(string.Format("INSERT INTO {0}(k,i) VALUES({1},{{ '{2}' : '{3}' }})", uniqueTableName, Key, mapKey, mapVal), ConsistencyLevel.Quorum);

            using (var rs = _session.Execute(string.Format("SELECT * FROM {0} WHERE k = {1}", uniqueTableName, Key.ToString()), ConsistencyLevel.Quorum))
            {
                Row row = rs.GetRows().FirstOrDefault();
                Assert.AreEqual(mapKey, ((SortedDictionary<string, string>)row["i"]).First().Key);
                Assert.AreEqual(mapVal, ((SortedDictionary<string, string>)row["i"]).First().Value);
            }
        }

        /// <summary>
        ///  Test map with max allowed key size + 1
        /// </summary>
        [Test]
        public void Map_TextKey_MaxPlusOne()
        {
            string uniqueTableName = GetUniqueTableName();
            CreateTable(_session, uniqueTableName, "map<text, text>");

            // given MAX = 65535
            // for C* 2.1.x -- map string key max = MAX - 9 and map string value max = MAX
            // for C* 2.0.x -- map string key max = MAX - 6
            string mapKey = new string('a', UInt16.MaxValue - 6);
            string mapVal = new string('b', 1); // something safe
            try
            {
                _session.Execute(string.Format("INSERT INTO {0}(k,i) VALUES({1},{{ '{2}' : '{3}' }})", uniqueTableName, Key, mapKey, mapVal), ConsistencyLevel.Quorum);
                Assert.Fail("Expected exception was not thrown!");
            }
            catch (Cassandra.InvalidQueryException e)
            {
                string expectedErrMsg = "The sum of all clustering columns is too long";
                Assert.True(e.Message.Contains(expectedErrMsg),
                    string.Format("Exception message: '{0}' did not contain error message '{1}'", e.Message, expectedErrMsg));
            }
        }

        /// <summary>
        ///  Test map with max allowed value size + 1
        /// </summary>
        [Test]
        public void Map_Value_MaxPlusOne()
        {
            string uniqueTableName = GetUniqueTableName();
            CreateTable(_session, uniqueTableName, "map<text, text>");

            // given MAX = 65535, map string key max = MAX - 9 and map string value max = MAX
            string mapKey = new string('a', UInt16.MaxValue - 9);
            string mapVal = new string('b', UInt16.MaxValue + 1);
            try
            {
                _session.Execute(string.Format("INSERT INTO {0}(k,i) VALUES({1},{{ '{2}' : '{3}' }})", uniqueTableName, Key, mapKey, mapVal), ConsistencyLevel.Quorum);
                Assert.Fail("Expected exception was not thrown!");
            }
            catch (Cassandra.InvalidQueryException e)
            {
                string expectedErrMsg = "Map value is too long.";
                Assert.True(e.Message.Contains(expectedErrMsg),
                    string.Format("Exception message: '{0}' did not contain error message '{1}'", e.Message, expectedErrMsg));
            }
        }

        ///////////////////////////////////////
        // Test Helpers
        ///////////////////////////////////////

        private static void CreateTable(ISession session, string tableName, string cqlType)
        {
            session.CreateKeyspaceIfNotExists(KeyspaceNameDefault);
            session.ChangeKeyspace(KeyspaceNameDefault);
            session.Execute(string.Format("CREATE TABLE {0} (k INT, i {1}, PRIMARY KEY(k))", tableName, cqlType));
        }

        // Test a wide row
        private static void TestWideRows(ISession session, string tableName)
        {
            string cql = string.Format("CREATE TABLE {0} (i INT, str {1}, PRIMARY KEY(i,str))", tableName, "text");
            session.Execute(cql);

            // Write data
            //Use a row length of 1024, we are testing the driver not Cassandra itself
            List<string> expectedStrings = new List<string>();
            for (int str = 0; str < 1024; ++str)
            {
                string insertCql = string.Format("INSERT INTO {0} (i,str) VALUES({1},'{2}')", tableName, Key, str);
                expectedStrings.Add(str.ToString());
                session.Execute(insertCql, ConsistencyLevel.Quorum);
            }

            // Read data
            expectedStrings.Sort();
            var rs = session.Execute(string.Format("SELECT str FROM {0} WHERE i = {1}", tableName, Key), ConsistencyLevel.Quorum);
            {
                // Verify data
                List<Row> rows = rs.GetRows().ToList();
                for (int j = 0; j < rows.Count; j++)
                    Assert.AreEqual(expectedStrings[j].ToString(), rows[j]["str"]);
            }
        }

        // Test a batch that writes a row of size
        private static void TestWideBatchRows(ISession session, string tableName)
        {
            string cql = String.Format("CREATE TABLE {0} (i INT, str {1}, PRIMARY KEY(i,str))", tableName, "text");
            session.Execute(cql);

            // Write data
            List<string> expectedStrings = new List<string>();
            var sb = new StringBuilder("BEGIN BATCH ");
            for (int str = 0; str < 1024; ++str)
            {
                string insertCql = string.Format("INSERT INTO {0} (i,str) VALUES({1},'{2}')", tableName, Key, str);
                expectedStrings.Add(str.ToString());
                sb.AppendLine(insertCql);
            }
            sb.Append("APPLY BATCH");
            session.Execute(sb.ToString(), ConsistencyLevel.Quorum);

            // Read data
            expectedStrings.Sort();
            var rs = session.Execute(string.Format("SELECT str FROM {0} WHERE i = {1}", tableName, Key), ConsistencyLevel.Quorum);
            {
                // Verify data
                List<Row> rows = rs.GetRows().ToList();
                for (int j = 0; j < rows.Count; j++)
                    Assert.AreEqual(expectedStrings[j].ToString(), rows[j]["str"]);
            }
        }

        // Test a wide row consisting of a ByteBuffer
        private static void TestByteRows(ISession session, string tableName)
        {
            session.Execute(String.Format("CREATE TABLE {0} (k INT, i {1}, PRIMARY KEY(k,i))", tableName, "BLOB"));

            // Build small ByteBuffer sample
            var bw = new FrameWriter(new MemoryStream(), new Serializer(1));
            for (int i = 0; i < 56; i++)
                bw.WriteByte(0);
            bw.WriteUInt16(0xCAFE);
            var bb = new byte[58];
            Array.Copy(bw.GetBuffer(), bb, 58);

            // Write data
            for (int i = 0; i < 1024; ++i)
                session.Execute(string.Format("INSERT INTO {0}(k,i) values({1},0x{2})", tableName, Key, CqlQueryTools.ToHex(bb)),
                                ConsistencyLevel.Quorum);

            // Read data
            var rs = session.Execute("SELECT i FROM " + tableName + " WHERE k = " + Key, ConsistencyLevel.Quorum);
            // Verify data
            foreach (var row in rs)
                Assert.AreEqual((byte[])row["i"], bb);
        }

        // Test a row with a single extra large text value
        private static void TestLargeText(ISession session, string tableName)
        {
            session.Execute(String.Format("CREATE TABLE {0} (k INT, i {1}, PRIMARY KEY(k,i))", tableName, "text"));

            // Write data
            var b = new StringBuilder();
            for (int i = 0; i < 1000; ++i)
                b.Append(i); // Create ultra-long text

            session.Execute(string.Format("INSERT INTO {0}(k,i) VALUES({1},'{2}')", tableName, Key, b), ConsistencyLevel.Quorum);

            // Read data
            var rs = session.Execute("SELECT * FROM " + tableName + " WHERE k = " + Key, ConsistencyLevel.Quorum);
            {
                Row row = rs.GetRows().FirstOrDefault(); // select().all().from("large_text").where(eq("k", key))).one();
                // Verify data
                Assert.True(b.ToString().Equals(row["i"]));
            }
        }

        // Converts an integer to an string of letters
        private static String CreateColumnName(int i)
        {
            String[] letters = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
            StringBuilder columnName;
            int currentI;

            currentI = i;
            columnName = new StringBuilder();
            while (true)
            {
                columnName.Append(letters[currentI % 10]);
                currentI /= 10;
                if (currentI == 0)
                    break;
            }

            return columnName.ToString();
        }

        // Creates a table with 330 columns
        private static void TestWideTable(ISession session, String tableName)
        {
            session.Execute(GetTableDeclaration(tableName));

            // Write data
            var insrt = new StringBuilder("INSERT INTO " + tableName + "(k");
            var valus = new StringBuilder(" VALUES(" + Key);
            for (int i = 0; i < 330; ++i)
            {
                insrt.Append(",\"" + CreateColumnName(i) + "\"");
                valus.Append("," + i);
            }
            insrt.Append(") " + valus + ")");
            session.Execute(insrt.ToString(), ConsistencyLevel.Quorum);

            // Read data
            var rs = session.Execute("SELECT * FROM " + tableName + " WHERE k = " + Key, ConsistencyLevel.Quorum);
            {
                Row row = rs.GetRows().FirstOrDefault();
                Assert.True(row != null, "row is null");
                Assert.True(row.Length >= 330, "not enough columns");

                // Verify data
                for (int i = 0; i < 330; ++i)
                {
                    string cn = CreateColumnName(i);
                    Assert.True(row[cn] != null, "column is null");
                    Assert.True(row[cn] is int, "column is not int");
                    Assert.True((int)row[cn] == i);
                }
            }
        }

        private static string GetUniqueTableName()
        {
            return "LgDataTsts_" + Randomm.RandomAlphaNum(16);
        }

        private static String GetTableDeclaration(string tableName)
        {
            var tableDeclaration = new StringBuilder();
            tableDeclaration.Append("CREATE TABLE " + tableName + " (");
            tableDeclaration.Append("k INT PRIMARY KEY");
            for (int i = 0; i < 330; ++i)
            {
                tableDeclaration.Append(String.Format(", \"{0}\" INT", CreateColumnName(i)));
            }
            tableDeclaration.Append(")");
            return tableDeclaration.ToString();
        }

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cladosporium phragmitis Opiz

### Remarks
null


text:
__author__ = 'jpi'

import json

from django.views.generic import View
from django.http import HttpResponse
from SPARQLWrapper import SPARQLWrapper, JSON
from rest_framework.generics import GenericAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView, ListAPIView

from stadtgedaechtnis_backend.utils import get_nearby_locations
from stadtgedaechtnis_backend.services.views import GZIPAPIView
from stadtgedaechtnis_backend.services.serializer.serializers import *
from stadtgedaechtnis_backend.services.serializer.generics import MultipleRequestSerializerAPIView
from stadtgedaechtnis_backend.services.authentication.permissions import IsAuthenticatedOrReadOnlyOrModerated

RETURN_TYPE_JSON = "application/json"

class GetNearbyPlacesDBPedia(View):
    """
    Returns a list of places to a given location.
    Parameters: lat - Latitude, lon - Longitude
    A query to DBpedia is made and the results are given in JSON.
    """

    def get(self, request, *args, **kwargs):
        lat, lon = float(kwargs["lat"]), float(kwargs["lon"])
        min_lat, max_lat = lat - 0.01, lat + 0.01
        min_lon, max_lon = lon - 0.01, lon + 0.01

        # build query
        sparql = SPARQLWrapper("http://dbpedia.org/sparql")
        sparql.setQuery("select distinct ?link, ?name, ?latitude, ?longitude where "
                        "{?link geo:lat ?latitude . ?link geo:long ?longitude . ?link foaf:name ?name "
                        "filter (xsd:decimal(?latitude) >= " + str(min_lat) + ") "
                                                                              "filter (xsd:decimal(?latitude) <= " + str(
            max_lat) + ") "
                       "filter (xsd:decimal(?longitude) >= " + str(min_lon) + ") "
                                                                              "filter (xsd:decimal(?longitude) <= " + str(
            max_lon) + ")}")
        sparql.setReturnFormat(JSON)
        # query DBpedia
        places = sparql.query().convert()

        result = {"entries": []}

        # iterate over results
        for place in places["results"]["bindings"]:
            result["entries"].append({
                "name": place["name"]["value"],
                "url": place["link"]["value"],
                "lat": place["latitude"]["value"],
                "lon": place["longitude"]["value"]
            })

        return HttpResponse(json.dumps(result),
                            content_type="application/json")

class LocationView(GZIPAPIView, GenericAPIView):
    """
    Base class for use with Locations
    """
    queryset = Location.objects.all()
    serializer_class = LocationSerializer
    permission_classes = (IsAuthenticatedOrReadOnlyOrModerated, )

class LocationListCreate(LocationView, ListCreateAPIView, MultipleRequestSerializerAPIView):
    """
    List all locations or create a new one
    """
    serializer_classes = {
        "GET": LocationSerializer,
        "POST": LocationSerializerWithUniqueID,
    }

class LocationList(LocationView, ListAPIView):
    """
    Simply lists all locations
    """

class LocationListWithStoryIDs(LocationList):
    """
    Gets all the location and the story IDs
    """
    serializer_class = LocationSerializerWithStoryIDs

class LocationListWithStoryTitle(LocationList):
    """
    Retrieves a list of locations. Also includes a list of attached story IDs.
    """
    serializer_class = LocationSerializerWithStoryTitle

class LocationListWithStories(LocationList):
    """
    Retrieves a list of locations. Also includes all the story information attached to these locations.
    """
    serializer_class = LocationSerializerWithStories

class SingleLocation(LocationView, RetrieveUpdateDestroyAPIView):
    """
    Gets a single Location.
    """

class SingleLocationWithStoryIDs(SingleLocation, LocationListWithStoryIDs):
    """
    Retrieves a single location by its ID.
    Also includes a list of attached story IDs.
    """

class SingleLocationWithStoryTitle(SingleLocation, LocationListWithStoryTitle):
    """
    Retrieves a single location by its ID.
    Also includes a list of attached story title.
    """

class SingleLocationWithStories(SingleLocation, LocationListWithStories):
    """
    Retrieves a single location by its ID.
    Also includes a list of attached stories.
    """

class LocationListNearby(LocationList):
    """
    Retrieves a list of locations to given lat and lon coordinates.
    """

    def get_queryset(self):
        return get_nearby_locations(self.kwargs["lat"], self.kwargs["lon"],
                                    self.kwargs["maxlat"] if "maxlat" in self.kwargs else 0,
                                    self.kwargs["maxlon"] if "maxlon" in self.kwargs else 0,
                                    True
        ).prefetch_related("stories__assets__sources")

class LocationListNearbyWithStoryIDs(LocationListNearby, LocationListWithStoryIDs):
    """
    Retrieves a list of locations to given lat and lon coordinates. Also includes a list of attached story IDs.
    """

class LocationListNearbyWithImages(LocationListNearby):
    """
    Retrieves a list of locations. Also includes all the story information attached to these locations.
    """
    serializer_class = LocationSerializerWithStoryImages

class SingleLocationWithStoriesImage(SingleLocation):
    """
    Retrieves a single location by its ID.
    also includes al ist of attached stories and images.
    """
    serializer_class = LocationSerializerWithStoryImages

class LocationListNearbyWithStoryTitle(LocationListWithStoryTitle, LocationListNearby):
    """
    Retrieves a list of locations to given lat and lon coordinates. Also includes a list of attached story titles.
    """

class LocationListNearbyWithStories(LocationListWithStories, LocationListNearby):
    """
    Retrieves a list of locations to given lat and lon coordinates.
    Also includes all the story information attached to these locations.
    """


text:
import { Component } from '@angular/core';
import { App, NavController, PopoverController } from 'ionic-angular';
import { Auth } from '../../providers';
import { User, Plan, CustomMeal } from '../../models';
import { MealsHomePage } from '../';
import { PlansPopoversOptionsPage, PlansMealPage, PlansShoppingListPage } from '../';

@Component({
  selector: 'page-plans-home',
  templateUrl: 'home.html'
})
export class PlansHomePage {

  /** Propriétés de la classe */
  user: User;
  plan: Plan;

  /** Constructeur */
  constructor(
    public app: App, public nav: NavController, public popover: PopoverController,
    public auth: Auth
  ) {}

  /** Initialisation */
  ngOnInit() {
    this.auth.loggedUser().subscribe((user: User) => {
      this.user = user;

      console.log('user home plan', this.user)
      this.getPlan();
    });
  }

  /**
   * Chargement du plan depuis la base de données
   */
  getPlan() {
    this.user.getPlan().subscribe((plan: any) => {
      this.plan = plan;
    });
  }

  /**
   * Affichage d'un plat
   */
  showMeal(customMeal: CustomMeal) {
    this.nav.push(PlansMealPage, {customMeal: customMeal});
  }

  /**
   * Ajouter un nouveau plat
   */
  addMeal() {
    this.nav.setRoot(MealsHomePage)
  }

  /**
   * Options du plan
   */
  options(event: any) {
    let popover = this.popover.create(PlansPopoversOptionsPage, {user: this.user});
    popover.present({
      ev: event
    });
    popover.onDidDismiss((data: any) => {
     this.getPlan();
   });
  }

  /**
   * Affichage de la liste des courses
   */
  shoppingList() {
    this.nav.push(PlansShoppingListPage, {plan: this.plan});
  }

}


text:
default['zap']['yum_repos']['pattern'] = '*'
default['zap']['yum_repos']['immediately'] = true


text:
namespace url {
class Origin;
}

namespace media {
class AudioRendererSink;

// Caches AudioRendererSink instances, provides them to the clients for usage,
// tracks their used/unused state, reuses them to obtain output device
// information, garbage-collects unused sinks.
// Thread safe.
class MEDIA_EXPORT AudioRendererSinkCache {
 public:
  virtual ~AudioRendererSinkCache() {}

  // Creates default cache, to be used by AudioRendererMixerManager.
  static std::unique_ptr<AudioRendererSinkCache> Create();

  // Returns output device information for a specified sink.
  virtual media::OutputDeviceInfo GetSinkInfo(
      int source_render_frame_id,
      int session_id,
      const std::string& device_id,
      const url::Origin& security_origin) = 0;

  // Provides a sink for usage. The sink must be returned to the cache by
  // calling ReleaseSink(). The sink must be stopped by the user before
  // deletion, but after releasing it from the cache.
  virtual scoped_refptr<media::AudioRendererSink> GetSink(
      int source_render_frame_id,
      const std::string& device_id,
      const url::Origin& security_origin) = 0;

  // Notifies the cache that the sink is not in use any more. Must be
  // called by the client, so that the cache can garbage-collect the sink
  // reference.
  virtual void ReleaseSink(const media::AudioRendererSink* sink_ptr) = 0;

 protected:
  AudioRendererSinkCache() {}

  DISALLOW_COPY_AND_ASSIGN(AudioRendererSinkCache);
};

}  // namespace media

#endif  // CHROMIUM_MEDIA_LIB_AUDIO_RENDERER_SINK_CACHE_H_


text:
<?php

namespace Arthem\GoogleApi\Domain\Place\Query\Search;

use Arthem\GoogleApi\Domain\Place\Query\AbstractHandler;
use Arthem\GoogleApi\Domain\Place\VO\PlaceCollection;

class NearbySearchHandler extends AbstractHandler
{
    /**
     * @param NearbySearchQuery $query
     *
     * @return PlaceCollection
     */
    public function handle(NearbySearchQuery $query)
    {
        $location = $query->getLocation();
        $params = [
            'location' => $location->getLatitude().','.$location->getLongitude(),
        ];

        if (null !== $query->getName()) {
            $params['name'] = $query->getName();
        }

        if (null !== $query->getRadius()) {
            $params['radius'] = $query->getRadius()->getRadius();
        }

        if (null !== $rankBy = $query->getRankBy()) {
            $params['rankby'] = $rankBy;
        }

        if (null !== $types = $query->getTypes()) {
            $params['types'] = implode('|', $types);
        }

        return $this->client->nearbysearch($params);
    }
}


text:
#include "Entity_MarkerType.hpp"
#include <fstream>

Entity_MarkerType::Entity_MarkerType(int x, int y, int w, int h)
{
    this->type = "MarkerType"; //we need the type because it counteracts the ambiguity of polymorphism
    this->x = x;
    this->y = y;
    this->w = w;
    this->h = h;
    this->rotation = 0;
    this->bounds.x = this->x-(this->w/2);
    this->bounds.y = this->y-(this->h/2);
    this->bounds.w = this->w;
    this->bounds.h = this->h;
}

/*void Entity_SignType::update(Camera camera)
{
    if(GetDistanceSquared(x,y,camera.x,camera.y)<10000&&fade_state==0)
    {
        fade_state = 1;
    }
    else if(GetDistanceSquared(x,y,camera.x,camera.y)>10000&&fade_state==1)
    {
        fade_state = 3;
    }
    if(fade_state==1)
    {
        fade_alpha+=.001;
    }
    else if(fade_state==2)
    {
        fade_alpha-=.001;
    }
}*/

bool Entity_MarkerType::serialize(fstream& file)
{
    if(!file.is_open()) return false;
    string::size_type type_length = type.size();
    file.write((char*) &type_length, sizeof type_length);
    file.write(type.data(), type_length); //this is so when we open the file, we can know who this entity is. (Basically my shitty programming, not knowing of Templates)

    int entity_version = 1;
    file.write((char*) &entity_version, sizeof(entity_version));
    file.write((char*) &x, sizeof(x));
    file.write((char*) &y, sizeof(y));
    file.write((char*) &w, sizeof(w));
    file.write((char*) &h, sizeof(h));
    return true;
}

bool Entity_MarkerType::unserialize(ifstream& file)
{
    if(!file.is_open()) return false;
    int entity_version;
    file.read((char*) &entity_version, sizeof(int));
    if(entity_version==1){
        file.read((char*) &x, sizeof(x));
        file.read((char*) &y, sizeof(y));
        file.read((char*) &w, sizeof(w));
        file.read((char*) &h, sizeof(h));
        bounds.x = x-(w/2);
        bounds.y = y-(h/2);
        bounds.w = w;
        bounds.h = h;
        return true;
    }
    else return false;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

 -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="wallpaper_instructions" msgid="3524143401182707094">"Angi bakgrunn"</string>
    <string name="wallpaper_load_fail" msgid="4800700444605404650">"Kunne ikke laste inn bildet som bakgrunn"</string>
    <string name="crop_wallpaper" msgid="4882870800623585836">"Beskjær bakgrunnen"</string>
</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.henry.hh">

    <!-- 网络权限 -->
    <!-- 用于进行网络定位 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 用于访问GPS定位 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- 获取运营商信息,用于支持提供运营商信息相关的接口 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位 -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位 -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!-- 用于访问网络,网络定位需要上网 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 用于读取手机当前的状态 -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- 写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:name=".activity.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="48f94a1c9215e71dc15b0db6c53b3421" />

        <service android:name="com.amap.api.location.APSService" />
        <service
            android:name=".service.ChatService"
            android:enabled="true"
            android:exported="true" />

        <activity android:name=".activity.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activity.GuideActivity" />
        <activity android:name=".activity.ChatActivity" />
        <activity android:name=".activity.Test1Activity" />
        <activity android:name=".activity.MainActivity" />
        <activity
            android:name=".activity.SearchActivity"
            android:windowSoftInputMode="adjustPan|stateHidden" />
        <activity android:name=".activity.PublishActivity" />
        <activity android:name=".activity.LocationActivity" />
        <activity android:name=".activity.SwipeCardsActivity" />
        <activity android:name=".activity.LoginActivity" />
        <activity android:name=".activity.RegisterActivity" />
        <activity android:name=".activity.FindPasswordActivity" />
        <activity android:name=".activity.ModifyPasswordActivity" />
        <activity android:name=".activity.UserInfoActivity" />
        <activity android:name=".activity.FriendApplyListActivity"></activity>
    </application>

</manifest>


text:
<?php
/**
 * Created by PhpStorm.
 * User: daniel
 * Date: 13.10.14
 * Time: 13:02
 */

namespace Cundd\PersistentObjectStore\Server;

use Cundd\PersistentObjectStore\Formatter\FormatterInterface;
use Cundd\PersistentObjectStore\Server\BodyParser\BodyParserInterface;
use Cundd\PersistentObjectStore\Server\Exception\InvalidEventLoopException;
use Cundd\PersistentObjectStore\Server\Handler\HandlerInterface;
use Cundd\PersistentObjectStore\Server\Handler\HandlerResultInterface;
use Cundd\PersistentObjectStore\Server\ValueObject\Statistics;
use DateTime;
use React\Http\Request;
use React\Http\Response;

/**
 * Interface for server implementations
 *
 * @package Cundd\PersistentObjectStore\Server
 */
interface ServerInterface {
	/**
	 * Server is in normal operation mode
	 */
	const SERVER_MODE_NORMAL = 0;

	/**
	 * Server is in test mode
	 */
	const SERVER_MODE_TEST = 1;

	/**
	 * Handle the given request
	 *
	 * @param \React\Http\Request  $request
	 * @param \React\Http\Response $response
	 */
	public function handle($request, $response);

	/**
	 * Handle the given request result
	 *
	 * @param HandlerResultInterface $result
	 * @param Request                $request
	 * @param Response               $response
	 */
	public function handleResult($result, $request, $response);

	/**
	 * Handles the given exception
	 *
	 * @param \Exception           $error
	 * @param \React\Http\Request  $request
	 * @param \React\Http\Response $response
	 * @throws \Exception
	 */
	public function handleError($error, $request, Response $response);

	/**
	 * Starts the request loop
	 */
	public function start();

	/**
	 * Stops to listen for connections
	 */
	public function stop();

	/**
	 * Restarts the server
	 */
	public function restart();

	/**
	 * Total shutdown of the server
	 *
	 * Stops to listen for incoming connections, runs the maintenance task and terminates the program
	 */
	public function shutdown();

	/**
	 * Returns the servers global unique identifier
	 *
	 * @return string
	 */
	public function getGuid();

	/**
	 * Returns the servers start time
	 *
	 * @return DateTime
	 */
	public function getStartTime();

	/**
	 * Returns if the server is running
	 *
	 * @return bool
	 */
	public function isRunning();

	/**
	 * Collects and returns the current server statistics
	 *
	 * @param bool $detailed If detailed is TRUE more data will be collected and an array will be returned
	 * @return Statistics|array
	 */
	public function collectStatistics($detailed = FALSE);

	/**
	 * Returns the formatter for the given request
	 *
	 * @param Request $request
	 * @return FormatterInterface
	 */
	public function getFormatterForRequest(Request $request);

	/**
	 * Returns the handler for the given request
	 *
	 * @param Request $request
	 * @return HandlerInterface
	 */
	public function getHandlerForRequest(Request $request);

	/**
	 * Returns the body parser for the given request
	 *
	 * @param Request $request
	 * @return BodyParserInterface
	 */
	public function getBodyParserForRequest(Request $request);

	/**
	 * Sets the IP to listen on
	 *
	 * @param string $ip
	 * @return $this
	 */
	public function setIp($ip);

	/**
	 * Returns the IP to listen on
	 *
	 * @return string
	 */
	public function getIp();

	/**
	 * Sets the port number to listen on
	 *
	 * @param int $port
	 * @return $this
	 */
	public function setPort($port);

	/**
	 * Returns the port number to listen on
	 *
	 * @return int
	 */
	public function getPort();

	/**
	 * Returns the event loop instance
	 *
	 * @throws InvalidEventLoopException if the event loop is not set
	 * @return \React\EventLoop\LoopInterface
	 */
	public function getEventLoop();

	/**
	 * Sets the event loop
	 *
	 * @param \React\EventLoop\LoopInterface $eventLoop
	 * @return $this
	 */
	public function setEventLoop($eventLoop);

	/**
	 * Returns the mode of the server
	 *
	 * @return int
	 */
	public function getMode();

	/**
	 * Sets the mode of the server
	 *
	 * @param int $mode
	 * @return $this
	 */
	public function setMode($mode);

	/**
	 * Returns the number of seconds after which to stop the server if run in test mode
	 *
	 * @return int
	 */
	public function getAutoShutdownTime();

	/**
	 * Sets the number of seconds after which to stop the server if run in test mode
	 *
	 * @param int $autoShutdownTime
	 * @return $this
	 */
	public function setAutoShutdownTime($autoShutdownTime);
}


text:
RailsDb::Engine.routes.draw do
  root :to => 'dashboard#index'

  resources :tables, :only => [:index, :show] do
    get 'data'
    get 'csv'
    get 'truncate'
    get 'destroy' # to handle opens in new window (GET)
    get 'edit'    # to handle opens in new window (GET)
    put 'update'  # to handle opens in new window (GET)
    get 'xlsx'
    get 'new'
    post 'create'
  end

  get '/sql' => 'sql#index', as: :sql
  get '/import' => 'sql#import', as: :sql_import

  post '/execute' => 'sql#execute', as: :sql_execute
  post '/sql-csv' => 'sql#csv', as: :sql_csv
  post '/sql-xls' => 'sql#xls', as: :sql_xls
  post '/import-start' => 'sql#import_start', as: :sql_start_import

  get '/data-table' => 'dashboard#data_table', as: :data_table
  get '/standalone' => 'dashboard#standalone', as: :standalone
end

if RailsDb.automatic_routes_mount
  Rails.application.routes.draw do
    mount_rails_db_routes
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-dataflow-parent</artifactId>
		<version>1.2.1.BUILD-SNAPSHOT</version>
	</parent>
	<artifactId>spring-cloud-dataflow-configuration-metadata</artifactId>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-loader</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-metadata</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session.TransactionalAction (Permazen 4.1.9 API)</title>
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

io.permazen

Interface Session.TransactionalAction

All Known Subinterfaces:

Session.HasTransactionOptions, Session.RetryableAction

All Known Implementing Classes:

AbstractTransactionRaftCommand.RaftTransactionAction, EvalCommand.EvalAction

Enclosing class:

Session

public static interface Session.TransactionalAction

Tagging interface indicating an Session.Action that requires there to be an open transaction.

 A new transaction will be created if necessary before this action is executed.
 If a transaction already exists, it will be (re)used.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2022. All rights reserved.


text: <create-memory-controller></create-memory-contorller>


text:
import os
import fnmatch

# Names that are exluded from globbing results:
EXCLUDE_NAMES = ['{arch}', 'CVS', '.cvsignore', '_darcs',
                 'RCS', 'SCCS', '.svn']
EXCLUDE_PATTERNS = ['*.py[cdo]', '*.s[ol]', '.#*', '*~', '*.py']

def _filter_names(names):
    """
    Given a list of file names, return those names that should be copied.
    """
    names = [n for n in names
             if n not in EXCLUDE_NAMES]
    # This is needed when building a distro from a working
    # copy (likely a checkout) rather than a pristine export:
    for pattern in EXCLUDE_PATTERNS:
        names = [n for n in names
                 if (not fnmatch.fnmatch(n, pattern))
                 and (not n.endswith('.py'))]
    return names

def relative_to(base, relativee):
    """
    Gets 'relativee' relative to 'basepath'.

    i.e.,

    >>> relative_to('/home/', '/home/radix/')
    'radix'
    >>> relative_to('.', '/home/radix/Projects/Twisted')
    'Projects/Twisted'

    The 'relativee' must be a child of 'basepath'.
    """
    basepath = os.path.abspath(base)
    relativee = os.path.abspath(relativee)
    if relativee.startswith(basepath):
        relative = relativee[len(basepath):]
        if relative.startswith(os.sep):
            relative = relative[1:]
        return os.path.join(base, relative)
    raise ValueError("%s is not a subpath of %s" % (relativee, basepath))

def get_packages(dname, pkgname=None, results=None, ignore=None, parent=None):
    """
    Get all packages which are under dname. This is necessary for
    Python 2.2's distutils. Pretty similar arguments to getDataFiles,
    including 'parent'.
    """
    parent = parent or ""
    prefix = []
    if parent:
        prefix = [parent]
    bname = os.path.basename(dname)
    ignore = ignore or []
    if bname in ignore:
        return []
    if results is None:
        results = []
    if pkgname is None:
        pkgname = []
    subfiles = os.listdir(dname)
    abssubfiles = [os.path.join(dname, x) for x in subfiles]

    if '__init__.py' in subfiles:
        results.append(prefix + pkgname + [bname])
        for subdir in filter(os.path.isdir, abssubfiles):
            get_packages(subdir, pkgname=pkgname + [bname],
                         results=results, ignore=ignore,
                         parent=parent)
    res = ['.'.join(result) for result in results]
    return res

def get_data_files(dname, ignore=None, parent=None):
    """
    Get all the data files that should be included in this distutils Project.

    'dname' should be the path to the package that you're distributing.

    'ignore' is a list of sub-packages to ignore.  This facilitates
    disparate package hierarchies.  That's a fancy way of saying that
    the 'twisted' package doesn't want to include the 'twisted.conch'
    package, so it will pass ['conch'] as the value.

    'parent' is necessary if you're distributing a subpackage like
    twisted.conch.  'dname' should point to 'twisted/conch' and 'parent'
    should point to 'twisted'.  This ensures that your data_files are
    generated correctly, only using relative paths for the first element
    of the tuple ('twisted/conch/*').
    The default 'parent' is the current working directory.
    """
    parent = parent or "."
    ignore = ignore or []
    result = []
    for directory, subdirectories, filenames in os.walk(dname):
        resultfiles = []
        for exname in EXCLUDE_NAMES:
            if exname in subdirectories:
                subdirectories.remove(exname)
        for ig in ignore:
            if ig in subdirectories:
                subdirectories.remove(ig)
        for filename in _filter_names(filenames):
            resultfiles.append(filename)
        if resultfiles:
            for filename in resultfiles:
                file_path = os.path.join(directory, filename)
                if parent:
                    file_path = file_path.replace(parent + os.sep, '')
                result.append(file_path)

    return result


text:
package org.jasig.cas.adaptors.ldappwd;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.ArrayList;

import javax.management.timer.Timer;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;

import org.jasig.cas.authentication.AbstractPasswordWarningCheck;
import org.jasig.cas.util.LdapUtils;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.util.Assert;

/**
 * Class that fetches an password expiration date from an LDAP database.
 * Based on AccountStatusGetter by Bart Ophelders & Johan Peeters
 *
 * @author Eric Pierce
 * @version 1.3 12/14/2009 11:47:37
 *
 */
public class LdapPasswordWarningCheck extends AbstractPasswordWarningCheck {

	private static final String CHECK_TYPE_PWDCHANGE = "change";
	private static final String CHECK_TYPE_PWDEXPIRE = "expire";

	/** Time Segments for AD Password age **/
	private long INTERVALS_PER_MILLISECOND = 10000;

	/** Number of milliseconds between 1/1/1601 and 1/1/1970 **/
	private long MILLISECONDS_BETWEEN_1601_AND_1970 = Timer.ONE_DAY * 134775;

	/** The default maximum number of results to return. */
    private static final int DEFAULT_MAX_NUMBER_OF_RESULTS = 10;

    /** The default timeout. */
    private static final int DEFAULT_TIMEOUT = 1000;

    /** The list of valid scope values. */
    private static final int[] VALID_SCOPE_VALUES = new int[] {
        SearchControls.OBJECT_SCOPE, SearchControls.ONELEVEL_SCOPE,
        SearchControls.SUBTREE_SCOPE};

    /** LdapTemplate to execute ldap queries. */
    private LdapTemplate ldapTemplate;

    /** The filter path to the lookup value of the user. */
    private String filter;

    /** Disregard WarnPeriod and warn all users of password expiration */
    protected Boolean WarnAll;

    /** Calculate password warning from last password change time or expiration date */
    protected String WarningCheckType;

    /** The attribute that contains the date the password will expire or last password change */
    protected String DateAttribute;

    /** The attribute that contains the user's warning days */
    protected String WarningDaysAttribute;

    /** The attribute that contains the number of days the user's password is valid */
    protected String ValidDaysAttribute;

    /** The format of the date in DateAttribute */
    protected String dateFormat;

    /** default number of days that a warning message will be displayed */
    private int warningDays;

    /** default number of days a password is valid */
    private int validDays;

    /** The search base to find the user under. */
    private String searchBase;

    /** The scope. */
    private int scope = SearchControls.SUBTREE_SCOPE;

    /** Whether the LdapTemplate should ignore partial results. */
    private boolean ignorePartialResultException = false;

    /** The maximum number of results to return. */
    private int maxNumberResults = DEFAULT_MAX_NUMBER_OF_RESULTS;

    /** The amount of time to wait. */
    private int timeout = DEFAULT_TIMEOUT;

    private String[] attributeIds;

    public int getPasswordWarning(String userID) {

    	//Create a list of LDAP attributes we need to search for
    	List<String> attributeList = new ArrayList<String>();
    	attributeList.add(this.DateAttribute);
    	if (this.WarningDaysAttribute != null) {
    		attributeList.add(this.WarningDaysAttribute);
    	}
    	if (this.ValidDaysAttribute != null) {
    		attributeList.add(this.ValidDaysAttribute);
    	}

    	//Convert the list to a string array
    	this.attributeIds = new String[attributeList.size()];
    	attributeList.toArray(this.attributeIds);

        LdapResult ldapResult = getResultsFromLDAP(userID);

        if (ldapResult == null) {
            this.logger.warn("No LDAP entry for " + userID);
            return STATUS_ERROR;
        }

        String WarnDaysResult = ldapResult.getWarnDaysResult();
        String ValidDaysResult = ldapResult.getValidDaysResult();

        if (WarnDaysResult == null) {
            this.logger.info("No Warning Days found for " + userID + " using system default of " + warningDays);
        } else {
            warningDays = Integer.parseInt(WarnDaysResult);
        }

        //Convert number of days to number of seconds
        long CurrentTime = (new Date()).getTime();
        long ExpireTime = CurrentTime;

        //Use the last password change date for expiration calculations
        if (this.WarningCheckType.equals(CHECK_TYPE_PWDCHANGE)) {
        	String ChangeDateResult = ldapResult.getDateResult();
        	this.logger.debug("Calculating warning period from last change date");
        	this.logger.debug("WarnDays Result='" + WarnDaysResult + "'");
        	this.logger.debug("ChangeDate Result='" + ChangeDateResult + "'");
        	this.logger.debug("ValidDays Result='" + ValidDaysResult + "'");
        	if (ChangeDateResult == null) {
                this.logger.warn("No password change date for " + userID);
                return STATUS_ERROR;
            }

        	GregorianCalendar ChangeDate = new GregorianCalendar();
        	if (dateFormat.equals("ActiveDirectory")) {
	        	ChangeDate = convertDateAD(ChangeDateResult);
	        } else {
	        	ChangeDate = convertDate(ChangeDateResult, dateFormat);
	            if (ChangeDate == null) {
	            	this.logger.warn("Returning error, last password change date is invalid");
	            	return STATUS_ERROR;
	            }
	        }

            if (ValidDaysResult == null) {
            	this.logger.info("No maximum password age found for " + userID + ".  Using system default of " + validDays + " days");
            } else {
                validDays = Integer.parseInt(ValidDaysResult);

            }

            //Password expiration is the time the password was last changed plus the maximum password age
            long ValidPeriod = validDays * Timer.ONE_DAY;
        	long ChangeTime = (ChangeDate.getTime()).getTime();
        	ExpireTime = ChangeTime + ValidPeriod;

        //The expiration date is stored in LDAP
        } else if (this.WarningCheckType.equals(CHECK_TYPE_PWDEXPIRE)) {
        	String ExpireDateResult = ldapResult.getDateResult();
        	this.logger.debug("Calculating warning period from expiration date");
        	this.logger.debug("WarnDays Result='" + WarnDaysResult + "'");
        	this.logger.debug("ExpireDate Result='" + ExpireDateResult + "'");
        	if (ExpireDateResult == null) {
                this.logger.warn("No Expiration date for " + userID);
                return STATUS_ERROR;
            }

        	GregorianCalendar ExpireDate = convertDate(ExpireDateResult, dateFormat);
            if (ExpireDate == null) {
                this.logger.warn("Returning error, expiration date is invalid");
                return STATUS_ERROR;
            }

        	ExpireTime = (ExpireDate.getTime()).getTime();

        } else {
        	this.logger.warn("Invalid value for 'warningCheckType': " + this.WarningCheckType);
            return STATUS_ERROR;
        }

        float DateDiff = ExpireTime - CurrentTime;
        float WarnPeriod = warningDays * Timer.ONE_DAY;

        this.logger.debug("Current Time=" + CurrentTime / 1000);
        this.logger.debug("Expiration Time=" + ExpireTime / 1000);
        this.logger.debug("Difference in seconds=" + DateDiff);
        this.logger.debug("Warn Period in seconds=" + WarnPeriod);

        //The LDAP server should have thrown an error because the password has already expired
        if (DateDiff < 0) {
            this.logger.warn("Expiration Date has passed for " + userID + " but authentication succeeded!");
            return STATUS_ERROR;
        }

        //WarnAll is true -- warn everyone
        if (WarnAll.equals(true)) {
     	   this.logger.info("Show Warning (WarnALL is TRUE!) -- The password for " + userID + " will expire in " + Math.round(DateDiff / Timer.ONE_DAY) + " days");
     	   return (int) Math.round(DateDiff / Timer.ONE_DAY);
        }

       int comp = Float.compare(DateDiff, (float) WarnPeriod );
       if (comp > 0) {
    	   this.logger.debug("Skip Warning -- The password for " + userID + " will expire in " + Math.round(DateDiff / Timer.ONE_DAY) + " days");
    	   return STATUS_PASS;
       } else {
    	   this.logger.info("Show Warning -- The password for " + userID + " will expire in " + Math.round(DateDiff / Timer.ONE_DAY) + " days");
    	   return (int) Math.round(DateDiff / Timer.ONE_DAY);
       }

    }

    private GregorianCalendar convertDateAD(String pwdLastSet) {
    	long l = Long.parseLong(pwdLastSet.trim());
    	long t= l / INTERVALS_PER_MILLISECOND  ;
        this.logger.debug("pwdLastSet= " + t + " millisec since 1601");

        t-= MILLISECONDS_BETWEEN_1601_AND_1970;
        this.logger.debug("pwdLastSet= " + t + " millisec since 1970");

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(t);
        this.logger.debug("pwdLastSet= " + calendar.getTime().toString() );
        return calendar;
      }

    private GregorianCalendar convertDate(String ldapResult, String dateFormat) {
        DateFormat format = new SimpleDateFormat(dateFormat);
        format.setTimeZone(java.util.TimeZone.getTimeZone("Zulu"));
        format.setLenient(false);
        Date date = null;
        try {
            date = format.parse(ldapResult);
        } catch (ParseException e) {
            this.logger.warn("The attribute'" + DateAttribute
                + "' with value '" + ldapResult
                + "' should contain a date in the format " + dateFormat);
            return null;
        }
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        return calendar;
    }

    private SearchControls getSearchControls(String[] attributeIds) {
        final SearchControls constraints = new SearchControls();

        constraints.setSearchScope(this.scope);
        constraints.setReturningAttributes(this.attributeIds);
        constraints.setTimeLimit(this.timeout);
        constraints.setCountLimit(this.maxNumberResults);

        return constraints;
    }

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.ldapTemplate, "ldapTemplate cannot be null");
        Assert.notNull(this.filter, "filter cannot be null");
        Assert.notNull(this.searchBase, "searchBase cannot be null");
        Assert.notNull(this.WarningCheckType, "warningCheckType cannot be null");
        Assert.notNull(this.WarnAll, "warnAll cannot be null");
        Assert.notNull(this.DateAttribute, "dateAttribute cannot be null");
        Assert.notNull(this.dateFormat, "dateFormat cannot be null");
        Assert.notNull(this.warningDays, "warningDays cannot be null");
        Assert.isTrue(this.filter.contains("%u"), "filter must contain %u");
        this.ldapTemplate.setIgnorePartialResultException(this.ignorePartialResultException);

        for (int i = 0; i < VALID_SCOPE_VALUES.length; i++) {
            if (this.scope == VALID_SCOPE_VALUES[i]) {
                return;
            }
        }
        throw new IllegalStateException("You must set a valid scope.");
    }

    private LdapResult getResultsFromLDAP(final String userID) {
        final String searchFilter = LdapUtils.getFilterWithValues(this.filter,
            userID);

        this.logger.info("LDAP: starting search with searchFilter '" + searchFilter + "'");
        String attributeListLog = this.attributeIds[0];
        for(int i=1;i<this.attributeIds.length;i++) {
        	attributeListLog = attributeListLog.concat(":" + this.attributeIds[i]);
    	}
        this.logger.info("LDAP: Returning attributes '" + attributeListLog + "'");

        try {
            // searching the directory

            AttributesMapper mapper = new AttributesMapper(){

                public Object mapFromAttributes(Attributes attrs)
                    throws NamingException {
                    LdapResult result = new LdapResult();

                    if (LdapPasswordWarningCheck.this.DateAttribute != null){
	                    if (attrs.get(LdapPasswordWarningCheck.this.DateAttribute) != null) {
	                        String date = (String) attrs.get(LdapPasswordWarningCheck.this.DateAttribute).get();
	                        result.setDateResult(date);
	                    }
                    }

                    if (LdapPasswordWarningCheck.this.WarningDaysAttribute != null){
	                    if (attrs.get(LdapPasswordWarningCheck.this.WarningDaysAttribute) != null) {
	                        String warn = (String) attrs.get(LdapPasswordWarningCheck.this.WarningDaysAttribute).get();
	                        result.setWarnDaysResult(warn);
	                    }
                    }

                    if (WarningCheckType.equals(CHECK_TYPE_PWDCHANGE)) {
                    	if (attrs.get(LdapPasswordWarningCheck.this.ValidDaysAttribute) != null) {
                    		String valid = (String) attrs.get(LdapPasswordWarningCheck.this.ValidDaysAttribute).get();
                    		result.setValidDaysResult(valid);
                    	}
                    }

                    return result;
                }
            };

            List<?> LdapResultList = this.ldapTemplate.search(this.searchBase,searchFilter, getSearchControls(this.attributeIds), mapper);

            return (LdapResult) LdapResultList.get(0);

        } catch (Exception e) {
            logger.error("Error searching the directory",e);
            return null;
        }
    }

    /**
     * Method to set the datasource and generate a LDAPTemplate.
     *
     * @param dataSource the datasource to use.
     */
    public final void setContextSource(final ContextSource contextSource) {
        this.ldapTemplate = new LdapTemplate(contextSource);
    }

    /**
     * @param filter The LDAP filter to set.
     */
    public void setFilter(final String filter) {
        this.filter = filter;
        this.logger.info("Search Filter: '" + filter + "'");
    }

    /**
     * @param warnAll Disregard warningPeriod and warn all users of password expiration.
     */
    public final void setWarnAll(Boolean warnAll) {
        this.WarnAll = warnAll;
        this.logger.info("warnAll: '" + warnAll + "'");
    }

    /**
     * @param warningCheckType The warningCheckType to set.
     */
    public final void setWarningCheckType(String WarningCheckType) {
        this.WarningCheckType = WarningCheckType;
        this.logger.info("warningCheckType: '" + WarningCheckType + "'");
    }

    /**
     * @param DateAttribute The DateAttribute to set.
     */
    public final void setDateAttribute(String DateAttribute) {
        this.DateAttribute = DateAttribute;
        this.logger.info("Date Attribute: '" + DateAttribute + "'");
    }

    /**
     * @param WarningDaysAttribute The WarningDaysAttribute to set.
     */
    public final void setWarningDaysAttribute(String WarningDaysAttribute) {
        this.WarningDaysAttribute = WarningDaysAttribute;
        this.logger.info("Warning Days Attribute: '" + WarningDaysAttribute + "'");
    }

    /**
     * @param ValidDaysAttribute The ValidDaysAttribute to set.
     */
    public final void setValidDaysAttribute(String ValidDaysAttribute) {
        this.ValidDaysAttribute = ValidDaysAttribute;
        this.logger.info("Valid Days Attribute: '" + ValidDaysAttribute + "'");
    }

    /**
     * @param filter The scope to set.
     */
    public final void setScope(final int scope) {
        this.scope = scope;
    }

    /**
     * @param maxNumberResults The maxNumberResults to set.
     */
    public final void setMaxNumberResults(final int maxNumberResults) {
        this.maxNumberResults = maxNumberResults;
    }

    /**
     * @param searchBase The searchBase to set.
     */
    public final void setSearchBase(final String searchBase) {
        this.searchBase = searchBase;
        this.logger.info("LDAP Search Base: '" + searchBase + "'");
    }

    /**
     * @param timeout The timeout to set.
     */
    public final void setTimeout(final int timeout) {
        this.timeout = timeout;
    }

    /**
     * @param warningDays Number of days before expiration that a warning
     * message is displayed to set. Used as a default if warningDaysAttribute is
     * not set or is not found in the LDAP results. This parameter is required.
     */
    public final void setWarningDays(final int warningDays) {
        this.warningDays = warningDays;
        this.logger.info("Default Warning Days: '" + warningDays + "'");
    }

    /**
     * @param validDays Number of days that a password is valid for.
     * Used as a default if DateAttribute is not set or is not found in the LDAP results
     */
    public final void setValidDays(final int validDays) {
        this.validDays = validDays;
        this.logger.info("Password Max Age (in days): '" + validDays + "'");
    }

    /**
     * @param dateFormat String to pass to SimpleDateFormat() that describes the
     * date in the ExpireDateAttribute. This parameter is required.
     */
    public final void setDateFormat(final String dateFormat) {
        this.dateFormat = dateFormat;
        this.logger.info("Date format: '" + dateFormat + "'");
    }

    public final void setIgnorePartialResultException(final boolean ignorePartialResultException) {
        this.ignorePartialResultException = ignorePartialResultException;
    }

    /**
     * Class to hold the data returned from LDAP
     *
     */
    public class LdapResult {

        String warnDaysResult;
        String validDaysResult;
        String DateResult;

        public String getWarnDaysResult() {
            return warnDaysResult;
        }

        public void setWarnDaysResult(String warn) {
            this.warnDaysResult = warn;
        }

        public String getValidDaysResult() {
            return validDaysResult;
        }

        public void setValidDaysResult(String valid) {
            this.validDaysResult = valid;
        }

        public String getDateResult() {
            return DateResult;
        }

        public void setDateResult(String date) {
            this.DateResult = date;
        }
    }
}


text:
from servicelayer import env
from servicelayer import settings as sls
from ftmstore import settings as fts

TESTING = False

# Document conversion service
CONVERT_URL = env.get("UNOSERVICE_URL", "http://convert-document:3000/convert")
CONVERT_URL = env.get("INGESTORS_CONVERT_DOCUMENT_URL", CONVERT_URL)
CONVERT_TIMEOUT = env.to_int("INGESTORS_CONVERT_TIMEOUT", 7200)  # 2 hrs
CONVERT_RETRIES = env.to_int("INGESTORS_CONVERT_RETRIES", 256)

# Enable (expensive!) Google Cloud API
OCR_VISION_API = env.to_bool("INGESTORS_OCR_VISION_API", False)

# Geonames data file
GEONAMES_PATH = env.get("INGESTORS_GEONAMES_PATH", "/ingestors/data/geonames.txt")

# FastText lid model file
LID_MODEL_PATH = env.get("INGESTORS_LID_MODEL_PATH", "/ingestors/data/lid.176.ftz")

# Disable entity extraction
ANALYZE_ENTITIES = env.to_bool("INGESTORS_ANALYZE_ENTITIES", True)

# List available NER models
NER_MODELS = {
    "eng": "en_core_web_sm",
    "deu": "de_core_news_sm",
    "fra": "fr_core_news_sm",
    "spa": "es_core_news_sm",
    "rus": "ru_core_news_sm",
    "por": "pt_core_news_sm",
    "ron": "ro_core_news_sm",
    "mkd": "mk_core_news_sm",
    "ell": "el_core_news_sm",
    "pol": "pl_core_news_sm",
    "ita": "it_core_news_sm",
    "lit": "lt_core_news_sm",
}

# FastText type prediction model file
NER_TYPE_MODEL_PATH = env.get(
    "INGESTORS_TYPE_MODEL_PATH", "/models/model_type_prediction.ftz"
)

# Use the environment variable set in aleph.env
fts.DATABASE_URI = env.get("ALEPH_DATABASE_URI", fts.DATABASE_URI)

# Also store cached values in the SQL database
sls.TAGS_DATABASE_URI = fts.DATABASE_URI


text:
//  (C) Copyright Edward Diener 2011-2015
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#if !defined(BOOST_VMD_DETAIL_IS_SEQ_HPP)
#define BOOST_VMD_DETAIL_IS_SEQ_HPP

#include <boost/vmd/detail/is_entire.hpp>
#include <boost/vmd/detail/seq.hpp>

#define BOOST_VMD_DETAIL_IS_SEQ(seq) \
    BOOST_VMD_DETAIL_IS_ENTIRE \
        ( \
        BOOST_VMD_DETAIL_SEQ_SPLIT(seq) \
        ) \
/**/

#define BOOST_VMD_DETAIL_IS_SEQ_D(d,seq) \
    BOOST_VMD_DETAIL_IS_ENTIRE \
        ( \
        BOOST_VMD_DETAIL_SEQ_SPLIT_D(d,seq) \
        ) \
/**/

#endif /* BOOST_VMD_DETAIL_IS_SEQ_HPP */


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
// Components
import Question from './components/Question/Question'
// Selectors
import { currentQuestionKeySelector } from 'redux/selectors/plays'

@connect(state => ({
  questionKey: currentQuestionKeySelector(state),
}))
class Abcd extends Component {
  static propTypes = {
    questionKey: PropTypes.string,
  }

  render() {
    const { questionKey } = this.props
    return (
      <div>
        <Question
          questionKey={questionKey}
        />
      </div>
    )
  }
}

export default Abcd


text:
#include "pybind11/pybind11.h"
#include "pybind11/pytypes.h"
#include "pybind11/stl.h"
#include "tensorflow/lite/python/interpreter_wrapper/interpreter_wrapper.h"
#include "tensorflow/python/lib/core/pybind11_lib.h"

namespace py = pybind11;
using tflite::interpreter_wrapper::InterpreterWrapper;

PYBIND11_MODULE(_pywrap_tensorflow_interpreter_wrapper, m) {
  m.doc() = R"pbdoc(
    _pywrap_tensorflow_interpreter_wrapper
    -----
  )pbdoc";

  // pybind11 suggests to convert factory functions into constructors, but
  // when bytes are provided the wrapper will be confused which
  // constructor to call.
  m.def("CreateWrapperFromFile",
        [](const std::string& model_path,
           const std::vector<std::string>& registerers) {
          std::string error;
          auto* wrapper = ::InterpreterWrapper::CreateWrapperCPPFromFile(
              model_path.c_str(), registerers, &error);
          if (!wrapper) {
            throw std::invalid_argument(error);
          }
          return wrapper;
        });
  m.def("CreateWrapperFromBuffer",
        [](const py::bytes& data, const std::vector<std::string>& registerers) {
          std::string error;
          auto* wrapper = ::InterpreterWrapper::CreateWrapperCPPFromBuffer(
              data.ptr(), registerers, &error);
          if (!wrapper) {
            throw std::invalid_argument(error);
          }
          return wrapper;
        });
  py::class_<InterpreterWrapper>(m, "InterpreterWrapper")
      .def("AllocateTensors",
           [](InterpreterWrapper& self) {
             return tensorflow::PyoOrThrow(self.AllocateTensors());
           })
      .def("Invoke",
           [](InterpreterWrapper& self) {
             return tensorflow::PyoOrThrow(self.Invoke());
           })
      .def("InputIndices",
           [](const InterpreterWrapper& self) {
             return tensorflow::PyoOrThrow(self.InputIndices());
           })
      .def("OutputIndices",
           [](InterpreterWrapper& self) {
             return tensorflow::PyoOrThrow(self.OutputIndices());
           })
      .def("ResizeInputTensor",
           [](InterpreterWrapper& self, int i, py::handle& value) {
             return tensorflow::PyoOrThrow(
                 self.ResizeInputTensor(i, value.ptr()));
           })
      .def("NumTensors", &InterpreterWrapper::NumTensors)
      .def("TensorName", &InterpreterWrapper::TensorName)
      .def("TensorType",
           [](const InterpreterWrapper& self, int i) {
             return tensorflow::PyoOrThrow(self.TensorType(i));
           })
      .def("TensorSize",
           [](const InterpreterWrapper& self, int i) {
             return tensorflow::PyoOrThrow(self.TensorSize(i));
           })
      .def("TensorSizeSignature",
           [](const InterpreterWrapper& self, int i) {
             return tensorflow::PyoOrThrow(self.TensorSizeSignature(i));
           })
      .def("TensorSparsityParameters",
           [](const InterpreterWrapper& self, int i) {
             return tensorflow::PyoOrThrow(self.TensorSparsityParameters(i));
           })
      .def(
          "TensorQuantization",
          [](const InterpreterWrapper& self, int i) {
            return tensorflow::PyoOrThrow(self.TensorQuantization(i));
          },
          R"pbdoc(
            Deprecated in favor of TensorQuantizationParameters.
          )pbdoc")
      .def(
          "TensorQuantizationParameters",
          [](InterpreterWrapper& self, int i) {
            return tensorflow::PyoOrThrow(self.TensorQuantizationParameters(i));
          })
      .def("SetTensor",
           [](InterpreterWrapper& self, int i, py::handle& value) {
             return tensorflow::PyoOrThrow(self.SetTensor(i, value.ptr()));
           })
      .def("GetTensor",
           [](const InterpreterWrapper& self, int i) {
             return tensorflow::PyoOrThrow(self.GetTensor(i));
           })
      .def("ResetVariableTensors",
           [](InterpreterWrapper& self) {
             return tensorflow::PyoOrThrow(self.ResetVariableTensors());
           })
      .def("NumNodes", &InterpreterWrapper::NumNodes)
      .def("NodeName", &InterpreterWrapper::NodeName)
      .def("NodeInputs",
           [](const InterpreterWrapper& self, int i) {
             return tensorflow::PyoOrThrow(self.NodeInputs(i));
           })
      .def("NodeOutputs",
           [](const InterpreterWrapper& self, int i) {
             return tensorflow::PyoOrThrow(self.NodeOutputs(i));
           })
      .def(
          "tensor",
          [](InterpreterWrapper& self, py::handle& base_object, int i) {
            return tensorflow::PyoOrThrow(self.tensor(base_object.ptr(), i));
          },
          R"pbdoc(
            Returns a reference to tensor index i as a numpy array. The
            base_object should be the interpreter object providing the memory.
          )pbdoc")
      .def(
          "ModifyGraphWithDelegate",
          // Address of the delegate is passed as an argument.
          [](InterpreterWrapper& self, uintptr_t delegate_ptr) {
            return tensorflow::PyoOrThrow(self.ModifyGraphWithDelegate(
                reinterpret_cast<TfLiteDelegate*>(delegate_ptr)));
          },
          R"pbdoc(
            Adds a delegate to the interpreter.
          )pbdoc");
}


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <title>Tag tear-down</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">

        <link href="../../assets/css/bootstrap.css" rel="stylesheet">
        <link href="../../assets/css/bootstrap-responsive.css" rel="stylesheet">
        <link href="../../assets/css/custom.css" rel="stylesheet">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".doc-navbar-collapse">
                Toggle navigation

              </button>
              Moya Documentation

                        Reference

                        Tags

                        Tutorial

                ↑ Index

                ← <suite>

        <input type="hidden" name="tag_name" value="tear-down"/>
        <input type="hidden" name="synopsis" value="tear down (finalize) code for a test suite"/>

<tear-down> tear down (finalize) code for a test suite

name

tear-down

xml namespace

<tt>http://moyaproject.com/test</tt>

Logic to tear down a unit test suite. Must be inside a <suite>

inherited attributes

                name
                purpose
                type
                required?
                default
                choices

                if
                Conditional expression
                expression
                No
                yes

            case

            fail

            get-response

            load-project

            request

            require

            set-up

            suite

            tear-down

Moya is © 2014 Moya Software Foundation.


text:
require 'spec_helper'

module QueueBus
  describe Driver do
    before(:each) do
      Application.new('app1').subscribe(test_list(test_sub('event1'), test_sub('event2'), test_sub('event3')))
      Application.new('app2').subscribe(test_list(test_sub('event2', 'other'), test_sub('event4', 'more')))
      Application.new('app3').subscribe(test_list(test_sub('event[45]'), test_sub('event5'), test_sub('event6')))
      Timecop.freeze
    end
    after(:each) do
      Timecop.return
    end

    let(:bus_attrs) { { 'bus_driven_at' => Time.now.to_i, 'bus_rider_class_name' => '::QueueBus::Rider', 'bus_class_proxy' => '::QueueBus::Rider' } }

    describe '.subscription_matches' do
      it 'return empty array when none' do
        expect(Driver.subscription_matches('bus_event_type' => 'else').collect { |s| [s.app_key, s.key, s.queue_name, s.class_name] }).to eq([])
        expect(Driver.subscription_matches('bus_event_type' => 'event').collect { |s| [s.app_key, s.key, s.queue_name, s.class_name] }).to eq([])
      end
      it 'should return a match' do
        expect(Driver.subscription_matches('bus_event_type' => 'event1').collect { |s| [s.app_key, s.key, s.queue_name, s.class_name] }).to match_array([['app1', 'event1', 'default', '::QueueBus::Rider']])
        expect(Driver.subscription_matches('bus_event_type' => 'event6').collect { |s| [s.app_key, s.key, s.queue_name, s.class_name] }).to match_array([['app3', 'event6', 'default', '::QueueBus::Rider']])
      end
      it 'should match multiple apps' do
        expect(Driver.subscription_matches('bus_event_type' => 'event2').collect { |s| [s.app_key, s.key, s.queue_name, s.class_name] }).to match_array([['app1', 'event2', 'default', '::QueueBus::Rider'], ['app2', 'event2', 'other', '::QueueBus::Rider']])
      end
      it 'should match multiple apps with patterns' do
        expect(Driver.subscription_matches('bus_event_type' => 'event4').collect { |s| [s.app_key, s.key, s.queue_name, s.class_name] }).to match_array([['app3', 'event[45]', 'default', '::QueueBus::Rider'], ['app2', 'event4', 'more', '::QueueBus::Rider']])
      end
      it 'should match multiple events in same app' do
        expect(Driver.subscription_matches('bus_event_type' => 'event5').collect { |s| [s.app_key, s.key, s.queue_name, s.class_name] }).to match_array([['app3', 'event[45]', 'default', '::QueueBus::Rider'], ['app3', 'event5', 'default', '::QueueBus::Rider']])
      end
    end

    describe '.perform' do
      let(:attributes) { { 'x' => 'y' } }

      before(:each) do
        expect(QueueBus.redis { |redis| redis.smembers('queues') }).to eq([])
        expect(QueueBus.redis { |redis| redis.lpop('queue:app1_default') }).to be_nil
        expect(QueueBus.redis { |redis| redis.lpop('queue:app2_default') }).to be_nil
        expect(QueueBus.redis { |redis| redis.lpop('queue:app3_default') }).to be_nil
      end

      it 'should do nothing when empty' do
        Driver.perform(attributes.merge('bus_event_type' => 'else'))
        expect(QueueBus.redis { |redis| redis.smembers('queues') }).to eq([])
      end

      it 'should queue up the riders in redis' do
        expect(QueueBus.redis { |redis| redis.lpop('queue:app1_default') }).to be_nil
        Driver.perform(attributes.merge('bus_event_type' => 'event1'))
        expect(QueueBus.redis { |redis| redis.smembers('queues') }).to match_array(['default'])

        hash = JSON.parse(QueueBus.redis { |redis| redis.lpop('queue:default') })
        expect(hash['class']).to eq('QueueBus::Worker')
        expect(hash['args'].size).to eq(1)
        expect(JSON.parse(hash['args'].first)).to eq({ 'bus_rider_app_key' => 'app1', 'x' => 'y', 'bus_event_type' => 'event1', 'bus_rider_sub_key' => 'event1', 'bus_rider_queue' => 'default' }.merge(bus_attrs))
      end

      it 'should queue up to multiple' do
        Driver.perform(attributes.merge('bus_event_type' => 'event4'))
        expect(QueueBus.redis { |redis| redis.smembers('queues') }).to match_array(%w[default more])

        hash = JSON.parse(QueueBus.redis { |redis| redis.lpop('queue:more') })
        expect(hash['class']).to eq('QueueBus::Worker')
        expect(hash['args'].size).to eq(1)
        expect(JSON.parse(hash['args'].first)).to eq({ 'bus_rider_app_key' => 'app2', 'x' => 'y', 'bus_event_type' => 'event4', 'bus_rider_sub_key' => 'event4', 'bus_rider_queue' => 'more' }.merge(bus_attrs))

        hash = JSON.parse(QueueBus.redis { |redis| redis.lpop('queue:default') })
        expect(hash['class']).to eq('QueueBus::Worker')
        expect(hash['args'].size).to eq(1)
        expect(JSON.parse(hash['args'].first)).to eq({ 'bus_rider_app_key' => 'app3', 'x' => 'y', 'bus_event_type' => 'event4', 'bus_rider_sub_key' => 'event[45]', 'bus_rider_queue' => 'default' }.merge(bus_attrs))
      end

      it 'should queue up to the same' do
        Driver.perform(attributes.merge('bus_event_type' => 'event5'))
        expect(QueueBus.redis { |redis| redis.smembers('queues') }).to match_array(['default'])

        expect(QueueBus.redis { |redis| redis.llen('queue:default') }).to eq(2)

        pop1 = JSON.parse(QueueBus.redis { |redis| redis.lpop('queue:default') })
        pop2 = JSON.parse(QueueBus.redis { |redis| redis.lpop('queue:default') })

        pargs1 = JSON.parse(pop1['args'].first)
        pargs2 = JSON.parse(pop2['args'].first)
        if pargs1['bus_rider_sub_key'] == 'event5'
          hash1 = pop1
          hash2 = pop2
          args1 = pargs1
          args2 = pargs2
        else
          hash1 = pop2
          hash2 = pop1
          args1 = pargs2
          args2 = pargs1
        end

        expect(hash1['class']).to eq('QueueBus::Worker')
        expect(args1).to eq({ 'bus_rider_app_key' => 'app3', 'x' => 'y', 'bus_event_type' => 'event5', 'bus_rider_sub_key' => 'event5', 'bus_rider_queue' => 'default' }.merge(bus_attrs))

        expect(hash2['class']).to eq('QueueBus::Worker')
        expect(args2).to eq({ 'bus_rider_app_key' => 'app3', 'x' => 'y', 'bus_event_type' => 'event5', 'bus_rider_sub_key' => 'event[45]', 'bus_rider_queue' => 'default' }.merge(bus_attrs))
      end
    end
  end
end


text:
#include <limits.h>
#include <algorithm>
#include <set>
#include <iostream>

#include "TimerGraph.h"
using namespace std;
class OrderArcs {
public:
	bool operator()(const ActionLog::Arc& a1, const ActionLog::Arc& a2) const {
		if (a1.from == a2.from) return a1.to < a2.to;
		return a1.from < a2.from;
	}
};

TimerGraph::TimerGraph(const std::vector<ActionLog::Arc>& arcs, const SimpleDirectedGraph& graph) {
	int num_timed_arcs = 0;
	for (size_t i = 0; i < arcs.size(); ++i) {
		if (arcs[i].m_duration >= 0 &&
				!graph.isNodeDeleted(arcs[i].to) &&
				!graph.isNodeDeleted(arcs[i].from)) {
			m_timedArcs.push_back(arcs[i]);
			++num_timed_arcs;
//			cout<<"From: "<<arcs[i].from<<"  To: "<<arcs[i].to<<"  Duration: "<<arcs[i].m_duration<<"\n";
		}
	}
	std::sort(m_timedArcs.begin(), m_timedArcs.end(), OrderArcs());
	printf("Using %d timed arcs\n", num_timed_arcs);
}

void TimerGraph::build(SimpleDirectedGraph* graph) {
	std::vector<int> min_outgoing_duration(graph->numNodes(), 0x3fffffff);
	std::vector<std::vector<int> > outgoing_arc_indices(graph->numNodes());

	int num_added_arcs = 0;
	for (size_t arci = 0; arci < m_timedArcs.size(); ++arci) {
		const ActionLog::Arc& arc = m_timedArcs[arci];
		if (arci % 1000 == 999) {
			printf("Adding timed arcs %f%% done. %d arcs added.\n",
					(arci * 100.0) / m_timedArcs.size(), num_added_arcs);
		}
		SimpleDirectedGraph::BFIterator it(*graph, 0x3fffffff, false);
		it.addNode(arc.from);
		int node_id;

		std::set<int> covered_arcs;
		while (it.readNoAddFollowers(&node_id)) {

			// All previous timers with lower or equal duration are before the current one.
			if (min_outgoing_duration[node_id] <= arc.m_duration) {
				const std::vector<int>& node_arcs = outgoing_arc_indices[node_id];
				for (size_t i = node_arcs.size(); i > 0;) {
					--i;
					const ActionLog::Arc& prev_arc = m_timedArcs[node_arcs[i]];
					if (it.isVisited(prev_arc.to)) continue;
					if (prev_arc.m_duration <= arc.m_duration) {
						// TODO(veselin): This is a bit slow for the cases when there are several seconds long arcs.
						if (covered_arcs.count(prev_arc.to) == 0) {
							num_added_arcs += graph->addArcIfNeeded(prev_arc.to, arc.to);
						}
						covered_arcs.insert(
								graph->nodePredecessors(prev_arc.to).begin(),
								graph->nodePredecessors(prev_arc.to).end());
					}
					if (prev_arc.m_duration == arc.m_duration) break;
				}
			}
			// If the previous timer has the same duration as the current one,
			// there's no need to explore more backwards.
			// If (the previous had strictly lower duration, there may be other
			// timers with higher than the previous duration, but lower that the
			// current duration).
			if (min_outgoing_duration[node_id] != arc.m_duration) {
				it.addNodeFollowers(node_id);
			}
		}

		min_outgoing_duration[arc.from] = std::min(
				min_outgoing_duration[arc.from],
				arc.m_duration);
		outgoing_arc_indices[arc.from].push_back(arci);
	}
	printf("Timers added %d new arcs\n", num_added_arcs);
}