text:
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using Microsoft.VisualStudio.Text.IncrementalSearch;
using TestUtilities.Mocks;

namespace Microsoft.VisualStudioTools.MockVsTests {
    class MockIncrementalSearch : IIncrementalSearch {
        private readonly MockTextView _view;

        public MockIncrementalSearch(MockTextView textView) {
            _view = textView;
        }

        public IncrementalSearchResult AppendCharAndSearch(char toAppend) {
            throw new NotImplementedException();
        }

        public void Clear() {
            throw new NotImplementedException();
        }

        public IncrementalSearchResult DeleteCharAndSearch() {
            throw new NotImplementedException();
        }

        public void Dismiss() {
            throw new NotImplementedException();
        }

        public bool IsActive {
            get { return false; }
        }

        public IncrementalSearchDirection SearchDirection {
            get {
                throw new NotImplementedException();
            }
            set {
                throw new NotImplementedException();
            }
        }

        public string SearchString {
            get {
                throw new NotImplementedException();
            }
            set {
                throw new NotImplementedException();
            }
        }

        public IncrementalSearchResult SelectNextResult() {
            throw new NotImplementedException();
        }

        public void Start() {
            throw new NotImplementedException();
        }

        public VisualStudio.Text.Editor.ITextView TextView {
            get { throw new NotImplementedException(); }
        }
    }
}


text:
\section{Introduction} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:intro}

%Motivate the problem
%Give a summary of the paper: what you did and how
%Explicitly state your contribution

Classic algebraic data types as seen in functional languages are closed and their
variants are disjoint, which allows for efficient implementation of case analysis
on such types. Data types in object-oriented languages are extensible
and hierarchical (implying that variants are not necessarily
disjoint).
To be general, case analysis on such types must be \emph{open}: allow for
independent extensions, modular type-checking, and dynamic linking. To be
accepted for production code, its implementation must also equal or outperform
all known workarounds. Existing approaches to case analysis on hierarchical
extensible data types are either efficient or open, but not both.
Truly open approaches rely on expensive class-membership tests combined with
decision trees. Efficient approaches rely on sealing either the class
hierarchy or the set of functions, which loses extensibility (\textsection\ref{sec:prev}). %~\cite{Cohen91,DesignPatterns1993,Vitek97,PQEncoding}.
Consider for example a simple expression language:
\begin{displaymath}
\SynCat{exp} \is{} \SynCat{val}
  \Alt{} \SynCat{exp} + \SynCat{exp}
  \Alt{} \SynCat{exp} - \SynCat{exp}
  \Alt{} \SynCat{exp} * \SynCat{exp}
  \Alt{} \SynCat{exp} / \SynCat{exp}
\end{displaymath}

\noindent
In an object-oriented language without direct support for algebraic data types,
the type representing an expression tree in the language will typically be
encoded as an abstract base class, %listing the (sealed set of) allowed virtual functions,
with derived classes implementing specific variants:
%
\begin{lstlisting}[keepspaces,columns=flexible]
struct Expr { virtual int eval() = 0; };
struct Value : Expr { @$\cdots$@ int eval(); int value; };
struct Plus  : Expr { @$\cdots$@ Expr& e1; Expr& e2; };
\end{lstlisting}

\noindent
A simple evaluator for this language can be implemented with the aid of a
virtual function \code{eval()} declared in the base class \code{Expr}.
The approach is \emph{intrusive}, however, as the base class has to be
modified every time we add a new functionality.
With \emph{Mach7}, we offer an external introspection of objects with case analysis:
%A less-intrusive solution can be achieved
%with \emph{visitor design pattern}~\cite{DesignPatterns1993}, which tries to
%leverage the case analysis common to all such functions. That solution, however,
%is not open as it restricts extensibility of classes.

%Our solution overcomes the limitations of visitor design pattern by allowing
%external introspection of objects with case analysis:

\begin{lstlisting}[columns=flexible]
int eval(const Expr& e)
{
  Match(e)
   Case(const  Value& x) return x.value;
   Case(const   Plus& x) return eval(x.e1)+eval(x.e2);
   Case(const  Minus& x) return eval(x.e1)-eval(x.e2);
   Case(const  Times& x) return eval(x.e1)*eval(x.e2);
   Case(const Divide& x) return eval(x.e1)/eval(x.e2);
  EndMatch
}
\end{lstlisting}

\noindent
This is all a user of \emph{Mach7} has to write.
The syntax is provided without any external tool support or
additional definitions from the user. The library is implemented in
standard ISO \Cpp{}11~\cite{C++11} with template meta-programming,
and a few macros (\textsection\ref{sec:vtblmem}). It runs
about as fast as OCaml and Haskell equivalents (\textsection\ref{sec:ocaml}),
and occasionally
%, depending on the usage scenario, compiler and underlying hardware,
comes close or
outperforms the handcrafted \Cpp{} code based on the \emph{visitor design pattern}
(\textsection\ref{sec:viscmp}).

The ideas and the
\emph{Mach7} library were motivated by our unsatisfactory experiences working
with various \Cpp{} front-ends and program analysis frameworks~\cite{Pivot09,gdr-2012:liz,Phoenix,Clang}.
The problem was not in the frameworks per se, but in the fact that we had to use
the \emph{visitor design pattern}~\cite{DesignPatterns1993} to inspect, traverse, and
elaborate abstract syntax trees of target languages. We found visitors
unsuitable to express application logic directly, surprisingly hard to teach
students, and often slower than handcrafted workaround techniques. Instead,
users were relying on dynamic casts in many places, often nested, thus preferring
shorter, cleaner, and more direct code to visitors. The consequential
performance penalty was usually not discovered until later, when it was hard to
remedy.

\subsection{Summary}

This paper makes the following contributions:
%
  \begin{itemize}
  \setlength{\itemsep}{0pt}
  \setlength{\parskip}{0pt}
  \item A technique for implementing open and efficient type
        switching on extensible hierarchical data types as seen in
        object-oriented languages.
  \item The technique delivers equivalent performance to that
        of closed algebraic data types, and outperforms the visitor design pattern for open class hierarchies.
  \item A library implementation provides the notational convenience of
        functional-language constructs for selecting among types.
  \item A new approach to type switching that combines subtype tests and type
        conversion, outperforming approaches that
        combine subtype tests (even constant-time ones) with decision trees, even over
        small class hierarchies.
  \item Complete integration with the existing \Cpp{} abstraction mechanisms and
        object model.
  \item A constant-time function that partitions
        a set of objects with the same static type into equivalence classes
        based on the inheritance path of the static type within the dynamic type.
%  \item We demonstrate that combining (even constant-time) subtype tests with
%        decision trees to the implementation of type switching is inferior in
%        performance to workaround techniques like visitor design pattern and our
%        approach for even small class hierarchies.
%  \item We advocate for taking the (space and time) complexity of type casts
%        into account when studying techniques for subtype testing, type
%        switching and run-time dispatch as these two operations are highly
%        coupled in the presence of multiple inheritance.
  \end{itemize}

\noindent
In particular, our technique for efficient type switching:
%
  \begin{itemize}
  \setlength{\itemsep}{0pt}
  \setlength{\parskip}{0pt}
  \item Is open by construction (\textsection\ref{sec:poets}), non-intrusive,
        and avoids the control inversion, as typical for visitors.
  \item Works in the presence of multiple inheritance, both repeated and
        virtual, as well as in generic code (\textsection\ref{sec:vtblmem}).
  \item Comes close to and often significantly outperforms the workaround techniques used in
        practice, e.g. the visitor design pattern, without sacrificing extensibility
        (\textsection\ref{sec:viscmp}).
  \item Does not require any changes to the \Cpp{} object model or computations at
        link or load time.
  \item Can be used in object-oriented languages with
        object models similar to that of \Cpp{}.
  \item Is implemented as a library written in ISO Standard \Cpp{}11.
%  \item It applies to polymorphic (\textsection\ref{sec:vtp}-\ref{sec:vtblmem}) and
%        tagged (\textsection\ref{sec:cotc}) class hierarchies through a unified
%        syntax~\cite[\textsection 8]{TR}.
%  \item Our memoization device (\textsection\ref{sec:memdev}) generalizes to
%        other languages and can be used to implement type switching
%        (\textsection\ref{sec:vtblmem}), type testing
%        (\textsection\ref{sec:poets},\cite[\textsection 9]{TR}), predicate dispatch
%        (\textsection\ref{sec:memdev}), and multiple dispatch efficiently.
%  \item We list conditions under which virtual table pointers, commonly used in
%        \Cpp{} implementations, uniquely identify the exact subobject within the
%        dynamic type (\textsection\ref{sec:vtp}).
%  \item We also build an efficient cache indexing function for virtual table
%        pointers that minimizes the number of conflicts
%        (\textsection\ref{sec:sovtp},\ref{sec:moc}).
  \end{itemize}

\noindent
This is the first technique for handling type switching efficiently
in the presence of the general multiple inheritance present in \Cpp{}.
Being a library, \emph{Mach7} can be used with any
ISO \Cpp{}11 compiler (e.g., Microsoft, GNU, or Clang) without requiring
any additional tools or preprocessors. It
sets a new threshold for acceptable performance, brevity, clarity, and
usefulness of a forthcoming compiler implementation of the open type switch in \Cpp{}.

%To the best of our knowledge this is the first technique capable of handling
%type switching in the presence of multiple inheritance in its full generality
%present in \Cpp{}. Prior work was mainly concentrating on constant-time type
%inclusion tests under assumptions that were oversimplifying the reality of \Cpp{}.
% and omitted discussion of type casts typically following such
%tests. We argue that in the presence of multiple inheritance the implementation
%of casts may be significantly slower than that of subtype tests and thus the
%complexity of the combined operation should be addressed by all the type
%inclusion testing techniques. Besides, approaches based on constant-time subtype
%tests require changes to object model and rely on load-time computations to
%ensure openness. In contrast, our approach requires neither changes to the \Cpp{}
%object model nor any computations at link or load time. We demonstrate that
%applying even the fastest subtype tests to the implementation of type switching
%is inferior in performance to visitor design pattern and our approach for even
%small class hierarchies.
%
%A practical benefit of our library solution is that it can be used right away with any
%compiler with a decent support of \Cpp{}11 without requiring the installation of
%any additional tools or preprocessors. The solution is a proof of concept that
%sets a minimum threshold for the performance, brevity, clarity and usefulness of
%a language solution for open type-switching in \Cpp{}.

%Due to page restrictions, we will only deal here with the part of the library
%concerned with efficient type testing, type identification, and type switching.
%These primitive operations are essential in providing support for type patterns
%and constructor patterns, and their efficiency relative to the visitor design
%pattern might become a major argument for their adoption. We refer the reader to
%technical report~\cite{TR} for more details on our pattern-matching
%library.

%Section~\ref{sec:probl} will motivate the problem as well as discuss some
%existing solutions and their limitations. Section~\ref{sec:copc} will outline
%the three techniques that comprise our solution, while the
%section~\ref{sec:eval} will evaluate their performance. Related work is
%discussed in Section~\ref{sec:rw}, followed by concluding remarks in
%Section~\ref{sec:cc}.

redpajama_set_name: RedPajamaGithub


text:
var assert = require('assert');
var ActiveDirectory = require('../index');
var config = require('./config');

describe('ActiveDirectory', function() {
  var ad;
  var settings = require('./settings').groupExists;

  before(function() {
   ad = new ActiveDirectory(config);
  });

  describe('#groupExists()', function() {
    it('should return true if the groupName (commonName) exists', function(done) {
      ad.groupExists(settings.sAMAccountName, settings.groupName.cn, function(err, exists) {
        if (err) return(done(err));
        assert(exists);
        done();
      });
    });
    it('should return true if the groupName (distinguishedName) exists', function(done) {
      ad.groupExists(settings.sAMAccountName, settings.groupName.dn, function(err, exists) {
        if (err) return(done(err));
        assert(exists);
        done();
      });
    });
    it('should return false if the groupName doesn\'t exist', function(done) {
      ad.groupExists(settings.sAMAccountName, '!!!NON-EXISTENT GROUP!!!', function(err, exists) {
        if (err) return(done(err));
        assert(! exists);
        done();
      });
    });
  });
});


text:
<?php

declare(strict_types=1);

namespace Core\Infrastructure\Configuration\NotificationPolicy\Api;

use Centreon\Application\Controller\AbstractController;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindMetaServiceNotificationPolicy;
use Core\Application\Configuration\NotificationPolicy\UseCase\FindNotificationPolicyPresenterInterface;

class FindMetaServiceNotificationPolicyController extends AbstractController
{
    /**
     * @param int $metaId
     * @param FindMetaServiceNotificationPolicy $useCase
     * @param FindNotificationPolicyPresenterInterface $presenter
     * @return object
     */
    public function __invoke(
        int $metaId,
        FindMetaServiceNotificationPolicy $useCase,
        FindNotificationPolicyPresenterInterface $presenter
    ): object {
        /**
         * Access denied if no rights given to the configuration and realtime for the current user
         */
        $this->denyAccessUnlessGrantedForApiConfiguration();
        $this->denyAccessUnlessGrantedForApiRealtime();

        $useCase($metaId, $presenter);

        return $presenter->show();
    }
}


text:
/** @file    proxy.hpp
 *  @author  William Emfinger
 *  @date    2016.07.20
 *  @brief   This file declares the proxy class
 */

#ifndef PROXY
#define PROXY
#include "component.hpp"

namespace zcm {

  /**
   * @brief proxy class
   */
  class proxy : public Component {
  public:

    /**
     * @brief Construct proxy & register all exposed functionality
     */
    proxy();

    /**
     * @brief Function for handling HiL service interface
     */
    void timer_function();

    /**
     * @brief Function for receiving traffic light state data
     */
    void state_sub_function();

    /**
     * @brief Function for receiving sensor data
     */
    void sensor_sub_function();

    /**
     * @brief Function for receiving service interface data
     */
    void interface_sub_function();

  private:
    std::map<std::string, int> sensorMap;
    std::map<std::string, std::string> stateMap;
  };
}

#endif


text:
namespace permissions {

// Observer for use in tests that want to detect whether a permission request
// was shown.  Can be used in a blocking or non-blocking way.
class PermissionRequestObserver : public PermissionRequestManager::Observer {
 public:
  explicit PermissionRequestObserver(content::WebContents* web_contents);
  PermissionRequestObserver(const PermissionRequestObserver&) = delete;
  PermissionRequestObserver& operator=(const PermissionRequestObserver&) =
      delete;
  ~PermissionRequestObserver() override;

  bool request_shown() const { return request_shown_; }

  // Blocks until a request is shown.
  void Wait();

  // PermissionRequestManager::Observer:
  void OnBubbleAdded() override;

 private:
  ScopedObserver<PermissionRequestManager, PermissionRequestManager::Observer>
      observer_{this};
  base::RunLoop loop_;
  bool request_shown_ = false;
};

}  // namespace permissions

#endif  // COMPONENTS_PERMISSIONS_TEST_PERMISSION_REQUEST_OBSERVER_H_


text:
<?php

// No direct access.
defined('_HZEXEC_') or die();

/**
 * Short description for 'WordLevelDiff'
 *
 * Long description (if any) ...
 */
class WordLevelDiff extends MappedDiff
{
	/**
	 * Description for 'AX_LINE_LENGTH'
	 */
	const MAX_LINE_LENGTH = 10000;

	/**
	 * Short description for 'WordLevelDiff'
	 *
	 * Long description (if any) ...
	 *
	 * @param      unknown $orig_lines Parameter description (if any) ...
	 * @param      unknown $closing_lines Parameter description (if any) ...
	 * @return     void
	 */
	public function __construct($orig_lines, $closing_lines)
	{
		list($orig_words, $orig_stripped) = $this->_split($orig_lines);
		list($closing_words, $closing_stripped) = $this->_split($closing_lines);

		parent::__construct($orig_words, $closing_words, $orig_stripped, $closing_stripped);
	}

	/**
	 * Short description for '_split'
	 *
	 * Long description (if any) ...
	 *
	 * @param      array $lines Parameter description (if any) ...
	 * @return     array Return description (if any) ...
	 */
	public function _split($lines)
	{
		$words = array();
		$stripped = array();
		$first = true;
		foreach ($lines as $line)
		{
			// If the line is too long, just pretend the entire line is one big word
			// This prevents resource exhaustion problems
			if ($first)
			{
				$first = false;
			}
			else
			{
				$words[] = "\n";
				$stripped[] = "\n";
			}
			if (strlen($line) > self::MAX_LINE_LENGTH)
			{
				$words[] = $line;
				$stripped[] = $line;
			}
			else
			{
				$m = array();
				if (preg_match_all('/ ([^\S\n]+ | [0-9_A-Za-z\x80-\xff]+ | .) (?: (?!< \n) [^\S\n])? /xs', $line, $m))
				{
					$words = array_merge($words, $m[0]);
					$stripped = array_merge($stripped, $m[1]);
				}
			}
		}
		return array($words, $stripped);
	}

	/**
	 * Short description for 'orig'
	 *
	 * Long description (if any) ...
	 *
	 * @return     unknown Return description (if any) ...
	 */
	public function orig()
	{
		$orig = new _HWLDF_WordAccumulator;

		foreach ($this->edits as $edit)
		{
			if ($edit->type == 'copy')
			{
				$orig->addWords($edit->orig);
			}
			elseif ($edit->orig)
			{
				$orig->addWords($edit->orig, 'del');
			}
		}
		$lines = $orig->getLines();

		return $lines;
	}

	/**
	 * Short description for 'closing'
	 *
	 * Long description (if any) ...
	 *
	 * @return     unknown Return description (if any) ...
	 */
	public function closing()
	{
		$closing = new _HWLDF_WordAccumulator;

		foreach ($this->edits as $edit)
		{
			if ($edit->type == 'copy')
			{
				$closing->addWords($edit->closing);
			}
			elseif ($edit->closing)
			{
				$closing->addWords($edit->closing, 'ins');
			}
		}
		$lines = $closing->getLines();

		return $lines;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Autofac;
using NHibernate;
using NUnit.Framework;
using Orchard.ContentManagement.FieldStorage.InfosetStorage;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;
using Orchard.Environment.Configuration;
using Orchard.Services;
using Orchard.Tests.ContentManagement;
using Orchard.Tests.Data;
using Orchard.Tests.Stubs;

namespace Orchard.Tests {
    public abstract class DatabaseEnabledTestsBase {

        protected IContainer _container;

        protected ISession _session;
        protected string _databaseFilePath;
        protected ISessionFactory _sessionFactory;
        protected StubClock _clock;

        [TestFixtureSetUp]
        public void InitFixture() {
        }

        [TestFixtureTearDown]
        public void TearDownFixture() {
            File.Delete(_databaseFilePath);
        }

        [SetUp]
        public virtual void Init() {
            _databaseFilePath = Path.GetTempFileName();
            _sessionFactory = DataUtility.CreateSessionFactory(_databaseFilePath, DatabaseTypes.ToArray());
            _session = _sessionFactory.OpenSession();
            _clock = new StubClock();

            var builder = new ContainerBuilder();
            //builder.RegisterModule(new ImplicitCollectionSupportModule());
            builder.RegisterType<InfosetHandler>().As<IContentHandler>();
            builder.RegisterInstance(new StubLocator(_session)).As<ISessionLocator>();
            builder.RegisterInstance(_clock).As<IClock>();
            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
            builder.RegisterInstance(new ShellSettings { Name = ShellSettings.DefaultName, DataProvider = "SqlCe" });
            builder.RegisterInstance(new TestTransactionManager(_session)).As<ITransactionManager>();

            Register(builder);
            _container = builder.Build();
        }

        [TearDown]
        public void Cleanup() {
            if(_container != null)
                _container.Dispose();
        }

        public abstract void Register(ContainerBuilder builder);

        protected virtual IEnumerable<Type> DatabaseTypes {
            get {
                return Enumerable.Empty<Type>();
            }
        }

        protected void ClearSession() {
            Trace.WriteLine("Flush and clear session");
            _session.Flush();
            _session.Clear();
            Trace.WriteLine("Flushed and cleared session");
        }
    }
}


text:
set -eu

ACCOUNT_ARN=$(aws sts get-caller-identity --query Arn --output text)

# Assume that the final portion of the ARN is the username
# Works for ARNs like `users/<user>` and `users/engineers/<user>`
USERNAME=$(echo "$ACCOUNT_ARN" | rev | cut -d/ -f1 | rev)

ACCOUNT_ID=$(echo "$ACCOUNT_ARN" | cut -d: -f5)
SERIAL_NUMBER="arn:aws:iam::${ACCOUNT_ID}:mfa/${USERNAME}"

CODE1=$(ykman oath accounts code -s "$SERIAL_NUMBER")

WAIT_TIME=$((30-$(date +%s)%30))
echo "Waiting $WAIT_TIME seconds before generating a second code" >&2
sleep $WAIT_TIME

CODE2=$(ykman oath accounts code -s "$SERIAL_NUMBER")

aws iam resync-mfa-device \
  --user-name "$USERNAME" \
  --serial-number "$SERIAL_NUMBER" \
  --authentication-code1 "$CODE1" \
  --authentication-code2 "$CODE2"


text:
using System;
using System.Collections.Generic;
using Quilt4.Service.Entity;

namespace Quilt4.Service.Interface.Business
{
    public interface IApplicationBusiness
    {
        IEnumerable<Application> GetApplications(Guid projectKey);
        IEnumerable<Application> GetApplications(string userName, Guid projectKey);
    }
}


text:
package org.scribe.builder.api;

public class VimeoApi extends DefaultApi10a
{
  @Override
  protected String getAccessTokenEndpoint()
  {
    return "http://vimeo.com/oauth/access_token";
  }

  @Override
  protected String getRequestTokenEndpoint()
  {
    return "http://vimeo.com/oauth/request_token";
  }
}


text:
package com.inappropirates.lightwalker.config;

import android.content.Context;
import android.widget.Button;

import com.inappropirates.lightwalker.ui.Color;

public class ColorButton extends Button {
    private Color color;

    public ColorButton(Context context, Color color) {
        super(context);

        this.color = color;

        setBackgroundColor(color.getAndroidColor());
        setText(color.getName());
    }

    public Color getColor() {
        return color;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<plugin
xmlns="http://www.phonegap.com/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="me.hanul.cordova.locale"
version="0.0.1">
	<name>Cordova Locale Plugin</name>
	<author>Hanul</author>
	<license>MIT</license>
	<repo>https://github.com/Hanul/Cordova-Locale-Plugin.git</repo>
	<issue>https://github.com/Hanul/Cordova-Locale-Plugin/issues</issue>
	<js-module src="www/Locale.js" name="Locale">
		<clobbers target="Locale" />
	</js-module>
	<platform name="android">
		<config-file target="res/xml/config.xml" parent="/*">
			<feature name="CordovaLocalePlugin">
				<param name="android-package" value="me.hanul.cordova.locale.CordovaLocalePlugin" />
			</feature>
		</config-file>
		<source-file src="src/me/hanul/cordova/locale/CordovaLocalePlugin.java" target-dir="src/me/hanul/cordova/locale" />
	</platform>
</plugin>


text:
SERVICE_NAME = 'example'

DEBUG = True

SERVER = {
	'host': 'localhost',
	'port': 5000,
}

# Modules loaded when application is initialized.
MODULES = ['example.views',]

# Modules loaded when tests are run
TEST_MODULES = ['example.tests',]

# Modules with additional configuration. Loaded from first to last.
CONFIG_MODULES = []


text:
#pragma once

#include <core/config_filesystem.h>
#include <core/Track.h>
#include <boost/scoped_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <sigslot/sigslot.h>
#include <list>

//////////////////////////////////////////////////////////////////////////////

namespace musik{ namespace core{

//////////////////////////////////////////////////////////////////////////////

class NonLibraryTrackHelper{
    public:
        static  NonLibraryTrackHelper& Instance();
        static boost::mutex& TrackMutex();

        void ReadTrack(musik::core::TrackPtr track);

        typedef sigslot::signal1<musik::core::TrackPtr> TrackMetadataUpdatedEvent;
        TrackMetadataUpdatedEvent TrackMetadataUpdated;

    private:
        static NonLibraryTrackHelper sInstance;

        NonLibraryTrackHelper(void);
        ~NonLibraryTrackHelper(void);

        void ThreadLoop();

    private:
        boost::mutex trackMutex;
        boost::mutex mutex;
        bool threadIsRunning;

        typedef boost::weak_ptr<musik::core::Track> TrackWeakPtr;
        std::list<TrackWeakPtr> tracksToRead;

        typedef boost::scoped_ptr<boost::thread> ThreadPtr;
        ThreadPtr helperThread;
};

//////////////////////////////////////////////////////////////////////////////
} } // musik::core
//////////////////////////////////////////////////////////////////////////////


text:
"""
Provides tests related with allowed TLS protocol version restrictions.
"""
import os
import ssl
import sys
import re
from subprocess import Popen, PIPE
from qpid_dispatch.management.client import Node
from system_test import TestCase, main_module, Qdrouterd, DIR, SkipIfNeeded
from system_test import unittest
from proton import SASL, Url, SSLDomain, SSLUnavailable
from proton.utils import BlockingConnection
from distutils.version import StrictVersion
import proton
import cproton

class RouterTestSslBase(TestCase):
    """
    Base class to help with SSL related testing.
    """
    # If unable to determine which protocol versions are allowed system wide
    DISABLE_SSL_TESTING = False
    DISABLE_REASON = "Unable to determine MinProtocol"

    @staticmethod
    def ssl_file(name):
        """
        Returns fully qualified ssl certificate file name
        :param name:
        :return:
        """
        return os.path.join(DIR, 'ssl_certs', name)

    @classmethod
    def create_sasl_files(cls):
        """
        Creates the SASL DB
        :return:
        """
        # Create a sasl database.
        pipe = Popen(['saslpasswd2', '-c', '-p', '-f', 'qdrouterd.sasldb',
                      '-u', 'domain.com', 'test'],
                     stdin=PIPE, stdout=PIPE, stderr=PIPE,
                     universal_newlines=True)
        result = pipe.communicate('password')
        assert pipe.returncode == 0, \
            "saslpasswd2 exit status %s, output:\n%s" % (pipe.returncode, result)

        # Create a SASL configuration file.
        with open('tests-mech-PLAIN.conf', 'w') as sasl_conf:
            sasl_conf.write("""
pwcheck_method: auxprop
auxprop_plugin: sasldb
sasldb_path: qdrouterd.sasldb
mech_list: ANONYMOUS DIGEST-MD5 EXTERNAL PLAIN
# The following line stops spurious 'sql_select option missing' errors when cyrus-sql-sasl plugin is installed
sql_select: dummy select
""")

class RouterTestSslClient(RouterTestSslBase):
    """
    Starts a router with multiple listeners, all of them using an sslProfile.
    Then it runs multiple tests to validate that only the allowed protocol versions
    are being accepted through the related listener.
    """
    # Listener ports for each TLS protocol definition
    PORT_TLS1 = 0
    PORT_TLS11 = 0
    PORT_TLS12 = 0
    PORT_TLS13 = 0
    PORT_TLS1_TLS11 = 0
    PORT_TLS1_TLS12 = 0
    PORT_TLS11_TLS12 = 0
    PORT_TLS_ALL = 0
    PORT_TLS_SASL = 0
    PORT_SSL3 = 0
    TIMEOUT = 3

    # If using OpenSSL 1.1 or greater, TLSv1.2 is always being allowed
    OPENSSL_OUT_VER = None
    try:
        OPENSSL_VER_1_1_GT = ssl.OPENSSL_VERSION_INFO[:2] >= (1, 1)
    except AttributeError:
        OPENSSL_VER_1_1_GT = False

    # If still False, try getting it from "openssl version" (command output)
    # The version from ssl.OPENSSL_VERSION_INFO reflects OpenSSL version in which
    # Python was compiled with, not the one installed in the system.
    if not OPENSSL_VER_1_1_GT:
        print("Python libraries SSL Version < 1.1")
        try:
            p = Popen(['openssl', 'version'], stdout=PIPE, universal_newlines=True)
            openssl_out = p.communicate()[0]
            m = re.search(r'[0-9]+\.[0-9]+\.[0-9]+', openssl_out)
            OPENSSL_OUT_VER = m.group(0)
            OPENSSL_VER_1_1_GT = StrictVersion(OPENSSL_OUT_VER) >= StrictVersion('1.1')
            print("OpenSSL Version found = %s" % OPENSSL_OUT_VER)
        except:
            pass

    # Following variables define TLS versions allowed by openssl
    OPENSSL_MIN_VER = 0
    OPENSSL_MAX_VER = 9999
    OPENSSL_ALLOW_TLSV1 = True
    OPENSSL_ALLOW_TLSV1_1 = True
    OPENSSL_ALLOW_TLSV1_2 = True
    OPENSSL_ALLOW_TLSV1_3 = False

    # Test if OpenSSL has TLSv1_3
    OPENSSL_HAS_TLSV1_3 = False
    if OPENSSL_VER_1_1_GT:
        try:
            ssl.TLSVersion.TLSv1_3
            OPENSSL_HAS_TLSV1_3 = True
        except:
            pass

    # Test if Proton supports TLSv1_3
    try:
        dummydomain = SSLDomain(SSLDomain.MODE_CLIENT)
        PROTON_HAS_TLSV1_3 = cproton.PN_OK == cproton.pn_ssl_domain_set_protocols(dummydomain._domain, "TLSv1.3")
        print("TLSV1_3? Proton has: %s, OpenSSL has: %s" % (PROTON_HAS_TLSV1_3, OPENSSL_HAS_TLSV1_3))
    except SSLUnavailable:
        PROTON_HAS_TLSV1_3 = False

    # When using OpenSSL >= 1.1 and python >= 3.7, we can retrieve OpenSSL min and max protocols
    if OPENSSL_VER_1_1_GT:
        if sys.version_info >= (3, 7):
            if OPENSSL_HAS_TLSV1_3 and not PROTON_HAS_TLSV1_3:
                # If OpenSSL has 1.3 but proton won't let us turn it on and off then
                # this test fails because v1.3 runs unexpectedly.
                RouterTestSslBase.DISABLE_SSL_TESTING = True
                RouterTestSslBase.DISABLE_REASON = "Proton version does not support TLSv1.3 but OpenSSL does"
            else:
                OPENSSL_CTX = ssl.create_default_context()
                OPENSSL_MIN_VER = OPENSSL_CTX.minimum_version
                OPENSSL_MAX_VER = OPENSSL_CTX.maximum_version if OPENSSL_CTX.maximum_version > 0 else 9999
                OPENSSL_ALLOW_TLSV1 = OPENSSL_MIN_VER <= ssl.TLSVersion.TLSv1 <= OPENSSL_MAX_VER
                OPENSSL_ALLOW_TLSV1_1 = OPENSSL_MIN_VER <= ssl.TLSVersion.TLSv1_1 <= OPENSSL_MAX_VER
                OPENSSL_ALLOW_TLSV1_2 = OPENSSL_MIN_VER <= ssl.TLSVersion.TLSv1_2 <= OPENSSL_MAX_VER
                OPENSSL_ALLOW_TLSV1_3 = OPENSSL_HAS_TLSV1_3 and PROTON_HAS_TLSV1_3 \
                                    and OPENSSL_MIN_VER <= ssl.TLSVersion.TLSv1_3 <= OPENSSL_MAX_VER
        else:
            # At this point we are not able to precisely determine what are the minimum and maximum
            # TLS versions allowed in the system, so tests will be disabled
            RouterTestSslBase.DISABLE_SSL_TESTING = True
            RouterTestSslBase.DISABLE_REASON = "OpenSSL >= 1.1 but Python < 3.7 - Unable to determine MinProtocol"
    else:
        if OPENSSL_HAS_TLSV1_3 and not PROTON_HAS_TLSV1_3:
            # If OpenSSL has 1.3 but proton won't let us turn it on and off then
            # this test fails because v1.3 runs unexpectedly.
            RouterTestSslBase.DISABLE_SSL_TESTING = True
            RouterTestSslBase.DISABLE_REASON = "Proton version does not support TLSv1.3 but OpenSSL does"

    @classmethod
    def setUpClass(cls):
        """
        Prepares a single router with multiple listeners, each one associated with a particular
        sslProfile and each sslProfile has its own specific set of allowed protocols.
        """
        super(RouterTestSslClient, cls).setUpClass()

        cls.routers = []

        if SASL.extended():
            router = ('router', {'id': 'QDR.A',
                                 'mode': 'interior',
                                 'saslConfigName': 'tests-mech-PLAIN',
                                 'saslConfigDir': os.getcwd()})

            # Generate authentication DB
            super(RouterTestSslClient, cls).create_sasl_files()
        else:
            router = ('router', {'id': 'QDR.A',
                                 'mode': 'interior'})

        # Saving listener ports for each TLS definition
        cls.PORT_TLS1 = cls.tester.get_port()
        cls.PORT_TLS11 = cls.tester.get_port()
        cls.PORT_TLS12 = cls.tester.get_port()
        cls.PORT_TLS13 = cls.tester.get_port()
        cls.PORT_TLS1_TLS11 = cls.tester.get_port()
        cls.PORT_TLS1_TLS12 = cls.tester.get_port()
        cls.PORT_TLS11_TLS12 = cls.tester.get_port()
        cls.PORT_TLS_ALL = cls.tester.get_port()
        cls.PORT_TLS_SASL = cls.tester.get_port()
        cls.PORT_SSL3 = cls.tester.get_port()

        conf = [
            router,
            # TLSv1 only
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS1,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-tls1'}),
            # TLSv1.1 only
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS11,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-tls11'}),
            # TLSv1.2 only
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS12,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-tls12'}),
            # TLSv1 and TLSv1.1 only
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS1_TLS11,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-tls1-tls11'}),
            # TLSv1 and TLSv1.2 only
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS1_TLS12,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-tls1-tls12'}),
            # TLSv1.1 and TLSv1.2 only
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS11_TLS12,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-tls11-tls12'}),
            # All TLS versions
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS_ALL,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-tls-all'}),
            # Invalid protocol version
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_SSL3,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-ssl3'})
        ]

        # Adding SASL listener only when SASL is available
        if SASL.extended():
            conf += [
                # TLS 1 and 1.2 with SASL PLAIN authentication for proton client validation
                ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS_SASL,
                              'authenticatePeer': 'yes', 'saslMechanisms': 'PLAIN',
                              'requireSsl': 'yes', 'requireEncryption': 'yes',
                              'sslProfile': 'ssl-profile-tls1-tls12'})
            ]

        # Adding SSL profiles
        conf += [
            # SSL Profile for TLSv1
            ('sslProfile', {'name': 'ssl-profile-tls1',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1',
                            'password': 'server-password'}),
            # SSL Profile for TLSv1.1
            ('sslProfile', {'name': 'ssl-profile-tls11',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1.1',
                            'password': 'server-password'}),
            # SSL Profile for TLSv1.2
            ('sslProfile', {'name': 'ssl-profile-tls12',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1.2',
                            'password': 'server-password'}),
            # SSL Profile for TLSv1 and TLSv1.1
            ('sslProfile', {'name': 'ssl-profile-tls1-tls11',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1 TLSv1.1',
                            'password': 'server-password'}),
            # SSL Profile for TLSv1 and TLSv1.2
            ('sslProfile', {'name': 'ssl-profile-tls1-tls12',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1 TLSv1.2',
                            'password': 'server-password'}),
            # SSL Profile for TLSv1.1 and TLSv1.2
            ('sslProfile', {'name': 'ssl-profile-tls11-tls12',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1.1 TLSv1.2',
                            'password': 'server-password'}),
            # SSL Profile for all TLS versions (protocols element not defined)
            ('sslProfile', {'name': 'ssl-profile-tls-all',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'password': 'server-password'}),
            # SSL Profile for invalid protocol version SSLv23
            ('sslProfile', {'name': 'ssl-profile-ssl3',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'SSLv23',
                            'password': 'server-password'})
        ]

        if cls.OPENSSL_ALLOW_TLSV1_3:
            conf += [
            # TLSv1.3 only
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_TLS13,
                          'authenticatePeer': 'no',
                          'sslProfile': 'ssl-profile-tls13'}),
            # SSL Profile for TLSv1.3
            ('sslProfile', {'name': 'ssl-profile-tls13',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'protocols': 'TLSv1.3',
                            'password': 'server-password'})

            ]

        config = Qdrouterd.Config(conf)

        cls.routers.append(cls.tester.qdrouterd("A", config, wait=False))
        cls.routers[0].wait_ports()

    def get_allowed_protocols(self, listener_port):
        """
        Loops through TLSv1, TLSv1.1 and TLSv1.2 and attempts to connect
        to the listener_port using each version. The result is a boolean list
        with results in respective order for TLSv1 [0], TLSv1.1 [1] and TLSv1.2 [2].
        :param listener_port:
        :return:
        """
        results = []

        for proto in ['TLSv1', 'TLSv1.1', 'TLSv1.2']:
            results.append(self.is_proto_allowed(listener_port, proto))
        if self.OPENSSL_ALLOW_TLSV1_3:
            results.append(self.is_proto_allowed(listener_port, 'TLSv1.3'))
        else:
            results.append(False)
        return results

    def is_proto_allowed(self, listener_port, tls_protocol):
        """
        Opens a simple proton client connection to the provided TCP port using
        a specific TLS protocol version and returns True in case connection
        was established and accepted or False otherwise.
        :param listener_port: TCP port number
        :param tls_protocol: TLSv1, TLSv1.1 or TLSv1.2 (string)
        :return:
        """
        # Management address to connect using the given TLS protocol
        url = Url("amqps://0.0.0.0:%d/$management" % listener_port)
        # Preparing SSLDomain (client cert) and SASL authentication info
        domain = SSLDomain(SSLDomain.MODE_CLIENT)
        # Enforcing given TLS protocol
        cproton.pn_ssl_domain_set_protocols(domain._domain, tls_protocol)

        # Try opening the secure and authenticated connection
        try:
            connection = BlockingConnection(url, sasl_enabled=False, ssl_domain=domain, timeout=self.TIMEOUT)
        except proton.Timeout:
            return False
        except proton.ConnectionException:
            return False
        except:
            return False

        # TLS version provided was accepted
        connection.close()
        return True

    def is_ssl_sasl_client_accepted(self, listener_port, tls_protocol):
        """
        Attempts to connect a proton client to the management address
        on the given listener_port using the specific tls_protocol provided.
        If connection was established and accepted, returns True and False otherwise.
        :param listener_port:
        :param tls_protocol:
        :return:
        """
        # Management address to connect using the given TLS protocol
        url = Url("amqps://0.0.0.0:%d/$management" % listener_port)
        # Preparing SSLDomain (client cert) and SASL authentication info
        domain = SSLDomain(SSLDomain.MODE_CLIENT)
        domain.set_credentials(self.ssl_file('client-certificate.pem'),
                               self.ssl_file('client-private-key.pem'),
                               'client-password')
        # Enforcing given TLS protocol
        cproton.pn_ssl_domain_set_protocols(domain._domain, tls_protocol)

        # Try opening the secure and authenticated connection
        try:
            connection = BlockingConnection(url,
                                            sasl_enabled=True,
                                            ssl_domain=domain,
                                            allowed_mechs='PLAIN',
                                            user='test@domain.com',
                                            password='password')
        except proton.ConnectionException:
            return False

        # TLS version provided was accepted
        connection.close()
        return True

    def get_expected_tls_result(self, expected_results):
        """
        Expects a list with three boolean elements, representing
        TLSv1, TLSv1.1 and TLSv1.2 (in the respective order).
        When using OpenSSL >= 1.1.x, allowance of a given TLS version is
        based on MinProtocol / MaxProtocol definitions.
        It is also important
        to mention that TLSv1.2 is being allowed even when not specified in a
        listener when using OpenSSL >= 1.1.x.

        :param expected_results:
        :return:
        """
        (tlsv1, tlsv1_1, tlsv1_2, tlsv1_3) = expected_results
        return [self.OPENSSL_ALLOW_TLSV1 and tlsv1,
                self.OPENSSL_ALLOW_TLSV1_1 and tlsv1_1,
                self.OPENSSL_ALLOW_TLSV1_2 and tlsv1_2,
                self.OPENSSL_ALLOW_TLSV1_3 and tlsv1_3]

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_tls1_only(self):
        """
        Expects TLSv1 only is allowed
        """
        self.assertEqual(self.get_expected_tls_result([True, False, False, False]),
                          self.get_allowed_protocols(self.PORT_TLS1))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_tls11_only(self):
        """
        Expects TLSv1.1 only is allowed
        """
        self.assertEqual(self.get_expected_tls_result([False, True, False, False]),
                          self.get_allowed_protocols(self.PORT_TLS11))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_tls12_only(self):
        """
        Expects TLSv1.2 only is allowed
        """
        self.assertEqual(self.get_expected_tls_result([False, False, True, False]),
                          self.get_allowed_protocols(self.PORT_TLS12))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_tls13_only(self):
        """
        Expects TLSv1.3 only is allowed
        """
        self.assertEqual(self.get_expected_tls_result([False, False, False, True]),
                          self.get_allowed_protocols(self.PORT_TLS13))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_tls1_tls11_only(self):
        """
        Expects TLSv1 and TLSv1.1 only are allowed
        """
        self.assertEqual(self.get_expected_tls_result([True, True, False, False]),
                          self.get_allowed_protocols(self.PORT_TLS1_TLS11))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_tls1_tls12_only(self):
        """
        Expects TLSv1 and TLSv1.2 only are allowed
        """
        self.assertEqual(self.get_expected_tls_result([True, False, True, False]),
                          self.get_allowed_protocols(self.PORT_TLS1_TLS12))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_tls11_tls12_only(self):
        """
        Expects TLSv1.1 and TLSv1.2 only are allowed
        """
        self.assertEqual(self.get_expected_tls_result([False, True, True, False]),
                          self.get_allowed_protocols(self.PORT_TLS11_TLS12))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_tls_all(self):
        """
        Expects all supported versions: TLSv1, TLSv1.1, TLSv1.2 and TLSv1.3 to be allowed
        """
        self.assertEqual(self.get_expected_tls_result([True, True, True, True]),
                          self.get_allowed_protocols(self.PORT_TLS_ALL))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING, RouterTestSslBase.DISABLE_REASON)
    def test_ssl_invalid(self):
        """
        Expects connection is rejected as SSL is no longer supported
        """
        self.assertEqual(False, self.is_proto_allowed(self.PORT_SSL3, 'SSLv3'))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING or not SASL.extended(),
                  "Cyrus library not available. skipping test")
    def test_ssl_sasl_client_valid(self):
        """
        Attempts to connect a Proton client using a valid SASL authentication info
        and forcing the TLS protocol version, which should be accepted by the listener.
        :return:
        """
        if not SASL.extended():
            self.skipTest("Cyrus library not available. skipping test")

        exp_tls_results = self.get_expected_tls_result([True, False, True, False])
        self.assertEqual(exp_tls_results[0], self.is_ssl_sasl_client_accepted(self.PORT_TLS_SASL, "TLSv1"))
        self.assertEqual(exp_tls_results[2], self.is_ssl_sasl_client_accepted(self.PORT_TLS_SASL, "TLSv1.2"))

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING or not SASL.extended(),
                  "Cyrus library not available. skipping test")
    def test_ssl_sasl_client_invalid(self):
        """
        Attempts to connect a Proton client using a valid SASL authentication info
        and forcing the TLS protocol version, which should be rejected by the listener.
        :return:
        """
        if not SASL.extended():
            self.skipTest("Cyrus library not available. skipping test")

        exp_tls_results = self.get_expected_tls_result([True, False, True, False])
        self.assertEqual(exp_tls_results[1], self.is_ssl_sasl_client_accepted(self.PORT_TLS_SASL, "TLSv1.1"))

class RouterTestSslInterRouter(RouterTestSslBase):
    """
    Starts 5 routers with several listeners and connectors and validate if communication
    between them is working as expected.
    """
    # Listener ports for each TLS protocol definition
    PORT_NO_SSL = 0
    PORT_TLS_ALL = 0
    PORT_TLS12 = 0
    PORT_TLS1_TLS12 = 0

    @classmethod
    def setUpClass(cls):
        """
        Prepares 5 routers to form a network. One of them will provide listeners with
        multiple sslProfiles, and the other 4 will try to connect with a respective listener.
        It expects that routers A to D will connect successfully, while E will not succeed due
        to an SSL handshake failure (as allowed TLS protocol versions won't match).
        """
        super(RouterTestSslInterRouter, cls).setUpClass()

        if not SASL.extended():
            return

        os.environ["ENV_SASL_PASSWORD"] = "password"

        # Generate authentication DB
        super(RouterTestSslInterRouter, cls).create_sasl_files()

        # Router expected to be connected
        cls.connected_tls_sasl_routers = ['QDR.A', 'QDR.B', 'QDR.C', 'QDR.D']

        # Generated router list
        cls.routers = []

        # Saving listener ports for each TLS definition
        cls.PORT_NO_SSL = cls.tester.get_port()
        cls.PORT_TLS_ALL = cls.tester.get_port()
        cls.PORT_TLS12 = cls.tester.get_port()
        cls.PORT_TLS1_TLS12 = cls.tester.get_port()

        config_a = Qdrouterd.Config([
            ('router', {'id': 'QDR.A',
                        'mode': 'interior',
                        'saslConfigName': 'tests-mech-PLAIN',
                        'saslConfigDir': os.getcwd()}),
            # No auth and no SSL
            ('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.PORT_NO_SSL}),
            # All TLS versions
            ('listener', {'host': '0.0.0.0', 'role': 'inter-router', 'port': cls.PORT_TLS_ALL,
                          'authenticatePeer': 'yes', 'saslMechanisms': 'PLAIN',
                          'requireEncryption': 'yes', 'requireSsl': 'yes',
                          'sslProfile': 'ssl-profile-tls-all'}),
            # TLSv1.2 only
            ('listener', {'host': '0.0.0.0', 'role': 'inter-router', 'port': cls.PORT_TLS12,
                          'authenticatePeer': 'yes', 'saslMechanisms': 'PLAIN',
                          'requireEncryption': 'yes', 'requireSsl': 'yes',
                          'sslProfile': 'ssl-profile-tls12'}),
            # TLSv1 and TLSv1.2 only
            ('listener', {'host': '0.0.0.0', 'role': 'inter-router', 'port': cls.PORT_TLS1_TLS12,
                          'authenticatePeer': 'yes', 'saslMechanisms': 'PLAIN',
                          'requireEncryption': 'yes', 'requireSsl': 'yes',
                          'sslProfile': 'ssl-profile-tls1-tls12'}),
            # SSL Profile for all TLS versions (protocols element not defined)
            ('sslProfile', {'name': 'ssl-profile-tls-all',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'password': 'server-password'}),
            # SSL Profile for TLSv1.2
            ('sslProfile', {'name': 'ssl-profile-tls12',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1.2',
                            'password': 'server-password'}),
            # SSL Profile for TLSv1 and TLSv1.2
            ('sslProfile', {'name': 'ssl-profile-tls1-tls12',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('server-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('server-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1 TLSv1.2',
                            'password': 'server-password'})

        ])

        # Router B will connect to listener that allows all protocols
        config_b = Qdrouterd.Config([
            ('router', {'id': 'QDR.B',
                        'mode': 'interior'}),
            # Connector to All TLS versions allowed listener
            ('connector', {'host': '0.0.0.0', 'role': 'inter-router', 'port': cls.PORT_TLS_ALL,
                           'verifyHostname': 'no', 'saslMechanisms': 'PLAIN',
                           'saslUsername': 'test@domain.com', 'saslPassword': 'pass:password',
                           'sslProfile': 'ssl-profile-tls-all'}),
            # SSL Profile for all TLS versions (protocols element not defined)
            ('sslProfile', {'name': 'ssl-profile-tls-all',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('client-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('client-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'password': 'client-password'})
        ])

        # Router C will connect to listener that allows TLSv1.2 only
        config_c = Qdrouterd.Config([
            ('router', {'id': 'QDR.C',
                        'mode': 'interior'}),
            # Connector to listener that allows TLSv1.2 only
            ('connector', {'host': '0.0.0.0', 'role': 'inter-router', 'port': cls.PORT_TLS12,
                           'verifyHostname': 'no', 'saslMechanisms': 'PLAIN',
                           'saslUsername': 'test@domain.com', 'saslPassword': 'env:ENV_SASL_PASSWORD',
                           'sslProfile': 'ssl-profile-tls12'}),
            # SSL Profile for TLSv1.2
            ('sslProfile', {'name': 'ssl-profile-tls12',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('client-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('client-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1.2',
                            'password': 'client-password'})
        ])

        # Router D will connect to listener that allows TLSv1 and TLS1.2 only using TLSv1
        config_d = Qdrouterd.Config([
            ('router', {'id': 'QDR.D',
                        'mode': 'interior'}),
            # Connector to listener that allows TLSv1 and TLSv1.2 only
            ('connector', {'host': '0.0.0.0', 'role': 'inter-router', 'port': cls.PORT_TLS1_TLS12,
                           'verifyHostname': 'no', 'saslMechanisms': 'PLAIN',
                           'saslUsername': 'test@domain.com', 'saslPassword': 'pass:password',
                           'sslProfile': 'ssl-profile-tls1'}),
            # SSL Profile for TLSv1
            ('sslProfile', {'name': 'ssl-profile-tls1',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('client-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('client-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1',
                            'password': 'client-password'})
        ])

        # Router E will try connect to listener that allows TLSv1 and TLS1.2 only using TLSv1.1
        config_e = Qdrouterd.Config([
            ('router', {'id': 'QDR.E',
                        'mode': 'interior'}),
            # Connector to listener that allows TLSv1 and TLSv1.2 only
            ('connector', {'host': '0.0.0.0', 'role': 'inter-router', 'port': cls.PORT_TLS1_TLS12,
                           'verifyHostname': 'no', 'saslMechanisms': 'PLAIN',
                           'saslUsername': 'test@domain.com', 'saslPassword': 'password',
                           'sslProfile': 'ssl-profile-tls11'}),
            # SSL Profile for TLSv1.1
            ('sslProfile', {'name': 'ssl-profile-tls11',
                            'caCertFile': cls.ssl_file('ca-certificate.pem'),
                            'certFile': cls.ssl_file('client-certificate.pem'),
                            'privateKeyFile': cls.ssl_file('client-private-key.pem'),
                            'ciphers': 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:' \
                                       'DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS',
                            'protocols': 'TLSv1.1',
                            'password': 'client-password'})
        ])

        cls.routers.append(cls.tester.qdrouterd("A", config_a, wait=False))
        cls.routers.append(cls.tester.qdrouterd("B", config_b, wait=False))
        cls.routers.append(cls.tester.qdrouterd("C", config_c, wait=False))
        cls.routers.append(cls.tester.qdrouterd("D", config_d, wait=False))
        cls.routers.append(cls.tester.qdrouterd("E", config_e, wait=False))

        # Wait till listener is running and all expected connectors are connected
        cls.routers[0].wait_ports()
        for router in cls.connected_tls_sasl_routers[1:]:
            cls.routers[0].wait_router_connected(router)

    def get_router_nodes(self):
        """
        Retrieves connected router nodes.
        :return:
        """
        if not SASL.extended():
            self.skipTest("Cyrus library not available. skipping test")

        url = Url("amqp://0.0.0.0:%d/$management" % self.PORT_NO_SSL)
        node = Node.connect(url)
        response = node.query(type="org.apache.qpid.dispatch.router.node", attribute_names=["id"])
        router_nodes = []
        for resp in response.get_dicts():
            router_nodes.append(resp['id'])
        node.close()
        return router_nodes

    @SkipIfNeeded(RouterTestSslBase.DISABLE_SSL_TESTING or not SASL.extended(),
                  "Cyrus library not available. skipping test")
    def test_connected_tls_sasl_routers(self):
        """
        Validates if all expected routers are connected in the network
        """
        if not SASL.extended():
            self.skipTest("Cyrus library not available. skipping test")

        router_nodes = self.get_router_nodes()
        self.assertTrue(router_nodes)
        for node in router_nodes:
            self.assertTrue(node in self.connected_tls_sasl_routers,
                            "%s should not be connected" % node)

        # Router A and B are always expected (no tls version restriction)
        expected_nodes = len(self.connected_tls_sasl_routers)

        # Router C only if TLSv1.2 is allowed
        if not RouterTestSslClient.OPENSSL_ALLOW_TLSV1_2:
            expected_nodes -= 1

        # Router D only if TLSv1.1 is allowed
        if not RouterTestSslClient.OPENSSL_ALLOW_TLSV1_1:
            expected_nodes -= 1

        self.assertEqual(len(router_nodes), expected_nodes)

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


text:
.cesium-cesiumInspector {
    border-radius: 5px;
    transition: width ease-in-out 0.25s;
    background: rgba(48, 51, 54, 0.8);
    border: 1px solid #444;
    color: #edffff;
    display: inline-block;
    position: relative;
    padding: 4px 12px;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
    overflow: hidden;
}

.cesium-cesiumInspector-button {
    text-align: center;
    font-size: 11pt;
}

.cesium-cesiumInspector-visible .cesium-cesiumInspector-button {
    border-bottom: 1px solid #aaa;
    padding-bottom: 3px;
}

.cesium-cesiumInspector input:enabled, .cesium-cesiumInspector-button {
    cursor: pointer;
}

.cesium-cesiumInspector-visible {
    width: 185px;
    height: auto;
}

.cesium-cesiumInspector-hidden {
    width: 122px;
    height: 17px;
}

.cesium-cesiumInspector-sectionContent {
    max-height: 500px;
}

.cesium-cesiumInspector-section-collapsed .cesium-cesiumInspector-sectionContent {
    max-height: 0;
    padding: 0 !important;
    overflow: hidden;
}

.cesium-cesiumInspector-dropDown {
    margin: 5px 0;
    font-family: sans-serif;
    font-size: 10pt;
    width: 185px;
}

.cesium-cesiumInspector-frustumStatistics {
    padding-left: 10px;
    padding: 5px;
    background-color: rgba(80, 80, 80, 0.75);
}

.cesium-cesiumInspector-pickButton {
    background-color: rgba(0, 0, 0, 0.3);
    border: 1px solid #444;
    color: #edffff;
    border-radius: 5px;
    padding: 3px 7px;
    cursor: pointer;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
    margin: 0 auto;
}

.cesium-cesiumInspector-pickButton:focus {
    outline: none;
}

.cesium-cesiumInspector-pickButton:active, .cesium-cesiumInspector-pickButtonHighlight {
    color: #000; /* For text buttons */
    background: #adf;
    border-color: #fff;
    box-shadow: 0 0 8px #fff;
}

.cesium-cesiumInspector-center {
    text-align: center;
}

.cesium-cesiumInspector-sectionHeader {
    font-weight: bold;
    font-size: 10pt;
    margin: 0;
    cursor: pointer;
}

.cesium-cesiumInspector-pickSection {
    border: 1px solid #aaa;
    border-radius: 5px;
    padding: 3px;
    margin-bottom: 5px;
}

.cesium-cesiumInspector-sectionContent {
    margin-bottom: 10px;
    transition: max-height 0.25s;
}

.cesium-cesiumInspector-tileText {
    padding-bottom: 10px;
    border-bottom: 1px solid #aaa;
}

.cesium-cesiumInspector-relativeText {
    padding-top: 10px;
}

.cesium-cesiumInspector-sectionHeader::before {
    margin-right: 5px;
    content: '-';
    width: 1ch;
    display: inline-block;
}

.cesium-cesiumInspector-section-collapsed .cesium-cesiumInspector-sectionHeader::before {
    content: '+';
}


text:
using System;
using Newtonsoft.Json;

namespace ClashClient.Net {
    /// <summary>
    /// Type that represents the "cursor" object within a pager in an API response for a collection of data.
    /// </summary>
    [Serializable]
    public class PagingCursor {
        #region --Fields--

        private string _after;
        private string _before;

        #endregion

        #region --Constructors--

        /// <summary>
        /// Initializes a new instance of the <see cref="PagingCursor"/> class.
        /// </summary>
        public PagingCursor() {
            this._after = string.Empty;
            this._before = string.Empty;
        } // end default constructor

        #endregion

        #region --Properties--

        /// <summary>
        /// Gets or sets the "after" token or "marker" used to determine the starting point of the next query.  Can be empty if no additional pages are availabile.
        /// </summary>
        [JsonProperty("after")]
        public virtual string After {
            get => this._after;
            set => this._after = string.IsNullOrEmpty(value) ? string.Empty : value;
        } // end property After

        /// <summary>
        /// Gets or sets the "before" token or "marker" used to determine the ending point of the current query.  Can be empty if no additional pages are available.
        /// </summary>
        [JsonProperty("before")]
        public virtual string Before {
            get => this._before;
            set => this._before = string.IsNullOrEmpty(value) ? string.Empty : value;
        } // end property Before

        #endregion
    } // end class PagingCursor
} // end namespace


text:
package restlib.net;

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

import org.junit.Test;

import com.google.common.net.InetAddresses;
import com.google.common.net.InternetDomainName;
import com.google.common.testing.NullPointerTester;

public final class UriBuilderTest {
    @Test
    public void testBuild() {
        assertEquals(
                Uri.parse("http://userinfo@host:80/path?query#fragment"),
                Uri.builder()
                    .setScheme(UriSchemes.HTTP)
                    .setUserinfo("userinfo")
                    .setHost("host")
                    .setPort(80)
                    .setPath("/path")
                    .setQuery("query")
                    .setFragment("fragment")
                    .build());
        assertEquals(
                Uri.parse("http://userinfo@host:80/path?query#fragment"),
                Uri.builder()
                    .setScheme(UriSchemes.HTTP)
                    .setAuthority("userinfo@host:80")
                    .setPath("/path")
                    .setQuery("query")
                    .setFragment("fragment")
                    .build());

        assertEquals(
                Uri.parse("http://192.168.1.1"),
                Uri.builder()
                    .setScheme(UriSchemes.HTTP)
                    .setHost(InetAddresses.forUriString("192.168.1.1"))
                    .build());
        assertEquals(
                Uri.parse("http://xn--rsum-bpad.example.org"),
                Uri.builder()
                    .setScheme(UriSchemes.HTTP)
                    .setHost(InternetDomainName.from("r\u00E9sum\u00E9.example.org"))
                    .build());
    }

    @Test
    public void testNulls() {
        new NullPointerTester()
            .testAllPublicInstanceMethods(Uri.builder());
    }

    @Test
    public void testSetFragment_withInvalid() {
        try {
            Uri.builder().setFragment("\u00E9");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};
    }

    @Test
    public void testSetHost_withInvalid() {
        try {
            Uri.builder().setHost("r\u00E9sum\u00E9.example.org");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};
    }

    @Test
    public void testSetPath_withInvalid() {
        try {
            Uri.builder().setPath("/red%09ros\u00E9#red");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};

        try {
            Uri.builder().setPath("/a?b");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};

        try {
            Uri.builder().setPath("/a#b");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};
    }

    @Test
    public void testSetQuery_withInvalid() {
        try {
            Uri.builder().setQuery("#");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};

        try {
            Uri.builder().setQuery("\u00E9");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};
    }

    @Test
    public void testSetUserinfo_withInvalid() {
        try {
            Uri.builder().setUserinfo("@");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};
        try {
            Uri.builder().setUserinfo("\u00E9");
            fail("expected IllegalArgumentException");
        } catch (final IllegalArgumentException expected){};
    }
}


text:
/**
 * External dependencies
 */
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { themeHelpers } from '@googleforcreators/design-system';

const Wrapper = styled.dd`
  display: block;
  margin: 0;

  kbd {
    ${themeHelpers.expandTextPreset(
      ({ paragraph }, { X_SMALL }) => paragraph[X_SMALL]
    )}

    display: flex;
    justify-content: ${({ alignment }) => alignment};
    align-items: center;
    margin: 0;
    padding: 0;
    color: ${({ theme }) => theme.colors.fg.secondary};
    background-color: transparent;

    & > kbd {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 5px;
      height: 24px;
      width: 24px;
      border-radius: ${({ theme }) => theme.borders.radius.medium};
      border: 1px solid ${({ theme }) => theme.colors.border.defaultNormal};
      color: ${({ theme }) => theme.colors.fg.primary};
    }

    & > kbd.large-key {
      width: auto;
    }

    kbd + kbd {
      margin-left: 2px;
    }

    kbd + span {
      margin-left: 4px;
    }

    span + kbd {
      margin-left: 4px;
    }
  }
`;

function ShortCutLabel({ keys, alignment = 'center', ...rest }) {
  return (
    <Wrapper alignment={alignment} {...rest}>
      {keys}
    </Wrapper>
  );
}

ShortCutLabel.propTypes = {
  keys: PropTypes.PropTypes.element,
  alignment: PropTypes.oneOf(['left', 'center', 'right']),
};

export default ShortCutLabel;