text:
using System;
using System.Collections.Generic;
using ALinq.Mapping;
using System.Linq.Expressions;
using ALinq.Provider;

namespace ALinq.SqlClient
{
    internal static class Funcletizer
    {
        // Methods
        public static Expression Funcletize(Expression expression)
        {
            var mapLocals = new LocalMapper().MapLocals(expression);
            return new Localizer(mapLocals).Localize(expression);
        }

        // Nested Types
        private class DependenceChecker : ExpressionVisitor
        {
            // Fields
            private readonly HashSet<ParameterExpression> inScope = new HashSet<ParameterExpression>();
            private bool isIndependent = true;

            // Methods
            public static bool IsIndependent(Expression expression)
            {
                var checker = new DependenceChecker();
                checker.Visit(expression);
                return checker.isIndependent;
            }

            public override Expression VisitLambda(LambdaExpression lambda)
            {
                foreach (ParameterExpression expression in lambda.Parameters)
                {
                    inScope.Add(expression);
                }
                return base.VisitLambda(lambda);
            }

            public override Expression VisitParameter(ParameterExpression p)
            {
                isIndependent &= inScope.Contains(p);
                return p;
            }
        }

        private class Localizer : ExpressionVisitor
        {
            // Fields
            private readonly Dictionary<Expression, bool> locals;

            // Methods
            internal Localizer(Dictionary<Expression, bool> locals)
            {
                this.locals = locals;
            }

            internal Expression Localize(Expression expression)
            {
                return Visit(expression);
            }

            private static Expression MakeLocal(Expression e)
            {
                if (e.NodeType == ExpressionType.Constant)
                {
                    return e;
                }
                if ((e.NodeType == ExpressionType.Convert) || (e.NodeType == ExpressionType.ConvertChecked))
                {
                    var expression = (UnaryExpression)e;
                    if (expression.Type == typeof(object))
                    {
                        Expression expression2 = MakeLocal(expression.Operand);
                        if (e.NodeType != ExpressionType.Convert)
                        {
                            return Expression.ConvertChecked(expression2, e.Type);
                        }
                        return Expression.Convert(expression2, e.Type);
                    }
                    if (expression.Operand.NodeType == ExpressionType.Constant)
                    {
                        var operand = (ConstantExpression)expression.Operand;
                        if (operand.Value == null)
                        {
                            return Expression.Constant(null, expression.Type);
                        }
                    }
                }
                return Expression.Invoke(
                    Expression.Constant(Expression.Lambda(e, new ParameterExpression[0]).Compile()), new Expression[0]);
            }

            public override Expression Visit(Expression exp)
            {
                if (exp == null)
                {
                    return null;
                }
                if (locals.ContainsKey(exp))
                {
                    return MakeLocal(exp);
                }
                if (exp.NodeType == ((ExpressionType)0x7d0))
                {
                    return exp;
                }
                return base.Visit(exp);
            }
        }

        private class LocalMapper : ExpressionVisitor
        {
            // Fields
            private bool isRemote;
            private bool isUpdateInsertMethod = false;
            private Dictionary<Expression, bool> locals;

            // Methods
            internal Dictionary<Expression, bool> MapLocals(Expression expression)
            {
                locals = new Dictionary<Expression, bool>();
                isRemote = false;
                if(expression.NodeType == ExpressionType.Call)
                {
                    var methodName = ((MethodCallExpression) expression).Method.Name;
                    if (methodName == "Insert" || methodName == "Update")
                        isUpdateInsertMethod = true;
                }
                Visit(expression);
                return locals;
            }

            public override Expression Visit(Expression expression)
            {
                if (expression == null)
                {
                    return null;
                }
                bool oldValue = isRemote;
                ExpressionType nodeType = expression.NodeType;

                if (nodeType != ExpressionType.Constant)
                {
                    if (nodeType == ((ExpressionType)0x7d0))
                    {
                        return expression;
                    }
                    isRemote = false;
                    base.Visit(expression);
                    if ((!isRemote && (expression.NodeType != ExpressionType.Lambda)) &&
                        ((expression.NodeType != ExpressionType.Quote) &&
                         IsIndependent(expression)))
                    {
                        locals[expression] = true;
                    }
                }

                if (typeof(ITable).IsAssignableFrom(expression.Type) ||
                    typeof(DataContext).IsAssignableFrom(expression.Type))
                {
                    isRemote = true;
                }

                //isRemote |= oldValue;
                isRemote = isRemote | oldValue;
                return expression;
            }

            private bool IsIndependent(Expression expression)
            {
                if (isUpdateInsertMethod && expression.NodeType == ExpressionType.MemberInit)
                    return false;
                return DependenceChecker.IsIndependent(expression);
            }

            public override Expression VisitMemberAccess(MemberExpression m)
            {
                base.VisitMemberAccess(m);
                isRemote |= (m.Expression != null) && typeof(ITable).IsAssignableFrom(m.Expression.Type);
                return m;
            }

            //private static readonly Type DataManipulationType =
            //    ReflectObject.GetType("ALinq.Provider.DataManipulation");

            public override Expression VisitMethodCall(MethodCallExpression m)
            {
                base.VisitMethodCall(m);
                isRemote |= ((m.Method.DeclaringType == typeof(DataManipulation) ||
                              m.Method.DeclaringType == typeof(DataManipulation)) ||
                             Attribute.IsDefined(m.Method, typeof(FunctionAttribute)));

                return m;
            }
        }
    }
}


text:
<?php

/**
 * Using TBaseValidator class
 */
Prado::using('System.Web.UI.WebControls.TBaseValidator');

/**
 * TListControlValidator class.
 *
 * TListControlValidator checks the number of selection and their values
 * for a TListControl that allows multiple selection.
 *
 * You can specify the minimum or maximum (or both) number of selections
 * required using the {@link setMinSelection MinSelection} and
 * {@link setMaxSelection MaxSelection} properties, respectively. In addition,
 * you can specify a comma separated list of required selected values via the
 * {@link setRequiredSelections RequiredSelections} property.
 *
 * Examples
 * - At least two selections
 *
 *	<com:TListBox ID="listbox" SelectionMode="Multiple">
 *		<com:TListItem Text="item1" Value="value1" />
 *		<com:TListItem Text="item2" Value="value2" />
 *		<com:TListItem Text="item3" Value="value3" />
 *	</com:TListBox>
 *
 *	<com:TListControlValidator
 *		ControlToValidate="listbox"
 *		MinSelection="2"
 *		ErrorMessage="Please select at least 2" />
 *
 * - "value1" must be selected and at least 1 other
 *
 *	<com:TCheckBoxList ID="checkboxes">
 *		<com:TListItem Text="item1" Value="value1" />
 *		<com:TListItem Text="item2" Value="value2" />
 *		<com:TListItem Text="item3" Value="value3" />
 *	</com:TCheckBoxList>
 *
 *	<com:TListControlValidator
 *		ControlToValidate="checkboxes"
 *		RequiredSelections="value1"
 *		MinSelection="2"
 *		ErrorMessage="Please select 'item1' and at least 1 other" />
 *
 *
 * @author Xiang Wei Zhuo <weizhuo[at]gmail.com>
 * @package System.Web.UI.WebControls
 * @since 3.0
 */
class TListControlValidator extends TBaseValidator
{
	/**
	 * Gets the name of the javascript class responsible for performing validation for this control.
	 * This method overrides the parent implementation.
	 * @return string the javascript class name
	 */
	protected function getClientClassName()
	{
		return 'Prado.WebUI.TListControlValidator';
	}

	/**
	 * @return integer min number of selections. Defaults to -1, meaning not set.
	 */
	public function getMinSelection()
	{
		return $this->getViewState('MinSelection',-1);
	}

	/**
	 * @param integer minimum number of selections.
	 */
	public function setMinSelection($value)
	{
		if(($value=TPropertyValue::ensureInteger($value))<0)
			$value=-1;
		$this->setViewState('MinSelection',$value,-1);
	}

	/**
	 * @return integer max number of selections.  Defaults to -1, meaning not set.
	 */
	public function getMaxSelection()
	{
		return $this->getViewState('MaxSelection',-1);
	}

	/**
	 * @param integer max number of selections.
	 */
	public function setMaxSelection($value)
	{
		if(($value=TPropertyValue::ensureInteger($value))<0)
			$value=-1;
		$this->setViewState('MaxSelection',$value,-1);
	}

	/**
	 * Get a comma separated list of required selected values.
	 * @return string comma separated list of required values.
	 */
	public function getRequiredSelections()
	{
		return $this->getViewState('RequiredSelections','');
	}

	/**
	 * Set the list of required values, using aa comma separated list.
	 * @param string comma separated list of required values.
	 */
	public function setRequiredSelections($value)
	{
		$this->setViewState('RequiredSelections',$value,'');
	}

	/**
	 * This method overrides the parent's implementation.
	 * The validation succeeds if the input component changes its data
	 * from the InitialValue or the input component is not given.
	 * @return boolean whether the validation succeeds
	 */
	protected function evaluateIsValid()
	{
		$control=$this->getValidationTarget();

		$exists = true;
		$values = $this->getSelection($control);
		$count = count($values);
		$required = $this->getRequiredValues();

		//if required, check the values
		if(!empty($required))
		{
			if($count < count($required) )
				return false;
			foreach($required as $require)
				$exists = $exists && in_array($require, $values);
		}

		$min = $this->getMinSelection();
		$max = $this->getMaxSelection();

		if($min !== -1 && $max !== -1)
			return $exists && $count >= $min && $count <= $max;
		else if($min === -1 && $max !== -1)
			return $exists && $count <= $max;
		else if($min !== -1 && $max === -1)
			return $exists && $count >= $min;
		else
			return $exists;
	}

	/**
	 * @param TListControl control to validate
	 * @return array number of selected values and its values.
	 */
	protected function getSelection($control)
	{
		$values = array();

		//get the data
		foreach($control->getItems() as $item)
		{
			if($item->getSelected())
				$values[] = $item->getValue();
		}
		return $values;
	}

	/**
	 * @return array list of required values.
	 */
	protected function getRequiredValues()
	{
		$required = array();
		$string = $this->getRequiredSelections();
		if(!empty($string))
			$required = preg_split('/,\s*/', $string);
		return $required;
	}

	/**
	 * Returns an array of javascript validator options.
	 * @return array javascript validator options.
	 */
	protected function getClientScriptOptions()
	{
		$options = parent::getClientScriptOptions();
		$control = $this->getValidationTarget();

		if(!$control instanceof TListControl)
		{
			throw new TConfigurationException(
				'listcontrolvalidator_invalid_control',
				$this->getID(),$this->getControlToValidate(), get_class($control));
		}

		$min = $this->getMinSelection();
		$max = $this->getMaxSelection();
		if($min !== -1)
			$options['Min']= $min;
		if($max !== -1)
			$options['Max']= $max;
		$required = $this->getRequiredSelections();
		if(strlen($required) > 0)
			$options['Required']= $required;
		$options['TotalItems'] = $control->getItemCount();

		return $options;
	}
}

redpajama_set_name: RedPajamaGithub


text:
import org.msgpack.MessagePack;
import org.msgpack.type.MapValue;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试MsgPack
 * Created by wuy on 2017/5/17.
 */
public class TestMsgPack {

	public static byte[] pack() throws IOException {
		Map<String, Object> data = new HashMap<>();
		data.put("S", "GAC");
		data.put("D", "GAS");
		Map<String, Object> param = new HashMap<>();
		param.put("url", "http://www.test.com");
		List<Integer> list = new ArrayList<>();
		list.add(10);
		list.add(60);
		param.put("other", list);
		data.put("P", param);
		MessagePack messagePack = new MessagePack();
		byte[] raw = messagePack.write(data);
		return raw;
	}

	public static Map unpack(byte[] raw) throws IOException {
		MessagePack messagePack = new MessagePack();
		MapValue mapValue = messagePack.read(raw).asMapValue();
//		for (Value v : mapValue.keySet()) {
//			Value temp = mapValue.getByServerId(v);
//			System.out.println(v + ":" + temp);
//		}
		return mapValue;
	}

	public static void main(String[] args) throws Exception {
		byte[] raw = pack();
		Map data = unpack(raw);
		System.out.println(data);
	}
}


text:
using System;

namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2;

[Flags]
internal enum Http2HeadersFrameFlags : byte
{
    NONE = 0x0,
    END_STREAM = 0x1,
    END_HEADERS = 0x4,
    PADDED = 0x8,
    PRIORITY = 0x20
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sorting;

[TestClass]
public class SortingTests
{
    [TestMethod]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Test_SelectionNull()
    {
        new SelectionSorter<int>().Sort(null);
    }

    [TestMethod]
    public void Test_Selection0()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 0);
        var list = array.ToList();

        new SelectionSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_Selection1()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 1);
        var list = array.ToList();

        new SelectionSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_SelectionRandom1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 1000);
        var list = array.ToList();

        new SelectionSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_SelectionSorted1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Sorted, 1000);
        var list = array.ToList();

        new SelectionSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_SelectionReversed1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Reversed, 1000);
        var list = array.ToList();

        new SelectionSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Test_QuickNull()
    {
        new QuickSorter<int>().Sort(null);
    }

    [TestMethod]
    public void Test_Quick0()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 0);
        var list = array.ToList();

        new QuickSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_Quick1()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 1);
        var list = array.ToList();

        new QuickSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_QuickRandom1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 1000);
        var list = array.ToList();

        new QuickSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_QuickSorted1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Sorted, 1000);
        var list = array.ToList();

        new QuickSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_QuickReversed1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Reversed, 1000);
        var list = array.ToList();

        new QuickSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Test_MergeNull()
    {
        new MergeSorter<int>().Sort(null);
    }

    [TestMethod]
    public void Test_Merge0()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 0);
        var list = array.ToList();

        new MergeSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_Merge1()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 1);
        var list = array.ToList();

        new MergeSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_MergeRandom1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Random, 1000);
        var list = array.ToList();

        new MergeSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_MergeSorted1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Sorted, 1000);
        var list = array.ToList();

        new MergeSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }

    [TestMethod]
    public void Test_MergeReversed1000()
    {
        var array = TestHelpers.GenerateIntArray(ArrayOptions.Reversed, 1000);
        var list = array.ToList();

        new MergeSorter<int>().Sort(list);

        Assert.IsTrue(list.IsSorted());
        Assert.IsTrue(list.SameContents(array));
    }
}

internal enum ArrayOptions
{
    Random,
    Sorted,
    Reversed
}

internal static class TestHelpers
{
    private static readonly Random Rand = new Random();

    public static bool IsSorted<T>(this IEnumerable<T> seq)
    {
        return seq.OrderBy(x => x, Comparer<T>.Default)
                  .SequenceEqual(seq);
    }

    public static bool SameContents<T>(this IEnumerable<T> seq1, IEnumerable<T> seq2)
    {
        return seq1.OrderBy(x => x, Comparer<T>.Default).SequenceEqual(
               seq2.OrderBy(x => x, Comparer<T>.Default));
    }

    public static int[] GenerateIntArray(ArrayOptions option, int length)
    {
        var arr = new int[length];
        for (var i = 0; i < length; ++i)
        {
            arr[i] = Rand.Next();
        }

        if (option == ArrayOptions.Sorted)
        {
            Array.Sort(arr);
        }

        if (option == ArrayOptions.Reversed)
        {
            Array.Sort(arr);
            Array.Reverse(arr);
        }

        return arr;
    }
}


text:
package net.java.sip.communicator.impl.gui.main.presence;

import java.awt.*;

import javax.swing.*;

import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.account.*;
import net.java.sip.communicator.util.skin.*;

/**
 * @author Damian Minkov
 */
public class ReadonlyStatusItem
    extends JMenuItem
    implements  StatusEntry,
                Skinnable
{
    /**
     * Our logger.
     */
    private final Logger logger = Logger.getLogger(ReadonlyStatusItem.class);

    /**
     * The connecting icon.
     */
    private Image connectingIcon;

    /**
     * Indicates if this menu is currently connecting.
     */
    private boolean isConnecting;

    /**
     * The offline status.
     */
    private PresenceStatus offlineStatus;

    /**
     * The online status.
     */
    private PresenceStatus onlineStatus;

    /**
     * The <tt>ProtocolProviderService</tt> associated with this status menu.
     */
    protected ProtocolProviderService protocolProvider;

    /**
     * Constructs the item with default values.
     *
     * @param protocolProvider the provider to represent.
     */
    public ReadonlyStatusItem(ProtocolProviderService protocolProvider)
    {
        super(protocolProvider.getAccountID().getDisplayName(),
            ImageLoader.getAccountStatusImage(protocolProvider));
        this.protocolProvider = protocolProvider;

        loadSkin();

        String tooltip =
            "" + protocolProvider.getAccountID().getDisplayName()
                + "
Connecting";

        this.setToolTipText(tooltip);

        this.offlineStatus
            = AccountStatusUtils.getOfflineStatus(protocolProvider);
        this.onlineStatus
            = AccountStatusUtils.getOnlineStatus(protocolProvider);

        this.setSelectedStatus(offlineStatus);
        updateStatus(offlineStatus);
    }

    /**
     * Selects the given status in the status menu.
     *
     * @param status the status to select
     */
    public void setSelectedStatus(PresenceStatus status)
    {
        Icon statusImage = ImageLoader.getAccountStatusImage(protocolProvider);

        this.setIcon(statusImage);

        String tooltip = this.getToolTipText();

        tooltip = tooltip.substring(0, tooltip.lastIndexOf("
"));

        if(status != null)
            this.setToolTipText(
                    tooltip.concat("
" + status.getStatusName()));
    }

    /**
     * Paints this component. If the state of this menu is connecting, paints
     * the connecting icon.
     *
     * @param g the <tt>Graphics</tt> object used for painting
     */
    @Override
    public void paintComponent(Graphics g)
    {
        AntialiasingManager.activateAntialiasing(g);
        super.paintComponent(g);

        if(isConnecting)
            g.drawImage(getConnectingIcon(), 0, 3, this);
    }

    /**
     * Returns the connecting icon, if missing create it.
     * @return the connecting icon, if missing create it.
     */
    private Image getConnectingIcon()
    {
        if(connectingIcon == null)
        {
            connectingIcon
                = GuiActivator.getResources()
                    .getImage("service.gui.icons.CONNECTING").getImage();
        }

        return connectingIcon;
    }

    /**
     * Clears the connecting icon.
     */
    private void clearConnectingIcon()
    {
        if(connectingIcon != null)
        {
            connectingIcon.flush();
            connectingIcon = null;
        }
    }

    /**
     * Updates the menu icon.
     * @param img the image to update
     * @param infoflags the info flags
     * @param x the x coordinate
     * @param y the y coordinate
     * @param w the width
     * @param h the height
     * @return <tt>true</tt> if the image has been updated, <tt>false</tt>
     * otherwise
     */
    @Override
    public boolean imageUpdate(Image img, int infoflags,
                               int x, int y,
                               int w, int h)
    {
        repaint();
        return true;
    }

    /**
     * Returns the protocol provider associated with this status menu.
     * @return the protocol provider associated with this status menu
     */
    public ProtocolProviderService getProtocolProvider()
    {
        return protocolProvider;
    }

    /**
     * Returns the Offline status in this selector box.
     *
     * @return the Offline status in this selector box
     */
    public PresenceStatus getOfflineStatus()
    {
        return offlineStatus;
    }

    /**
     * Returns the Online status in this selector box.
     *
     * @return the Online status in this selector box
     */
    public PresenceStatus getOnlineStatus()
    {
        return onlineStatus;
    }

    /**
     * Load connecting icon.
     */
    @Override
    public void loadSkin()
    {
        clearConnectingIcon();
        this.setIcon(ImageLoader.getAccountStatusImage(protocolProvider));
    }

    /**
     * Clears resources.
     */
    public void dispose()
    {
        protocolProvider = null;
        clearConnectingIcon();
        onlineStatus = null;
        offlineStatus = null;
    }

    /**
     * The component of this entry.
     * @return the component used to add to global status
     */
    public JMenuItem getEntryComponent()
    {
        return this;
    }

    /**
     * Starts the connecting.
     */
    public void startConnecting()
    {
        setConnecting(true);
    }

    /**
     * Stops the connecting.
     */
    public void stopConnecting()
    {
        clearConnectingIcon();

        setConnecting(false);
    }

    /**
     * Sets the connecting state for this menu.
     * @param isConnecting indicates if this menu is currently connecting
     */
    private void setConnecting(boolean isConnecting)
    {
        this.isConnecting = isConnecting;
        this.repaint();
    }

    /**
     * Selects a specific <tt>PresenceStatus</tt> in this instance and the
     * <tt>ProtocolProviderService</tt> it depicts.
     *
     * @param presenceStatus the <tt>PresenceStatus</tt> to be selected in this
     * instance and the <tt>ProtocolProviderService</tt> it depicts
     */
    public void updateStatus(PresenceStatus presenceStatus)
    {
        if (logger.isTraceEnabled())
            logger.trace("Update status for provider: "
                + protocolProvider.getAccountID().getAccountAddress()
                + ". The new status will be: " + presenceStatus.getStatusName());

        this.setSelectedStatus(presenceStatus);
    }
}


text:
module Fog
  module AWS
    class CloudWatch
      class Real
        require 'fog/aws/parsers/cloud_watch/delete_alarms'

        # Delete a list of alarms
        # ==== Options
        # * AlarmNames<~Array>: A list of alarms to be deleted
        #
        # ==== Returns
        # * response<~Excon::Response>:
        #
        # ==== See Also
        # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/index.html?API_DeleteAlarms.html
        #

        def delete_alarms(alarm_names)
          options = {}
          options.merge!(AWS.indexed_param('AlarmNames.member.%d', [*alarm_names]))
          request({
              'Action'    => 'DeleteAlarms',
              :parser     => Fog::Parsers::AWS::CloudWatch::DeleteAlarms.new
            }.merge(options))
        end
      end

      class Mock
        def delete_alarms(alarm_names)
          [*alarm_names].each do |alarm_name|
            unless data[:metric_alarms].key?(alarm_name)
              raise Fog::AWS::AutoScaling::NotFound, "The alarm '#{alarm_name}' does not exist."
            end
          end

          [*alarm_names].each { |alarm_name| data[:metric_alarms].delete(alarm_name) }
          response = Excon::Response.new
          response.status = 200
          response.body = {
            'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }
          }
          response
        end
      end
    end
  end
end


text:
Command-line flags are documented in the [rustc book][cli-docs]. All *stable*
flags should be documented there. Unstable flags should be documented in the
[unstable book].

See the [forge guide for new options] for details on the *procedure* for
adding a new command-line argument.

## Guidelines

- Flags should be orthogonal to each other. For example, if we'd have a
  json-emitting variant of multiple actions `foo` and `bar`, an additional
  `--json` flag is better than adding `--foo-json` and `--bar-json`.
- Avoid flags with the `no-` prefix. Instead, use the [`parse_bool`] function,
  such as `-C embed-bitcode=no`.
- Consider the behavior if the flag is passed multiple times. In some
  situations, the values should be accumulated (in order!). In other
  situations, subsequent flags should override previous flags (for example,
  the lint-level flags). And some flags (like `-o`) should generate an error
  if it is too ambiguous what multiple flags would mean.
- Always give options a long descriptive name, if only for more understandable
  compiler scripts.
- The `--verbose` flag is for adding verbose information to `rustc`
  output. For example, using it with the `--version`
  flag gives information about the hashes of the compiler code.
- Experimental flags and options must be guarded behind the `-Z
  unstable-options` flag.

[cli-docs]: https://doc.rust-lang.org/rustc/command-line-arguments.html
[forge guide for new options]: https://forge.rust-lang.org/compiler/new_option.html
[unstable book]: https://doc.rust-lang.org/nightly/unstable-book/
[`parse_bool`]: https://github.com/rust-lang/rust/blob/e5335592e78354e33d798d20c04bcd677c1df62d/src/librustc_session/options.rs#L307-L313


text:
require 'spec_helper'

describe Betarigs do
  it 'should have a version number' do
    Betarigs::VERSION.should_not be_nil
  end

  it 'should do something useful' do
    false.should eq(true)
  end
end


text:
namespace Pook.SlackAPI.RTMHandlers
{
    public class ReconnectUrl
    {
        public string type;
        public string url;
    }
}


text:
<component name="libraryTable">
  <library name="Maven: io.github.classgraph:classgraph:4.8.69">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/io/github/classgraph/classgraph/4.8.69/classgraph-4.8.69.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/io/github/classgraph/classgraph/4.8.69/classgraph-4.8.69-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/io/github/classgraph/classgraph/4.8.69/classgraph-4.8.69-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 77(5): 771 (1985)

#### Original name
Hypomyces leotiicola Rogerson & Samuels, 1985

### Remarks
null


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Aulomyrcia apiocarpa O.Berg

### Remarks
null


text:
package main

import (
	"fmt"

	"github.com/mikespook/gorbac"
)

type myRole struct {
	gorbac.Role
	Label       string
	Description string
}

func loadByName(name string) (label, description string) {
	// loading data from storages or somewhere
	return name, "This is the description for " + name
}

func newMyRole(rbac *gorbac.RBAC, name string) gorbac.Role {
	// loading extra properties by `name`.
	label, desc := loadByName(name)
	role := &myRole{
		Role:        gorbac.NewBaseRole(rbac, name),
		Label:       label,
		Description: desc,
	}
	return role
}

func main() {
	rbac := gorbac.NewWithFactory(newMyRole)
	rbac.Add("role-1", []string{"a", "b", "c"}, nil)
	role := rbac.Get("role-1")
	if myRole, ok := role.(*myRole); ok {
		fmt.Printf("Name:\t%s\nLabel:\t%s\nDesc:\t%s\n",
			myRole.Name(), myRole.Label, myRole.Description)
	}
}


text:
using System;
using OpenTK.Graphics.ES20;
#if __IOS__ || __TVOS__
using OpenTK.Graphics.ES20;
#elif __MACOS__ || __DESKTOP__
//using OpenTK.Graphics.OpenGL;
#endif

#if __ANDROID__
namespace SkiaSharp.Views.Android
#elif __TVOS__
namespace SkiaSharp.Views.tvOS
#elif __IOS__
namespace SkiaSharp.Views.iOS
#elif __DESKTOP__ || __WPF__
namespace SkiaSharp.Views.Desktop
#elif __MACOS__
namespace SkiaSharp.Views.Mac
#endif
{
    internal static class SKGLDrawable
    {
        public static GRBackendRenderTargetDesc CreateRenderTarget()
        {
            int framebuffer, stencil, samples;
            GL.GetInteger(GetPName.FramebufferBinding, out framebuffer);
            GL.GetInteger(GetPName.StencilBits, out stencil);
            GL.GetInteger(GetPName.Samples, out samples);

            int bufferWidth = 0;
            int bufferHeight = 0;
//#if __IOS__ || __TVOS__
			GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferWidth, out bufferWidth);
			GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferHeight, out bufferHeight);
//#endif

            return new GRBackendRenderTargetDesc
            {
                Width = bufferWidth,
                Height = bufferHeight,
                Config = GRPixelConfig.Rgba8888,
                Origin = GRSurfaceOrigin.TopLeft,
                SampleCount = samples,
                StencilBits = stencil,
                RenderTargetHandle = (IntPtr)framebuffer,
            };
        }
    }
}


text:
The zone mail.protection.outlook.com has two nameservers:

```
$ dig +dnssec +short ns mail.protection.outlook.com
ns1-proddns.glbdns.o365filtering.com.
ns2-proddns.glbdns.o365filtering.com.
```

Queries to these nameservers using EDNS0 result in a response with a response code of FORMERR and an empty QUESTION section.  Recursive resolvers may drop the invalid response and fail to deduce that the nameserver does not support EDNS.

[RFC 1035](https://tools.ietf.org/html/rfc1035) section 7.3 specifies:

  > The next step is to match the response to a current resolver request.  The recommended strategy is to do a preliminary matching using the ID field in the domain header, and then to verify that the question section corresponds to the information currently desired.

[RFC 5452 section 4.2](https://tools.ietf.org/html/rfc5452#section-4.2) specifies:

  > DNS packets, both queries and responses, contain a question section.  Incoming responses should be verified to have a question section that is equivalent to that of the outgoing query.

## Evidence

Evidence is provided here for one nameserver.  Both nameservers behave in the same way.

```
$ dig +edns=0 +norecurse ns mail.protection.outlook.com @ns1-proddns.glbdns.o365filtering.com

; <<>> DiG 9.11.5-P4-5.1-Debian <<>> +edns=0 +norecurse ns mail.protection.outlook.com @ns1-proddns.glbdns.o365filtering.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: FORMERR, id: 22548
;; flags: qr; QUERY: 0, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; WARNING: EDNS query returned status FORMERR - retry with '+noedns'

;; Query time: 26 msec
;; SERVER: 104.47.118.145#53(104.47.118.145)
;; WHEN: Fri May 29 22:41:02 UTC 2020
;; MSG SIZE  rcvd: 12
```

## Proposed fix

Nameservers should populate the QUESTION section with the content of the query QUESTION section.

## DNS Operator/Vendor Response

It has not been possible to contact the vendor.

## Metadata

Submitter: Brian Somers
Submit-Date: 2020-05-29
Tags: EDNS, FORMERR


text:
package org.valkyriercp.command.support;

import org.springframework.util.Assert;
import org.valkyriercp.command.GroupContainerPopulator;

import javax.swing.*;
import java.awt.*;

/**
 * A default implementation of the {@link GroupContainerPopulator} interface.
 *
 */
public class SimpleGroupContainerPopulator implements GroupContainerPopulator {

    private final Container container;

    /**
     * Creates a new {@code SimpleGroupContainerPopulator} that will populate the given container.
     *
     * @param container The container to be populated. Must not be null.
     *
     * @throws IllegalArgumentException if {@code container} is null.
     */
    public SimpleGroupContainerPopulator(Container container) {
        Assert.notNull(container, "container");
        this.container = container;
    }

    /**
     * {@inheritDoc}
     */
    public Container getContainer() {
        return container;
    }

    /**
     * {@inheritDoc}
     */
    public void add(Component c) {
        container.add(c);
    }

    /**
     * {@inheritDoc}
     */
    public void addSeparator() {
        if (container instanceof JMenu) {
            ((JMenu)container).addSeparator();
        }
        else if (container instanceof JPopupMenu) {
            ((JPopupMenu)container).addSeparator();
        }
        else if (container instanceof JToolBar) {
            ((JToolBar)container).addSeparator();
        }
        else {
            container.add(new JSeparator(SwingConstants.VERTICAL));
        }
    }

    /**
     * Default implementation, no action is performed.
     */
    public void onPopulated() {
        //do nothing
    }

}


text:
require 'spec_helper'

describe DiscourseApi::API::Categories do
  subject { DiscourseApi::Client.new("#{host}", "test_d7fd0429940", "test_user") }

  describe "#categories" do
    before do
      stub_get("#{host}/categories.json")
        .to_return(body: fixture("categories.json"), headers: { content_type: "application/json" })
    end

    it "requests the correct resource" do
      subject.categories
      expect(a_get("#{host}/categories.json")).to have_been_made
    end

    it "returns the requested categories" do
      categories = subject.categories
      expect(categories).to be_an Array
      expect(categories.first).to be_a Hash
    end

    it "returns the requested categories with hash arg" do
      categories = subject.categories({})
      expect(categories).to be_an Array
      expect(categories.first).to be_a Hash
    end
  end

  describe "#categories_full" do
    before do
      stub_get("#{host}/categories.json")
        .to_return(body: fixture("categories.json"), headers: { content_type: "application/json" })
    end

    it "requests the correct resource" do
      subject.categories
      expect(a_get("#{host}/categories.json")).to have_been_made
    end

    it "returns the entire categories response" do
      categories = subject.categories_full
      expect(categories).to be_a Hash
      expect(categories).to have_key 'category_list'
      expect(categories).to have_key 'featured_users'
    end
  end

  describe '#category_latest_topics' do
    before do
      stub_get("#{host}/c/category-slug/l/latest.json")
        .to_return(body: fixture("category_latest_topics.json"), headers: { content_type: "application/json" })
    end

    it "returns the latest topics in a category" do
      latest_topics = subject.category_latest_topics(category_slug: 'category-slug')
      expect(latest_topics).to be_an Array
    end
  end

  describe '#category_latest_topics_full' do
    before do
      stub_get("#{host}/c/category-slug/l/latest.json")
        .to_return(body: fixture("category_latest_topics.json"), headers: { content_type: "application/json" })
    end

    it "returns the entire latest topics in a category response" do
      latest_topics = subject.category_latest_topics_full(category_slug: 'category-slug')
      expect(latest_topics).to be_a Hash
      expect(latest_topics).to have_key 'topic_list'
      expect(latest_topics).to have_key 'users'
    end
  end

  describe '#category_top_topics' do
    before do
      stub_get("#{host}/c/category-slug/l/top.json")
        .to_return(
        body: fixture("category_topics.json"),
        headers: { content_type: "application/json" }
      )
    end

    it "returns the top topics in a category" do
      topics = subject.category_top_topics('category-slug')
      expect(topics).to be_an Array
    end
  end

  describe '#category_top_topics_full' do
    before do
      stub_get("#{host}/c/category-slug/l/top.json")
        .to_return(
        body: fixture("category_topics.json"),
        headers: { content_type: "application/json" }
      )
    end

    it "returns the entire top topics in a category response" do
      topics = subject.category_top_topics_full('category-slug')
      expect(topics).to be_a Hash
      expect(topics).to have_key 'topic_list'
      expect(topics).to have_key 'users'
    end
  end

  describe '#category_new_topics' do
    before do
      stub_get("#{host}/c/category-slug/l/new.json")
        .to_return(
        body: fixture("category_topics.json"),
        headers: { content_type: "application/json" }
      )
    end

    it "returns the new topics in a category" do
      topics = subject.category_new_topics('category-slug')
      expect(topics).to be_an Array
    end
  end

  describe '#category_new_topics_full' do
    before do
      stub_get("#{host}/c/category-slug/l/new.json")
        .to_return(
        body: fixture("category_topics.json"),
        headers: { content_type: "application/json" }
      )
    end

    it "returns the new topics in a category" do
      topics = subject.category_new_topics_full('category-slug')
      expect(topics).to be_a Hash
      expect(topics).to have_key 'topic_list'
      expect(topics).to have_key 'users'
    end
  end

  describe '#category_new_category' do
    before do
      stub_post("#{host}/categories")
      subject.create_category(name: "test_category", color: "283890", text_color: "FFFFFF",
                              description: "This is a description",
                              permissions: { "group_1" => 1, "admins" => 1 })
    end

    it "makes a create category request" do
      expect(a_post("#{host}/categories").with(body:
          "color=283890&description=This+is+a+description&name=test_category&parent_category_id&permissions%5Badmins%5D=1&permissions%5Bgroup_1%5D=1&text_color=FFFFFF")
        ).to have_been_made
    end
  end

  describe "#category_set_user_notification" do
    before do
      stub_post("#{host}/category/1/notifications").to_return(body: fixture("notification_success.json"), headers: { content_type: "application/json" })
    end

    it "makes the post request" do
      response = subject.category_set_user_notification(id: 1, notification_level: 3)
      expect(a_post("#{host}/category/1/notifications")).to have_been_made
      expect(response['success']).to eq('OK')
    end
  end

  describe "#category_set_user_notification_level" do
    before do
      stub_post("#{host}/category/1/notifications").to_return(body: fixture("notification_success.json"), headers: { content_type: "application/json" })
    end

    it "makes the post request" do
      response = subject.category_set_user_notification_level(1, notification_level: 3)
      expect(a_post("#{host}/category/1/notifications").with(body: "notification_level=3")).to have_been_made
      expect(response['success']).to eq('OK')
    end
  end
end


text:
package org.csanchez.jenkins.plugins.kubernetes.pipeline;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;

import hudson.AbortException;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.client.http.WebSocketHandshakeException;
import org.apache.commons.io.output.TeeOutputStream;
import org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate;
import org.csanchez.jenkins.plugins.kubernetes.KubernetesSlave;
import org.jenkinsci.plugins.workflow.steps.EnvironmentExpander;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.LauncherDecorator;
import hudson.Proc;
import hudson.model.Computer;
import hudson.model.Node;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.ExecListener;
import io.fabric8.kubernetes.client.dsl.ExecWatch;
import io.fabric8.kubernetes.client.dsl.Execable;

import static org.csanchez.jenkins.plugins.kubernetes.pipeline.Constants.EXIT;

/**
 * This decorator interacts directly with the Kubernetes exec API to run commands inside a container. It does not use
 * the Jenkins agent to execute commands.
 *
 */
public class ContainerExecDecorator extends LauncherDecorator implements Serializable, Closeable {

    private static final long serialVersionUID = 4419929753433397655L;

    private static final String WEBSOCKET_CONNECTION_MAX_RETRY_SYSTEM_PROPERTY = ContainerExecDecorator.class.getName()
        + ".websocketConnectionMaxRetries";
    private static final String WEBSOCKET_CONNECTION_MAX_RETRY_BACKOFF_SYSTEM_PROPERTY = ContainerExecDecorator.class.getName()
        + ".websocketConnectionMaxRetryBackoff";
    private static final String WEBSOCKET_CONNECTION_TIMEOUT_SYSTEM_PROPERTY = ContainerExecDecorator.class.getName()
            + ".websocketConnectionTimeout";
    /** time to wait in seconds for websocket to connect */
    private static final int WEBSOCKET_CONNECTION_TIMEOUT = Integer
            .getInteger(WEBSOCKET_CONNECTION_TIMEOUT_SYSTEM_PROPERTY, 30);
    /** maximum number of times to retry failed websocket connection */
    private static final int WEBSOCKET_CONNECTION_MAX_RETRY = Integer
        .getInteger(WEBSOCKET_CONNECTION_MAX_RETRY_SYSTEM_PROPERTY, 5);
    /** maximum backoff time for retrying failed websocket connection  */
    private static final int WEBSOCKET_CONNECTION_MAX_RETRY_BACKOFF = Integer
        .getInteger(WEBSOCKET_CONNECTION_MAX_RETRY_BACKOFF_SYSTEM_PROPERTY, 30);
    private static final String COOKIE_VAR = "JENKINS_SERVER_COOKIE";

    private static final Logger LOGGER = Logger.getLogger(ContainerExecDecorator.class.getName());

    /**
     * stdin buffer size for commands sent to Kubernetes exec api. A low value will cause slowness in commands executed.
     * A higher value will consume more memory
     */
    private static final int STDIN_BUFFER_SIZE = Integer.getInteger(ContainerExecDecorator.class.getName() + ".stdinBufferSize", 16 * 1024);
    /**
     * time in milliseconds to wait for checking whether the process immediately returned
     */
    public static final int COMMAND_FINISHED_TIMEOUT_MS = 200;

    @SuppressFBWarnings(value = "SE_TRANSIENT_FIELD_NOT_RESTORED", justification = "not needed on deserialization")
    private transient List<Closeable> closables;

    private String containerName;
    private EnvironmentExpander environmentExpander;
    private EnvVars globalVars;
    private EnvVars rcEnvVars;
    private String shell;
    private KubernetesNodeContext nodeContext;

    public ContainerExecDecorator() {
    }

    @Deprecated
    public ContainerExecDecorator(KubernetesClient client, String podName, String containerName, String namespace, EnvironmentExpander environmentExpander, FilePath ws) {
        this.containerName = containerName;
        this.environmentExpander = environmentExpander;
    }

    @Deprecated
    public ContainerExecDecorator(KubernetesClient client, String podName, String containerName, String namespace, EnvironmentExpander environmentExpander) {
        this(client, podName, containerName, namespace, environmentExpander, null);
    }

    @Deprecated
    public ContainerExecDecorator(KubernetesClient client, String podName, String containerName, String namespace) {
        this(client, podName, containerName, namespace, null, null);
    }

    @Deprecated
    public ContainerExecDecorator(KubernetesClient client, String podName, String containerName, AtomicBoolean alive, CountDownLatch started, CountDownLatch finished, String namespace) {
        this(client, podName, containerName, namespace, null, null);
    }

    @Deprecated
    public ContainerExecDecorator(KubernetesClient client, String podName, String containerName, AtomicBoolean alive, CountDownLatch started, CountDownLatch finished) {
        this(client, podName, containerName, (String) null, null, null);
    }

    @Deprecated
    public ContainerExecDecorator(KubernetesClient client, String podName, String containerName, String path, AtomicBoolean alive, CountDownLatch started, CountDownLatch finished) {
        this(client, podName, containerName, (String) null, null, null);
    }

    @Deprecated
    public KubernetesClient getClient() {
        try {
            return nodeContext.connectToCloud();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Deprecated
    public void setClient(KubernetesClient client) {
        // NOOP
    }

    @Deprecated
    // TODO make private
    public String getPodName() {
        try {
            return getNodeContext().getPodName();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Deprecated
    public void setPodName(String podName) {
        // NOOP
    }

    @Deprecated
    // TODO make private
    public String getNamespace() {
        try {
            return getNodeContext().getNamespace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Deprecated
    public void setNamespace(String namespace) {
        // NOOP
    }

    public String getContainerName() {
        return containerName;
    }

    public void setContainerName(String containerName) {
        this.containerName = containerName;
    }

    public EnvironmentExpander getEnvironmentExpander() {
        return environmentExpander;
    }

    public void setEnvironmentExpander(EnvironmentExpander environmentExpander) {
        this.environmentExpander = environmentExpander;
    }

    public EnvVars getGlobalVars() {
        return globalVars;
    }

    public void setGlobalVars(EnvVars globalVars) {
        this.globalVars = globalVars;
    }

    public void setRunContextEnvVars(EnvVars rcVars) {
        this.rcEnvVars = rcVars;
    }

    public EnvVars getRunContextEnvVars() {
        return this.rcEnvVars;
    }

    public void setShell(String shell) {
        this.shell = shell;
    }

    public KubernetesNodeContext getNodeContext() {
        return nodeContext;
    }

    public void setNodeContext(KubernetesNodeContext nodeContext) {
        this.nodeContext = nodeContext;
    }

    @Override
    public Launcher decorate(final Launcher launcher, final Node node) {

        //Allows other nodes to be provisioned inside the container clause
        //If the node is not a KubernetesSlave return the original launcher
        if(node != null && !(node instanceof KubernetesSlave)) {
           return launcher;
        }
        return new Launcher.DecoratedLauncher(launcher) {
            @Override
            public Proc launch(ProcStarter starter) throws IOException {
                LOGGER.log(Level.FINEST, "Launch proc with environment: {0}", Arrays.toString(starter.envs()));

                // find container working dir
                KubernetesSlave slave = (KubernetesSlave) node;
                FilePath containerWorkingDirFilePath = starter.pwd();
                String containerWorkingDirFilePathStr = containerWorkingDirFilePath != null
                        ? containerWorkingDirFilePath.getRemote() : ContainerTemplate.DEFAULT_WORKING_DIR;
                String containerWorkingDirStr = ContainerTemplate.DEFAULT_WORKING_DIR;
                if (slave != null && slave.getPod().isPresent() && containerName != null) {
                    Optional<Container> container = slave.getPod().get().getSpec().getContainers().stream()
                            .filter(container1 -> container1.getName().equals(containerName))
                            .findAny();
                    Optional<String> containerWorkingDir = Optional.empty();
                    if (container.isPresent() && container.get().getWorkingDir() != null) {
                        containerWorkingDir = Optional.of(container.get().getWorkingDir());
                    }
                    if (containerWorkingDir.isPresent()) {
                        containerWorkingDirStr = containerWorkingDir.get();
                    }

                    if (containerWorkingDir.isPresent() &&
                            containerWorkingDirFilePath != null &&
                            ! containerWorkingDirFilePath.getRemote().startsWith(containerWorkingDirStr)) {
                        // Container has a custom workingDir, updated the pwd to match container working dir
                        containerWorkingDirFilePathStr = containerWorkingDirFilePath.getRemote().replaceFirst(
                                ContainerTemplate.DEFAULT_WORKING_DIR, containerWorkingDirStr);
                        containerWorkingDirFilePath = new FilePath(containerWorkingDirFilePath.getChannel(), containerWorkingDirFilePathStr);
                        LOGGER.log(Level.FINEST, "Modified the pwd to match {0} containers workspace directory : {1}",
                                new String[]{containerName, containerWorkingDirFilePathStr});
                    }
                }

                String[] envVars = starter.envs();
                // modify the working dir on envvars part of starter env vars
                if (!containerWorkingDirStr.equals(ContainerTemplate.DEFAULT_WORKING_DIR)) {
                    for (int i = 0; i < envVars.length; i++) {
                        String keyValue = envVars[i];
                        String[] split = keyValue.split("=", 2);
                        if (split[1].startsWith(ContainerTemplate.DEFAULT_WORKING_DIR)) {
                            // Container has a custom workingDir, update env vars with right workspace folder
                            split[1] = split[1].replaceFirst(ContainerTemplate.DEFAULT_WORKING_DIR, containerWorkingDirStr);
                            envVars[i] = split[0] + "=" + split[1];
                            LOGGER.log(Level.FINEST, "Updated the starter environment variable, key: {0}, Value: {1}",
                                    new String[]{split[0], split[1]});
                        }
                    }
                }

                if (node != null) { // It seems this is possible despite the method javadoc saying it is non-null
                    final Computer computer = node.toComputer();
                    if (computer != null) {
                        List<String> resultEnvVar = new ArrayList<>();
                        try {
                            EnvVars environment = computer.getEnvironment();
                            if (environment != null) {
                                Set<String> overriddenKeys = new HashSet<>();
                                for (String keyValue : envVars) {
                                    String[] split = keyValue.split("=", 2);
                                    if (!split[1].equals(environment.get(split[0]))) {
                                        // Only keep environment variables that differ from Computer's environment
                                        resultEnvVar.add(keyValue);
                                        overriddenKeys.add(split[0]);
                                    }
                                }

                                // modify the working dir on envvars part of Computer
                                if (!containerWorkingDirStr.equals(ContainerTemplate.DEFAULT_WORKING_DIR)) {
                                    for (Map.Entry<String, String> entry : environment.entrySet()) {
                                        if (entry.getValue().startsWith(ContainerTemplate.DEFAULT_WORKING_DIR)
                                                && !overriddenKeys.contains(entry.getKey())) {
                                            // Value should be overridden and is not overridden earlier
                                            String newValue = entry.getValue().replaceFirst(ContainerTemplate.DEFAULT_WORKING_DIR, containerWorkingDirStr);
                                            String keyValue = entry.getKey() + "=" + newValue;
                                            LOGGER.log(Level.FINEST, "Updated the value for envVar, key: {0}, Value: {1}",
                                                    new String[]{entry.getKey(), newValue});
                                            resultEnvVar.add(keyValue);
                                        }
                                    }
                                }
                                envVars = resultEnvVar.toArray(new String[resultEnvVar.size()]);
                            }
                        } catch (InterruptedException e) {
                            throw new IOException("Unable to retrieve environment variables", e);
                        }
                    }
                }
                return doLaunch(starter.quiet(), fixDoubleDollar(envVars), starter.stdout(), containerWorkingDirFilePath, starter.masks(),
                        getCommands(starter, containerWorkingDirFilePathStr, launcher.isUnix()));
            }

            private Proc doLaunch(boolean quiet, String[] cmdEnvs, OutputStream outputForCaller, FilePath pwd,
                    boolean[] masks, String... commands) throws IOException {
                long startMethod = System.nanoTime();

                PrintStream printStream;
                OutputStream stream;

                // Only output to stdout at the beginning for diagnostics.
                ByteArrayOutputStream stdout = new ByteArrayOutputStream();
                // Wrap stdout so that we can toggle it off.
                ToggleOutputStream toggleStdout = new ToggleOutputStream(stdout);

                // Do not send this command to the output when in quiet mode
                if (quiet) {
                    stream = toggleStdout;
                    printStream = new PrintStream(stream, true, StandardCharsets.UTF_8.toString());
                } else {
                    printStream = launcher.getListener().getLogger();
                    stream = new TeeOutputStream(toggleStdout, printStream);
                }

                ByteArrayOutputStream dryRunCaller = null;;
                ToggleOutputStream toggleDryRunCaller = null;
                ToggleOutputStream toggleOutputForCaller = null;
                // Send to proc caller as well if they sent one
                if (outputForCaller != null && !outputForCaller.equals(printStream)) {
                    if (launcher.isUnix()) {
                        stream = new TeeOutputStream(outputForCaller, stream);
                    } else {
                        // Prepare to capture output for later.
                        dryRunCaller = new ByteArrayOutputStream();
                        toggleDryRunCaller = new ToggleOutputStream(dryRunCaller);
                        // Initially disable the output for the caller, to prevent it from getting unwanted output such as prompt
                        toggleOutputForCaller = new ToggleOutputStream(outputForCaller, true);
                        stream = new TeeOutputStream(toggleOutputForCaller, stream);
                        stream = new TeeOutputStream(toggleDryRunCaller, stream);
                    }
                }
                ByteArrayOutputStream error = new ByteArrayOutputStream();

                String[] sh = shell != null ? new String[]{shell} : launcher.isUnix() ? new String[] {"sh"} : new String[] {"cmd", "/Q"};
                String msg = "Executing " + String.join(" ", sh) + " script inside container " + containerName + " of pod " + getPodName();
                LOGGER.log(Level.FINEST, msg);
                printStream.println(msg);

                if (closables == null) {
                    closables = new ArrayList<>();
                }

                int attempts = 0;
                ExecWatchWrapper watchWrapper = null;
                while (watchWrapper == null && attempts < WEBSOCKET_CONNECTION_MAX_RETRY) {

                    if (attempts > 0) {
                        // Exponential backoff: Waits 2s, next attempt 4s, next attempts 8s, next attempts 16s, ...
                        // with a maximum of wait of WEBSOCKET_CONNECTION_MAX_RETRY_BACKOFF
                        long backoffInSeconds = Math.min(Integer.toUnsignedLong((int) Math.pow(2, attempts)), WEBSOCKET_CONNECTION_MAX_RETRY_BACKOFF);
                        launcher.getListener().getLogger().println("Retrying in " + backoffInSeconds + "s ...");
                        try {
                            Thread.sleep(backoffInSeconds * 1000);
                        } catch (InterruptedException ex) {
                            launcher.getListener().getLogger().println("Retry wait interrupted");
                        } finally {
                            launcher.getListener().getLogger().println("Retrying...");
                        }
                    }

                    try {
                        final AtomicBoolean alive = new AtomicBoolean(false);
                        final CountDownLatch started = new CountDownLatch(1);
                        final CountDownLatch finished = new CountDownLatch(1);
                        final AtomicLong startAlive = new AtomicLong();

                        ExecWatch watch = getClient().pods().inNamespace(getNamespace()).withName(getPodName()).inContainer(containerName)
                            .redirectingInput(STDIN_BUFFER_SIZE) // JENKINS-50429
                            .writingOutput(stream)
                            .writingError(stream)
                            .writingErrorChannel(error)
                            .usingListener(new ExecListener() {
                                @Override
                                public void onOpen() {
                                    alive.set(true);
                                    started.countDown();
                                    startAlive.set(System.nanoTime());
                                    LOGGER.log(Level.FINEST, "onOpen : {0}", finished);
                                }

                                @Override
                                public void onFailure(Throwable t, Response response) {
                                    alive.set(false);
                                    t.printStackTrace(launcher.getListener().getLogger());
                                    started.countDown();
                                    LOGGER.log(Level.FINEST, "onFailure : {0}", finished);
                                    if (finished.getCount() == 0) {
                                        LOGGER.log(Level.WARNING,
                                            "onFailure called but latch already finished. This may be a bug in the kubernetes-plugin");
                                    }
                                    finished.countDown();
                                }

                                @Override
                                public void onClose(int i, String s) {
                                    alive.set(false);
                                    started.countDown();
                                    LOGGER.log(Level.FINEST, "onClose : {0} [{1} ms]", new Object[]{finished, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startAlive.get())});
                                    if (finished.getCount() == 0) {
                                        LOGGER.log(Level.WARNING,
                                            "onClose called but latch already finished. This indicates a bug in the kubernetes-plugin");
                                    }
                                    finished.countDown();
                                }
                            }).exec(sh);

                        // prevent a wait forever if the connection is closed as the listener would never be called
                        try {
                            if (started.await(WEBSOCKET_CONNECTION_TIMEOUT, TimeUnit.SECONDS)) {
                                watchWrapper = new ExecWatchWrapper(watch, alive, finished);
                            } else {
                                closeWatch(watch);
                                launcher.getListener().error("Timed out waiting for websocket connection. "
                                    + "You should increase the value of system property "
                                    + WEBSOCKET_CONNECTION_TIMEOUT_SYSTEM_PROPERTY + " currently set at "
                                    + WEBSOCKET_CONNECTION_TIMEOUT + " seconds");
                            }
                        } catch (InterruptedException e) {
                            closeWatch(watch);
                            throw e;
                        }

                    } catch (KubernetesClientException e) {
                        launcher.getListener().getLogger().print("Failed to start websocket connection: ");

                        // In case of 400 / Bad Request, do not attempt a retry
                        if (e.getCause() instanceof WebSocketHandshakeException) {
                            WebSocketHandshakeException wsException = (WebSocketHandshakeException) e.getCause();
                            if (wsException.getResponse() != null && wsException.getResponse().code() == 400) {
                                throw e;
                            }
                        }

                        e.printStackTrace(launcher.getListener().getLogger());
                    } catch (InterruptedException e) {
                        launcher.getListener().getLogger().println("Failed to start websocket connection: " +
                            "Interrupted while waiting for websocket connection, you should consider increasing the Max connections to Kubernetes API.");
                        e.printStackTrace(launcher.getListener().getLogger());
                    } finally {
                        attempts++;
                    }
                }

                if (watchWrapper == null || watchWrapper.getExecWatch() == null) {
                    throw new AbortException("Failed to start websocket connection after "
                        + attempts + " attempts. Check logs above for more details.");
                }

                ExecWatch watch = watchWrapper.getExecWatch();
                final AtomicBoolean alive = watchWrapper.getAlive();
                final CountDownLatch finished = watchWrapper.getFinished();

                try {
                    // Depends on the ping time with the Kubernetes API server
                    // Not fully satisfied with this solution because it can delay the execution
                    if (finished.await(COMMAND_FINISHED_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                        launcher.getListener().error("Process exited immediately after creation. See output below%n%s", stdout.toString(StandardCharsets.UTF_8.name()));
                        throw new AbortException("Process exited immediately after creation. Check logs above for more details.");
                    }
                    toggleStdout.disable();
                    OutputStream stdin = watch.getInput();
                    PrintStream in = new PrintStream(stdin, true, StandardCharsets.UTF_8.name());
                    if (!launcher.isUnix()) {
                        in.print("@echo off");
                        in.print(newLine(true));
                    }
                    if (pwd != null) {
                        // We need to get into the project workspace.
                        // The workspace is not known in advance, so we have to execute a cd command.
                        in.print(String.format("cd \"%s\"", pwd));
                        in.print(newLine(!launcher.isUnix()));
                    }

                    EnvVars envVars = new EnvVars();

                    //get global vars here, run the export first as they'll get overwritten.
                    if (globalVars != null) {
                        envVars.overrideAll(globalVars);
                    }

                    if(rcEnvVars != null) {
                        envVars.overrideAll(rcEnvVars);
                    }

                    if (environmentExpander != null) {
                        environmentExpander.expand(envVars);
                    }

                    //setup specific command envs passed into cmd
                    if (cmdEnvs != null) {
                        for (String cmdEnv : cmdEnvs) {
                            envVars.addLine(cmdEnv);
                        }
                    }

                    LOGGER.log(Level.FINEST, "Launching with env vars: {0}", envVars.toString());

                    setupEnvironmentVariable(envVars, in, !launcher.isUnix());
                    if (!launcher.isUnix() && toggleOutputForCaller!= null) {
                        // Windows welcome message should not be sent to the caller as it is a side-effect of calling the wrapping cmd.exe
                        // Microsoft Windows [Version 10.0.17763.2686]
                        // (c) 2018 Microsoft Corporation. All rights reserved.
                        //
                        // C:\>
                        stream.flush();
                        long beginning = System.currentTimeMillis();
                        // watch for the prompt character
                        while(!dryRunCaller.toString(StandardCharsets.UTF_8.name()).contains(">")) {
                            Thread.sleep(100);
                        }
                        LOGGER.log(Level.FINEST, "Windows prompt printed after " + (System.currentTimeMillis() - beginning) + " ms");
                    }
                    // We don't need to capture output anymore
                    if (toggleDryRunCaller != null) {
                        toggleDryRunCaller.disable();
                    }
                    // Clear any captured bytes
                    if (dryRunCaller != null) {
                        dryRunCaller.reset();
                    }
                    if (toggleOutputForCaller != null) {
                        toggleOutputForCaller.enable();
                    }
                    doExec(in, !launcher.isUnix(), printStream, masks, commands);

                    LOGGER.log(Level.INFO, "Created process inside pod: [" + getPodName() + "], container: ["
                            + containerName + "]" + "[" + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startMethod) + " ms]");
                    ContainerExecProc proc = new ContainerExecProc(watch, alive, finished, stdin, error);
                    closables.add(proc);
                    return proc;
                } catch (InterruptedException ie) {
                    throw new InterruptedIOException(ie.getMessage());
                } catch (Exception e) {
                    closeWatch(watch);
                    throw e;
                }
            }

            @Override
            public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException {
                getListener().getLogger().println("Killing processes");

                String cookie = modelEnvVars.get(COOKIE_VAR);

                int exitCode = doLaunch(
                        true, null, null, null, null,
                        // TODO Windows
                        "sh", "-c", "kill \\`grep -l '" + COOKIE_VAR + "=" + cookie  +"' /proc/*/environ | cut -d / -f 3 \\`"
                ).join();

                getListener().getLogger().println("kill finished with exit code " + exitCode);
            }

            private void setupEnvironmentVariable(EnvVars vars, PrintStream out, boolean windows) throws IOException {
                for (Map.Entry<String, String> entry : vars.entrySet()) {
                    //Check that key is bash compliant.
                    if (entry.getKey().matches("[a-zA-Z_][a-zA-Z0-9_]*")) {
                            out.print(
                                    String.format(
                                            windows ? "set %s=%s" : "export %s='%s'",
                                            entry.getKey(),
                                            windows ? entry.getValue() : entry.getValue().replace("'", "'\\''")
                                    )
                            );
                            out.print(newLine(windows));
                        }
                    }
            }
        };
    }

    private static String newLine(boolean windows) {
        return windows ? "\r\n" : "\n";
    }

    @Override
    public void close() throws IOException {
        if (closables == null) return;

        for (Closeable closable : closables) {
            try {
                closable.close();
            } catch (Exception e) {
                LOGGER.log(Level.FINE, "failed to close", e);
            }
        }
    }

    /**
     * Wrapper of ExecWatch that also hold watch attributes for liveness and closure.
     */
    private static class ExecWatchWrapper {

        /* the watch */
        private final ExecWatch execWatch;
        /* atomic boolean value for watch liveness */
        private final AtomicBoolean alive;
        /* count down latch value for watch exit */
        private final CountDownLatch finished;

        public ExecWatchWrapper(ExecWatch execWatch, AtomicBoolean alive, CountDownLatch finished) {
            this.execWatch = execWatch;
            this.alive = alive;
            this.finished = finished;
        }

        public ExecWatch getExecWatch() {
            return execWatch;
        }

        public AtomicBoolean getAlive() {
            return alive;
        }

        public CountDownLatch getFinished() {
            return finished;
        }
    }

    private static class ToggleOutputStream extends FilterOutputStream {
        private boolean disabled;
        public ToggleOutputStream(OutputStream out) {
            this(out, false);
        }

        public ToggleOutputStream(OutputStream out, boolean disabled) {
            super(out);
            this.disabled = disabled;
        }

        public void disable() {
            disabled = true;
        }

        public void enable() {
            disabled = false;
        }

        @Override
        public void write(int b) throws IOException {
            if (!disabled) {
                out.write(b);
            }
        }

        @Override
        public void write(byte[] b) throws IOException {
            if (!disabled) {
                out.write(b);
            }
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            if (!disabled) {
                out.write(b, off, len);
            }
        }
    }

    /**
     * Process given stream and mask as specified by the bitfield.
     * Uses space as a separator to determine which fragments to hide.
     */
    private static class MaskOutputStream extends FilterOutputStream {
        private static final String MASK_STRING = "********";

        private final boolean[] masks;
        private final static char SEPARATOR = ' ';
        private int index;
        private boolean wrote;

        public MaskOutputStream(OutputStream out, boolean[] masks) {
            super(out);
            this.masks = masks;
        }

        @Override
        public void write(int b) throws IOException {
            if (masks == null || index >= masks.length) {
                out.write(b);
            } else if (isSeparator(b)) {
                out.write(b);
                index++;
                wrote = false;
            } else if (masks[index]) {
                if (!wrote) {
                    wrote = true;
                    for (char c : MASK_STRING.toCharArray()) {
                        out.write(c);
                    }
                }
            } else {
                out.write(b);
            }
        }

        private boolean isSeparator(int b) {
            return b == SEPARATOR;
        }
    }

    private static void doExec(PrintStream in, boolean windows, PrintStream out, boolean[] masks, String... statements) {
        long start = System.nanoTime();
        // For logging
        ByteArrayOutputStream loggingOutput = new ByteArrayOutputStream();
        // Tee both outputs
        TeeOutputStream teeOutput = new TeeOutputStream(out, loggingOutput);
        // Mask sensitive output
        MaskOutputStream maskedOutput = new MaskOutputStream(teeOutput, masks);
        // Tee everything together
        PrintStream tee;
        try {
            String encoding = StandardCharsets.UTF_8.name();
            tee = new PrintStream(new TeeOutputStream(in, maskedOutput), false, encoding);
            // To output things that shouldn't be considered for masking
            PrintStream unmasked = new PrintStream(teeOutput, false, encoding);
            unmasked.print("Executing command: ");
            for (String statement : statements) {
                if (windows) {
                    tee.append(statement).append(" ");
                } else {
                    tee.append("\"").append(statement).append("\" ");
                }
            }
            tee.print(newLine(windows));
            LOGGER.log(Level.FINEST, loggingOutput.toString(encoding) + "[" + TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - start) + " μs." + "]");
            // We need to exit so that we know when the command has finished.
            tee.print(EXIT);
            tee.print(newLine(windows));
            tee.flush();
        } catch (UnsupportedEncodingException e) {
            LOGGER.log(Level.SEVERE, "Failed to execute command because of unsupported encoding", e);
        }
    }

    static String[] getCommands(Launcher.ProcStarter starter, String containerWorkingDirStr, boolean unix) {
        List<String> allCommands = new ArrayList<String>();

        for (String cmd : starter.cmds()) {
            // BourneShellScript.launchWithCookie escapes $ as $$, we convert it to \$
            String fixedCommand = cmd.replaceAll("\\$\\$", Matcher.quoteReplacement("\\$"));
            if (unix) {
                fixedCommand = fixedCommand.replaceAll("\\\"", Matcher.quoteReplacement("\\\""));
            }

            String oldRemoteDir = null;
            FilePath oldRemoteDirFilepath = starter.pwd();
            if (oldRemoteDirFilepath != null) {
                oldRemoteDir = oldRemoteDirFilepath.getRemote();
            }
            if (oldRemoteDir != null && ! oldRemoteDir.isEmpty() &&
                    !oldRemoteDir.equals(containerWorkingDirStr) && fixedCommand.contains(oldRemoteDir)) {
                // Container has a custom workingDir, update the dir in commands
                fixedCommand = fixedCommand.replaceAll(oldRemoteDir, containerWorkingDirStr);
            }
            allCommands.add(fixedCommand);
        }
        return allCommands.toArray(new String[allCommands.size()]);
    }

    private static void closeWatch(ExecWatch watch) {
        try {
            watch.close();
        } catch (Exception e) {
            LOGGER.log(Level.INFO, "failed to close watch", e);
        }
    }

    @Deprecated
    public void setKubernetesClient(KubernetesClient client) {
        // NOOP
    }

    private static String[] fixDoubleDollar(String[] envVars) {
        return Arrays.stream(envVars)
                .map(ev -> ev.replaceAll("\\$\\$", Matcher.quoteReplacement("$")))
                .toArray(String[]::new);
    }
}


text:
package com.amazonaws.services.ec2.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * LaunchTemplateCapacityReservationSpecificationResponse StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LaunchTemplateCapacityReservationSpecificationResponseStaxUnmarshaller implements
        Unmarshaller<LaunchTemplateCapacityReservationSpecificationResponse, StaxUnmarshallerContext> {

    public LaunchTemplateCapacityReservationSpecificationResponse unmarshall(StaxUnmarshallerContext context) throws Exception {
        LaunchTemplateCapacityReservationSpecificationResponse launchTemplateCapacityReservationSpecificationResponse = new LaunchTemplateCapacityReservationSpecificationResponse();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return launchTemplateCapacityReservationSpecificationResponse;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("capacityReservationPreference", targetDepth)) {
                    launchTemplateCapacityReservationSpecificationResponse.setCapacityReservationPreference(StringStaxUnmarshaller.getInstance().unmarshall(
                            context));
                    continue;
                }

                if (context.testExpression("capacityReservationTarget", targetDepth)) {
                    launchTemplateCapacityReservationSpecificationResponse.setCapacityReservationTarget(CapacityReservationTargetResponseStaxUnmarshaller
                            .getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return launchTemplateCapacityReservationSpecificationResponse;
                }
            }
        }
    }

    private static LaunchTemplateCapacityReservationSpecificationResponseStaxUnmarshaller instance;

    public static LaunchTemplateCapacityReservationSpecificationResponseStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new LaunchTemplateCapacityReservationSpecificationResponseStaxUnmarshaller();
        return instance;
    }
}


text:
package net.pryden.accounts.reports;

import static com.google.common.truth.Truth.assertThat;

import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Fake implementation of {@link FormHelper} for testing.
 *
 * <p>Also implements {@link net.pryden.accounts.reports.FormHelper.Factory} for convenience; the
 * factory always returns {@code this} instance.
 */
final class FakeFormHelper extends FormHelper implements FormHelper.Factory {
  private final Map<String, String> formValues = new HashMap<>();
  private final Map<String, Boolean> formCheckboxes = new HashMap<>();

  @Override
  public FormHelper create(String formFilePath, Path outputFilePath) throws IOException {
    return this;
  }

  @Override
  void setValue(String fieldName, String value) {
    formValues.put(fieldName, value);
  }

  Optional<String> getValue(String fieldName) {
    return Optional.ofNullable(formValues.get(fieldName));
  }

  void assertValue(String fieldName, String value) {
    assertThat(formValues).containsEntry(fieldName, value);
  }

  @Override
  void setCheckBox(String fieldName, boolean checked) {
    formCheckboxes.put(fieldName, checked);
  }

  Optional<Boolean> getCheckBox(String fieldName) {
    return Optional.ofNullable(formCheckboxes.get(fieldName));
  }

  void assertChecked(String fieldName) {
    assertThat(formCheckboxes).containsEntry(fieldName, true);
  }

  @Override
  void save() throws IOException {}

  @Override
  public void close() throws IOException {}
}


text:
Serializer [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/schmittjoh/serializer/badges/quality-score.png?s=189df68e00c75d3fe155bc0da0b53b53709a9895)](https://scrutinizer-ci.com/g/schmittjoh/serializer/)
==========

Learn more about it in its [documentation](http://jmsyst.com/libs/serializer).


text:
from .base import FilmQueryInfoCrawler, FilmDownloadInfoCrawler
from .factory import FilmDownloadInfoCrawlerFactory
from .douban import DoubanCrawler
from .dy2018 import Dy2018Crawler
from .dytt8 import Dytt8Crawler
from .btrenren import BTRenRenCrawler

__all__ = ['FilmQueryInfoCrawler', 'FilmDownloadInfoCrawler', 'FilmDownloadInfoCrawlerFactory', 'DoubanCrawler',
           'Dy2018Crawler', 'Dytt8Crawler', 'BTRenRenCrawler']


text:
ab_test "Age and Zipcode" do
  description <<-TEXT
Testing new registration form that asks for age and zipcode. Option A presents
the existing form, and option B adds age and zipcode fields.

We know option B will convert less, but higher quality leads. If we lose less
than 20% conversions, we're going to switch to option B.
  TEXT
  metrics :signups

  complete_if do
    alternatives.all? { |alt| alt.participants > 100 }
  end
  outcome_is do
    one_field = alternative(false)
    three_fields = alternative(true)
    three_fields.conversion_rate >= 0.8 * one_field.conversion_rate ? three_fields : one_field
  end
end