text:
import os
import re
from contextlib import contextmanager

import numpy.testing as npt
import astropy.units as u
import pytest
from astropy.io.fits.verify import VerifyWarning

from ...import nvas
from astroquery.utils.mocks import MockResponse
from ...utils import commons

COORDS_GAL = commons.GalacticCoordGenerator(
    l=49.489, b=-0.37, unit=(u.deg, u.deg))  # ARM 2000
COORDS_ICRS = commons.ICRSCoordGenerator(
    "12h29m06.69512s +2d03m08.66276s")  # 3C 273

DATA_FILES = {'image': 'image.imfits',
              'image_search': 'image_results.html'}

def data_path(filename):
    data_dir = os.path.join(os.path.dirname(__file__), 'data')
    return os.path.join(data_dir, filename)

@pytest.fixture
def patch_post(request):
    mp = request.getfixturevalue("monkeypatch")

    mp.setattr(nvas.Nvas, '_request', post_mockreturn)
    return mp

@pytest.fixture
def patch_parse_coordinates(request):
    def parse_coordinates_mock_return(c):
        return c

    mp = request.getfixturevalue("monkeypatch")

    mp.setattr(commons, 'parse_coordinates', parse_coordinates_mock_return)
    return mp

def post_mockreturn(method, url, data, timeout, **kwargs):
    filename = data_path(DATA_FILES['image_search'])
    with open(filename, 'rb') as infile:
        content = infile.read()
    response = MockResponse(content, **kwargs)
    return response

@pytest.fixture
def patch_get_readable_fileobj(request):
    @contextmanager
    def get_readable_fileobj_mockreturn(filename, **kwargs):
        encoding = kwargs.get('encoding', None)
        if encoding == 'binary':
            with open(data_path(DATA_FILES["image"]), 'rb') as file_obj:
                yield file_obj
        else:
            with open(data_path(DATA_FILES["image"]), "r", encoding=encoding) as file_obj:
                yield file_obj

    mp = request.getfixturevalue("monkeypatch")

    mp.setattr(commons, 'get_readable_fileobj',
               get_readable_fileobj_mockreturn)
    return mp

def deparse_coordinates(cstr):
    """
    '19 23 40.001395 +14 31 01.550347' -> '19:23:40.001395 +14:31:01.550347'
    """
    return re.sub(r" ([\+-])", r",\1", cstr).replace(" ", ":").replace(",", " ")

@pytest.mark.parametrize(('coordinates'), [COORDS_GAL, COORDS_ICRS])
def test_parse_coordinates(coordinates):
    out_str = nvas.core._parse_coordinates(coordinates)
    new_coords = commons.ICRSCoordGenerator(
        deparse_coordinates(out_str), unit=(u.hour, u.deg))
    # if all goes well new_coords and coordinates have same ra and dec
    npt.assert_approx_equal(new_coords.ra.degree,
                            coordinates.transform_to('fk5').ra.degree,
                            significant=3)
    npt.assert_approx_equal(new_coords.dec.degree,
                            coordinates.transform_to('fk5').dec.degree,
                            significant=3)

def test_extract_image_urls():
    with open(data_path(DATA_FILES['image_search']), 'r') as infile:
        html_in = infile.read()
    image_list = nvas.core.Nvas.extract_image_urls(html_in)
    assert len(image_list) == 2

def test_get_images_async(patch_post, patch_parse_coordinates):
    image_list = nvas.core.Nvas.get_images_async(COORDS_ICRS, band='K',
                                                 radius=2 * u.arcsec,
                                                 max_rms=100)
    assert len(image_list) == 2

def test_get_images(patch_post, patch_parse_coordinates,
                    patch_get_readable_fileobj):
    with pytest.warns(VerifyWarning, match="Invalid 'BLANK' keyword in header"):
        images = nvas.core.Nvas.get_images(COORDS_GAL, radius='5d0m0s', band='all')
    assert images is not None

def test_get_image_list(patch_post, patch_parse_coordinates):
    image_list = nvas.core.Nvas.get_image_list(
        COORDS_GAL, radius=15 * u.arcsec,
        max_rms=500, band="all", get_query_payload=True)
    npt.assert_approx_equal(image_list["nvas_rad"], 0.25, significant=2)
    assert image_list["nvas_bnd"] == ""
    assert image_list["nvas_rms"] == 500
    image_list = nvas.core.Nvas.get_image_list(
        COORDS_GAL, radius=15 * u.arcsec, max_rms=500, band="all")

    assert len(image_list) == 2

redpajama_set_name: RedPajamaGithub


text:
package org.nbone.monitor.annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.HashSet;
import java.util.Set;

/**
 * @author thinking
 * @version 1.0
 * @since 2019-10-14
 */
@Configuration
public class MonitorConfiguration implements ImportAware {

    private static final Logger logger = LoggerFactory.getLogger(MonitorConfiguration.class);

    private AnnotationAttributes enableMonitor;

    protected Set<Class<? extends Throwable>> ignoresException;

    @Autowired(required = false)
    void setConfigurer(MonitorConfigurer configurer) {
        if (configurer == null) {
            return;
        }
        logger.info("initialize MonitorConfigurer... ");
        useMonitorConfigurer(configurer);
    }

    protected void useMonitorConfigurer(MonitorConfigurer config) {
        addIgnoresException(config.ignoresException());
    }

    @Bean
    public MonitorAnnotationParser monitorAnnotationParser() {
        logger.info("initialize monitorAnnotationParser... ");

        MonitorAnnotationParser monitorAnnotationParser = new MonitorAnnotationParser();
        if (this.ignoresException != null) {
            monitorAnnotationParser.setIgnoresException(ignoresException);
        }
        return monitorAnnotationParser;
    }

    @Override
    public void setImportMetadata(AnnotationMetadata importMetadata) {
        logger.info("initialize setImportMetadata... ");

        this.enableMonitor = AnnotationAttributes.fromMap(
                importMetadata.getAnnotationAttributes(EnableMonitor.class.getName(), false));
        if (this.enableMonitor == null) {
            throw new IllegalArgumentException(
                    "@EnableMonitor is not present on importing class " + importMetadata.getClassName());
        }

        Class<?>[] ignores = enableMonitor.getClassArray("ignores");
        addIgnoresException(ignores);

    }

    private void addIgnoresException(Class<?>[] ignores) {
        if (ignoresException == null && ignores != null) {
            ignoresException = new HashSet<>(ignores.length + 4);
        }

        for (Class<?> ignore : ignores) {
            ignoresException.add((Class<? extends Throwable>) ignore);
        }

        if (logger.isInfoEnabled()) {
            for (Class<?> ex : ignores) {
                logger.info("ignoresException: " + ex.getName());
            }
        }
    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Docs For Class Swift_Transport_SendmailTransport</title>
  <link rel="stylesheet" href="../../media/stylesheet.css" />

<link id="webfx-tab-style-sheet" type="text/css" rel="stylesheet" href="../../media/lib/tab.webfx.css" />

	Class Swift_Transport_SendmailTransport

 (line 27)

Description

Swift_Transport_AbstractSmtpTransport
   |
   --Swift_Transport_SendmailTransport

	Located in File: /vendors/swiftMailer/classes/Swift/Transport/SendmailTransport.php

SendmailTransport for sending mail through a sendmail/postfix (etc..) binary.

Supported modes are -bs and -t, with any additional flags desired.  It is advised to use -bs mode since error reporting with -t mode is not  possible.

author: - Chris Corbyn

Classes extended from Swift_Transport_SendmailTransport:

Swift_SendmailTransport

SendmailTransport for sending mail through a sendmail/postfix (etc..) binary.

Class Variables

Summary:

Class Constants

Summary:

Method Detail

Summary:

            Swift_Transport_SendmailTransport
        __construct
        (Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher)

            string
        getCommand
        ()

            int
        send
        (Swift_Mime_Message $message, [string[] &$failedRecipients = null])

            void
        setCommand
        (string $command)

            void
        start
        ()

            void
        _getBufferParams
        ()

 Constructor __construct (line 48)

Swift_Transport_SendmailTransport __construct(
Swift_Transport_IoBuffer
$buf, Swift_Events_EventDispatcher
$dispatcher)

Overridden in child classes as:

Swift_SendmailTransport::__construct()

Create a new SendmailTransport, optionally using $command for sending.

Overrides : Swift_Transport_AbstractSmtpTransport::__construct() Creates a new EsmtpTransport using the given I/O buffer.

Create a new SendmailTransport with $buf for I/O.

Parameters

Swift_Transport_IoBuffer $buf:

Swift_Events_EventDispatcher $dispatcher:

Info

access - public

 Method getCommand (line 84)

string getCommand(
)

Get the sendmail command which will be invoked.

Info

access - public

 Method send (line 99)

int send(
Swift_Mime_Message
$message, [string[]
&$failedRecipients = null])

Overrides : Swift_Transport_AbstractSmtpTransport::send() Send the given Message.

Send the given Message.

Recipient/sender data will be retreived from the Message API.  The return value is the number of recipients who were accepted for delivery.  NOTE: If using 'sendmail -t' you will not be aware of any failures until  they bounce (i.e. send() will always return 100% success).

Parameters

Swift_Mime_Message $message:

string[] &$failedRecipients: to collect failures by-reference

Info

access - public

 Method setCommand (line 74)

void setCommand(
string
$command)

Set the command to invoke.

If using -t mode you are strongly advised to include -oi or -i in the  flags. For example: /usr/sbin/sendmail -oi -t  Swift will append a -f<sender> flag if one is not present.  The recommended mode is "-bs" since it is interactive and failure notifications  are hence possible.

Parameters

string $command:

Info

access - public

 Method start (line 57)

void start(
)

Overrides : Swift_Transport_AbstractSmtpTransport::start() Start the SMTP connection.

Start the standalone SMTP session if running in -bs mode.

Info

access - public

 Method _getBufferParams (line 168)

void _getBufferParams(
)

Overrides : Swift_Transport_AbstractSmtpTransport::_getBufferParams() Return an array of params for the Buffer

Get the params to initialize the buffer

Info

access - protected

Inherited Variables

Inherited Class Variable Summary

Inherited From Class Swift_Transport_AbstractSmtpTransport

 Swift_Transport_AbstractSmtpTransport::$_buffer - Input-Output buffer for sending/receiving SMTP commands and responses

 Swift_Transport_AbstractSmtpTransport::$_domain - The domain name to use in HELO command

 Swift_Transport_AbstractSmtpTransport::$_eventDispatcher - The event dispatching layer

 Swift_Transport_AbstractSmtpTransport::$_started - Connection status

Inherited Methods

Inherited Method Summary

Inherited From Class Swift_Transport_AbstractSmtpTransport

 Swift_Transport_AbstractSmtpTransport::__construct() - Creates a new EsmtpTransport using the given I/O buffer.

 Swift_Transport_AbstractSmtpTransport::executeCommand() - Run a command against the buffer, expecting the given response codes.

 Swift_Transport_AbstractSmtpTransport::getBuffer() - Get the IoBuffer where read/writes are occurring.

 Swift_Transport_AbstractSmtpTransport::getLocalDomain() - Get the name of the domain Swift will identify as.

 Swift_Transport_AbstractSmtpTransport::isStarted() - Test if an SMTP connection has been established.

 Swift_Transport_AbstractSmtpTransport::registerPlugin() - Register a plugin.

 Swift_Transport_AbstractSmtpTransport::reset() - Reset the current mail transaction.

 Swift_Transport_AbstractSmtpTransport::send() - Send the given Message.

 Swift_Transport_AbstractSmtpTransport::setLocalDomain() - Set the name of the local domain which Swift will identify itself as.

 Swift_Transport_AbstractSmtpTransport::start() - Start the SMTP connection.

 Swift_Transport_AbstractSmtpTransport::stop() - Stop the SMTP connection.

 Swift_Transport_AbstractSmtpTransport::_assertResponseCode() - Throws an Exception if a response code is incorrect

 Swift_Transport_AbstractSmtpTransport::_doDataCommand() - Send the DATA command

 Swift_Transport_AbstractSmtpTransport::_doHeloCommand() - Send the HELO welcome

 Swift_Transport_AbstractSmtpTransport::_doMailFromCommand() - Send the MAIL FROM command

 Swift_Transport_AbstractSmtpTransport::_doRcptToCommand() - Send the RCPT TO command

 Swift_Transport_AbstractSmtpTransport::_getBufferParams() - Return an array of params for the Buffer

 Swift_Transport_AbstractSmtpTransport::_getFullResponse() - Get an entire multi-line response using its sequence number

 Swift_Transport_AbstractSmtpTransport::_getReversePath() - Determine the best-use reverse path for this message

 Swift_Transport_AbstractSmtpTransport::_readGreeting() - Read the opening SMTP greeting

 Swift_Transport_AbstractSmtpTransport::_streamMessage() - Stream the contents of the message over the buffer

 Swift_Transport_AbstractSmtpTransport::_throwException() - Throw a TransportException, first sending it to any listeners

 Swift_Transport_AbstractSmtpTransport::__destruct() - Destructor.

		Documentation generated on Fri, 12 Nov 2010 20:45:28 +0000 by phpDocumentor 1.4.3


text:
#include "libtorrent/config.hpp"
#include "libtorrent/disk_buffer_pool.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/aux_/session_settings.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/disk_observer.hpp"
#include "libtorrent/platform_util.hpp" // for total_physical_ram
#include "libtorrent/disk_interface.hpp" // for default_block_size

#include "libtorrent/aux_/disable_warnings_push.hpp"

#ifdef TORRENT_BSD
#include <sys/sysctl.h>
#endif

#ifdef TORRENT_LINUX
#include <linux/unistd.h>
#endif

#include "libtorrent/aux_/disable_warnings_pop.hpp"

namespace libtorrent {

	namespace {

	// this is posted to the network thread
	void watermark_callback(std::vector<std::weak_ptr<disk_observer>> const& cbs)
	{
		for (auto const& i : cbs)
		{
			std::shared_ptr<disk_observer> o = i.lock();
			if (o) o->on_disk();
		}
	}

	} // anonymous namespace

	disk_buffer_pool::disk_buffer_pool(io_service& ios
		, std::function<void()> const& trigger_trim)
		: m_in_use(0)
		, m_max_use(64)
		, m_low_watermark(std::max(m_max_use - 32, 0))
		, m_trigger_cache_trim(trigger_trim)
		, m_exceeded_max_size(false)
		, m_ios(ios)
	{
#if TORRENT_USE_ASSERTS
		m_magic = 0x1337;
		m_settings_set = false;
#endif
	}

	disk_buffer_pool::~disk_buffer_pool()
	{
		TORRENT_ASSERT(m_magic == 0x1337);
#if TORRENT_USE_ASSERTS
		m_magic = 0;
#endif

	}

	int disk_buffer_pool::num_to_evict(int const num_needed)
	{
		int ret = 0;

		std::unique_lock<std::mutex> l(m_pool_mutex);

		if (m_exceeded_max_size)
			ret = m_in_use - std::min(m_low_watermark, m_max_use - int(m_observers.size()) * 2);

		if (m_in_use + num_needed > m_max_use)
			ret = std::max(ret, m_in_use + num_needed - m_max_use);

		if (ret < 0) ret = 0;
		else if (ret > m_in_use) ret = m_in_use;

		return ret;
	}

	// checks to see if we're no longer exceeding the high watermark,
	// and if we're in fact below the low watermark. If so, we need to
	// post the notification messages to the peers that are waiting for
	// more buffers to received data into
	void disk_buffer_pool::check_buffer_level(std::unique_lock<std::mutex>& l)
	{
		TORRENT_ASSERT(l.owns_lock());
		if (!m_exceeded_max_size || m_in_use > m_low_watermark) return;

		m_exceeded_max_size = false;

		std::vector<std::weak_ptr<disk_observer>> cbs;
		m_observers.swap(cbs);
		l.unlock();
		m_ios.post(std::bind(&watermark_callback, std::move(cbs)));
	}

#if TORRENT_USE_ASSERTS
	bool disk_buffer_pool::is_disk_buffer(char* buffer
		, std::unique_lock<std::mutex>& l) const
	{
		TORRENT_ASSERT(m_magic == 0x1337);
		TORRENT_ASSERT(l.owns_lock());
		TORRENT_UNUSED(l);

#if TORRENT_USE_INVARIANT_CHECKS
		return m_buffers_in_use.count(buffer) == 1;
#else
		TORRENT_UNUSED(buffer);
		return true;
#endif
	}

	bool disk_buffer_pool::is_disk_buffer(char* buffer) const
	{
		std::unique_lock<std::mutex> l(m_pool_mutex);
		return is_disk_buffer(buffer, l);
	}
#endif

	char* disk_buffer_pool::allocate_buffer(char const* category)
	{
		std::unique_lock<std::mutex> l(m_pool_mutex);
		return allocate_buffer_impl(l, category);
	}

	// we allow allocating more blocks even after we exceed the max size,
	// but communicate back to the allocator (typically the peer_connection)
	// that we have exceeded the limit via the out-parameter "exceeded". The
	// caller is expected to honor this by not allocating any more buffers
	// until the disk_observer object (passed in as "o") is invoked, indicating
	// that there's more room in the pool now. This caps the amount of over-
	// allocation to one block per peer connection.
	char* disk_buffer_pool::allocate_buffer(bool& exceeded
		, std::shared_ptr<disk_observer> o, char const* category)
	{
		std::unique_lock<std::mutex> l(m_pool_mutex);
		char* ret = allocate_buffer_impl(l, category);
		if (m_exceeded_max_size)
		{
			exceeded = true;
			if (o) m_observers.push_back(o);
		}
		return ret;
	}

// this function allocates buffers and
// fills in the iovec array with the buffers
	int disk_buffer_pool::allocate_iovec(span<iovec_t> iov)
	{
		std::unique_lock<std::mutex> l(m_pool_mutex);
		for (auto& i : iov)
		{
			i = { allocate_buffer_impl(l, "pending read"), std::size_t(default_block_size)};
			if (i.data() == nullptr)
			{
				// uh oh. We failed to allocate the buffer!
				// we need to roll back and free all the buffers
				// we've already allocated
				for (auto j : iov)
				{
					if (j.data() == nullptr) break;
					char* buf = j.data();
					TORRENT_ASSERT(is_disk_buffer(buf, l));
					remove_buffer_in_use(buf);
					free_buffer_impl(buf, l);
				}
				return -1;
			}
		}
		return 0;
	}

	void disk_buffer_pool::free_iovec(span<iovec_t const> iov)
	{
		// TODO: perhaps we should sort the buffers here?
		std::unique_lock<std::mutex> l(m_pool_mutex);
		for (auto i : iov)
		{
			char* buf = i.data();
			TORRENT_ASSERT(is_disk_buffer(buf, l));
			remove_buffer_in_use(buf);
			free_buffer_impl(buf, l);
		}
		check_buffer_level(l);
	}

	char* disk_buffer_pool::allocate_buffer_impl(std::unique_lock<std::mutex>& l
		, char const*)
	{
		TORRENT_ASSERT(m_settings_set);
		TORRENT_ASSERT(m_magic == 0x1337);
		TORRENT_ASSERT(l.owns_lock());
		TORRENT_UNUSED(l);

		char* ret = static_cast<char*>(std::malloc(default_block_size));

		if (ret == nullptr)
		{
			m_exceeded_max_size = true;
			m_trigger_cache_trim();
			return nullptr;
		}

		++m_in_use;

#if TORRENT_USE_INVARIANT_CHECKS
		try
		{
			TORRENT_ASSERT(m_buffers_in_use.count(ret) == 0);
			m_buffers_in_use.insert(ret);
		}
		catch (...)
		{
			free_buffer_impl(ret, l);
			return nullptr;
		}
#endif

		if (m_in_use >= m_low_watermark + (m_max_use - m_low_watermark)
			/ 2 && !m_exceeded_max_size)
		{
			m_exceeded_max_size = true;
			m_trigger_cache_trim();
		}

		TORRENT_ASSERT(is_disk_buffer(ret, l));
		return ret;
	}

	void disk_buffer_pool::free_multiple_buffers(span<char*> bufvec)
	{
		// sort the pointers in order to maximize cache hits
		std::sort(bufvec.begin(), bufvec.end());

		std::unique_lock<std::mutex> l(m_pool_mutex);
		for (char* buf : bufvec)
		{
			TORRENT_ASSERT(is_disk_buffer(buf, l));
			remove_buffer_in_use(buf);
			free_buffer_impl(buf, l);
		}

		check_buffer_level(l);
	}

	void disk_buffer_pool::free_buffer(char* buf)
	{
		std::unique_lock<std::mutex> l(m_pool_mutex);
		TORRENT_ASSERT(is_disk_buffer(buf, l));
		remove_buffer_in_use(buf);
		free_buffer_impl(buf, l);
		check_buffer_level(l);
	}

	void disk_buffer_pool::set_settings(aux::session_settings const& sett)
	{
		std::unique_lock<std::mutex> l(m_pool_mutex);

		int const cache_size = sett.get_int(settings_pack::cache_size);
		if (cache_size < 0)
		{
			std::int64_t phys_ram = total_physical_ram();
			if (phys_ram == 0) m_max_use = 1024;
			else
			{
				// this is the logic to calculate the automatic disk cache size
				// based on the amount of physical RAM.
				// The more physical RAM, the smaller portion of it is allocated
				// for the cache.

				// we take a 40th of everything exceeding 4 GiB
				// a 30th of everything exceeding 1 GiB
				// and a 10th of everything below a GiB

				constexpr std::int64_t gb = 1024 * 1024 * 1024;

				std::int64_t result = 0;
				if (phys_ram > 4 * gb)
				{
					result += (phys_ram - 4 * gb) / 40;
					phys_ram = 4 * gb;
				}
				if (phys_ram > 1 * gb)
				{
					result += (phys_ram - 1 * gb) / 30;
					phys_ram = 1 * gb;
				}
				result += phys_ram / 20;
				m_max_use = int(result / default_block_size);
			}

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4127 ) /* warning C4127: conditional expression is constant */
#endif // _MSC_VER
			if (sizeof(void*) == 4)
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
			{
				// 32 bit builds should  capped below 2 GB of memory, even
				// when more actual ram is available, because we're still
				// constrained by the 32 bit virtual address space.
				m_max_use = std::min(2 * 1024 * 1024 * 3 / 4 * 1024
					/ default_block_size, m_max_use);
			}
		}
		else
		{
			m_max_use = cache_size;
		}
		m_low_watermark = m_max_use - std::max(16, sett.get_int(settings_pack::max_queued_disk_bytes) / 0x4000);
		if (m_low_watermark < 0) m_low_watermark = 0;
		if (m_in_use >= m_max_use && !m_exceeded_max_size)
		{
			m_exceeded_max_size = true;
			m_trigger_cache_trim();
		}

#if TORRENT_USE_ASSERTS
		m_settings_set = true;
#endif
	}

	void disk_buffer_pool::remove_buffer_in_use(char* buf)
	{
		TORRENT_UNUSED(buf);
#if TORRENT_USE_INVARIANT_CHECKS
		std::set<char*>::iterator i = m_buffers_in_use.find(buf);
		TORRENT_ASSERT(i != m_buffers_in_use.end());
		m_buffers_in_use.erase(i);
#endif
	}

	void disk_buffer_pool::free_buffer_impl(char* buf, std::unique_lock<std::mutex>& l)
	{
		TORRENT_ASSERT(buf);
		TORRENT_ASSERT(m_magic == 0x1337);
		TORRENT_ASSERT(m_settings_set);
		TORRENT_ASSERT(l.owns_lock());
		TORRENT_UNUSED(l);

		std::free(buf);

		--m_in_use;
	}

}


text:
import unittest
from collections import namedtuple

from applications.threaded_discussion import group

Message = namedtuple("Message", "pk parent_id body")

class ThreadedDiscussionTests(unittest.TestCase):
    def test_grouping(self):
        m1 = Message(1, None, 'hi')
        m2 = Message(2, None, 'hi')
        m3 = Message(3, 1, 'yo mate')
        m4 = Message(4, 1, 'yo too')

        raw_messages = [m1, m2, m3, m4]
        self.assertEqual(
            group(raw_messages),
            [(0, m1),
             (1, m3),
             (1, m4),
             (0, m2)]
        )


text:
package com.temple.util;

/**
 * TODOC
 *
 * @author Florent Pallaver
 * @version 1.0
 */
public final class TempleLogger extends AbstractLogger {

	/**
	 * Constructor.
	 */
	public TempleLogger() {
		super();
	}

	/**
	 * Constructor.
	 * TODOC
	 *
	 * @param prefix
	 */
	public TempleLogger(String prefix) {
		super(prefix);
	}

	/**
	 *
	 * @param loggerName
	 * @param prefix
	 */
	public TempleLogger(String loggerName, String prefix) {
		super(loggerName, prefix);
	}

	@Override
	public boolean isDebugLoggable() {
		return super.isDebugLoggable();
	}

	@Override
	public boolean isInfoLoggable() {
		return super.isInfoLoggable();
	}

	@Override
	public boolean isWarningLoggable() {
		return super.isWarningLoggable();
	}

	@Override
	public boolean isErrorLoggable() {
		return super.isErrorLoggable();
	}

	@Override
	public void debug(Object o) {
		super.debug(o);
	}

	@Override
	public void debug(String format, Object... params) {
		// TODO Auto-generated method stub
		super.debug(format, params);
	}

	@Override
	public void info(Object o) {
		super.info(o);
	}

	@Override
	public void info(String format, Object... params) {
		super.info(format, params);
	}

	@Override
	public void warning(Object o) {
		super.warning(o);
	}

	@Override
	public void warning(String format, Object... params) {
		super.warning(format, params);
	}

	@Override
	public void error(Object o) {
		super.error(o);
	}

	@Override
	public void error(String format, Object... params) {
		super.error(format, params);
	}

	@Override
	public void thrown(Throwable t) {
		super.thrown(t);
	}

	@Override
	public void thrown(String msg, Throwable t) {
		super.thrown(msg, t);
	}

	@Override
	public void report(Throwable t) {
		super.report(t);
	}

	@Override
	public void report(Object o) {
		super.report(o);
	}

	@Override
	public void ignored(Throwable t) {
		super.ignored(t);
	}

}


text:
package org.apache.activemq.bugs;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Topic;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.jmx.QueueViewMBean;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.usage.MemoryUsage;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AMQ6387Test {

    private static final Logger LOG = LoggerFactory.getLogger(AMQ6387Test.class);

    private final String QUEUE_NAME = "testQueue";
    private final String TOPIC_NAME = "testTopic";
    private final String SUBSCRIPTION_NAME = "subscriberId";
    private final String CLIENT_ID = "client1";
    private final int MSG_COUNT = 150;

    private ActiveMQConnectionFactory connectionFactory;
    private BrokerService brokerService;

    @Rule
    public TestName testName = new TestName();

    @Before
    public void setUp() throws Exception {

        LOG.info("=============== Starting test: {} ====================", testName.getMethodName());

        brokerService = new BrokerService();
        brokerService.setAdvisorySupport(false);
        brokerService.setPersistent(false);
        brokerService.setUseJmx(true);
        brokerService.setKeepDurableSubsActive(false);
        brokerService.start();
        connectionFactory = new ActiveMQConnectionFactory(brokerService.getVmConnectorURI());
    }

    @After
    public void tearDown() throws Exception {
        brokerService.stop();

        LOG.info("=============== Finished test: {} ====================", testName.getMethodName());
    }

    @Test
    public void testQueueMessagesKeptAfterDelivery() throws Exception {
        createDurableSubscription();
        assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
        assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

        sendBytesMessage(Queue.class);

        logBrokerMemoryUsage(Queue.class);

        assertEquals(0, brokerService.getAdminView().getQueueSubscribers().length);

        receiveMessages(Queue.class);

        assertEquals(0, brokerService.getAdminView().getQueueSubscribers().length);

        logBrokerMemoryUsage(Queue.class);

        assertEquals(0, getCurrentMemoryUsage(Queue.class));
    }

    @Test
    public void testQueueMessagesKeptAfterPurge() throws Exception {
        createDurableSubscription();
        assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
        assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

        sendBytesMessage(Queue.class);

        logBrokerMemoryUsage(Queue.class);

        assertEquals(0, brokerService.getAdminView().getQueueSubscribers().length);

        getProxyToQueue(QUEUE_NAME).purge();

        assertEquals(0, brokerService.getAdminView().getQueueSubscribers().length);

        logBrokerMemoryUsage(Queue.class);

        assertEquals(0, getCurrentMemoryUsage(Queue.class));
    }

    @Test
    public void testDurableTopicSubscriptionMessagesKeptAfterDelivery() throws Exception {
        createDurableSubscription();
        assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
        assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

        sendBytesMessage(Topic.class);

        logBrokerMemoryUsage(Topic.class);

        assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
        assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

        receiveMessages(Topic.class);

        assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
        assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

        logBrokerMemoryUsage(Topic.class);

        assertEquals(0, getCurrentMemoryUsage(Topic.class));
    }

    @Test
    public void testDurableTopicSubscriptionMessagesKeptAfterUnsubscribe() throws Exception {
        createDurableSubscription();
        assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
        assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

        sendBytesMessage(Topic.class);

        logBrokerMemoryUsage(Topic.class);

        assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
        assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

        unsubscribeDurableSubscription();

        assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
        assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

        logBrokerMemoryUsage(Topic.class);

        assertEquals(0, getCurrentMemoryUsage(Topic.class));
    }

    private void createDurableSubscription() throws JMSException {
        final Connection connection = connectionFactory.createConnection();
        connection.setClientID(CLIENT_ID);
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final Topic topic = session.createTopic(TOPIC_NAME);
        connection.start();

        session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, null, false);
        LOG.info("Created durable subscription.");

        connection.stop();
        connection.close();
    }

    private void receiveMessages(Class<? extends Destination> destType) throws JMSException {
        final Connection connection = connectionFactory.createConnection();
        connection.setClientID(CLIENT_ID);
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final Destination destination;
        if (destType.equals(Queue.class)) {
            destination = session.createQueue(QUEUE_NAME);
        } else {
            destination = session.createTopic(TOPIC_NAME);
        }

        final MessageConsumer consumer;
        if (destType.equals(Queue.class)) {
            consumer = session.createConsumer(destination);
        } else {
            consumer = session.createDurableSubscriber((Topic) destination, SUBSCRIPTION_NAME, null, false);
        }

        connection.start();

        for (int i = 0; i < MSG_COUNT; ++i) {
            assertNotNull(consumer.receive(5000));
        }

        connection.close();
    }

    private void sendBytesMessage(Class<? extends Destination> destType) throws JMSException {
        final Connection connection = connectionFactory.createConnection();
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final Destination destination;
        if (destType.equals(Queue.class)) {
            destination = session.createQueue(QUEUE_NAME);
        } else {
            destination = session.createTopic(TOPIC_NAME);
        }
        final MessageProducer producer = session.createProducer(destination);
        final BytesMessage bytesMessage = session.createBytesMessage();

        bytesMessage.writeBytes(new byte[1024 * 1024]);

        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        for (int i = 0; i < MSG_COUNT; ++i) {
            producer.send(bytesMessage);
        }

        connection.close();
    }

    private void unsubscribeDurableSubscription() throws JMSException {
        final Connection connection = connectionFactory.createConnection();
        connection.setClientID(CLIENT_ID);
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        session.unsubscribe(SUBSCRIPTION_NAME);
        LOG.info("Unsubscribed durable subscription.");

        connection.stop();
        connection.close();
    }

    private long getCurrentMemoryUsage(Class<? extends Destination> destType) throws Exception {
        final MemoryUsage usage;
        if (destType.equals(Queue.class)) {
            usage = brokerService.getDestination(ActiveMQDestination.createDestination(QUEUE_NAME, ActiveMQDestination.QUEUE_TYPE)).getMemoryUsage();
        } else {
            usage = brokerService.getDestination(ActiveMQDestination.createDestination(TOPIC_NAME, ActiveMQDestination.TOPIC_TYPE)).getMemoryUsage();
        }

        return usage.getUsage();
    }

    private void logBrokerMemoryUsage(Class<? extends Destination> destType) throws Exception {
        LOG.info("Memory usage: broker={}% destination={}", brokerService.getAdminView().getMemoryPercentUsage(), getCurrentMemoryUsage(destType));
    }

    protected QueueViewMBean getProxyToQueue(String name) throws MalformedObjectNameException, JMSException {
        ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName="+name);
        QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext()
                .newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true);
        return proxy;
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';
import { Textarea } from '@strapi/design-system/Textarea';

const TextareaEnum = ({
  description,
  disabled,
  error,
  intlLabel,
  labelAction,
  name,
  onChange,
  placeholder,
  value,
}) => {
  const { formatMessage } = useIntl();
  const errorMessage = error ? formatMessage({ id: error, defaultMessage: error }) : '';
  const hint = description
    ? formatMessage(
        { id: description.id, defaultMessage: description.defaultMessage },
        { ...description.values }
      )
    : '';
  const label = formatMessage(intlLabel);
  const formattedPlaceholder = placeholder
    ? formatMessage(
        { id: placeholder.id, defaultMessage: placeholder.defaultMessage },
        { ...placeholder.values }
      )
    : '';

  const inputValue = Array.isArray(value) ? value.join('\n') : '';

  const handleChange = e => {
    const arrayValue = e.target.value.split('\n');

    onChange({ target: { name, value: arrayValue } });
  };

  return (
    <Textarea
      disabled={disabled}
      error={errorMessage}
      label={label}
      labelAction={labelAction}
      id={name}
      hint={hint}
      name={name}
      onChange={handleChange}
      placeholder={formattedPlaceholder}
      value={inputValue}
    >
      {inputValue}
    </Textarea>
  );
};

TextareaEnum.defaultProps = {
  description: null,
  disabled: false,
  error: '',
  labelAction: undefined,
  placeholder: null,
  value: '',
};

TextareaEnum.propTypes = {
  description: PropTypes.shape({
    id: PropTypes.string.isRequired,
    defaultMessage: PropTypes.string.isRequired,
    values: PropTypes.object,
  }),
  disabled: PropTypes.bool,
  error: PropTypes.string,
  intlLabel: PropTypes.shape({
    id: PropTypes.string.isRequired,
    defaultMessage: PropTypes.string.isRequired,
    values: PropTypes.object,
  }).isRequired,
  labelAction: PropTypes.element,
  name: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
  placeholder: PropTypes.shape({
    id: PropTypes.string.isRequired,
    defaultMessage: PropTypes.string.isRequired,
    values: PropTypes.object,
  }),
  value: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
};

export default TextareaEnum;


text:
@interface CIMuseumVideosViewController ()

@end

@implementation CIMuseumVideosViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Configure nav button
    if (IS_IPHONE) {
        CINavigationItem *navItem = (CINavigationItem *)self.navigationItem;
        [navItem setLeftBarButtonType:CINavigationItemLeftBarButtonTypeMenu target:self action:@selector(navLeftButtonDidPress:)];
    }

    // Load videos
    NSURL *url = [NSURL URLWithString:FEED_URL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [videosWebView loadRequest:request];
}

- (void)viewDidAppear:(BOOL)animated {
    // Analytics
    [CIAnalyticsHelper sendEvent:@"CMOA_TV"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)navLeftButtonDidPress:(id)sender {
    [self performSegueWithIdentifier:@"exitMuseumVideos" sender:self];
}

- (void)viewWillAppear:(BOOL)animated {
    // Show the navigation bar
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (IBAction)segueGoMuseumVideos:(UIStoryboardSegue *)segue {
}

#pragma mark - Webview delegate

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    // Show error view
    [webView removeFromSuperview];
    errorView.hidden = NO;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        requestURL = [[request URL] absoluteString];
        [self performSegueWithIdentifier:@"showBrowser" sender:self];
        return NO;
    }

    return YES;
}

- (IBAction)visitDidPress:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://cmoa.org"]];
}

#pragma mark - Transition

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showBrowser"]) {
        CIBrowserViewController *browserViewController = (CIBrowserViewController *)segue.destinationViewController;
        browserViewController.parentMode = @"museumVideos";
        browserViewController.viewTitle = @"CMOA TV";
        browserViewController.url = requestURL;
    }
}

@end


text:
<?php

/**
 * @file
 * Contains \Drupal\menu\Controller\MenuController.
 */

namespace Drupal\menu\Controller;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityManager;
use Drupal\menu_link\MenuLinkStorageControllerInterface;
use Drupal\system\MenuInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Returns responses for Menu routes.
 */
class MenuController implements ContainerInjectionInterface {

  /**
   * The menu link storage.
   *
   * @var \Drupal\menu_link\MenuLinkStorageControllerInterface
   */
  protected $menuLinkStorage;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManager
   */
  protected $entityManager;

  /**
   * Constructs a new MenuController.
   *
   * @param \Drupal\menu_link\MenuLinkStorageControllerInterface $menu_link_storage
   *   The storage controller.
   * @param \Drupal\Core\Entity\EntityManager $entity_manager
   *   The entity manager.
   */
  public function __construct(MenuLinkStorageControllerInterface $menu_link_storage, EntityManager $entity_manager) {
    $this->menuLinkStorage = $menu_link_storage;
    $this->entityManager = $entity_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity.manager')->getStorageController('menu_link'),
      $container->get('entity.manager')
    );
  }

  /**
   * Gets all the available menus and menu items as a JavaScript array.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request of the page.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The available menu and menu items.
   */
  public function getParentOptions(Request $request) {
    $available_menus = array();
    if ($menus = $request->request->get('menus')) {
      foreach ($menus as $menu) {
        $available_menus[$menu] = $menu;
      }
    }
    $options = _menu_get_options(menu_get_menus(), $available_menus, array('mlid' => 0));

    return new JsonResponse($options);
  }

  /**
   * Provides the menu link submission form.
   *
   * @param \Drupal\system\MenuInterface $menu
   *   An entity representing a custom menu.
   *
   * @return array
   *   Returns the menu link submission form.
   */
  public function addLink(MenuInterface $menu) {
    // @todo Remove this when https://drupal.org/node/1981644 is in.
    drupal_set_title(t('Add menu link'));
    $menu_link = $this->menuLinkStorage->create(array(
      'mlid' => 0,
      'plid' => 0,
      'menu_name' => $menu->id(),
    ));
    return $this->entityManager->getForm($menu_link);
  }

}


text:
#pragma once
#include "coreexp.h"
#include "maxheap.h"
#include <WTypes.h>
#include "maxtypes.h"
#include "color.h"
#include "box2.h"

/*! \sa  Advanced Topics on
Palettes,
Class Color, Class GammaMgr, COLORREF.\n\n
\par Description:
A useful utility class for managing user interface colors. This class has
several purposes:\n\n
* Maintain the default 3ds Max palette for doing 256 color graphics.\n\n
* Provides a mechanism for allocating "animated color slots" in the default
palette for use in the user interface.\n\n
* Provide various functions for doing dithered graphics using the default 3ds
Max palette.\n\n
All methods of this class are implemented by the system.\n\n
The following global function is used to get a pointer that may be used to call
the methods of this class: */
class GPort: public MaxHeapOperators {
	public:
		/*! \remarks Destructor */
		virtual ~GPort() {;}

		// get the palette index associated with the ith slot
		/*! \remarks Retrieves the palette index associated with the 'i-th'
		slot.
		\par Parameters:
		int i\n\n
		Specifies the slot. */
		virtual int AnimPalIndex(int i)=0;

		// returns a slot number if available, -1 if not:
		// typically called in WM_INITDIALOG processing for as
		// may slots as you need (total availible is 8)
		/*! \remarks Returns a slot number if available, -1 if not. Typically
		this is called in WM_INITDIALOG processing code for as many
		slots as you need (the total number available is 8).
		\return  A slot number if available; otherwise -1. */
		virtual int GetAnimPalSlot()=0;

		// Release an animated palete slot slot
		// Typically called in WM_DESTROY for each slot
		// obtained with GetAnimPalSlot
		/*! \remarks Releases the specified animated palette slot. Typically
		this is called in the WM_DESTROY code for each slot obtained
		with GetAnimPalSlot().
		\par Parameters:
		int i\n\n
		The palette slot to release. */
		virtual void ReleaseAnimPalSlot(int i)=0;

		// set the color associated with the ith animated slot
		/*! \remarks Sets the color associated with the 'i-th' animated slot.
		\par Parameters:
		int i\n\n
		The slot index.\n\n
		COLORREF cr\n\n
		The color to set. */
		virtual void SetAnimPalEntry(int i, COLORREF cr)=0;

		// Stuff the standard MAX palette the palette for the HDC,
		// handing back a handle to the old palette.
		/*! \remarks This method puts the standard 3ds Max palette into the
		palette for the HDC, handing back a handle to the old palette.
		\par Parameters:
		HDC hdc\n\n
		The device context.
		\return  The handle of the old palette. */
		virtual HPALETTE PlugPalette(HDC hdc)=0;

		// Create a brush for drawing with the ith animated palette slot color
		/*! \remarks This method creates a brush for drawing with the
		specified animated palette slot color.
		\par Parameters:
		int slotNum\n\n
		The animated palette slot.\n\n
		COLORREF col\n\n
		The color to use.
		\return  The handle of the brush created. */
		virtual HBRUSH MakeAnimBrush(int slotNum, COLORREF col )=0;

		// Update colors calls the Windows UpdateColors on the hdc.
		// Returns 1 iff it changed screen pixel values .
	 	// Call this when get WM_PALETTECHANGED Msg
		/*! \remarks This method calls the Windows API UpdateColors()
		on the specified device context handle hdc. Call this when you
		get a WM_PALETTECHANGED message.
		\par Parameters:
		HDC hdc\n\n
		The handle of the device context.
		\return  Nonzero if it changed screen pixel values; otherwise zero. */
		virtual int UpdateColors(HDC hdc)=0;

		// After several SetAnimPalEntry calls, call this to affect the
		// HDC's palette
		/*! \remarks After several calls to SetAnimPalEntry(), call
		this to affect the HDC's palette. This puts the palette into the
		HDC so it will take effect.
		\par Parameters:
		HDC hdc\n\n
		The handle of the device context. */
		virtual void AnimPalette(HDC hdc)=0;

		// The companion function to PlugPalette.
		/*! \remarks This method puts the previous 3ds Max palette (returned
		from PlugPalette()) into the palette for the HDC.
		\par Parameters:
		HDC hDC\n\n
		The handle of the device context.\n\n
		HPALETTE hOldPal\n\n
		The palette to restore. */
		virtual void RestorePalette(HDC hDC,HPALETTE hOldPal)=0;

		// Map an single row of pixels 24 bit color to indices into
		// the current GPort palette, applying a dither pattern.
		// This routine does NOT do gamma correction.
		// inp points to an array of width RGB triples.
		// outp is an array of width bytes.  x and y are necessary to
		// establish dither pattern alignment.
		/*! \remarks This method maps a single row of pixels in 24 bit color
		to indices into the current GPort palette, applying a dither pattern.
		This routine does NOT do gamma correction.\n\n
		Note that x and y are necessary to establish the dither
		pattern alignment. The dither pattern covers the entire map, and if you
		want to just dither part of it, you need to tell this method where you
		are within the pattern.
		\par Parameters:
		UBYTE* inp\n\n
		Points to an array of width BGR triples. This is a sequence of bytes
		structured as B,G,R,B,G R, etc. The first pixel is B,G,R then the next
		pixel is B,G,R, etc.\n\n
		UBYTE *outp\n\n
		The result - the color indices into the GPort palette. This array is
		width bytes in length.\n\n
		int x\n\n
		The x alignment position.\n\n
		int y\n\n
		The y alignment position.\n\n
		int width\n\n
		The number of items in the arrays above. */
		virtual void MapPixels(UBYTE* inp, UBYTE *outp, int x, int y, int width)=0;

		// Display an array of 24bit colors in the HDC: if the current display is 8 bit
		//  it will display it (with dither) using in the GPort palette, otherwise it
		//  will just blit to the screen. Does NOT do gamma correction.
		//   "drect" is the destination rectangle in the hdc.
		//   "map" points to an array of RGB triples, with bytesPerRow bytes on each scanline.
		//   "xsrc" and "ysrc" are the position within this source raster of the upper left
		//    corner of the rectangle to be copied..
		/*! \remarks Display an array of 24 bit colors in the HDC. If the
		current display is 8 bit it will display it (with dither) using in the
		GPort palette, otherwise it will just blit to the screen. This method
		does NOT do gamma correction.
		\par Parameters:
		HDC hdc\n\n
		The handle of the device context.\n\n
		Rect\& drect\n\n
		The destination rectangle in the hdc.\n\n
		int xsrc\n\n
		The X position within this source raster of the upper left corner of
		the rectangle to be copied.\n\n
		int ysrc\n\n
		The Y position within this source raster of the upper left corner of
		the rectangle to be copied.\n\n
		UBYTE *map\n\n
		Points to an array of BGR triples.\n\n
		int bytesPerRow\n\n
		The number of bytes per row on each scanline of map. */
		virtual void DisplayMap(HDC hdc, Rect& drect,int xsrc, int ysrc, UBYTE *map, int bytesPerRow)=0;

		// This version stretches the image (if src!=dest).
		//  "dest" is the destination rectangle in the hdc;
		//  "src" is the source rectangle in map.
		/*! \remarks This version of DisplayMap() stretches the image
		if the source rectangle is not the same size as the destination
		rectangle. src should be the size of the image.
		\par Parameters:
		HDC hdc\n\n
		The handle of the device context.\n\n
		Rect\& dest\n\n
		The destination rectangle in the hdc.\n\n
		Rect\& src\n\n
		The source rectangle in map.\n\n
		UBYTE *map\n\n
		Points to an array of RGB triples.\n\n
		int bytesPerRow\n\n
		The number of bytes per row on each scanline of map. */
		virtual void DisplayMap(HDC hdc, Rect& dest, Rect& src, UBYTE *map, int bytesPerRow)=0;

		// DitherColorSwatch first gamma corrects Color c using the current
		// display gamma. In paletted modes, it will fill rectangle "r" with
		// a dithered pattern  approximating Color c.  In 24 bit modes it just
		// fills the rectange with c.
		/*! \remarks This method first gamma corrects Color c using the
		current display gamma. In paletted modes, it will fill rectangle
		r with a dithered pattern approximating Color c. In 24
		bit modes it just fills the rectangle with Color c.
		\par Parameters:
		HDC hdc\n\n
		The handle of the device context.\n\n
		Rect\& r\n\n
		The rectangle to fill.\n\n
		Color c\n\n
		The color to approximate (8 bit) or fill with (24 bit). */
		virtual void DitherColorSwatch(HDC hdc, Rect& r, Color c)=0;

		// This attempts to use the animated color slot indicated by "slot"
		// to paint a rectangular color swatch.
		// If slot is -1, it will uses DitherColorSwatch.  It does gamma correction.
		/*! \remarks This method attempts to use the animated color slot
		indicated by "slot" to paint a rectangular color swatch. If slot is -1,
		it will uses DitherColorSwatch(). This method does handle gamma
		correction.
		\par Parameters:
		HDC hdc\n\n
		The handle of the device context.\n\n
		DWORD col\n\n
		The color to paint. The format is the same as
		COLORREF.\n\n
		int slot\n\n
		Specifies the slot to use. If -1 then DitherColorSwatch() is
		used.\n\n
		int left\n\n
		The left coordinate of the rectangular area to paint.\n\n
		int top\n\n
		The top coordinate of the rectangular area to paint.\n\n
		int right\n\n
		The right coordinate of the rectangular area to paint.\n\n
		int bottom\n\n
		The bottom coordinate of the rectangular area to paint. */
		virtual void PaintAnimPalSwatch(HDC hdc, DWORD col, int slot, int left, int top, int right, int bottom)=0;

		// get the current GPort palette.
		/*! \remarks Returns the current GPort palette. */
		virtual HPALETTE GetPalette()=0;
	};

// Normally this is the only one of these, and this gets you a pointer to it.
/*! \remarks There is only a single global instance of this class, and this
method returns a pointer to it. A developer may use this pointer to call the
methods of GPort.
\par Sample Code:
int animColSlot = GetGPort()-\>GetAnimPalSlot();  */
extern CoreExport GPort* GetGPort();


text:
package io.reactivex.internal.operators.completable;

import static org.junit.Assert.assertTrue;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import io.reactivex.*;
import io.reactivex.functions.Function;
import io.reactivex.observers.TestObserver;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.*;
import io.reactivex.subjects.PublishSubject;

public class CompletableSubscribeOnTest {

    @Test
    public void normal() {
        List<Throwable> list = TestHelper.trackPluginErrors();
        try {
            TestScheduler scheduler = new TestScheduler();

            TestObserver<Void> ts = Completable.complete()
            .subscribeOn(scheduler)
            .test();

            scheduler.advanceTimeBy(1, TimeUnit.SECONDS);

            ts.assertResult();

            assertTrue(list.toString(), list.isEmpty());
        } finally {
            RxJavaPlugins.reset();
        }
    }

    @Test
    public void dispose() {
        TestHelper.checkDisposed(PublishSubject.create().ignoreElements().subscribeOn(new TestScheduler()));
    }

    @Test
    public void doubleOnSubscribe() {
        TestHelper.checkDoubleOnSubscribeCompletable(new Function<Completable, CompletableSource>() {
            @Override
            public CompletableSource apply(Completable c) throws Exception {
                return c.subscribeOn(Schedulers.single());
            }
        });
    }
}


text:
Flic is a lightweight but thread-safe Ruby implementation of the [Fliclib](https://github.com/50ButtonsEach/fliclib-linux-hci/blob/master/ProtocolDocumentation.md). It interfaces with [flicd](https://github.com/50ButtonsEach/fliclib-linux-hci), and allows [Flic buttons](https://flic.io/) to be used as an input for Ruby applications.

## Installation
Add this line to your application's Gemfile:

```ruby
gem 'flic'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install flic

## Simple Usage
The easiest way to get up an running is to use `Flic::SimpleClient`. It is a thin wrapper around `Flic::Client` that provides a simplified, synchronous API for the most intuative uses of a Flic button.

### Establishing a connection to `flicd`
By default, `flicd` binds to `localhost` on port `5551`. These are also the defaults for `Filc::SimpleClient`. This means that if you are running `flicd` on your local machine, establishing a connection is as easy as creating a new instance of `Flic::SimpleClient`. For other configurations, you can initialize `Flic::SimpleCient` with host and port. For example, `Flic::SimpleClient.new('192.168.1.200', 5553)` will open a connection to `flicd` on `192.168.1.200` listening on port `5553`.

### Getting a list of buttons
To get a list of verified buttons (buttons associated and ready to be used with a given `flicd`), call `Flic::SimpleClient#buttons`. This will return a list of button's bluetooth addresses.

### Connecting a new button
A button must be in public mode before it can be added. To put a button in public mode, press and hold it for at least 7 seconds. `Flic::SimpleClient#connect_button` will return the bluetooh address of the button that was added or `nil` if no button was added.

### Disconnecting a button
Similarly, a button may be disconnected by passing `Flic::SimpleClient#disconnect_button` a button's bluetooth address.

### Listening for button events
`Flic::SimpleClient#listen` accepts a latency mode (`:low`, `:normal`, or `:high`) as it's first argument and button bluetooth addresses as its other arguments. For each event that occurs to those buttons, it yields the bluetooth address of the button responsible for a given event, the type of click involved in the event (`:button_down`, `:button_up`, `:button_single_click`, `:button_double_click`, or `:button_hold`), the time in seconds since the event occured, and whether the event was queued. **It will block until the connection is closed or the block raises some other exception.**

### Closing the connection to `flicd`
To gracefully cleanup all connection channels and close the socket connection, call `Flic::SimpleClient#shutdown`. Once a `Flic::SimpleClient` has been shutdown it will close the underlying socket and cannot be used anymore.

### Example
This is the script that I wrote to allow some of my Flic buttons to control Wink-enabled smart devices in home.
```ruby
#!/usr/bin/env ruby

require 'bundler/setup'
require 'flic'
require 'httparty'

# These bluetooth addresses were obtained from SimpleClient#connect_button
COFFEE_TABLE_BUTTON  = 'XX:XX:XX:XX:XX:XX'
LIVING_ROOM_BUTTON   = 'XX:XX:XX:XX:XX:XX'
BEDROOM_BUTTON       = 'XX:XX:XX:XX:XX:XX'
NIGHTSTAND_BUTTON    = 'XX:XX:XX:XX:XX:XX'

# Obtained from https://winkbearertoken.appspot.com/
WINK_REQUEST_OPTIONS = {
    headers: {
        Authorization: 'Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    }
}

# Get a list of all scenes
# HTTParty.get('https://api.wink.com/users/me/scenes', WINK_REQUEST_OPTIONS)
SCENES = {
    arriving:                     'XXXXXXX',
    leaving:                      'XXXXXXX',
    sleeping:                     'XXXXXXX',
    turn_on_living_room_lights:   'XXXXXXX',
    turn_off_living_room_lights:  'XXXXXXX',
    turn_on_bedroom_lights:       'XXXXXXX',
    turn_off_bedroom_lights:      'XXXXXXX',
    waking_up:                    'XXXXXXX'
}

ACTIONS = {
    COFFEE_TABLE_BUTTON => {
        button_single_click:  :turn_on_living_room_lights,
        button_double_click:  :turn_off_living_room_lights,
        button_hold:          :leaving
    },
    LIVING_ROOM_BUTTON => {
        button_single_click:  :turn_on_living_room_lights,
        button_double_click:  :turn_off_living_room_lights,
        button_hold:          :leaving
    },
    BEDROOM_BUTTON => {
        button_single_click:  :turn_on_bedroom_lights,
        button_double_click:  :turn_off_bedroom_lights,
        button_hold:          :sleeping
    },
    NIGHTSTAND_BUTTON => {
        button_single_click:  :turn_on_bedroom_lights,
        button_double_click:  :turn_off_bedroom_lights,
        button_hold:          :waking_up
    }
}

# Let's get this party started!
begin
  puts '[*] Opening a connection to flicd...'
  client = Flic::SimpleClient.new

  puts '[*] Entering main loop'
  client.listen(:low, COFFEE_TABLE_BUTTON, LIVING_ROOM_BUTTON, BEDROOM_BUTTON, NIGHTSTAND_BUTTON) do |button, event, latency|
    begin
      scene = SCENES[ACTIONS[button][event]]

      if scene && latency < 5
        puts "[*] [#{button}] Handling #{event}"

        HTTParty.post("https://api.wink.com/scenes/#{scene}/activate", WINK_REQUEST_OPTIONS)
      else
        puts "[*] [#{button}] Ignoring #{event}"
      end
    rescue StandardError => error
      puts "[!] Whoops! `#{error.inspect}` occured while processing #{event} on #{button}."
    end
  end
rescue StandardError => error
  puts "[!] Whoops! #{error.inspect} occured. Wait for a few seconds and restart everything."
  sleep 3

  retry
rescue Interrupt
  puts '[*] Shutting down gracefully because of an interrupt'

  client.shutdown
end
```

## Advanced Usage
The interface of `Flic::Client` closely mirrors [the official Java implimentation](https://github.com/50ButtonsEach/fliclib-linux-hci/tree/master/clientlib/java). Unlike `Flic::SimpleClient`, none of it's methods are blocking except `Flic::Client#handle_next_event` which blocks until the next event is recevied and dispatches it to the approprate handlers and `Flic::Client#enter_main_loop` which blocks until the client is shutdown and dispatches events as they are received. Ideally, `Flic::Client#enter_main_loop` should be run in a dedicated networking / event dispatch thread.

## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/anarchocurious/flic.

## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
<?php
namespace Incompass\AirbrakeBundle\DependencyInjection;

use Airbrake\ErrorHandler;
use Airbrake\Notifier;
use Incompass\AirbrakeBundle\EventListener\ExceptionListener;
use Incompass\AirbrakeBundle\EventListener\ShutdownListener;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
 * Class IncompassAirbrakeExtension
 *
 * @package Incompass\AirbrakeBundle\DependencyInjection
 * @author  Joe Mizzi <joe@casechek.com>
 */
class AirbrakeExtension extends Extension
{
    /**
     * @param array $configs
     * @param ContainerBuilder $container
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('airbrake.project_id', $config['project_id']);
        $container->setParameter('airbrake.project_key', $config['project_key']);
        $container->setParameter('airbrake.host', $config['host']);
        $container->setParameter('airbrake.ignored_exceptions', $config['ignored_exceptions']);

        if ($config['project_key']) {

            $rootDirectory = dirname($container->getParameter('kernel.root_dir'));

            // Airbrake notifier
            $container->setDefinition(
                'airbrake.notifier',
                new Definition(
                    Notifier::class,
                    [[
                        'projectId'     => $config['project_id'],
                        'projectKey'    => $config['project_key'],
                        'host'          => $config['host'],
                        'appVersion'    => $this->getVersion($rootDirectory),
                        'environment'   => $container->getParameter('kernel.environment'),
                        'rootDirectory' => $rootDirectory
                    ]]
                )
            );

            // Exception Listener
            $container->setDefinition(
                'airbrake.exception_listener',
                (new Definition(
                    ExceptionListener::class,
                    [new Reference('airbrake.notifier'), $config['ignored_exceptions']]
                ))->addTag(
                    'kernel.event_listener',
                    ['event' => 'kernel.exception', 'method' => 'onKernelException']
                )->addTag(
                    'kernel.event_listener',
                    ['event' => 'console.exception', 'method' => 'onKernelException']
                )
            );

            // PHP Shutdown Listener
            $container->setDefinition(
                'airbrake.shutdown_listener',
                (new Definition(
                    ShutdownListener::class,
                    [new Reference('airbrake.notifier'), $config['ignored_exceptions']]
                ))->addTag(
                    'kernel.event_listener',
                    ['event' => 'kernel.controller', 'method' => 'register']
                )
            );

            /** @var Notifier $notifier */
            $notifier = $container->get('airbrake.notifier');
            $handler = new ErrorHandler($notifier);
            $handler->register();

            // Error Handler
            $container->set('airbrake.error_handler', $handler);
        }
    }

    /**
     * @param string $rootDirectory
     * @return null|string
     */
    public function getVersion($rootDirectory)
    {
        if (is_dir($rootDirectory . DIRECTORY_SEPARATOR . '.git')) {
            chdir($rootDirectory);
            exec('git describe --tags', $output, $return);
            return $return ? null : $output;
        } else {
            return null;
        }
    }
}


text:
'use strict';

const assert = require('assert');
const WebGLContext = require('../../src/core/WebGLContext');
require('webgl-mock');

describe('WebGLContext', function() {

	describe('#get()', function() {
		it('should return a WebGLRenderingContext when given a HTMLCanvasElement', function() {
			const canvas = new HTMLCanvasElement();
			const gl = WebGLContext.get(canvas);
			assert(gl instanceof WebGLRenderingContext);
			WebGLContext.remove(canvas);
		});
		it('should return a WebGLRenderingContext when given an id string referencing a HTMLCanvasElement', function() {
			const canvas = new HTMLCanvasElement();
			global.document = {
				getElementById: function() {
					return canvas;
				}
			};
			const gl = WebGLContext.get('test-id');
			assert(gl instanceof WebGLRenderingContext);
			WebGLContext.remove(canvas);
			global.document = undefined;
		});
		it('should return a WebGLRenderingContext when given an selector string referencing a HTMLCanvasElement', function() {
			const canvas = new HTMLCanvasElement();
			global.document = {
				getElementById: function() {
					return undefined;
				},
				querySelector: function() {
					return canvas;
				}
			};
			const gl = WebGLContext.get('.test-class');
			assert(gl instanceof WebGLRenderingContext);
			WebGLContext.remove(canvas);
			global.document = undefined;
		});
		it('should throw an exception if no canvas element can be referenced from the argument', function() {
			let result = false;
			try {
				WebGLContext.get(null);
			} catch(err) {
				result = true;
			}
			assert(result);
		});
		it('should return the previously created context if no argument is provided', function() {
			const canvas = new HTMLCanvasElement();
			const gl = WebGLContext.get(canvas);
			assert(gl instanceof WebGLRenderingContext);
			assert(gl === WebGLContext.get());
			WebGLContext.remove(canvas);
		});
		it('should bind the most recently created context', function() {
			const canvas0 = new HTMLCanvasElement();
			const canvas1 = new HTMLCanvasElement();
			const gl0 = WebGLContext.get(canvas0);
			assert(gl0 === WebGLContext.get(canvas0));
			const gl1 = WebGLContext.get(canvas1);
			assert(gl1 === WebGLContext.get(canvas1));
			WebGLContext.remove(canvas0);
			WebGLContext.remove(canvas1);
		});
	});

	describe('#bind()', function() {
		it('should throw an exception if no argument is passed', function() {
			let result = false;
			try {
				WebGLContext.bind();
			} catch(err) {
				result = true;
			}
			assert(result);
		});
		it('should throw an exception if no canvas element can be referenced from the argument', function() {
			let result = false;
			try {
				WebGLContext.bind(null);
			} catch(err) {
				result = true;
			}
			assert(result);
		});
		it('should bind the context as the current implicit context', function() {
			const canvas0 = new HTMLCanvasElement();
			const canvas1 = new HTMLCanvasElement();
			const gl0 = WebGLContext.get(canvas0);
			assert(gl0 === WebGLContext.get());
			const gl1 = WebGLContext.get(canvas1);
			assert(gl1 === WebGLContext.get());
			WebGLContext.bind(canvas0);
			assert(gl0 === WebGLContext.get());
			WebGLContext.remove(canvas0);
			WebGLContext.remove(canvas1);
		});
	});

	describe('#remove()', function() {
		it('should throw an exception if no argument is passed', function() {
			let result = false;
			try {
				WebGLContext.remove();
			} catch(err) {
				result = true;
			}
			assert(result);
		});
		it('should throw an exception if no canvas element can be referenced from the argument', function() {
			let result = false;
			try {
				WebGLContext.remove(null);
			} catch(err) {
				result = true;
			}
			assert(result);
		});
		it('should remove the context', function() {
			const canvas = new HTMLCanvasElement();
			const gl = WebGLContext.get(canvas);
			assert(gl === WebGLContext.get());
			WebGLContext.remove(canvas);
			let result = false;
			try {
				WebGLContext.get();
			} catch(err) {
				result = true;
			}
			assert(result);
		});
		it('should unbind the removed context if it is currently bound', function() {
			const canvas = new HTMLCanvasElement();
			const gl = WebGLContext.get(canvas);
			assert(gl === WebGLContext.get());
			WebGLContext.remove(canvas);
			let result = false;
			try {
				WebGLContext.get();
			} catch(err) {
				result = true;
			}
			assert(result);
		});
	});

	describe('#supportedExtensions()', function() {
		it('should return an array of supported extensions', function() {
			const canvas = new HTMLCanvasElement();
			WebGLContext.get(canvas);
			const exts = WebGLContext.supportedExtensions();
			assert(exts instanceof Array);
			WebGLContext.remove(canvas);
		});
		it('should throw an exception if no context is referenced', function() {
			let result = false;
			try {
				WebGLContext.supportedExtensions();
			} catch(err) {
				result = true;
			}
			assert(result);
		});
	});

	describe('#unsupportedExtensions()', function() {
		it('should return an array of unsupported extensions', function() {
			const canvas = new HTMLCanvasElement();
			WebGLContext.get(canvas);
			const exts = WebGLContext.unsupportedExtensions();
			assert(exts instanceof Array);
			WebGLContext.remove(canvas);
		});
		it('should throw an exception if no context is referenced', function() {
			let result = false;
			try {
				WebGLContext.unsupportedExtensions();
			} catch(err) {
				result = true;
			}
			assert(result);
		});
	});

	describe('#checkExtension()', function() {
		it('should return a bool for whether or not the extension is support', function() {
			const canvas = new HTMLCanvasElement();
			WebGLContext.get(canvas);
			const supported = WebGLContext.supportedExtensions();
			const unsupported = WebGLContext.unsupportedExtensions();
			supported.forEach(function(ext) {
				const isSupported = WebGLContext.checkExtension(ext);
				assert(typeof isSupported === 'boolean');
				assert(isSupported);
			});
			unsupported.forEach(function(ext) {
				const isSupported = WebGLContext.checkExtension(ext);
				assert(typeof isSupported === 'boolean');
				assert(!isSupported);
			});
			WebGLContext.remove(canvas);
		});
		it('should query an unbound context if provided', function() {
			const canvas = new HTMLCanvasElement();
			WebGLContext.get(canvas);
			const isSupported = WebGLContext.checkExtension(canvas, 'randomExt');
			assert(typeof isSupported === 'boolean');
			WebGLContext.remove(canvas);
		});
		it('should return throw an exception if no context is referenced', function() {
			let result = false;
			try {
				WebGLContext.checkExtension();
			} catch(err) {
				result = true;
			}
			assert(result);
		});
	});

	describe('#getExtension()', function() {
		it('should return an extension if it exists', function() {
			const canvas = new HTMLCanvasElement();
			WebGLContext.get(canvas);
			const supported = WebGLContext.supportedExtensions();
			supported.forEach(function(ext) {
				const instance = WebGLContext.getExtension(ext);
				assert(instance !== null);
			});
			WebGLContext.remove(canvas);
		});
		it('should return null if it doesnt exist', function() {
			const canvas = new HTMLCanvasElement();
			WebGLContext.get(canvas);
			const unsupported = WebGLContext.unsupportedExtensions();
			unsupported.forEach(function(ext) {
				const instance = WebGLContext.getExtension(ext);
				assert(instance === null);
			});
			WebGLContext.remove(canvas);
		});
		it('should query an unbound context if provided', function() {
			const canvas = new HTMLCanvasElement();
			const gl = WebGLContext.get(canvas);
			const instance = WebGLContext.getExtension('randomExt');
			assert(instance === null);
			WebGLContext.remove(gl);
		});
		it('should return throw an exception if no context is referenced', function() {
			let result = false;
			try {
				WebGLContext.getExtension();
			} catch(err) {
				result = true;
			}
			assert(result);
		});
	});

});


text:
{!! Form::select(
            'inventories[]',
            $allInventories,
            (isset($inventories) ? $inventories : null),
            array('class'=>'form-control select2', 'placeholder'=>'Search inventory...', 'multiple'=>true))
!!}


text:
This project follows semantic versioning.

Possible log types:

- `[added]` for new features.
- `[changed]` for changes in existing functionality.
- `[deprecated]` for once-stable features removed in upcoming releases.
- `[removed]` for deprecated features removed in this release.
- `[fixed]` for any bug fixes.
- `[security]` to invite users to upgrade in case of vulnerabilities.

### [v1.4.1][v1.4.1] (2020-09-04)

- [fixed] Syntax error in zsh completion file ([#138][i138])

Contributors to this version:

- [Francesco][@BachoSeven]
- [Bruno A. Muciño][@mucinoab]

Thanks!

### [v1.4.0][v1.4.0] (2020-09-03)

- [added] Configurable automatic cache updates ([#115][i115])
- [added] Improved color detection and support for `--color` argument and
  `NO_COLOR` env variable ([#111][i111])
- [changed] Make `--list` option comply with official spec ([#112][i112])
- [changed] Move cache age warning to stderr ([#113][i113])

Contributors to this version:

- [Atul Bhosale][@Atul9]
- [Danny Mösch][@SimplyDanny]
- [Ilaï Deutel][@ilai-deutel]
- [Kornel][@kornelski]
- [@LovecraftianHorror][@LovecraftianHorror]
- [@michaeldel][@michaeldel]
- [Niklas Mohrin][@niklasmohrin]

Thanks!

### [v1.3.0][v1.3.0] (2020-02-28)

- [added] New config option for compact output mode ([#89][i89])
- [added] New -m/--markdown parameter for raw rendering ([#95][i95])
- [added] Provide zsh autocompletion ([#86][i86])
- [changed] Require at least Rust 1.39 to build (previous: 1.32)
- [changed] Switch to GitHub actions, CI testing now covers Windows as well ([#99][i99])
- [changed] Tweak the "outdated cache" warning message ([#97][i97])
- [changed] General maintenance: Upgrade dependencies, fix linter warnings
- [fixed] Fix Fish autocompletion on macOS ([#87][i87])
- [fixed] Fix compilation on Windows by disabling pager ([#99][i99])

Contributors to this version:

- [@Calinou][@Calinou]
- [@Delapouite][@Delapouite]
- [@james2doyle][@james2doyle]
- [@jesdazrez][@jesdazrez]
- [@korrat][@korrat]
- [@ma-renaud][@ma-renaud]
- [@Plommonsorbet][@Plommonsorbet]

Thanks!

### [v1.2.0][v1.2.0] (2019-08-10)

- [added] Add Windows support ([#77][i77])
- [added] Add support for spaces in commands ([#75][i75])
- [added] Add support for Fish-based autocompletion ([#71][i71])
- [added] Add pager support ([#44][i44])
- [added] Print detected OS with `-v` / `--version` ([#57][i57])
- [changed] OS detection: Treat BSDs as "osx" ([#58][i58])
- [changed] Move from curl to reqwest ([#61][i61])
- [changed] Move to Rust 2018, require Rust 1.32 ([#69][i69] / [#84][i84])
- [fixed] Add (back) support for proxies ([#68][i68])

Contributors to this version:

- [@aldanor][@aldanor]
- [@Bassets][@Bassets]
- [@das-g][@das-g]
- [@jcgruenhage][@jcgruenhage]
- [@jdvr][@jdvr]
- [@jedahan][@jedahan]
- [@mystal][@mystal]
- [@natpen][@natpen]

Thanks!

### [v1.1.0][v1.1.0] (2018-10-22)

- [added] Configuration file support ([#43][i43])
- [added] Allow configuration of colors/style ([#43][i43])
- [added] New `--quiet` / `-q` option to suppress most non-error messages ([#48][i48])
- [changed] Require at least Rust 1.28 to build (previous: 1.19)
- [fixed] Fix building on systems with openssl 1.1.1 ([#47][i47])

Contributors to this version:

- [@equal-l2][@equal-l2]
- [Jonathan Dahan][@jedahan]
- [Lukas Bergdoll][@Voultapher]

Thanks!

### [v1.0.0][v1.0.0] (2018-02-11)

- [added] Include bash completions ([#34][i34])
- [changed] Update all dependencies
- [changed] Require at least Rust 1.19 to build (previous: 1.9)
- [changed] Improved unit/integration testing

### v0.4.0 (2016-11-25)

- [added] Support for new page format
- [changed] Update all dependencies

### v0.3.0 (2016-08-01)

- [changed] Update curl dependency

### v0.2.0 (2016-04-16)

- First crates.io release

[@aldanor]: https://github.com/aldanor
[@Atul9]: https://github.com/Atul9
[@BachoSeven]: https://github.com/BachoSeven
[@Bassets]: https://github.com/Bassets
[@Calinou]: https://github.com/Calinou
[@das-g]: https://github.com/das-g
[@Delapouite]: https://github.com/Delapouite
[@equal-l2]: https://github.com/equal-l2
[@ilai-deutel]: https://github.com/ilai-deutel
[@james2doyle]: https://github.com/james2doyle
[@jcgruenhage]: https://github.com/jcgruenhage
[@jdvr]: https://github.com/jdvr
[@jedahan]: https://github.com/jedahan
[@jesdazrez]: https://github.com/jesdazrez
[@kornelski]: https://github.com/kornelski
[@korrat]: https://github.com/korrat
[@LovecraftianHorror]: https://github.com/LovecraftianHorror
[@ma-renaud]: https://github.com/ma-renaud
[@michaeldel]: https://github.com/michaeldel
[@mucinoab]: https://github.com/mucinoab
[@mystal]: https://github.com/mystal
[@natpen]: https://github.com/natpen
[@niklasmohrin]: https://github.com/niklasmohrin
[@Plommonsorbet]: https://github.com/Plommonsorbet
[@SimplyDanny]: https://github.com/SimplyDanny
[@Voultapher]: https://github.com/Voultapher

[v1.0.0]: https://github.com/dbrgn/tealdeer/compare/v0.4.0...v1.0.0
[v1.1.0]: https://github.com/dbrgn/tealdeer/compare/v1.0.0...v1.1.0
[v1.2.0]: https://github.com/dbrgn/tealdeer/compare/v1.1.0...v1.2.0
[v1.3.0]: https://github.com/dbrgn/tealdeer/compare/v1.2.0...v1.3.0
[v1.4.0]: https://github.com/dbrgn/tealdeer/compare/v1.3.0...v1.4.0
[v1.4.1]: https://github.com/dbrgn/tealdeer/compare/v1.4.0...v1.4.1

[i34]: https://github.com/dbrgn/tealdeer/issues/34
[i43]: https://github.com/dbrgn/tealdeer/issues/43
[i44]: https://github.com/dbrgn/tealdeer/issues/44
[i47]: https://github.com/dbrgn/tealdeer/issues/47
[i48]: https://github.com/dbrgn/tealdeer/issues/48
[i57]: https://github.com/dbrgn/tealdeer/issues/57
[i58]: https://github.com/dbrgn/tealdeer/issues/58
[i61]: https://github.com/dbrgn/tealdeer/issues/61
[i68]: https://github.com/dbrgn/tealdeer/issues/68
[i69]: https://github.com/dbrgn/tealdeer/issues/69
[i71]: https://github.com/dbrgn/tealdeer/issues/71
[i75]: https://github.com/dbrgn/tealdeer/issues/75
[i77]: https://github.com/dbrgn/tealdeer/issues/77
[i84]: https://github.com/dbrgn/tealdeer/issues/84
[i86]: https://github.com/dbrgn/tealdeer/issues/86
[i87]: https://github.com/dbrgn/tealdeer/issues/87
[i89]: https://github.com/dbrgn/tealdeer/issues/89
[i95]: https://github.com/dbrgn/tealdeer/issues/95
[i97]: https://github.com/dbrgn/tealdeer/issues/97
[i99]: https://github.com/dbrgn/tealdeer/issues/99
[i111]: https://github.com/dbrgn/tealdeer/issues/111
[i112]: https://github.com/dbrgn/tealdeer/issues/112
[i113]: https://github.com/dbrgn/tealdeer/issues/113
[i115]: https://github.com/dbrgn/tealdeer/issues/115
[i138]: https://github.com/dbrgn/tealdeer/issues/138


text:
const cliente = require('./cliente/cliente.service.js');
const roles = require('./roles/roles.service.js');
const localidades = require('./localidades/localidades.service.js');
const provincias = require('./provincias/provincias.service.js');
const paises = require('./paises/paises.service.js');
const users = require('./users/users.service.js');
const empleados = require('./empleados/empleados.service.js');
module.exports = function () {
  const app = this; // eslint-disable-line no-unused-vars
  app.configure(cliente);
  app.configure(roles);
  app.configure(localidades);
  app.configure(provincias);
  app.configure(paises);
  app.configure(users);
  app.configure(empleados);
};


text:
require 'sequel'

require 'ghtorrent/migrations/mysql_defaults'

Sequel.migration do

  up do
    puts 'Adding table project_languages'

    create_table :project_languages do
      foreign_key :project_id, :projects, :null => false
      String :language, :null => false
      Integer :bytes, :null => false, :default => 0
      DateTime :created_at, :null => false,
               :default => Sequel::CURRENT_TIMESTAMP
    end
  end

  down do
    puts 'Dropping table project_languages'
    drop_table :project_languages
  end
end


text:
package br.ufs.demos.rxmvp.playground.core;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState;
import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView;
import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError;
import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

/**
 * Created by bira on 6/30/17.
 */

public class AssignEmptyStateTests {

    Scheduler uiScheduler = Schedulers.trampoline();
    AssignEmptyState<Integer> assignEmptyness;

    @Mock Action showEmtpyState;
    @Mock Action hideEmtpyState;

    @Before public void beforeEachTest() {
        MockitoAnnotations.initMocks(this);

        EmptyStateView view = new EmptyStateView() {

            @Override public Action showEmptyState() {
                return showEmtpyState;
            }

            @Override public Action hideEmptyState() {
                return hideEmtpyState;
            }
        };

        assignEmptyness = new AssignEmptyState<>(view, uiScheduler);
    }

    @Test public void shouldNotAssignEmpty_WhenFlowEmmits() throws Exception {
        Flowable.just(10, 20, 30)
                .compose(assignEmptyness)
                .subscribe();

        verify(hideEmtpyState, oneTimeOnly()).run();
        verify(showEmtpyState, never()).run();
    }

    @Test public void shouldNotAssignEmpty_WithEmptyFlow() throws Exception {
        Flowable<Integer> empty = Flowable.empty();
        empty.compose(assignEmptyness).subscribe();

        verify(hideEmtpyState, oneTimeOnly()).run();
        verify(showEmtpyState, never()).run();
    }

    @Test public void shouldNotAssignEmpty_WithNotTargetError() throws Exception {
        Flowable<Integer> broken = Flowable.error(new RuntimeException("WTF!!"));

        broken.compose(assignEmptyness)
                .subscribe(
                        some -> {},
                        Throwable::printStackTrace,
                        () -> {}
                );

        verify(hideEmtpyState, oneTimeOnly()).run();
        verify(showEmtpyState, never()).run();
    }

    @Test public void shouldAssignEmpty_WithNoContentError() throws Exception {
        Flowable<Integer> broken = Flowable.error(new ContentNotFoundError());

        broken.compose(assignEmptyness)
                .subscribe(
                        some -> {},
                        Throwable::printStackTrace,
                        () -> {}
                );

        verify(hideEmtpyState, oneTimeOnly()).run();
        verify(showEmtpyState, oneTimeOnly()).run();
    }
}


text:
print('Welcome to Tic Tac Toe!')

while True:
    # Function to print out a board
    row1 = [7, 8, 9]
    row2 = [4, 5, 6]
    row3 = [1, 2, 3]
    board = [row1, row2, row3]
    def display_board(board):
        print("Tic Tac Toe Board")
        print("-------------------")
        print('',board[0], '\n', board[1], '\n', board[2])
        print("-------------------")

    #Function to prompt and validate player marker
    player1 = ''
    player2 = ''
    def player_input():
        global player1
        global player2
        while True:
            player1 = input("Player 1, please select either X or O: ")
            player2 = input("Player 2, please select the remaining letter: ")
            if player1 != 'X' and player1 != 'O':
                print("Invalid choice, please choose again!")
            elif player2 != 'X' and player2 != 'O':
                print("Invalid choice, please choose again!")
            elif player2 == player1:
                print("Choice already taken, please choose again!")
            else:
                print("Player choices accepted!")
                print("Player 1 is: ", player1)
                print("Player 2 is: ", player2)
                break

    #Function to prompt user to input marker
    marker = ''
    position = ''
    def place_marker(board, marker, position):
        if position in range(1,4):
            x = (position-1) % 3
            board[2][x] = marker
        elif position in range(4,7):
            x = (position-1) % 3
            board[1][x] = marker
        elif position in range(7,10):
            x = (position-1) % 3
            board[0][x] = marker
        print('',board[0],'\n',board[1],'\n',board[2])

    #Function to check board for winner
    mark = ''
    def win_check(board, mark):
        first_col = [row[0] for row in board]
        second_col = [row[1] for row in board]
        third_col = [row[2] for row in board]
        diag1 = [board[0][0], board[1][1], board[2][2]]
        diag2 = [board[0][2], board[1][1], board[2][0]]
        this_player = ''
        if mark == player1:
            this_player = 'Player 1'
        else:
            this_player = 'Player 2'
        if len(set(first_col)) <= 1 and mark in set(first_col):
            print(this_player + ' wins!')
        elif len(set(second_col)) <= 1 and mark in set(second_col):
            print(this_player + ' wins!')
        elif len(set(third_col)) <= 1 and mark in set(third_col):
            print(this_player + ' wins!')
        elif len(set(diag1)) <= 1 and mark in set(diag1):
            print(this_player + ' wins!')
        elif len(set(diag2)) <= 1 and mark in set(diag2):
            print(this_player + ' wins!')
        elif len(set(board[0])) <= 1 and mark in set(board[0]):
            print(this_player + ' wins!')
        elif len(set(board[1])) <= 1 and mark in set(board[1]):
            print(this_player + ' wins!')
        elif len(set(board[2])) <= 1 and mark in set(board[2]):
            print(this_player + ' wins!')
        else:
            print(this_player + ' did not win yet!')

    #Function to randomly select which player goes first
    import random
    def choose_first():
        x = random.randint(1,2)
        if x == 1:
            return 'Player 1'
        else:
            return 'Player 2'

    #Function to check if a space on the board is free
    def space_check(board, position):
        x = int((9 - position)/3)
        y = (position - 1) % 3
        if board[x][y] == 'X' or board[x][y] == 'O':
            return False
        else:
            return True

    #Function to check if the board is full
    def full_board_check(board):
        for lists in board:
            if any(type(values) == int for values in lists):
                return False
        return True

    #Function to ask for player's next position
    def player_choice(board):
        position = int(input('Input position: '))
        x = space_check(board,position)
        if x is False:
            print('Space is not free!')
        else:
            print('Space is free!')
            return int(position)

    #Function to asks the player if they want to play again
    def replay():
        replay_value = input('Do you want to play again? Y/N: ')
        if replay_value == 'Y' or replay_value == 'y':
            return True
        elif replay_value == 'N' or replay_value == 'n':
            return False
        else:
            print('Invalid value!')

    player_input()
    turn = choose_first()
    print(turn + ' will go first.')
    game_on = True
    while game_on:
        if turn == 'Player 1':
            display_board(board)
            position = player_choice(board)
            place_marker(board, player1, position)

            if win_check(board,player1):
                display_board(board)
                break
            else:
                if full_board_check(board):
                    display_board(board)
                    print('Tie game!')
                    break
                else:
                    turn = 'Player 2'

        elif turn == 'Player 2':
            display_board(board)
            position = player_choice(board)
            place_marker(board,player2,position)

            if win_check(board,player2):
                display_board(board)
                break
            else:
                if full_board_check(board):
                    display_board(board)
                    print('Tie game!')
                    break
                else:
                    turn = 'Player 1'

    if not replay():
        break


text:
using System;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace BasicallyMe.RobinhoodNet
{
	public class InstrumentFundamentals
	{

        public decimal? Open { get; set; }
        public decimal? High { get; set; }
        public decimal? Low { get; set; }
        public decimal Volume { get; set; }
        public decimal? AverageVolume { get; set; }
        public decimal? High52Weeks { get; set; }
        public decimal? DividendYield { get; set; }
        public decimal? Low52Weeks { get; set; }
        public decimal? MarketCap { get; set; }
        public decimal? PERatio { get; set; }
        public string Description { get; set; }
        public Url<Instrument> Instrument { get; set; }

        public InstrumentFundamentals() { }

        internal InstrumentFundamentals(Newtonsoft.Json.Linq.JToken json) : this()
        {
            Open = (decimal?)json["open"];
            High = (decimal?)json["high"];
            Low = (decimal?)json["low"];
            Volume = (decimal)json["volume"];
            AverageVolume = (decimal?)json["average_volume"];
            High52Weeks = (decimal?)json["high_52_weeks"];
            DividendYield = (decimal?)json["dividend_yield"];
            Low52Weeks = (decimal?)json["low_52_weeks"];
            MarketCap = (decimal?)json["market_cap"];
            PERatio = (decimal?)json["pe_ratio"];
            Description = (string)json["description"];
            Instrument = new Url<Instrument>((string)json["instrument"]);
        }

    }
}


text:
import requests
from lxml import html

class so_scraper:
    base_url = "https://stackoverflow.com"  # Base URL for the SO website
    login_url = base_url + "/users/login"  # Login page URL
    session_request = []  # Independent instance of a web session request
    credentials = []  # Dictionary of login credentials with auth token
    main_page = []  # Main HTML page saved after successful login
    questions = []  # HTML element containing the sub elements of all the top questions belonging to class "question-mini-list"
    page_title = ""  # Title of the current page

    def __init__(self, email, password):

        """
        Initiates the session and Logs in with the provided credentials

        :param email:
        :param password:
        :return:
        """

        self.session_request = requests.session()
        result = self.session_request.get(self.login_url)
        login_page = html.fromstring(result.text)
        token = list(set(login_page.xpath("//input[@name='fkey']/@value")))[0]

        self.credentials = {
            "email": email,
            "password": password,
            "fkey": token
        }

        result = self.session_request.post(
            self.login_url,
            data=self.credentials,
            headers=dict(referer=self.login_url)
        )

        self.main_page = html.fromstring(result.content)
        self.page_title = str(self.main_page.xpath("//title/text()")[0])

        if self.page_title == "Stack Overflow":
            print "Login Successful" + "\n"
            self.questions = self.main_page.xpath("//div[@id='question-mini-list']")[0]
        else:
            print "Invalid Credentials" + "\n"

    def _get_reputation(self):

        """
        Parses the HTML page for reputation score

        :return: reputation as int
        """

        return int(str(self.main_page.xpath('//span[@class="reputation"]/text()')[0]).strip())

    def _get_ques_titles(self):

        """
        Parses the HTML page for all "Top Questions" titles

        :return: list of titles
        """

        return self.questions.xpath("//a[@class='question-hyperlink']/text()")

    def _get_ques_links(self):

        """
        Parses the HTML page for all "Top Questions" titles

        :return: list of questions links
        """

        return [self.base_url + link for link in self.questions.xpath("//a[@class='question-hyperlink']/@href")]

    def display_data(self):

        """
        Displays the reputation score along with all top questions and links in a neat format

        :return: none
        """

        try:
            print "Reputation: " + str(self._get_reputation()) + "\n"

            ques_titles = self._get_ques_titles()
            ques_links = self._get_ques_links()

            for i in xrange(len(ques_titles)):
                print "Question: " + str(i + 1)
                print ques_titles[i]
                print ques_links[i] + "\n"

        except:
            print "You are not logged in!"


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

<title>VehicleController</title>
<meta name="date" content="2015-11-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

ca.ualberta.cs.swapmyride

Class VehicleController

java.lang.Object

ca.ualberta.cs.swapmyride.VehicleController

public class VehicleController
extends java.lang.Object

Created by Garry on 2015-11-01.

Constructor Summary

Constructors

Constructor and Description

VehicleController()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
addPhoto(Drawable photo)

void
addVehicle(Vehicle vehicle)

void
deletePhoto(Vehicle vehicle,
           Context context)

void
editVehicle(Vehicle vehicle)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

VehicleController

public VehicleController()

Method Detail

addPhoto

public void addPhoto(Drawable photo)

addVehicle

public void addVehicle(Vehicle vehicle)

deletePhoto

public void deletePhoto(Vehicle vehicle,
                        Context context)

editVehicle

public void editVehicle(Vehicle vehicle)

Skip navigation links

Package

Class

Use

Tree

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
/**
 *
 */
package se.lbroman.msrp.data;

import se.lbroman.msrp.data.header.ContentTypeHeader;
import se.lbroman.msrp.data.packet.MsrpPacket.PACKET_TYPE;

/**
 * An MSRP transmission.
 *
 * @author Leonard Broman
 *
 */
public interface Transmission {

	public enum STATE {
		INCOMPLETE, COMPLETE, FAILED;
	}

	public void send();

	public void stop() throws IllegalStateException;

	public void pause() throws IllegalStateException;

	public void resume() throws IllegalStateException;

	public float percentTransmitted();

	public long size();

	/**
	 *
	 * @return the current state
	 */
	public STATE getState();

	public void setListener(TransmissionListener listener);

	/**
	 * @return the content type in the form of a header
	 */
	public ContentTypeHeader getContentType();

	public String getEncoding();

	public byte[] getContent();

	public String getId();

	public PACKET_TYPE getType();

}