text:
<?php

namespace Swarming\SubscribePro\Test\Unit\Model\Quote\SubscriptionOption;

use Magento\Framework\DataObject;
use Magento\Quote\Api\Data\CartItemInterface;
use Magento\Quote\Api\Data\ProductOptionExtensionFactory;
use Magento\Quote\Api\Data\ProductOptionExtensionInterface;
use Magento\Quote\Api\Data\ProductOptionInterface;
use Magento\Quote\Model\Quote\ProductOptionFactory;
use Swarming\SubscribePro\Api\Data\SubscriptionOptionInterface;
use Swarming\SubscribePro\Api\Data\SubscriptionOptionInterfaceFactory;
use Swarming\SubscribePro\Model\Quote\SubscriptionOption\OptionProcessor;
use Magento\Framework\DataObject\Factory as DataObjectFactory;

class OptionProcessorTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var \Swarming\SubscribePro\Model\Quote\SubscriptionOption\OptionProcessor
     */
    protected $optionProcessor;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject\Factory
     */
    protected $objectFactoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\ProductOptionFactory
     */
    protected $productOptionFactoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Api\Data\ProductOptionExtensionFactory
     */
    protected $extensionFactoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Swarming\SubscribePro\Api\Data\SubscriptionOptionInterfaceFactory
     */
    protected $subscriptionOptionFactoryMock;

    protected function setUp(): void
    {
        $this->objectFactoryMock = $this->getMockBuilder(DataObjectFactory::class)
            ->disableOriginalConstructor()->getMock();
        $this->productOptionFactoryMock = $this->getMockBuilder(ProductOptionFactory::class)
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();
        $this->extensionFactoryMock = $this->getMockBuilder(ProductOptionExtensionFactory::class)
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();
        $this->subscriptionOptionFactoryMock = $this->getMockBuilder(SubscriptionOptionInterfaceFactory::class)
            ->disableOriginalConstructor()
            ->setMethods(['create'])
            ->getMock();

        $this->optionProcessor = new OptionProcessor(
            $this->objectFactoryMock,
            $this->productOptionFactoryMock,
            $this->extensionFactoryMock,
            $this->subscriptionOptionFactoryMock
        );
    }

    public function testConvertToBuyRequestIfNoProductOption()
    {
        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->once())->method('getProductOption')->willReturn(null);

        $this->objectFactoryMock->expects($this->never())->method('create');

        $this->assertNull($this->optionProcessor->convertToBuyRequest($cartItemMock));
    }

    public function testConvertToBuyRequestIfNoExtensionAttributes()
    {
        $productOptionMock = $this->createProductOptionMock();
        $productOptionMock->expects($this->once())->method('getExtensionAttributes')->willReturn(null);

        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->exactly(2))->method('getProductOption')->willReturn($productOptionMock);

        $this->objectFactoryMock->expects($this->never())->method('create');

        $this->assertNull($this->optionProcessor->convertToBuyRequest($cartItemMock));
    }

    public function testConvertToBuyRequestIfNoSubscriptionOption()
    {
        $extensionAttributesMock = $this->createExtensionAttributesMock();
        $extensionAttributesMock->expects($this->once())
            ->method('getSubscriptionOption')
            ->willReturn(null);

        $productOptionMock = $this->createProductOptionMock();
        $productOptionMock->expects($this->exactly(2))
            ->method('getExtensionAttributes')
            ->willReturn($extensionAttributesMock);

        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->exactly(3))->method('getProductOption')->willReturn($productOptionMock);

        $this->objectFactoryMock->expects($this->never())->method('create');

        $this->assertNull($this->optionProcessor->convertToBuyRequest($cartItemMock));
    }

    /**
     * @param array $subscriptionOptions
     * @dataProvider convertToBuyRequestIfEmptySubscriptionOptionsDataProvider
     */
    public function testConvertToBuyRequestIfEmptySubscriptionOptions($subscriptionOptions)
    {
        $subscriptionOptionMock = $this->createSubscriptionOptionMock();
        $subscriptionOptionMock->expects($this->once())
            ->method('__toArray')
            ->willReturn($subscriptionOptions);

        $extensionAttributesMock = $this->createExtensionAttributesMock();
        $extensionAttributesMock->expects($this->exactly(2))
            ->method('getSubscriptionOption')
            ->willReturn($subscriptionOptionMock);

        $productOptionMock = $this->createProductOptionMock();
        $productOptionMock->expects($this->exactly(3))
            ->method('getExtensionAttributes')
            ->willReturn($extensionAttributesMock);

        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->exactly(4))->method('getProductOption')->willReturn($productOptionMock);

        $this->objectFactoryMock->expects($this->never())->method('create');

        $this->assertNull($this->optionProcessor->convertToBuyRequest($cartItemMock));
    }

    /**
     * @return array
     */
    public function convertToBuyRequestIfEmptySubscriptionOptionsDataProvider()
    {
        return [
            'Empty subscription options' => [
                'subscriptionOptions' => null,
            ],
            'Subscription options not array' => [
                'subscriptionOptions' => 'string',
            ],
            'Subscription options empty array' => [
                'subscriptionOptions' => 'string',
            ],
        ];
    }

    public function testConvertToBuyRequest()
    {
        $resultDataObject = $this->createDataObjectMock();

        $subscriptionOptions = ['array'];
        $subscriptionOptionMock = $this->createSubscriptionOptionMock();
        $subscriptionOptionMock->expects($this->once())
            ->method('__toArray')
            ->willReturn($subscriptionOptions);

        $extensionAttributesMock = $this->createExtensionAttributesMock();
        $extensionAttributesMock->expects($this->exactly(2))
            ->method('getSubscriptionOption')
            ->willReturn($subscriptionOptionMock);

        $productOptionMock = $this->createProductOptionMock();
        $productOptionMock->expects($this->exactly(3))
            ->method('getExtensionAttributes')
            ->willReturn($extensionAttributesMock);

        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->exactly(4))->method('getProductOption')->willReturn($productOptionMock);

        $this->objectFactoryMock->expects($this->once())
            ->method('create')
            ->with([OptionProcessor::KEY_SUBSCRIPTION_OPTION => $subscriptionOptions])
            ->willReturn($resultDataObject);

        $this->assertSame($resultDataObject, $this->optionProcessor->convertToBuyRequest($cartItemMock));
    }

    public function testProcessOptionsIfNoBuyRequest()
    {
        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->once())
            ->method('getOptionByCode')
            ->with('info_buyRequest')
            ->willReturn(null);
        $cartItemMock->expects($this->never())->method('setProductOption');

        $this->assertSame($cartItemMock, $this->optionProcessor->processOptions($cartItemMock));
    }

    /**
     * @param string $buyRequestValue
     * @dataProvider processOptionsIfNoSubscriptionOptionsDataProvider
     */
    public function testProcessOptionsIfNoSubscriptionOptions($buyRequestValue)
    {
        $buyRequestMock = $this->createBuyRequestMock();
        $buyRequestMock->expects($this->once())->method('getValue')->willReturn($buyRequestValue);

        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->exactly(2))
            ->method('getOptionByCode')
            ->with('info_buyRequest')
            ->willReturn($buyRequestMock);
        $cartItemMock->expects($this->never())->method('setProductOption');

        $this->assertSame($cartItemMock, $this->optionProcessor->processOptions($cartItemMock));
    }

    /**
     * @return array
     */
    public function processOptionsIfNoSubscriptionOptionsDataProvider()
    {
        return [
            'BuyRequest value not array' => [
                'buyRequestValue' => '',
            ],
            'BuyRequest value is empty array' => [
                'buyRequestValue' => json_encode([]),
            ],
            'BuyRequest value without subscription option' => [
                'buyRequestValue' => json_encode(['key' => 'value']),
            ],
            'Subscription option not array' => [
                'buyRequestValue' => json_encode([
                    'key' => 'value',
                    OptionProcessor::KEY_SUBSCRIPTION_OPTION => 'string'
                ]),
            ],
        ];
    }

    public function testProcessOptionsIfNoProductOption()
    {
        $subscriptionOptions = ['options'];
        $buyRequestValue = json_encode([
            'key' => 'value',
            OptionProcessor::KEY_SUBSCRIPTION_OPTION => $subscriptionOptions
        ]);
        $subscriptionOptionMock = $this->createSubscriptionOptionMock();

        $extensionAttributesMock = $this->createExtensionAttributesMock();
        $extensionAttributesMock->expects($this->once())
            ->method('setSubscriptionOption')
            ->with($subscriptionOptionMock);

        $productOptionMock = $this->createProductOptionMock();
        $productOptionMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($extensionAttributesMock);
        $productOptionMock->expects($this->once())
            ->method('setExtensionAttributes')
            ->willReturn($extensionAttributesMock);

        $buyRequestMock = $this->createBuyRequestMock();
        $buyRequestMock->expects($this->once())->method('getValue')->willReturn($buyRequestValue);

        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->exactly(2))
            ->method('getOptionByCode')
            ->with('info_buyRequest')
            ->willReturn($buyRequestMock);
        $cartItemMock->expects($this->once())
            ->method('getProductOption')
            ->willReturn(null);
        $cartItemMock->expects($this->once())
            ->method('setProductOption')
            ->with($productOptionMock);

        $this->subscriptionOptionFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($subscriptionOptionMock);

        $this->productOptionFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($productOptionMock);

        $this->assertSame($cartItemMock, $this->optionProcessor->processOptions($cartItemMock));
    }

    public function testProcessOptionsIfNoExtensionAttributes()
    {
        $subscriptionOptions = ['options'];
        $buyRequestValue = json_encode([
            'key' => 'value',
            OptionProcessor::KEY_SUBSCRIPTION_OPTION => $subscriptionOptions
        ]);
        $subscriptionOptionMock = $this->createSubscriptionOptionMock();

        $extensionAttributesMock = $this->createExtensionAttributesMock();
        $extensionAttributesMock->expects($this->once())
            ->method('setSubscriptionOption')
            ->with($subscriptionOptionMock);

        $productOptionMock = $this->createProductOptionMock();
        $productOptionMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn(null);
        $productOptionMock->expects($this->once())
            ->method('setExtensionAttributes')
            ->willReturn($extensionAttributesMock);

        $buyRequestMock = $this->createBuyRequestMock();
        $buyRequestMock->expects($this->once())->method('getValue')->willReturn($buyRequestValue);

        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->exactly(2))
            ->method('getOptionByCode')
            ->with('info_buyRequest')
            ->willReturn($buyRequestMock);
        $cartItemMock->expects($this->once())
            ->method('getProductOption')
            ->willReturn(null);
        $cartItemMock->expects($this->once())
            ->method('setProductOption')
            ->with($productOptionMock);

        $this->subscriptionOptionFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($subscriptionOptionMock);

        $this->productOptionFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($productOptionMock);

        $this->extensionFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($extensionAttributesMock);

        $this->assertSame($cartItemMock, $this->optionProcessor->processOptions($cartItemMock));
    }

    public function testProcessOptions()
    {
        $subscriptionOptions = ['options'];
        $buyRequestValue = json_encode([
            'key' => 'value',
            OptionProcessor::KEY_SUBSCRIPTION_OPTION => $subscriptionOptions
        ]);
        $subscriptionOptionMock = $this->createSubscriptionOptionMock();

        $extensionAttributesMock = $this->createExtensionAttributesMock();
        $extensionAttributesMock->expects($this->once())
            ->method('setSubscriptionOption')
            ->with($subscriptionOptionMock);

        $productOptionMock = $this->createProductOptionMock();
        $productOptionMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($extensionAttributesMock);
        $productOptionMock->expects($this->once())
            ->method('setExtensionAttributes')
            ->willReturn($extensionAttributesMock);

        $buyRequestMock = $this->createBuyRequestMock();
        $buyRequestMock->expects($this->once())->method('getValue')->willReturn($buyRequestValue);

        $cartItemMock = $this->createCartItemMock();
        $cartItemMock->expects($this->exactly(2))
            ->method('getOptionByCode')
            ->with('info_buyRequest')
            ->willReturn($buyRequestMock);
        $cartItemMock->expects($this->once())
            ->method('getProductOption')
            ->willReturn($productOptionMock);
        $cartItemMock->expects($this->once())
            ->method('setProductOption')
            ->with($productOptionMock);

        $this->subscriptionOptionFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($subscriptionOptionMock);

        $this->productOptionFactoryMock->expects($this->never())->method('create');
        $this->extensionFactoryMock->expects($this->never())->method('create');

        $this->assertSame($cartItemMock, $this->optionProcessor->processOptions($cartItemMock));
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Api\Data\CartItemInterface
     */
    private function createCartItemMock()
    {
        return $this->getMockBuilder(CartItemInterface::class)
            ->setMethods(['getOptionByCode', 'getProductOption', 'setProductOption'])
            ->getMockForAbstractClass();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Api\Data\ProductOptionInterface
     */
    private function createProductOptionMock()
    {
        return $this->getMockBuilder(ProductOptionInterface::class)->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject
     */
    private function createDataObjectMock()
    {
        return $this->getMockBuilder(DataObject::class)->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\DataObject
     */
    private function createBuyRequestMock()
    {
        return $this->getMockBuilder(DataObject::class)
            ->setMethods(['getValue'])
            ->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Api\Data\ProductOptionExtensionInterface
     */
    private function createExtensionAttributesMock()
    {
        return $this->getMockBuilder(ProductOptionExtensionInterface::class)
            ->setMethods(['getSubscriptionOption', 'setSubscriptionOption'])
            ->getMockForAbstractClass();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Swarming\SubscribePro\Api\Data\SubscriptionOptionInterface
     */
    private function createSubscriptionOptionMock()
    {
        return $this->getMockBuilder(SubscriptionOptionInterface::class)
            ->setMethods(['__toArray'])
            ->getMockForAbstractClass();
    }
}


text:
package com.topicsbot.services.api.telegram.handlers.user;

import com.topicsbot.model.chat.Chat;
import com.topicsbot.model.statistics.CounterType;
import com.topicsbot.services.analysis.AnalysisProvider;
import com.topicsbot.services.api.telegram.handlers.UpdateHandler;
import com.topicsbot.services.api.telegram.model.Message;
import com.topicsbot.services.api.telegram.model.Update;
import com.topicsbot.services.cache.CacheService;
import com.topicsbot.services.db.dao.ChatDAO;
import com.topicsbot.services.db.dao.UserDAO;

/**
 * Author: Artem Voronov
 */
public class ToStatisticsUserHandler extends CommonUserHandler implements UpdateHandler{

  private final AnalysisProvider analysisProvider;
  private final ChatDAO chatDAO;

  public ToStatisticsUserHandler(AnalysisProvider analysisProvider, CacheService cache,
                                 ChatDAO chatDAO, UserDAO userDAO) {
    super(cache, userDAO);
    this.analysisProvider = analysisProvider;
    this.chatDAO = chatDAO;
  }

  @Override
  public void handle(Update update) {
    Message message = update.getMessage();

    if (message == null)
      return;

    Chat chat = chatDAO.find(message.getChatId());

    String text = message.getText();

    if (text == null)
      return;

    text = text.trim();
    analysisProvider.index(text, chat);

    int wordsCount = getWordCounter(message);
    int floodSize = getFloodSize(message);

    updateChatCounters(chat, CounterType.FLOOD, floodSize);
    updateChatCounters(chat, CounterType.WORDS, wordsCount);
    updateChatCounters(chat, CounterType.MESSAGES, 1);

    updateUserCounter(message, chat, CounterType.FLOOD, floodSize);
    updateUserCounter(message, chat, CounterType.WORDS, wordsCount);
    updateUserCounter(message, chat, CounterType.MESSAGES, 1);
  }

  private static int getWordCounter(Message message) {
    return !message.hasText() ? 0 : message.getText().split(" ").length;
  }

  private static int getFloodSize(Message message) {
    return !message.hasText() ? 0 : message.getText().replaceAll("\\s+", "").length();
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace gvisor {
namespace testing {

namespace {

TEST(LseekTest, InvalidWhence) {
  const std::string kFileData = "hello world\n";
  const TempPath path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      GetAbsoluteTestTmpdir(), kFileData, TempPath::kDefaultFileMode));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(path.path(), O_RDWR, 0644));

  ASSERT_THAT(lseek(fd.get(), 0, -1), SyscallFailsWithErrno(EINVAL));
}

TEST(LseekTest, NegativeOffset) {
  const std::string kFileData = "hello world\n";
  const TempPath path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      GetAbsoluteTestTmpdir(), kFileData, TempPath::kDefaultFileMode));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(path.path(), O_RDWR, 0644));

  EXPECT_THAT(lseek(fd.get(), -(kFileData.length() + 1), SEEK_CUR),
              SyscallFailsWithErrno(EINVAL));
}

// A 32-bit off_t is not large enough to represent an offset larger than
// maximum file size on standard file systems, so it isn't possible to cause
// overflow.
#if defined(__x86_64__) || defined(__aarch64__)
TEST(LseekTest, Overflow) {
  // HA! Classic Linux. We really should have an EOVERFLOW
  // here, since we're seeking to something that cannot be
  // represented.. but instead we are given an EINVAL.
  const std::string kFileData = "hello world\n";
  const TempPath path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      GetAbsoluteTestTmpdir(), kFileData, TempPath::kDefaultFileMode));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(path.path(), O_RDWR, 0644));
  EXPECT_THAT(lseek(fd.get(), 0x7fffffffffffffff, SEEK_END),
              SyscallFailsWithErrno(EINVAL));
}
#endif

TEST(LseekTest, Set) {
  const std::string kFileData = "hello world\n";
  const TempPath path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      GetAbsoluteTestTmpdir(), kFileData, TempPath::kDefaultFileMode));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(path.path(), O_RDWR, 0644));

  char buf = '\0';
  EXPECT_THAT(lseek(fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
  ASSERT_THAT(read(fd.get(), &buf, 1), SyscallSucceedsWithValue(1));
  EXPECT_EQ(buf, kFileData.c_str()[0]);
  EXPECT_THAT(lseek(fd.get(), 6, SEEK_SET), SyscallSucceedsWithValue(6));
  ASSERT_THAT(read(fd.get(), &buf, 1), SyscallSucceedsWithValue(1));
  EXPECT_EQ(buf, kFileData.c_str()[6]);
}

TEST(LseekTest, Cur) {
  const std::string kFileData = "hello world\n";
  const TempPath path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      GetAbsoluteTestTmpdir(), kFileData, TempPath::kDefaultFileMode));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(path.path(), O_RDWR, 0644));

  char buf = '\0';
  EXPECT_THAT(lseek(fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
  ASSERT_THAT(read(fd.get(), &buf, 1), SyscallSucceedsWithValue(1));
  EXPECT_EQ(buf, kFileData.c_str()[0]);
  EXPECT_THAT(lseek(fd.get(), 3, SEEK_CUR), SyscallSucceedsWithValue(4));
  ASSERT_THAT(read(fd.get(), &buf, 1), SyscallSucceedsWithValue(1));
  EXPECT_EQ(buf, kFileData.c_str()[4]);
}

TEST(LseekTest, End) {
  const std::string kFileData = "hello world\n";
  const TempPath path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
      GetAbsoluteTestTmpdir(), kFileData, TempPath::kDefaultFileMode));
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open(path.path(), O_RDWR, 0644));

  char buf = '\0';
  EXPECT_THAT(lseek(fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
  ASSERT_THAT(read(fd.get(), &buf, 1), SyscallSucceedsWithValue(1));
  EXPECT_EQ(buf, kFileData.c_str()[0]);
  EXPECT_THAT(lseek(fd.get(), -2, SEEK_END), SyscallSucceedsWithValue(10));
  ASSERT_THAT(read(fd.get(), &buf, 1), SyscallSucceedsWithValue(1));
  EXPECT_EQ(buf, kFileData.c_str()[kFileData.length() - 2]);
}

TEST(LseekTest, InvalidFD) {
  EXPECT_THAT(lseek(-1, 0, SEEK_SET), SyscallFailsWithErrno(EBADF));
}

TEST(LseekTest, DirCurEnd) {
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(
      Open(GetAbsoluteTestTmpdir().c_str(), O_RDONLY));
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(0));
}

TEST(LseekTest, ProcDir) {
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open("/proc/self", O_RDONLY));
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_CUR), SyscallSucceeds());
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_END), SyscallSucceeds());
}

TEST(LseekTest, ProcFile) {
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open("/proc/meminfo", O_RDONLY));
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_CUR), SyscallSucceeds());
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_END), SyscallFailsWithErrno(EINVAL));
}

TEST(LseekTest, SysDir) {
  const FileDescriptor fd =
      ASSERT_NO_ERRNO_AND_VALUE(Open("/sys/devices", O_RDONLY));
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_CUR), SyscallSucceeds());
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_END), SyscallSucceeds());
}

TEST(LseekTest, SeekCurrentDir) {
  // From include/linux/fs.h.
  constexpr loff_t MAX_LFS_FILESIZE = 0x7fffffffffffffff;

  char* dir = getcwd(NULL, 0);
  const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(dir, O_RDONLY));

  ASSERT_THAT(lseek(fd.get(), 0, SEEK_CUR), SyscallSucceeds());
  ASSERT_THAT(lseek(fd.get(), 0, SEEK_END),
              // Some filesystems (like ext4) allow lseek(SEEK_END) on a
              // directory and return MAX_LFS_FILESIZE, others return EINVAL.
              AnyOf(SyscallSucceedsWithValue(MAX_LFS_FILESIZE),
                    SyscallFailsWithErrno(EINVAL)));
  free(dir);
}

TEST(LseekTest, ProcStatTwice) {
  const FileDescriptor fd1 =
      ASSERT_NO_ERRNO_AND_VALUE(Open("/proc/stat", O_RDONLY));
  const FileDescriptor fd2 =
      ASSERT_NO_ERRNO_AND_VALUE(Open("/proc/stat", O_RDONLY));

  ASSERT_THAT(lseek(fd1.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(0));
  ASSERT_THAT(lseek(fd1.get(), 0, SEEK_END), SyscallFailsWithErrno(EINVAL));
  ASSERT_THAT(lseek(fd1.get(), 1000, SEEK_CUR), SyscallSucceeds());
  // Check that just because we moved fd1, fd2 doesn't move.
  ASSERT_THAT(lseek(fd2.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(0));

  const FileDescriptor fd3 =
      ASSERT_NO_ERRNO_AND_VALUE(Open("/proc/stat", O_RDONLY));
  ASSERT_THAT(lseek(fd3.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(0));
}

TEST(LseekTest, EtcPasswdDup) {
  const FileDescriptor fd1 =
      ASSERT_NO_ERRNO_AND_VALUE(Open("/etc/passwd", O_RDONLY));
  const FileDescriptor fd2 = ASSERT_NO_ERRNO_AND_VALUE(fd1.Dup());

  ASSERT_THAT(lseek(fd1.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(0));
  ASSERT_THAT(lseek(fd2.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(0));
  ASSERT_THAT(lseek(fd1.get(), 1000, SEEK_CUR), SyscallSucceeds());
  // Check that just because we moved fd1, fd2 doesn't move.
  ASSERT_THAT(lseek(fd2.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(1000));

  const FileDescriptor fd3 = ASSERT_NO_ERRNO_AND_VALUE(fd1.Dup());
  ASSERT_THAT(lseek(fd3.get(), 0, SEEK_CUR), SyscallSucceedsWithValue(1000));
}

// TODO(magi): Add tests where we have donated in sockets.

}  // namespace

}  // namespace testing
}  // namespace gvisor


text:
package ai.verta.swagger._public.uac.audit.model

import scala.util.Try

import net.liftweb.json._

import ai.verta.swagger.client.objects._

case class VersioningAddAuditLogBatchResponse (
  response_rows: Option[List[VersioningBatchResponseRow]] = None
) extends BaseSwagger {
  def toJson(): JValue = VersioningAddAuditLogBatchResponse.toJson(this)
}

object VersioningAddAuditLogBatchResponse {
  def toJson(obj: VersioningAddAuditLogBatchResponse): JObject = {
    new JObject(
      List[Option[JField]](
        obj.response_rows.map(x => JField("response_rows", ((x: List[VersioningBatchResponseRow]) => JArray(x.map(((x: VersioningBatchResponseRow) => VersioningBatchResponseRow.toJson(x)))))(x)))
      ).flatMap(x => x match {
        case Some(y) => List(y)
        case None => Nil
      })
    )
  }

  def fromJson(value: JValue): VersioningAddAuditLogBatchResponse =
    value match {
      case JObject(fields) => {
        val fieldsMap = fields.map(f => (f.name, f.value)).toMap
        VersioningAddAuditLogBatchResponse(
          // TODO: handle required
          response_rows = fieldsMap.get("response_rows").map((x: JValue) => x match {case JArray(elements) => elements.map(VersioningBatchResponseRow.fromJson); case _ => throw new IllegalArgumentException(s"unknown type ${x.getClass.toString}")})
        )
      }
      case _ => throw new IllegalArgumentException(s"unknown type ${value.getClass.toString}")
    }
}


text:
<?php

namespace Intacct\Functions\Common\Query\Comparison\GreaterThanOrEqualTo;

use Intacct\Functions\Common\Query\Comparison\AbstractString;

class GreaterThanOrEqualToString extends AbstractString
{

    /**
     * @return string
     */
    public function __toString(): string
    {
        $clause = '';
        if ($this->isNegate() === true) {
            $clause = 'NOT ';
        }
        $clause .= $this->getField() . " >= '" . addcslashes($this->getValue(), "'") . "'";

        return $clause;
    }
}


text:
package uk.co.qmunity.lib.vec;

import java.util.ArrayList;
import java.util.List;

import net.minecraft.world.World;

public class VectorList extends ArrayList<Vec3d> {

    public VectorList(List<Vec3d> copied) {

        this();
        addAll(copied);
    }

    public VectorList() {

        super();
    }

    private static final long serialVersionUID = 1L;

    public boolean add(double x, double y, double z) {

        return super.add(new Vec3d(x, y, z));
    }

    public boolean add(double x, double y, double z, World w) {

        return super.add(new Vec3d(x, y, z, w));
    }

    public boolean remove(double x, double y, double z) {

        return super.remove(new Vec3d(x, y, z));
    }

    public boolean remove(double x, double y, double z, World w) {

        return super.remove(new Vec3d(x, y, z, w));
    }

}


text:
+++
title = "Tasks | Documentation"
type = "docs"
category = "docs"
lang = "en"
basename = "tasks.html"
+++

# Tasks

Task is a script that runs on remote or local servers. You can use it to automate your system administration tasks.

## Example

~~~lua
task "example" {
    description = "example task",

    targets = {
        "web",
    },

    filters = {
        "production",
    },

    backend = "local",

    parallel = true,

    prefix = true,

    script = {
        "echo foo",
        "echo bar"
    },
}
~~~

Notice: Task name mustn't be duplicated with any host names.

You can run a task below command.

~~~
$ essh example
~~~

You can pass arguments to a task.

~~~
$ essh example foo bar
~~~

## Properties

* `description` (string): Description of the task.

* `pty` (boolean): If it is true, SSH connection allocates pseudo-terminal by running ssh command with multiple -t options like `ssh -t -t`.

* `driver` (string): driver name is used in the task. see [Drivers](drivers.html).

* `parallel` (boolean): If it is true, runs task's script in parallel.

* `privileged` (boolean): If it is true, runs task's script by privileged user. If you use it, you have to configure your machine to be able to be used `sudo` without password.

* `user` (string): Runs task's script by specific user. If you use it, you have to configure your machine to be able to be used `sudo` without password.

* `hidden` (boolean): If it is true, this task is not displayed in tasks list.

* `targets` (string|table): Host names or tags that the task's scripts is executed for.

* `filters` (string|table): Host names or tags to filter target hosts. This property must be used with `targets`.

* `backend` (string): A place where the task's scripts will be executed on. You can set value only `remote` or `local`.

* `prefix` (boolean|string): If it is true, Essh displays task's output with hostname prefix. If it is string, Essh displays task's output with custom prefix. This string can be used with text/template format like `{{.Host.Name}}`.

* `prepare` (function): Prepare is a function to be executed when the task starts. See example:

    ~~~lua
    prepare = function (t)
        -- override task config
        t.targets = "web"
        -- get command line arguments
        print(t.args[1])
        -- cancel the task execution by returns false.
        return false
    end,
    ~~~

    By the prepare function returns false, you can cancel to execute the task's script.

* `props` (table): Props sets environment variables `ESSH_TASK_PROPS_${KEY}=VALUE` when the task is executed. The table key is modified to upper cased.

    ~~~lua
    props = {
        foo = "bar",
    }

    -- export ESSH_TASK_PROPS_FOO="bar"
    ~~~

* `script` (string|table): Code that will be executed. Example:

    ~~~lua
    script = [=[
        echo aaa
        echo bbb
        echo ccc
    ]=]
    ~~~

    or

    ~~~lua
    script = {
        "echo aaa",
        "echo bbb",
        "echo ccc",
    }
    ~~~

    If you set it as a table, Essh concatenates strings in the table with newline code. And Essh runs the script as a bash script. But this is just default behavior. You can change it by [Drivers](drivers.html).

    You can use predefined environment variables in your script, See below:

  * `ESSH_TASK_NAME`: Task name.

  * `ESSH_SSH_CONFIG`: Generated ssh_config file path.

  * `ESSH_DEBUG`: If you set `--debug` option by CLI. this variable is set "1".

  * `ESSH_TASK_PROPS_${KEY}`: The value that is set by task's `props`.

  * `ESSH_TASK_ARGS_${INDEX}`: The argument's value that is passed by a command line arguments. The index starts at '1'.

  * `ESSH_HOSTNAME`: Host name.

  * `ESSH_HOST_HOSTNAME`: Host name.

  * `ESSH_HOST_SSH_{SSH_CONFIG_KEY}`: ssh_config key/value pare.

  * `ESSH_HOST_TAGS_{TAG}`: Tag. If you set a tag, This variable has a value "1".

  * `ESSH_HOST_PROPS_{KEY}`: The value that is set by host's `props`. See [Hosts](hosts.html).

  * `ESSH_NAMESPACE_NAME`: Namespace name. See [Namespaces](namespaces.html).

* `script_file` (string): A file path or URL that can be accessed by http or https. The file's content will be executed. You can't use `script_file` and `script` at the same time.


text:
package com.jaamsim.render;

import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener;
import com.jogamp.newt.event.MouseEvent;

public interface WindowInteractionListener extends KeyListener {

	// Flags used as modifiers
	public static int MOD_SHIFT = 	1;
	public static int MOD_ALT = 	2;
	public static int MOD_CTRL = 	4;

	/**
	 *
	 * @author matt.chudleigh
	 *
	 */
	public static class DragInfo {
		public int windowID;
		public int x, y; // the current position
		public int dx, dy; // The change in x, y since the last dragged event
		public int startX, startY; // The point where the mouse first went down
		public int button; // the button that went down
		public int modFlags; // Modifiers

		public boolean shiftDown() {
			return (modFlags & MOD_SHIFT) != 0;
		}
		public boolean altDown() {
			return (modFlags & MOD_ALT) != 0;
		}
		public boolean controlDown() {
			return (modFlags & MOD_CTRL) != 0;
		}
	}
	/**
	 * The mouse was dragged in this window.
	 * @param info - a struct containing all the information for this drag event (this is just cleaner)
	 */
	public void mouseDragged(DragInfo info);

	/**
	 * The mouse wheel was moved
	 * @param windowID
	 * @param x
	 * @param y
	 * @param wheelRotation - the number of mouse wheel 'ticks'
	 */
	public void mouseWheelMoved(int windowID, int x, int y, int wheelRotation, int modifiers);

	/**
	 * A click occurred, registered on mouse button release
	 * @param windowID
	 * @param x
	 * @param y
	 */
	public void mouseClicked(int windowID, int x, int y, int button, int modifiers, short count);

	/**
	 * Basic mouse motion
	 * @param windowID
	 * @param x
	 * @param y
	 */
	public void mouseMoved(int windowID, int x, int y);

	/**
	 * Track mouse entry/exit
	 * @param isInWindow
	 */
	public void mouseEntry(int windowID, int x, int y, boolean isInWindow);

	/**
	 * Callback for mouse button press/release
	 * @param windowID
	 * @param x
	 * @param y
	 * @param button
	 * @param isDown
	 */
	public void mouseButtonDown(int windowID, int x, int y, int button, boolean isDown, int modifiers);

	/**
	 * In the event that the above definitions do not provide enough useful information, the
	 * raw NEWT mouse events can also be hooked
	 * @param me
	 */
	public void rawMouseEvent(MouseEvent me);

	/**
	 * The window is closing
	 */
	public void windowClosing();

	/**
	 * This window gained focus
	 */
	public void windowGainedFocus();
	public void windowMoved(int x, int y, int width, int height);

	@Override
	public void keyPressed(KeyEvent event);
	@Override
	public void keyReleased(KeyEvent event);
}


text:
package org.wikipedia.dataclient.restbase;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.wikipedia.dataclient.mwapi.page.MwMobileViewPageLead;
import org.wikipedia.dataclient.restbase.page.RbPageLead;
import org.wikipedia.server.BasePageLeadTest;
import org.wikipedia.test.TestRunner;

import static org.wikipedia.json.GsonUnmarshaller.unmarshal;

/**
 * Tests serialization via Gson.
 * Note the ApiService uses formatversion=2 for requests which return booleans in the responses.
 */
@RunWith(TestRunner.class)
public class RbPageLeadTest extends BasePageLeadTest {
    @Test
    public void testEnglishMainPage() throws Exception {
        RbPageLead props = unmarshal(RbPageLead.class, getEnglishMainPageJson());
        verifyEnglishMainPage(props);
    }

    @Test
    public void testUnprotectedDisambiguationPage() throws Exception {
        RbPageLead props = unmarshal(RbPageLead.class, getUnprotectedDisambiguationPageJson());
        verifyUnprotectedDisambiguationPage(props);
    }

    /**
     * Custom deserializer; um, yeah /o\.
     * An earlier version had issues with protection settings that don't include "edit" protection.
     */
    @Test
    public void testProtectedButNoEditProtectionPage() throws Exception {
        RbPageLead props = unmarshal(RbPageLead.class, getProtectedButNoEditProtectionPageJson());
        verifyProtectedNoEditProtectionPage(props);
    }

    /**
     * Test an error case
     */
    @Test
    public void testError() throws Exception {
        MwMobileViewPageLead pageLead = unmarshal(MwMobileViewPageLead.class, getErrorJson());
        MwMobileViewPageLead.Mobileview props = pageLead.getMobileview();
        verifyError(pageLead, props);
    }
}


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

<title>Uses of Interface java.util.stream.Collector (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<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

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
java.util.stream.Collector

Packages that use Collector

Package
Description

java.util.stream

Classes to support functional-style operations on streams of elements, such
 as map-reduce transformations on collections.

Uses of Collector in java.util.stream

Methods in java.util.stream that return Collector

Modifier and Type
Method and Description

static <T> Collector<T,?,Double>
Collectors.averagingDouble(ToDoubleFunction<? super T> mapper)

Returns a Collector that produces the arithmetic mean of a double-valued
 function applied to the input elements.

static <T> Collector<T,?,Double>
Collectors.averagingInt(ToIntFunction<? super T> mapper)

Returns a Collector that produces the arithmetic mean of an integer-valued
 function applied to the input elements.

static <T> Collector<T,?,Double>
Collectors.averagingLong(ToLongFunction<? super T> mapper)

Returns a Collector that produces the arithmetic mean of a long-valued
 function applied to the input elements.

static <T,A,R,RR> Collector<T,A,RR>
Collectors.collectingAndThen(Collector<T,A,R> downstream,
                 Function<R,RR> finisher)

Adapts a Collector to perform an additional finishing
 transformation.

static <T> Collector<T,?,Long>
Collectors.counting()

Returns a Collector accepting elements of type T that
 counts the number of input elements.

static <T,K> Collector<T,?,Map<K,List<T>>>
Collectors.groupingBy(Function<? super T,? extends K> classifier)

Returns a Collector implementing a "group by" operation on
 input elements of type T, grouping elements according to a
 classification function, and returning the results in a Map.

static <T,K,A,D> Collector<T,?,Map<K,D>>
Collectors.groupingBy(Function<? super T,? extends K> classifier,
          Collector<? super T,A,D> downstream)

Returns a Collector implementing a cascaded "group by" operation
 on input elements of type T, grouping elements according to a
 classification function, and then performing a reduction operation on
 the values associated with a given key using the specified downstream
 Collector.

static <T,K,D,A,M extends Map<K,D>>
Collector<T,?,M>
Collectors.groupingBy(Function<? super T,? extends K> classifier,
          Supplier<M> mapFactory,
          Collector<? super T,A,D> downstream)

Returns a Collector implementing a cascaded "group by" operation
 on input elements of type T, grouping elements according to a
 classification function, and then performing a reduction operation on
 the values associated with a given key using the specified downstream
 Collector.

static <T,K> Collector<T,?,ConcurrentMap<K,List<T>>>
Collectors.groupingByConcurrent(Function<? super T,? extends K> classifier)

Returns a concurrent Collector implementing a "group by"
 operation on input elements of type T, grouping elements
 according to a classification function.

static <T,K,A,D> Collector<T,?,ConcurrentMap<K,D>>
Collectors.groupingByConcurrent(Function<? super T,? extends K> classifier,
                    Collector<? super T,A,D> downstream)

Returns a concurrent Collector implementing a cascaded "group by"
 operation on input elements of type T, grouping elements
 according to a classification function, and then performing a reduction
 operation on the values associated with a given key using the specified
 downstream Collector.

static <T,K,A,D,M extends ConcurrentMap<K,D>>
Collector<T,?,M>
Collectors.groupingByConcurrent(Function<? super T,? extends K> classifier,
                    Supplier<M> mapFactory,
                    Collector<? super T,A,D> downstream)

Returns a concurrent Collector implementing a cascaded "group by"
 operation on input elements of type T, grouping elements
 according to a classification function, and then performing a reduction
 operation on the values associated with a given key using the specified
 downstream Collector.

static Collector<CharSequence,?,String>
Collectors.joining()

Returns a Collector that concatenates the input elements into a
 String, in encounter order.

static Collector<CharSequence,?,String>
Collectors.joining(CharSequence delimiter)

Returns a Collector that concatenates the input elements,
 separated by the specified delimiter, in encounter order.

static Collector<CharSequence,?,String>
Collectors.joining(CharSequence delimiter,
       CharSequence prefix,
       CharSequence suffix)

Returns a Collector that concatenates the input elements,
 separated by the specified delimiter, with the specified prefix and
 suffix, in encounter order.

static <T,U,A,R> Collector<T,?,R>
Collectors.mapping(Function<? super T,? extends U> mapper,
       Collector<? super U,A,R> downstream)

Adapts a Collector accepting elements of type U to one
 accepting elements of type T by applying a mapping function to
 each input element before accumulation.

static <T> Collector<T,?,Optional<T>>
Collectors.maxBy(Comparator<? super T> comparator)

Returns a Collector that produces the maximal element according
 to a given Comparator, described as an Optional<T>.

static <T> Collector<T,?,Optional<T>>
Collectors.minBy(Comparator<? super T> comparator)

Returns a Collector that produces the minimal element according
 to a given Comparator, described as an Optional<T>.

static <T,A,R> Collector<T,A,R>
Collector.of(Supplier<A> supplier,
  BiConsumer<A,T> accumulator,
  BinaryOperator<A> combiner,
  Function<A,R> finisher,
  Collector.Characteristics... characteristics)

Returns a new Collector described by the given supplier,
 accumulator, combiner, and finisher functions.

static <T,R> Collector<T,R,R>
Collector.of(Supplier<R> supplier,
  BiConsumer<R,T> accumulator,
  BinaryOperator<R> combiner,
  Collector.Characteristics... characteristics)

Returns a new Collector described by the given supplier,
 accumulator, and combiner functions.

static <T> Collector<T,?,Map<Boolean,List<T>>>
Collectors.partitioningBy(Predicate<? super T> predicate)

Returns a Collector which partitions the input elements according
 to a Predicate, and organizes them into a
 Map<Boolean, List<T>>.

static <T,D,A> Collector<T,?,Map<Boolean,D>>
Collectors.partitioningBy(Predicate<? super T> predicate,
              Collector<? super T,A,D> downstream)

Returns a Collector which partitions the input elements according
 to a Predicate, reduces the values in each partition according to
 another Collector, and organizes them into a
 Map<Boolean, D> whose values are the result of the downstream
 reduction.

static <T> Collector<T,?,Optional<T>>
Collectors.reducing(BinaryOperator<T> op)

Returns a Collector which performs a reduction of its
 input elements under a specified BinaryOperator.

static <T> Collector<T,?,T>
Collectors.reducing(T identity,
        BinaryOperator<T> op)

Returns a Collector which performs a reduction of its
 input elements under a specified BinaryOperator using the
 provided identity.

static <T,U> Collector<T,?,U>
Collectors.reducing(U identity,
        Function<? super T,? extends U> mapper,
        BinaryOperator<U> op)

Returns a Collector which performs a reduction of its
 input elements under a specified mapping function and
 BinaryOperator.

static <T> Collector<T,?,DoubleSummaryStatistics>
Collectors.summarizingDouble(ToDoubleFunction<? super T> mapper)

Returns a Collector which applies an double-producing
 mapping function to each input element, and returns summary statistics
 for the resulting values.

static <T> Collector<T,?,IntSummaryStatistics>
Collectors.summarizingInt(ToIntFunction<? super T> mapper)

Returns a Collector which applies an int-producing
 mapping function to each input element, and returns summary statistics
 for the resulting values.

static <T> Collector<T,?,LongSummaryStatistics>
Collectors.summarizingLong(ToLongFunction<? super T> mapper)

Returns a Collector which applies an long-producing
 mapping function to each input element, and returns summary statistics
 for the resulting values.

static <T> Collector<T,?,Double>
Collectors.summingDouble(ToDoubleFunction<? super T> mapper)

Returns a Collector that produces the sum of a double-valued
 function applied to the input elements.

static <T> Collector<T,?,Integer>
Collectors.summingInt(ToIntFunction<? super T> mapper)

Returns a Collector that produces the sum of a integer-valued
 function applied to the input elements.

static <T> Collector<T,?,Long>
Collectors.summingLong(ToLongFunction<? super T> mapper)

Returns a Collector that produces the sum of a long-valued
 function applied to the input elements.

static <T,C extends Collection<T>>
Collector<T,?,C>
Collectors.toCollection(Supplier<C> collectionFactory)

Returns a Collector that accumulates the input elements into a
 new Collection, in encounter order.

static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>
Collectors.toConcurrentMap(Function<? super T,? extends K> keyMapper,
               Function<? super T,? extends U> valueMapper)

Returns a concurrent Collector that accumulates elements into a
 ConcurrentMap whose keys and values are the result of applying
 the provided mapping functions to the input elements.

static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>
Collectors.toConcurrentMap(Function<? super T,? extends K> keyMapper,
               Function<? super T,? extends U> valueMapper,
               BinaryOperator<U> mergeFunction)

Returns a concurrent Collector that accumulates elements into a
 ConcurrentMap whose keys and values are the result of applying
 the provided mapping functions to the input elements.

static <T,K,U,M extends ConcurrentMap<K,U>>
Collector<T,?,M>
Collectors.toConcurrentMap(Function<? super T,? extends K> keyMapper,
               Function<? super T,? extends U> valueMapper,
               BinaryOperator<U> mergeFunction,
               Supplier<M> mapSupplier)

Returns a concurrent Collector that accumulates elements into a
 ConcurrentMap whose keys and values are the result of applying
 the provided mapping functions to the input elements.

static <T> Collector<T,?,List<T>>
Collectors.toList()

Returns a Collector that accumulates the input elements into a
 new List.

static <T,K,U> Collector<T,?,Map<K,U>>
Collectors.toMap(Function<? super T,? extends K> keyMapper,
     Function<? super T,? extends U> valueMapper)

Returns a Collector that accumulates elements into a
 Map whose keys and values are the result of applying the provided
 mapping functions to the input elements.

static <T,K,U> Collector<T,?,Map<K,U>>
Collectors.toMap(Function<? super T,? extends K> keyMapper,
     Function<? super T,? extends U> valueMapper,
     BinaryOperator<U> mergeFunction)

Returns a Collector that accumulates elements into a
 Map whose keys and values are the result of applying the provided
 mapping functions to the input elements.

static <T,K,U,M extends Map<K,U>>
Collector<T,?,M>
Collectors.toMap(Function<? super T,? extends K> keyMapper,
     Function<? super T,? extends U> valueMapper,
     BinaryOperator<U> mergeFunction,
     Supplier<M> mapSupplier)

Returns a Collector that accumulates elements into a
 Map whose keys and values are the result of applying the provided
 mapping functions to the input elements.

static <T> Collector<T,?,Set<T>>
Collectors.toSet()

Returns a Collector that accumulates the input elements into a
 new Set.

Methods in java.util.stream with parameters of type Collector

Modifier and Type
Method and Description

<R,A> R
Stream.collect(Collector<? super T,A,R> collector)

Performs a mutable
 reduction operation on the elements of this stream using a
 Collector.

static <T,A,R,RR> Collector<T,A,RR>
Collectors.collectingAndThen(Collector<T,A,R> downstream,
                 Function<R,RR> finisher)

Adapts a Collector to perform an additional finishing
 transformation.

static <T,K,A,D> Collector<T,?,Map<K,D>>
Collectors.groupingBy(Function<? super T,? extends K> classifier,
          Collector<? super T,A,D> downstream)

Returns a Collector implementing a cascaded "group by" operation
 on input elements of type T, grouping elements according to a
 classification function, and then performing a reduction operation on
 the values associated with a given key using the specified downstream
 Collector.

static <T,K,D,A,M extends Map<K,D>>
Collector<T,?,M>
Collectors.groupingBy(Function<? super T,? extends K> classifier,
          Supplier<M> mapFactory,
          Collector<? super T,A,D> downstream)

Returns a Collector implementing a cascaded "group by" operation
 on input elements of type T, grouping elements according to a
 classification function, and then performing a reduction operation on
 the values associated with a given key using the specified downstream
 Collector.

static <T,K,A,D> Collector<T,?,ConcurrentMap<K,D>>
Collectors.groupingByConcurrent(Function<? super T,? extends K> classifier,
                    Collector<? super T,A,D> downstream)

Returns a concurrent Collector implementing a cascaded "group by"
 operation on input elements of type T, grouping elements
 according to a classification function, and then performing a reduction
 operation on the values associated with a given key using the specified
 downstream Collector.

static <T,K,A,D,M extends ConcurrentMap<K,D>>
Collector<T,?,M>
Collectors.groupingByConcurrent(Function<? super T,? extends K> classifier,
                    Supplier<M> mapFactory,
                    Collector<? super T,A,D> downstream)

Returns a concurrent Collector implementing a cascaded "group by"
 operation on input elements of type T, grouping elements
 according to a classification function, and then performing a reduction
 operation on the values associated with a given key using the specified
 downstream Collector.

static <T,U,A,R> Collector<T,?,R>
Collectors.mapping(Function<? super T,? extends U> mapper,
       Collector<? super U,A,R> downstream)

Adapts a Collector accepting elements of type U to one
 accepting elements of type T by applying a mapping function to
 each input element before accumulation.

static <T,D,A> Collector<T,?,Map<Boolean,D>>
Collectors.partitioningBy(Predicate<? super T> predicate,
              Collector<? super T,A,D> downstream)

Returns a Collector which partitions the input elements according
 to a Predicate, reduces the values in each partition according to
 another Collector, and organizes them into a
 Map<Boolean, D> whose values are the result of the downstream
 reduction.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
function () {
    var mouseWheelHandler = function (e) {
        var wrapper      = e.currentTarget;
        var scrollTop    = wrapper.scrollTop;
        var scrollHeight = wrapper.scrollHeight;
        var height       = wrapper.offsetHeight;
        var delta        = e.wheelDelta;
        var up           = delta > 0;

        if (e.scopedScroll) {
            return;
        }

        if (!up && -delta > scrollHeight - height - scrollTop) {
            // Scrolling down, but this will take us past the bottom.
            wrapper.scrollTop = scrollHeight;
            e.preventDefault();
        } else if (up && delta > scrollTop) {
            wrapper.scrollTop = 0;
            e.preventDefault();
        } else {
            e.scopedScroll = true;
        }
    };

    return {
        scope: function (element) {
            var dom = typeof element === 'string' ? document.querySelector(element) : element;
            dom.addEventListener('mousewheel', mouseWheelHandler, false);
        },
        unscope: function (element) {
            var dom = typeof element === 'string' ? document.querySelector(element) : element;
            dom.removeEventListener('mousewheel', mouseWheelHandler, false);
        }
    };
}


text:
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;

abstract class ArraySeeder extends Seeder
{
    protected $table = '';
    protected $columns = [];
    protected $insertData = [];

    abstract protected function initData();

    public function run()
    {
        $this->initData();

        $inserts = [];
        foreach ($this->insertData as $data) {
            $row = [];
            foreach ($this->columns as $i => $col) {
                $row[$col] = $data[$i];
            }
            $row['created_at'] = Carbon::now()->toDateTimeString();//DB::raw('NOW()');
            $row['updated_at'] = Carbon::now()->toDateTimeString();//DB::raw('NOW()');
            $inserts[] = $row;
        }

        DB::table($this->table)->insert($inserts);
    }
}


text:
using namespace AhoViewer::Booru;

#include "curler.h"
#include "image.h"
#include "settings.h"
#include "site.h"
#include "threadpool.h"

#include <glibmm/i18n.h>
#include <iostream>

#define RETRY_COUNT 5

void Page::CellRendererThumbnail::get_preferred_width_vfunc(Gtk::Widget& widget,
                                                            int& minimum_width,
                                                            int& natural_width) const
{
    // Item padding is applied to right and left
    auto width{ widget.get_width() /
                (widget.get_width() / (Image::BooruThumbnailSize + IconViewItemPadding * 2)) };
    minimum_width = width - IconViewItemPadding * 2;
    natural_width = width - IconViewItemPadding * 2;
}

Page::Page()
    : Gtk::ScrolledWindow{},
      m_PopupMenu{ nullptr },
      m_IconView{ Gtk::make_managed<IconView>() },
      m_Tab{ Gtk::make_managed<Gtk::EventBox>() },
      m_TabIcon{ Gtk::make_managed<Gtk::Image>(Gtk::Stock::NEW, Gtk::ICON_SIZE_MENU) },
      m_TabLabel{ Gtk::make_managed<Gtk::Label>(_("New Tab")) },
      m_MenuLabel{ Gtk::make_managed<Gtk::Label>(_("New Tab")) },
      m_TabButton{ Gtk::make_managed<Gtk::Button>() },
      m_ImageList{ std::make_shared<ImageList>(this) },
      m_SaveCancel{ Gio::Cancellable::create() }
{
    set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
    set_shadow_type(Gtk::SHADOW_ETCHED_IN);

    // Create page tab {{{
    m_TabButton->add(*(Gtk::make_managed<Gtk::Image>(Gtk::Stock::CLOSE, Gtk::ICON_SIZE_MENU)));
    m_TabButton->property_relief() = Gtk::RELIEF_NONE;
    m_TabButton->set_focus_on_click(false);
    m_TabButton->set_tooltip_text(_("Close Tab"));
    m_TabButton->signal_clicked().connect([&]() { m_SignalClosed(this); });

    m_TabLabel->set_alignment(0.0, 0.5);
    m_TabLabel->set_ellipsize(Pango::ELLIPSIZE_END);

    m_MenuLabel->set_alignment(0.0, 0.5);
    m_MenuLabel->set_ellipsize(Pango::ELLIPSIZE_END);

    auto* hbox{ Gtk::make_managed<Gtk::HBox>() };
    hbox->pack_start(*m_TabIcon, false, false);
    hbox->pack_start(*m_TabLabel, true, true, 2);
    hbox->pack_start(*m_TabButton, false, false);
    hbox->show_all();

    m_Tab->set_visible_window(false);
    m_Tab->add(*hbox);
    m_Tab->signal_button_release_event().connect(
        sigc::mem_fun(*this, &Page::on_tab_button_release_event));
    // }}}

    m_ScrollConn = get_vadjustment()->signal_value_changed().connect(
        sigc::mem_fun(*this, &Page::on_value_changed));

    m_IconView->set_column_spacing(0);
    m_IconView->set_row_spacing(0);
    m_IconView->set_margin(0);
    m_IconView->set_item_padding(IconViewItemPadding);

    m_IconView->set_model(m_ListStore);
    m_IconView->set_selection_mode(Gtk::SELECTION_BROWSE);
    m_IconView->signal_selection_changed().connect(
        sigc::mem_fun(*this, &Page::on_selection_changed));
    m_IconView->signal_button_press_event().connect(
        sigc::mem_fun(*this, &Page::on_button_press_event));

    // Workaround to have fully centered pixbufs
    auto* cell{ Gtk::make_managed<CellRendererThumbnail>() };
    m_IconView->pack_start(*cell);
    m_IconView->add_attribute(cell->property_pixbuf(), m_Columns.pixbuf);

    m_SignalPostsDownloaded.connect(sigc::mem_fun(*this, &Page::on_posts_downloaded));
    m_SignalSaveProgressDisp.connect([&]() { m_SignalSaveProgress(this); });

    // Check if next page should be loaded after current finishes
    m_ImageList->signal_thumbnails_loaded().connect([&]() {
        on_selection_changed();
        if (!m_KeepAligned)
            on_value_changed();
    });

    add(*m_IconView);
    show_all();
}

Page::~Page()
{
    m_Curler.cancel();

    if (m_GetPostsThread.joinable())
        m_GetPostsThread.join();

    cancel_save();

    m_ListStore->clear();
}

void Page::set_pixbuf(const size_t index, const Glib::RefPtr<Gdk::Pixbuf>& pixbuf)
{
    m_ScrollConn.block();
    ImageList::Widget::set_pixbuf(index, pixbuf);
    while (Glib::MainContext::get_default()->pending())
        Glib::MainContext::get_default()->iteration(true);
    m_ScrollConn.unblock();

    // Only keep the thumbnail aligned if the user has not scrolled
    // and the thumbnail is most likely still being loaded
    if (m_KeepAligned && m_ImageList->get_index() >= index)
        scroll_to_selected();
}

void Page::set_selected(const size_t index)
{
    Gtk::TreePath path{ std::to_string(index) };
    m_IconView->select_path(path);
    scroll_to_selected();
}

void Page::scroll_to_selected()
{
    std::vector<Gtk::TreePath> paths{ m_IconView->get_selected_items() };

    if (!paths.empty())
    {
        Gtk::TreePath path{ paths[0] };
        if (path)
        {
            m_ScrollConn.block();
            m_IconView->scroll_to_path(path, false, 0, 0);
            m_ScrollConn.unblock();
        }
    }
}

void Page::search(const std::shared_ptr<Site>& site)
{
    if (!ask_cancel_save())
        return;

    m_Curler.cancel();

    cancel_save();
    m_ImageList->clear();

    if (m_GetPostsThread.joinable())
        m_GetPostsThread.join();

    m_Site       = site;
    m_Page       = 1;
    m_LastPage   = false;
    m_SearchTags = m_Tags;

    // Trim leading and trailing whitespace for tab label
    // and m_SearchTags which is used to display tags in other places
    if (!m_SearchTags.empty())
    {
        size_t f{ m_SearchTags.find_first_not_of(' ') }, l{ m_SearchTags.find_last_not_of(' ') };
        m_SearchTags = f == std::string::npos ? "" : m_SearchTags.substr(f, l - f + 1);
    }

    std::string label{ m_Site->get_name() + (m_SearchTags.empty() ? "" : " - " + m_SearchTags) };
    m_TabLabel->set_text(label);
    m_MenuLabel->set_text(label);
    m_TabIcon->set(m_Site->get_icon_pixbuf());

    m_Curler.set_share_handle(m_Site->get_share_handle());
    m_Curler.set_referer(m_Site->get_url());

    get_posts();
}

void Page::save_image(const std::string& path, const std::shared_ptr<Image>& img)
{
    m_SaveCancel->reset();
    if (m_SaveImagesThread.joinable())
        m_SaveImagesThread.join();

    m_Saving           = true;
    m_SaveImagesThread = std::thread([&, path, img]() {
        img->save(path);
        m_Saving = false;
    });
}

void Page::save_images(const std::string& path)
{
    m_SaveCancel->reset();
    if (m_SaveImagesThread.joinable())
        m_SaveImagesThread.join();

    m_Saving            = true;
    m_SaveImagesCurrent = 0;
    m_SaveImagesTotal   = m_ImageList->get_vector_size();
    m_SaveImagesThread  = std::thread([&, path]() {
        ThreadPool pool;
        for (const std::shared_ptr<AhoViewer::Image>& img : *m_ImageList)
        {
            pool.push([&, path, img]() {
                if (m_SaveCancel->is_cancelled())
                    return;

                std::shared_ptr<Image> bimage = std::static_pointer_cast<Image>(img);
                bimage->save(
                    Glib::build_filename(path, Glib::path_get_basename(bimage->get_filename())));
                ++m_SaveImagesCurrent;

                if (!m_SaveCancel->is_cancelled())
                    m_SignalSaveProgressDisp();
            });
        }

        m_SignalSaveProgressDisp();
        pool.wait();
        m_Saving = false;
    });
}

// Returns true if we want to cancel or we're not saving
bool Page::ask_cancel_save()
{
    if (!m_Saving)
        return true;

    auto* window = static_cast<Gtk::Window*>(get_toplevel());
    Gtk::MessageDialog dialog(*window,
                              _("Are you sure that you want to stop saving images?"),
                              false,
                              Gtk::MESSAGE_QUESTION,
                              Gtk::BUTTONS_YES_NO,
                              true);
    dialog.set_secondary_text(_("Closing this tab will stop the save operation."));

    return dialog.run() == Gtk::RESPONSE_YES;
}

void Page::cancel_save()
{
    m_SaveCancel->cancel();

    for (const std::shared_ptr<AhoViewer::Image>& img : *m_ImageList)
    {
        std::shared_ptr<Image> bimage{ std::static_pointer_cast<Image>(img) };
        bimage->cancel_download();
    }

    if (m_SaveImagesThread.joinable())
        m_SaveImagesThread.join();

    m_Saving = false;
}

void Page::get_posts()
{
    std::string tags{ m_SearchTags };
    m_KeepAligned = true;

    if (m_Tags.find("rating:") == std::string::npos)
    {
        if (Settings.get_booru_max_rating() == Rating::SAFE)
        {
            tags += " rating:safe";
        }
        else if (Settings.get_booru_max_rating() == Rating::QUESTIONABLE)
        {
            tags += " -rating:explicit";
        }
    }

    tags = m_Curler.escape(tags);

    m_GetPostsThread = std::thread([&, tags]() {
        // DanbooruV2 doesn't give the post count with the posts
        // Get it from thier counts api
        if (m_Page == 1 && m_Site->get_type() == Type::DANBOORU_V2)
        {
            m_Curler.set_url(m_Site->get_url() + "/counts/posts.xml?tags=" + tags);
            if (m_Curler.perform())
            {
                try
                {
                    xml::Document doc{ reinterpret_cast<char*>(m_Curler.get_data()),
                                       m_Curler.get_data_size() };
                    if (doc.get_n_nodes())
                    {
                        std::string posts_count{ doc.get_children()[0].get_value() };
                        // Usually when you use a wildcard operator danbooru's count api will return
                        // a blank value here (blank but contains some whitespace and newlines)
                        if (posts_count.find_first_not_of(" \n\r") != std::string::npos)
                            m_PostsCount = std::stoul(posts_count);
                    }
                }
                catch (const std::runtime_error& e)
                {
                    std::cerr << e.what() << std::endl << m_Curler.get_data() << std::endl;
                }
                catch (const std::invalid_argument& e)
                {
                    std::cerr << e.what() << std::endl
                              << "Failed to parse posts_count" << std::endl;
                }
            }
            else if (m_Curler.is_cancelled())
            {
                return;
            }
        }

        m_Curler.set_url(m_Site->get_posts_url(tags, m_Page));
        if (m_Site->get_url().find("gelbooru.com") == std::string::npos)
            m_Curler.set_http_auth(m_Site->get_username(), m_Site->get_password());

        bool success{ false };
        size_t retry_count{ 0 };
        do
        {
            success = m_Curler.perform();
            if (success)
            {
                auto [posts, posts_count, error]{ m_Site->parse_post_data(
                    m_Curler.get_data(), m_Curler.get_data_size()) };
                m_Posts = std::move(posts);
                if (posts_count > 0)
                    m_PostsCount = posts_count;
                m_PostsError = error;
            }
        } while (!m_Curler.is_cancelled() && !success && ++retry_count < RETRY_COUNT);

        if (!success && !m_Curler.is_cancelled())
        {
            std::cerr << "Error while downloading posts on " << m_Curler.get_url() << std::endl
                      << "  " << m_Curler.get_error() << std::endl;

            m_PostsError =
                Glib::ustring::compose(_("Failed to download posts on %1"), m_Site->get_name());
        }

        if (!m_Curler.is_cancelled())
            m_SignalPostsDownloaded();
    });

    m_SignalPostsDownloadStarted();
}

bool Page::get_next_page()
{
    // Do not fetch the next page if this is the last
    // or the current page is still loading
    if (m_LastPage || m_GetPostsThread.joinable() || m_ImageList->is_loading())
        return false;

    if (!m_Saving)
    {
        ++m_Page;
        get_posts();

        return false;
    }
    else if (!m_GetNextPageConn)
    {
        m_GetNextPageConn =
            Glib::signal_timeout().connect(sigc::mem_fun(*this, &Page::get_next_page), 1000);
    }

    return true;
}

// Adds the downloaded posts to the image list.
void Page::on_posts_downloaded()
{
    if (!m_PostsError.empty())
    {
        m_SignalDownloadError(m_PostsError);
    }
    // 401 = Unauthorized
    else if (m_Curler.get_response_code() == 401)
    {
        auto e{ Glib::ustring::compose(
            _("Failed to login as %1 on %2"), m_Site->get_username(), m_Site->get_name()) };
        m_SignalDownloadError(e);
    }
    else
    {
        auto n_posts{ m_Posts.size() };
        if (!m_Posts.empty())
        {
            auto size_before{ m_ImageList->get_vector_size() };
            m_ImageList->load(m_Posts, m_PostsCount);
            // Number of posts that actually got added to the image list
            // ie supported file types
            n_posts = m_ImageList->get_vector_size() - size_before;
        }

        // No posts added to the imagelist
        if (n_posts == 0)
        {
            if (m_Page == 1)
                m_SignalDownloadError(_("No results found"));
            else
                m_SignalOnLastPage();

            m_LastPage = true;
        }
    }

    m_Curler.clear();
    m_Posts.clear();
    m_GetPostsThread.join();
}

void Page::on_selection_changed()
{
    std::vector<Gtk::TreePath> paths{ m_IconView->get_selected_items() };

    if (!paths.empty())
    {
        Gtk::TreePath path{ paths[0] };
        if (path)
        {
            size_t index = path[0];

            if (index + Settings.get_int("CacheSize") >= m_ImageList->get_vector_size() - 1)
                get_next_page();

            m_SignalSelectedChanged(index);
        }
    }
}

// Vertical scrollbar value changed
void Page::on_value_changed()
{
    double value = get_vadjustment()->get_value(),
           limit = get_vadjustment()->get_upper() - get_vadjustment()->get_page_size() -
                   get_vadjustment()->get_step_increment() * 3;
    m_KeepAligned = false;

    if (value >= limit)
        get_next_page();
}

bool Page::on_button_press_event(GdkEventButton* e)
{
    if (e->type == GDK_BUTTON_PRESS && e->button == 3)
    {
        Gtk::TreePath path = m_IconView->get_path_at_pos(e->x, e->y);

        if (path)
        {
            m_IconView->select_path(path);
            m_IconView->scroll_to_path(path, false, 0, 0);

            m_PopupMenu->popup_at_pointer((GdkEvent*)e);

            return true;
        }
    }

    return false;
}

bool Page::on_tab_button_release_event(GdkEventButton* e)
{
    if (e->type == GDK_BUTTON_RELEASE && e->button == 2)
        m_SignalClosed(this);

    return false;
}


text:
EmailProcessor Application
==========================

Symfony Console application to get and process eMails.

EmailProcessor is a console application to retrieve and process eMails from a server.
Selection, identification and processing of the eMails is performed by plugins.

Installing
----------

Configuration
-------------

Features
--------

Testing
-------

Plugins
-------

Examples
--------

Roadmap
-------

Development / Requests
----------------------


text:
module HW1.TowersOfHanoi (hanoi) where

type Peg = Char
type Move = (Peg, Peg)

hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi = undefined


text:
// -*- c-basic-offset: 4 -*-

#include <click/config.h>
#include <click/error.hh>
#include "priosched.hh"
CLICK_DECLS

PrioSched::PrioSched()
    : _signals(0)
{
}

PrioSched::~PrioSched()
{
}

int
PrioSched::initialize(ErrorHandler *errh)
{
    if (!(_signals = new NotifierSignal[ninputs()]))
	return errh->error("out of memory!");
    for (int i = 0; i < ninputs(); i++)
	_signals[i] = Notifier::upstream_empty_signal(this, i, 0);
    return 0;
}

void
PrioSched::cleanup(CleanupStage)
{
    delete[] _signals;
}

Packet *
PrioSched::pull(int)
{
    Packet *p;
    for (int i = 0; i < ninputs(); i++)
	if (_signals[i] && (p = input(i).pull()))
	    return p;
    return 0;
}

CLICK_ENDDECLS
EXPORT_ELEMENT(PrioSched)
ELEMENT_MT_SAFE(PrioSched)


text:
local pubsub = require("pubsub")
local event = require("libs.event")

pubsub.sub("event:circd:chan", function()
	local msgpack = require("msgpack")
	local logger = require("libs.logger")
	local event = require("libs.event")
	local prettify = require("prettify")
	local clib = require("libs.clib")
	local command = require("libs.command")

	function print(...)
		logger.log("circd:chan", logger.normal, prettify(...))
	end

	local recv = function()
		local src = com.receive(threadcom)
		local args
		if src then
			return unpack(msgpack.unpack(src))
		end
	end

	local chans = {}

	while true do
		-- receive command
		local cmd, id, chan, arg = recv()

		if chan then
			chan = chan:gsub("%s+", "")
		end

		if cmd == "join" then -- join channel
			chans[chan] = chans[chan] or {}
			kvstore._set("circd:chan:exists:"..chan, true)
			chans[chan][id] = arg or ""
			local host = clib.gethost(id)
			if host then
				local msg = ":"..host.." JOIN "..chan
				for u_id, _ in pairs(chans[chan]) do
					--if u_id ~= id then
						local client = clib.getclient(u_id)
						clib.send(client, msg)
					--end
				end
				local client = clib.getclient(id)
				command.run("names", client, chan)
				event.fire("circd:chan:join", id, chan)
			end
		elseif cmd == "mode" then -- update mode
			chans[chan] = chans[chan] or {}
			chans[chan][id] = arg
		elseif cmd == "part" then -- leave channel
			chans[chan] = chans[chan] or {}
			chans[chan][id] = nil
			local msg = ":"..clib.gethost(id).." PART "..chan .. " :" .. (arg or "User left the channel.")
			local users = 0
			for u_id, _ in pairs(chans[chan]) do
				--if u_id ~= id then
					local client = clib.getclient(u_id)
					clib.send(client, msg)
					users = users + 1
				---end
			end
			if users <= 1 then
				chans[chan] = nil
				kvstore._del("circd:chan:exists:"..chan)
			end
			event.fire("circd:chan:part", id, chan, (arg or "User left the channel."))
		elseif cmd == "quit" then -- quit irc
			local to_clients = {}
			for name, users_chan in pairs(chans) do
				if users_chan[id] then
					chans[name][id] = nil
					local users = 0
					for u_id, _ in pairs(users_chan) do
						to_clients[u_id] = true
						users = users + 1
					end
					if users == 0 then
						chans[name] = nil
						kvstore._del("circd:chan:exists:"..name)
					end
				end
			end
			for u_id, _ in pairs(to_clients) do
				local client = clib.getclient(u_id)
				clib.send(client, ":"..clib.gethost(id).." QUIT :"..(arg or "Client Quit"))
			end
			clib.deleteuser(id)
			event.fire("circd:quit", id, (arg or "Client Quit"))
		elseif cmd == "send" then -- send to channel
			for u_id, _ in pairs(chans[chan] or {}) do
				if u_id ~= id then
					local client = clib.getclient(u_id)
					clib.send(client, arg)
				end
			end
		elseif cmd == "getusers" then -- get channels list of users
			com.send(arg, msgpack.pack(chans[chan]))
		elseif cmd == "getchannels" then -- get users list of channels
			local res = {}
			for chan_name, members in pairs(chans) do
				if members[id] then
					table.insert(res, chan_name)
				end
			end
			com.send(arg, msgpack.pack(res))
		else
			print("Unknown command: "..cmd)
		end
	end
end)

-- events
event.handle("circd:disconnect", function(client, err) -- ded
	local event = require("libs.event")
	event.fire("circd:chan", "quit", client.id, nil, err)
end)

event.handle("circd:chan:join", function(id, chan) -- topic
	local clib = require("libs.clib")
	local nick = clib.getnick(id)
	local topic = clib.gettopic(chan)
	if topic then
		clib.srvmsg(332, nick, chan, ":"..topic)
	end
end)

-- Commands
command.new("join", function(client, chan)
	local clib = require("libs.clib")
	if not chan then
		return 461, "JOIN", "Not enough parameters"
	end
	for word in string.gmatch(chan, '([^,]+)') do
		if word:match("^#[%w%d]*$") then
			if not clib.in_channel(chan, id) then
				clib.join_chan(client.id, word)
			end
		else
			return 403, chan, "No such channel"
		end
	end
end)

command.new("part",function(client, chan, reason)
	local clib = require("libs.clib")
	if not chan then
		return 461, "JOIN", "Not enough parameters"
	end
	if clib.in_channel(chan, client.id) then
		clib.part_chan(client.id, chan, reason)
	end
end)

command.new("privmsg", function(cl, to, msg)
	local clib = require("libs.clib")
	local nick = clib.getnick(cl.id)
	if not to then
		return 411, nick, "No recipient given (PRIVMSG)"
	end
	if not msg then
		return 412, nick, "No text to send"
	end
	if not clib.privmsg(cl.id, to, msg) then
		return 401, chan, "No such nick/channel"
	end
end)

command.new("notice", function(cl, to, msg)
	local clib = require("libs.clib")
	local nick = clib.getnick(cl.id)
	if not (to or msg) then
		return
	end
	if not clib.privmsg(cl.id, to, msg) then
		return 401, chan, "No such nick/channel"
	end
end)

command.new("names", function(cl, chan)
	print("names")
	if not chan then
		return 461, "NAMES", "Not enough parameters"
	end
	local clib = require("libs.clib")
	local nick = clib.getnick(cl.id)
	local users = clib.list_users(chan)
	if users then
		local ids = {}
		for id, mode in pairs(users) do
			print(id)
			table.insert(ids, id)
		end
		for l1=1, #ids, 50 do
			local o = {}
			for l2=l1, l1+49 do
				local id = ids[l2]
				if id then
					table.insert(o, (users[id] or "")..clib.getnick(id))
				end
			end
			clib.srvmsg(cl, 353, nick, "@", chan, ":"..table.concat(o, " "))
		end
	end
	clib.srvmsg(cl, 366, nick, chan, ":End of /NAMES list.")
end)


text:
<title>ISHFTC - The GNU Fortran Compiler</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="The GNU Fortran Compiler">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Intrinsic-Procedures.html#Intrinsic-Procedures" title="Intrinsic Procedures">
<link rel="prev" href="ISHFT.html#ISHFT" title="ISHFT">
<link rel="next" href="ISNAN.html#ISNAN" title="ISNAN">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: ISNAN,
Previous: ISHFT,
Up: Intrinsic Procedures

8.135 ISHFTC — Shift bits circularly

Description:
ISHFTC returns a value corresponding to <var>I</var> with the
rightmost <var>SIZE</var> bits shifted circularly <var>SHIFT</var> places; that
is, bits shifted out one end are shifted into the opposite end.  A value
of <var>SHIFT</var> greater than zero corresponds to a left shift, a value of
zero corresponds to no shift, and a value less than zero corresponds to
a right shift.  The absolute value of <var>SHIFT</var> must be less than
<var>SIZE</var>.  If the <var>SIZE</var> argument is omitted, it is taken to be
equivalent to BIT_SIZE(I).

Standard:
Fortran 95 and later

Class:
Elemental function

Syntax:
RESULT = ISHFTC(I, SHIFT [, SIZE])

Arguments:

<var>I</var> 	The type shall be INTEGER.

<var>SHIFT</var> 	The type shall be INTEGER.

<var>SIZE</var> 	(Optional) The type shall be INTEGER;
the value must be greater than zero and less than or equal to
BIT_SIZE(I).

Return value:
The return value is of type INTEGER and of the same kind as
<var>I</var>.

See also:
ISHFT


text:
(function (global) {

function DependencyResolver(container) {
	this.container = container;
}

DependencyResolver.prototype = {

	container: null,

	constructor: DependencyResolver,

	findDependency: function(info) {
		var instance = null, factory;

		if (isString(info)) {
			instance = this.container.resolve(info, true);
		}
		else if ("value" in info) {
			instance = info.value;
		}
		else {
			throw new Error("No dependency value found. Missing one of 'id', 'value' or 'factory'");
		}

		return instance;
	},

	injectDependencies: function(instance, config, propertiesSet) {
		if (!config.properties) {
			return;
		}

		var properties = config.properties,
		    key, dependency, setter;

		for (key in properties) {
			if (properties.hasOwnProperty(key) && !propertiesSet[key]) {
				setter = "set" + capitalize(key);
				dependency = this.findDependency(properties[key]);

				if (isFunction(instance[setter])) {
					instance[setter](dependency);
				}
				else {
					instance[key] = dependency;
				}

				propertiesSet[key] = true;
			}
		}
	}

};

global.Hypodermic.DependencyResolver = DependencyResolver;

// utils

var toString = Object.prototype.toString;

function capitalize(str) {
	return str.charAt(0).toUpperCase() + str.substring(1, str.length);
}

function isFunction(x) {
	return toString.call(x) === "[object Function]";
}

function isString(x) {
	return toString.call(x) === "[object String]";
}

})(this);


text:
#include <stdio.h>
#include BOSS_OPENSSL_V_openssl__err_h //original-code:<openssl/err.h>
#include BOSS_OPENSSL_V_openssl__crypto_h //original-code:<openssl/crypto.h>

/* BEGIN ERROR CODES */
#ifndef OPENSSL_NO_ERR

# define ERR_FUNC(func) ERR_PACK(ERR_LIB_CRYPTO,func,0)
# define ERR_REASON(reason) ERR_PACK(ERR_LIB_CRYPTO,0,reason)

static ERR_STRING_DATA CRYPTO_str_functs[] = {
    {ERR_FUNC(CRYPTO_F_CRYPTO_DUP_EX_DATA), "CRYPTO_dup_ex_data"},
    {ERR_FUNC(CRYPTO_F_CRYPTO_FREE_EX_DATA), "CRYPTO_free_ex_data"},
    {ERR_FUNC(CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX), "CRYPTO_get_ex_new_index"},
    {ERR_FUNC(CRYPTO_F_CRYPTO_MEMDUP), "CRYPTO_memdup"},
    {ERR_FUNC(CRYPTO_F_CRYPTO_NEW_EX_DATA), "CRYPTO_new_ex_data"},
    {ERR_FUNC(CRYPTO_F_CRYPTO_SET_EX_DATA), "CRYPTO_set_ex_data"},
    {ERR_FUNC(CRYPTO_F_FIPS_MODE_SET), "FIPS_mode_set"},
    {ERR_FUNC(CRYPTO_F_GET_AND_LOCK), "get_and_lock"},
    {ERR_FUNC(CRYPTO_F_OPENSSL_BUF2HEXSTR), "OPENSSL_buf2hexstr"},
    {ERR_FUNC(CRYPTO_F_OPENSSL_HEXSTR2BUF), "OPENSSL_hexstr2buf"},
    {ERR_FUNC(CRYPTO_F_OPENSSL_INIT_CRYPTO), "OPENSSL_init_crypto"},
    {0, NULL}
};

static ERR_STRING_DATA CRYPTO_str_reasons[] = {
    {ERR_REASON(CRYPTO_R_FIPS_MODE_NOT_SUPPORTED), "fips mode not supported"},
    {ERR_REASON(CRYPTO_R_ILLEGAL_HEX_DIGIT), "illegal hex digit"},
    {ERR_REASON(CRYPTO_R_ODD_NUMBER_OF_DIGITS), "odd number of digits"},
    {0, NULL}
};

#endif

int ERR_load_CRYPTO_strings(void)
{
#ifndef OPENSSL_NO_ERR

    if (ERR_func_error_string(CRYPTO_str_functs[0].error) == NULL) {
        ERR_load_strings(0, CRYPTO_str_functs);
        ERR_load_strings(0, CRYPTO_str_reasons);
    }
#endif
    return 1;
}


text:
'use strict';

var path = require('path');
var authorization = require(path.join(__dirname, 'middleware', 'authorization'))();
var talkIdValidator = require(path.join(__dirname, 'middleware', 'talkIdValidator'))();
var userValidator = require(path.join(__dirname, 'middleware', 'userValidator'))();
var questionIdValidator = require(path.join(__dirname, 'middleware', 'questionIdValidator'))();
var questionInTalkValidator = require(path.join(__dirname, 'middleware', 'questionInTalkValidator'))();
var speakerController = require(path.join(__dirname, '..', 'controllers', 'speakerController'))();

module.exports = function (app) {
  app.get('/talk', authorization.requiresLogin, speakerController.showCreateTalkForm);
  app.get('/talk/:talkId', authorization.requiresLogin, talkIdValidator.validate, userValidator.validate,
    speakerController.showEditTalkForm);

  app.get('/question', authorization.requiresLogin, speakerController.showCreateQuestionForm);

  app.get('/questionType', authorization.requiresLogin, speakerController.showCreateQuestionTypeForm);

  app.get('/wall/:talkId/:questionId', authorization.requiresLogin, talkIdValidator.validate, userValidator.validate,
    questionIdValidator.validate, questionInTalkValidator.validate, speakerController.showWall);
};


text:
package eu.scape_project.arcunpacker;

/**
 * Created by IntelliJ IDEA.
 * User: abr
 * Date: 4/25/12
 * Time: 9:08 AM
 * To change this template use File | Settings | File Templates.
 */
public class UnpackConfig {

    private int minResponseCode;
    private int maxResponseCode;
    private Naming naming;

    public UnpackConfig(int minResponseCode, int maxResponseCode, Naming naming) {
        this.minResponseCode = minResponseCode;
        this.maxResponseCode = maxResponseCode;
        this.naming = naming;
    }

    public int getMinResponseCode() {
        return minResponseCode;
    }

    public int getMaxResponseCode() {
        return maxResponseCode;
    }

    public Naming getNaming() {
        return naming;
    }

    public static enum Naming {
        URL,OFFSET, MD5;
    }
}


text:
<?php

namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Form\Type;

use Oro\Bundle\EntityExtendBundle\Form\Type\TextAssociationPropertyType;
use Oro\Bundle\EntityExtendBundle\Form\Util\AssociationTypeHelper;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class TextAssociationPropertyTypeTest extends AssociationTypeTestCase
{
    /**
     * {@inheritdoc}
     */
    protected function getFormType()
    {
        $entityClassResolver = $this->getMockBuilder('Oro\Bundle\EntityBundle\ORM\EntityClassResolver')
            ->disableOriginalConstructor()
            ->getMock();
        $entityClassResolver->expects($this->any())
            ->method('getEntityClass')
            ->will($this->returnArgument(0));

        return new TextAssociationPropertyType(
            new AssociationTypeHelper($this->configManager, $entityClassResolver),
            $this->configManager
        );
    }

    public function testGetName()
    {
        $this->assertEquals(
            'oro_entity_extend_association_property_text',
            $this->getFormType()->getName()
        );
    }

    public function testGetParent()
    {
        $this->assertEquals(
            TextType::class,
            $this->getFormType()->getParent()
        );
    }

    /**
     * @return array
     */
    protected function getDisabledFormView()
    {
        return [
            'disabled' => true,
            'attr'     => [],
            'value'    => null
        ];
    }
}


text:
import unittest
from flask_testing import TestCase
from app import app, db
from app.models import User, Vote, Candidate

class TestBase(TestCase):

    def create_app(self):
        config_name = 'testing'
        app.config.update(
            SQLALCHEMY_DATABASE_URI='sqlite:///dummy.db'
        )
        return app

    def setUp(self):
        '''
        Called before any test is run
        '''
        db.create_all()

        # ad 2 users
        user1 = User(name='user1', email='user1@mail.com', country='UK',
                     token='asdf')
        user2 = User(name='user2', email='user2@mail.com', country='US',
                     token='ewee')

        candidate1 = Candidate(name='A')
        candidate2 = Candidate(name='B')
        candidate3 = Candidate(name='C')

        # save users to database
        db.session.add(user1)
        db.session.add(user2)

        # save candidates to database
        db.session.add(candidate1)
        db.session.add(candidate2)
        db.session.add(candidate3)

        db.session.commit()

    def tearDown(self):
        '''
        Called after any test has run
        '''
        db.session.remove()
        db.drop_all()

class TestModels(TestBase):

    def test_user_model(self):
        '''
        Test number of records in User table
        '''
        self.assertEqual(User.query.count(), 2)

    def test_candidate_model(self):
        '''
        Test number of records in Candidate table
        '''
        self.assertEqual(Candidate.query.count(), 3)

class TestViews(TestBase):

    def test_register_candidate_view(self):
        '''
        Test register_candidate view
        '''
        response = self.client.post('/register_candidate',
                                    data=dict(candidate='D'))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['candidate'], 'D')

    def test_register_existing_candidate_view(self):
        '''
        Test register_candidate view fails as expected
        '''
        response = self.client.post('/register_candidate',
                                    data=dict(candidate='A'))
        self.assertEqual(response.status_code, 400)

    def test_register_user_view(self):
        '''
        Test register_user view
        '''
        response = self.client.post('/register_user',
                                    data=dict(name='userx',
                                              email='userx@mail.com'))
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.json['name'], 'userx')
        self.assertEqual(response.json['email'], 'userx@mail.com')

    def test_register_existing_user_view(self):
        '''
        Test register_user view fails when duplicating a user
        '''
        response = self.client.post('/register_user',
                                    data=dict(name='user1',
                                              email='user1@mail.com'))
        self.assertEqual(response.status_code, 400)

    def test_register_vote_view(self):
        '''
        Test register_vote view
        '''
        response = self.client.post('/register_user',
                                    data=dict(name='usery',
                                              email='usery@mail.com'))
        token = response.json['token']

        response = self.client.post('/register_vote',
                                    data=dict(name='A', token=token))
        self.assertEqual(response.status_code, 200)
        response = self.client.post('/register_vote',
                                    data=dict(name='B', token=token))
        self.assertEqual(response.status_code, 200)
        response = self.client.post('/register_vote',
                                    data=dict(name='C', token=token))
        self.assertEqual(response.status_code, 200)

        # this should fail on the 4th attempt by the same user
        response = self.client.post('/register_vote',
                                    data=dict(name='A', token=token))
        self.assertEqual(response.status_code, 403)

if __name__ == '__main__':
    unittest.main()


text:
<?php
/**
 * Author: Tomas Pavlatka (tomas.pavlatka@gmail.com)
 * Created: 2010-12-28
 */

// Needed classes.
require_once './calendar.class.php';

// Object.
$options = array(
    'date_format' => 'd',
    'day_names' => array('Mon','Tue','Wed','Thu','Fri','Sat','Sun'),
    'show_days_from_different_month' => false
);
$calendarObj =& new PTX_Calendar($options);

// Variables.
$month = (isset($_GET['month'])) ? (int)$_GET['month'] : 1;
$year = (isset($_GET['year'])) ? (int)$_GET['year'] : 2010;

// build month.
echo '<pre>';
    print_r($calendarObj->buildMonth($month,$year));
echo '</pre>';


text:
package models

import com.datastax.spark.connector.mapper.JavaBeanColumnMapper

/**
 * Created by cenk on 25/02/15.
 */

class Metric extends Serializable {
  private var _tenant: String = ""
  private var _period: Int = 0
  private var _rollup: Int = 0
  private var _path: String = ""
  private var _time: BigInt = 0
  private var _data: List[Double] = List()

  def setTenant(tenant: String): Unit = {
    _tenant = tenant
  }

  def setPeriod(rollup: Int): Unit = {
    _period = rollup
  }

  def setRollup(rollup: Int): Unit = {
    _rollup = rollup
  }

  def setPath(path: String): Unit = {
    _path = path
  }

  def setTime(time: BigInt): Unit = {
    _time = time
  }

  def setData(data: Double): Unit = {
    _data :+ data
  }

  override def toString = _tenant + "," + _period + "," + _rollup + "," + _path + "," + _time + "," + _data
}

object Metric {

  implicit object Mapper extends JavaBeanColumnMapper[Metric]

}


text:
(function() {
  var assert, t;

  assert = require('assert');

  t = require('../lib/timed.js');

  function delay(ms, func) {
    return setTimeout(func, ms);
  };

  describe('timed', function() {
    return describe('reset', function() {
      it('should reset the timer to 0', function() {
        var was;
        t.reset();
        was = t.rounded();
        console.log(was);
        return assert(was < 0.09);
      });
      return it('should return time in ms since reset', function(done) {
        var elapsed,
          _this = this;
        t.reset();
        delay(700, function() {
          elapsed = t.rounded();
          console.log("Elapsed: " + elapsed);
          assert.ok(elapsed > 699.99999);
          assert.ok(elapsed < 705.001);
          return done();
        });
      });
    });
  });

}).call(this);


text:
@implementation UILabel (Theming)

+ (void)load {
    [self
        mtf_registerThemeProperties:@[
            TypographyThemeProperties.fontSize,
            TypographyThemeProperties.fontName,
        ] requiringValuesOfType:@[
            NSNumber.class,
            NSString.class,
        ] applierBlock:^(NSDictionary *valuesForProperties, UILabel *label) {
            NSString *name = valuesForProperties[TypographyThemeProperties.fontName];
            CGFloat size = [valuesForProperties[TypographyThemeProperties.fontSize] floatValue];
            label.font = [UIFont fontWithName:name size:size];
        }];

    [self
        mtf_registerThemeProperty:ContentThemeProperties.color
        requiringValueOfClass:UIColor.class
        applierBlock:^(UIColor *color, UILabel *label) {
            label.textColor = color;
    }];
}

+ (NSDictionary *)mtf_textAttributesForThemeClass:(MTFThemeClass *)themeClass {
    NSMutableDictionary *attributes = [NSMutableDictionary new];

    NSString *name = themeClass.properties[TypographyThemeProperties.fontName];
    CGFloat size = [themeClass.properties[TypographyThemeProperties.fontSize] floatValue];

    UIFont *font = [UIFont fontWithName:name size:size];
    if (font != nil) {
        attributes[NSFontAttributeName] = font;
    }

    NSString *colorString = themeClass.properties[ContentThemeProperties.color];
    UIColor *color;
    if (colorString != nil) {
        NSValueTransformer *transformer = [NSValueTransformer mtf_valueTransformerForTransformingObject:colorString toClass:UIColor.class];
        color = [transformer transformedValue:colorString];
    }
    if (color != nil) {
        attributes[NSForegroundColorAttributeName] = color;
    }

    return [attributes copy];
}

@end